Tuesday, April 21, 2009

Ubuntu adventures - django install a breeze!

Installed django on ubuntu today. Do not make the mistake of installing django from the synaptic package manager. Firstly, its an older version than the current 1.0.2 and secondly, it does not install it in your python "site-packages" folder.

The best way to do it is as they say on the django site. Download the tar file and install using python setup.py install. The cool thing about this is is that I found that the symlinks were also created for you. I could access django-admin.py from any directory in my machine.

I also installed postgreSQL and psycopg2 (the python interface for postgres) from the synaptic package manager and I was good to go with django in a matter of minutes! For now I am developing with the webserver bundled inside django but I hope to be switching to apache with mod_wsgi soon.

I hope to be tinkering a lot with django over the next few weeks.

Perl power! Sorting dictionaries (or hashes in Perl lingo)

Theres a dictionary dict1 with keys key1, key2, etc such that $dict1{keyn} has a value which itself is a dictionary. Lets call this dictionary %subdict. Now subdict has different keys subkey1, subkey2 and so on such that $subdict{subkey5} = subvalue5.

Problem: How do I sort dict1 such that the keys are in the ascending order of subvalue5?

This would not be easy to do in a single line of code, unless of course the language is Perl! Ready? here it is:

dict1_keys_sorted = sort {$dict1{$a}{subkey5} cmp $dict1{$b}{subkey5}} keys %dict1

Lets take this apart. Going from the right side, you start of with dict1. Now, keys %dict1 returns a list of the keys. With the sort command being invoked, Perl feeds the first two values of the keys into $a and $b. So, $dict1{$a}{subkey5} gives the value of subvalue5 for that key value of dict1. The values are compared and depending on true or false value, it puts the value into the new list dict1_keys_sorted which is sorted.

Note: "cmp" is for sorting strings. To sort number use "<=>".