I finally found an opportunity to use ruby partition method. It splits an array you have upon a criteria you supply in a block. Typically, in the old days, I would have done this by doing something like this:
big_array = Array.new(11) {|i| i}
number_lower_than_5 = []
big_array.each do |number|
if number < 5
number_lower_than_5 << number
end
end
# >> number_lower_than_5
# => [0,1,2,3,4]
or more recently I would use select
big_array = Array.new(11) {|i| i}
number_lower_than_5 = []
number_lower_than_5 =
big_array.select do |number|
number < 5
end
# >> number_lower_than_5
# => [0,1,2,3,4]
These are both fine methods but what happens if you need the other halve as well? The above approaches just collect you an array to work with and both lack the convenient array of the other stuff you sometimes care about. That’s where ruby’s partition comes in handy. It may not be that often that’s why I was so pumped up when I found an opportunity to use it.
big_array = Array.new(11) {|i| i}
number_lower_than_5, the_rest =
big_array.partition do |number|
number < 5
end
# >> number_lower_than_5
# => [0,1,2,3,4]
# >> the_rest
# => [5,6,7,8,9,10]
One thing I do love is to spend 15 minutes to solve a problem that would have taken me 20 minutes to do manually … heck that’s how I got into this programming thing. Bash scripting is becoming one of my favorite tools as it’s so simple once you wrap your head around it’s weirdness … which I am hoping to do early 2010 :)
So the problem I had was that I had a bunch of photos with some stupid names which were automatically generated by my stupid scanner software, sc30rr.jpg not joking it was total rubbish so after spending roughly 30 minutes scanning photographs I had this folder filled with files with that stupid name and I just wanted to make it name_of_event_001 and have the last bit be a serialized number.
for filename in *.jpg ; \
do n=$(( $n+1 )); \
mv $filename name_of_event_`printf "%03d" $n`.jpg; \
done
My hope is next time I need to do this I will not have to fudge around for 15 minutes and just either remember how I did it this time or alternatively look it up on my blog :)
when ever I get an opportunity to swings this trick out I get very excited. Say you have a task you wanna do and it’s should be applied to a number of files with a common name or are all with the same extension, basically any situation where you would be doing something that seems too repetitive for you taste.
Too create our example we can actually use the same trick. Lets say you have a number of files with the same name but have different number at the back of it: test_1.txt, test_2.txt, test_3.txt. So instead of doing touch file.txt n number of times you can instead do the following.
$ touch test_{1,2,3}.txt
Now when I was trying to figure out where I learned this from I found the website where it came from so go there for more kewl tricks.
When I write web apps I try my best to keep my urls clean and legible. One thing that has always troubled me is how to handle label creation of named things web users key into the app. For example if a user enters a name of a restaurant Alicanté Café the uri safe for of that (if there is no intervention) ‘Alicant%C3%A9%20Caf%C3%A9’, which is total gobblygoo and one might as well show a uid or something of that nature since at least that doesn’t physically hurt the eye. As someone who has worked on a lot of Restaurant related apps this has always been something I wanted there to be an easy solution to. This weekend I decided it was worth trying once again to see what would work best. And after reading the “Internationalization in Ruby” in The Ruby Way. Here is the super simple trick
require 'iconv'
strange_name = "Alicanté Café"
converter = Iconv.new('ASCII//TRANSLIT', 'UTF-8')
converter.iconv(strange_name)
"Alicant'e Caf'e"
It leaves some odd ’ and “sfor some reason but they will get stripped away with all the other potential weird stuff out (”,’,etc). Still this discovery makes me stop complaining about pretentious foreign sounding restaurant names.
Here is an excellent case of a big problem … with a incredible simple solution. I upgraded my slicehost ubunto vpn from dapper to hardy. A risky business with nothing real in jeopardy except for the pride of a 380 days up time on the server. I shut down everything running on the server and upgrade to hardy. All is fine except that I realize that when I am starting all the services that small things tab completion doesn’t work among other annoyances and doing work on a server without that is practically unbearable. So I figured I would make some time to fix it… the best place to go on these issues is slicehost … THE ROCK. Tony on the slicehost campfire chat immediately identified the problem and it was fixed within 5 minutes.
*Tony | try just running “bash”
And as he said that I was like shit and ran echo $SHELL only to realize that I was in “sh” but now everything is fixed and dandy and I have my tab completion back along with other normal bashy things … thank god. Did I mention that slicehost rocks!
Using AWS::S3
Now setting a object to :public_read is trivial if it’s done when you store it to S3. That doesn’t seem to be the case if you want to change on an object that already has been stored privately. After banging my head against it a bit I finally “got it” and I figured I would share it to either show off or try to be helpful.
dial into s3sh session see url above for details on how to store keys in environment variables etc.
once in there get a bucket object
now get the s3obj that you want to become public
The access control on the buckets must be very rich since it’s this tricky make things public. I must be overlooking something.
A while back I decided to get fancy and start hosting this blog on ec2 cloud just to sort of get the hang of working on that kind of a system. This of course involved moving database over and the works. Everything seemed to be going fine until I started posting… things were just busted bad. I kept getting
ActiveRecord::StatementInvalid (Mysql::Error: Duplicate entry ‘0’ for key 1
errors and for the longest time I just ignored it since I was able to post by using a some of my masterpiece drafts that I wasn’t going to use any how… but then I ran out of those and I felt an urge to post but that meant I needed to tackle the problem and as it turned out it was a simple fix after I had done the research. The primary key fields had lost the AUTO_INCREMENT magic during my db move and the solution was simply to go in and ad them where a appropriate.
ALTER TABLE `contents` CHANGE `id` `id` INT NOT NULL AUTO_INCREMENT;
It’s a continues struggle to become efficient in using VIM, especially if one ventures outside of what one regularly needs to do. It’s well worth it though since it might be the last text editor that you’ll ever need to master.
I was faced with having to produce pdf with selected code snippets.
Here is the fastest approach… be warned this example is for macs but I am sure it can work in other Li/Unix environments as well.
Install CUPS PDF and setup a virtual printer as is described on that page. Make sure that it’s the default printer after you have set it up.
The command to print in vim is :ha which is a short for :hardcopy this will spool the whole file to the print que for that driver and ultimately drop a pdf in cups-pdf folder on your desktop. To print out a selection simply highlight some text before issuing :ha command. I needed the line-numers of the code samples and this can be achieved by setting printoptions.
set printoptions=number:y
Now to be a complete terminal snob you should check out pdftk
Once you get into the habit of using jslint it’s hard not to, it’s just so satisfying when it passes and all the lint has been cleared away. The first few times I used I went to the web application and pasted the file in there and looked at the results, fixed what was wrong and pasted it back into the original file. This is especially inconvenient if you use vim or emacs since pasting from an external environment has always been a bit of a challenge. But fear not, Douglas Crowford, best known for his work on the json spec, has an extended version that works with rhino the java javascript interpreter. The advantage of using jslint through rhino is that you can inspect your javascript files from the terminal. Installing it on a mac is trivial just follow Peters Michaux Install instructions
Here is the short version:
$> curl -O ftp://ftp.mozilla.org/pub/mozilla.org/js/rhino1_6R7.zip
$> unzip rhino1_6R7.zip
$> cp rhino1_6R7/js.jar /Library/java/Extensions/
Download the jslint file
$> curl -O http://www.jslint.com/rhino/jslint.js
And then you should be able to:
$> java org.mozilla.javascript.tools.shell.Main jslint.js your_program.js
Two things in my .bash_history today.
vim has an answer for every problem vimdiff file1.txt file2.txt
FileMerge looks promizing also
the screen app. see http://jmcpherson.org/screen.html
One cool thing I learned today was that you can set the columns when you generate the rails migration from the terminal. The prepopulates the tabel generation code with the table names and datatype. This isn’t such a big find since it’s well documented in script/generate model—help. But here is how it looks.
script/generate model members name:string age:integer
script/generate model portfolio member_id:integer body:text
Another thing I just came to realize is that defining explicit foreign_key constraint to the database is probably a good idea. I don’t know too much about database administration but if I understand it correctly it helps with dataintegrity and probably performance if the table grows big. Adding indexes is also a plus. A little specifity never hurt anyone. This example is for MYSQL with the InnoDB engine which I believe is the default for rails now.
. . . def self.up create_table :members do |t| t.column :name, :string t.column :age, :integer end end . . . def self.up create_table :portfolios do |t| t.column :member_id, :integer t.column :body, :text end execute 'ALTER TABLE portfolios ADD CONSTRAINT fk_portfolios_member \\ FOREIGN KEY (member_id) REFERENCES members(id)' end . . .
Here is one neat little vim trick
def some_method
return bla
end
These vim mappings allow you to quickly comment a block of code in VISUAL mode by pressing ,# or any other key command you prefer
#def some_method
# return bla
#end
And pressing ,c removes them again.
def some_method
return bla
end
It’s educational to watch other people at work! especially if they are really good at what they do. I had such luck today. I was clever enough to make sure I had a backup of my .bash_history file so I can go through his actions and try them myself in the hopes that I would remember them later on when I needed them again and that’s where I had this idea of maintaining a page where I can put down those tricks for me to remember and help others that happen to stumble upon it.
The fist thing I learned was that when you are in vi on the terminal and you want to quickly go out of it and get to the console you can hit control+z and that brings you to the bash shell and then you type fg to get back and if there is more than one buffer open you can do fg1 fg2 etc, pointer you can also get to the shell via the :sh command.
Here are some other things.
svn status | grep "^?" | grep -v tmp | \\
sed -e 's/^? *//' | xargs svn add
svn diff > changes_to_patch
svn diff -rHEAD:999 > changes_to_patch
patch -p0 < changes_to_patch
svn log --stop-on-copy