Sunday, March 15, 2009

Tree Traversal Ordering - Whats the order again?

I have always had trouble remembering what exactly are the orders of inorder, preorder and postorder traversals. Well today I think iv had the defining insight :). the "IN","PRE" and "POST" is based on where the root node is.

  • In "INorder" the root node is "IN" the middle of left and right nodes

  • In "PREorder" the root node is "PRE" i.e. before the left and right nodes

  • In "POSTorder" the root node is "POST" i.e. after the left and right nodes

This was that proverbial duhh moment :)

Sunday, March 08, 2009

How to test out ActiveRecord in irb

I like how interpreted languages provide this interpreter for you to try out stuff. As I am learning ruby on rails I frequently need to try out ActiveRecord's dark ways of doing things and I would like to be able to try it out in irb so here is what I do
Launch irb
irb --simple-prompt

and then execute the following code assuming you are in the rails app directory

require 'rubygems'

require 'active_record'

require 'yaml'

Dir.glob(File.join(File.dirname(__FILE__), './app/models/*.rb')).each {|f| require f }

dbconfig =

currenv =

if not currenv

currenv =


currdbconfig = dbconfig[currenv]

"database"] = currdbconfig["database"]

#p currdbconfig


After thins you can try out your model methods in the prompt.

This works with MySQL and should work with sqllite3 without any problems

Tuesday, February 19, 2008

Line numbers in Java Exception Stack Trace

This post is almost like a note in my java diary. I came across this problem while using the ant javac task. My javac task looked like this:

<javac srcdir="${src.dir}" destdir="${build.dir}">
<fileset dir="${lib.dir}">
<include name="*.jar" />

No real problems right? Except the fact that when an exception occured in the code compiled using this task I usually got something like this:

Exception in thread "main" java.lang.NullPointerException: Null
at SampleTrace.main(Unknown Source)

See that "Unknown Source" thing? It makes debugging an unusually hard task. So whats the problem here? The problem is the two attributes of the javac task debug and deubglevel.
These options translate into the -g command line option for javac. These options relate to how much debugging information will be present in class files generated. You can give a combination of three values for this option

  • lines - Line number debugging information.
  • vars - Local variable debugging information.
  • source - Source file debugging information.
Of course, more the debugging information the bigger your class files become. So what do these options really mean in terms of getting an exception stack trace in my program to show me line numbers. My initially understanding was that all I needed was line so that I could get line number information. Right? Wrong! If you are just looking for solution without knowing about the why of it, the answer is:
lines,source - i.e. Make debug="on" and debuglevel="lines,source" in you javac task.

The most important thing to understand is what does the combination of these options do:
  • lines,vars,source - Include all debugging information
  • lines,vars - Include line number information, preserve variable names for method local variables. Line number information is especially useful if you are going to use a debugger to debug your programs.
  • lines,source - line number information and source file information. This is what is required for exception stack trace to work properly.
  • vars,source - Preserve method local variable names as well as source file information.
The source option is what still remains a confusion point. I have tried compiling my class files without that option, but no apparent changes are reflected in my class file as viewed in the decompiler. So any comments are welcome :-)

Monday, December 17, 2007

Getting off the ground with SVN.

Do you frequently ask your colleague to email code to you and then "integrate" on your machine? Do you frequently miss somebody's code before deploying the application? Have you had days when you have felt, "it would have been great if i had my code of 2 days ago!"?
If you are in a situation similar to the ones above you should seriously consider using a version control system. At its most basic level a version control system would improve your situation in the following ways:

  1. Allow for easy collaboration:, no more "code emailing, pen drives".

  2. Maintain history: You can go back to your code of 2 days or 20 days ago, check what did you change, get it back if you want. This must be sweet music if you have redone code that you did sometime ago.

Ok - I want all that but question is which version control system do i use? Honestly, tough question, but from a newbie point of view I have found subversion (frequently called svn) the easiest to get off the ground.

So lets take our first baby steps to setting up subversion:

  • Step 1-Download and Install subversion: Subversion for Windows can be downloaded from here. Download the latest version (1.4.5 currently). Run the exe and you should get through the installation fairly easily.

  • Step 2: Create a Repository: Subversion can be thought of as a client server system. It works by having a central respository which several clients can access for doing various operations. To create a repository, open cmd from Run and type out the following command

    c:\>svnadmin create c:\my_repository

    This will create a folder called my_repository in c drive which will be the Subversion admin area.

  • Configure SVN Access - Now you have a repository, and you are the SVN Admin :), so time for you to decide who gets to access the repository, what rights do they have? To configure these things navigate to the folder c:my_repositoryconf and open the file called svnserve.conf. You will see a section title [general] and under that you will see 2 commented entries (# denotes a comment line), these commented entries which are the default values are

    anon-access = read
    auth-access = write

    These signify that a user with no credentials will be able to read whats in you repository, but not modify files in it, whereas an authenticated user will be able to modify files.

    If you are in a trusted environment then you could probably alter the anon-access (Please make sure that if you make any changes to file, you remove the # before that line and there is no space at the beginning of the line) property to write, so that almost anyone can edit the code in your repository, but going further you would want only authenticated users to change the code in the repository.

    Now to specify which file to use as the file which contains the usernames and passwords uncomment the line(remove the # from the beginning, again remember no spaces after line start).


    To configure users for your repository open the file called passwd.
    Under the [users] section in that file you will see that the format of users is


    Create the users that you want with their passwords, be sure that there is no # before the line, it indicates a comment.

  • Step 3: Start SVN Server - SVN comes with a bundled server that you can use for basic purpose. In advanced cases svn repository can be exposed through a webserver like apache.

    To start the SVN Server execute the following command

    c:\>svnserve -d -r c:\my_repository

    Now you have an svn server running on your machine which the others will be able to access. The -r argument above should be followed by the location of the repository. The -d argument specifies that the server should be run in daemon mode. This will keep a DOS window open all the time and if you restart your machine (i.e. the machine where the server is running) you will have to restart the server also by running this command again.

    In order to get around this problem you can run the svn server as a windows service if you have admin privileges on your machine. To create and automatically start the service each time the computer starts execute the following commands:

    c:\>sc create "SVN Server" binPath= "svnserve --service -r c:\my_repository" start= auto

    Please be careful about the spaces in the above command. There is no space between binPath and =, similarly there is no space between start and This creates a service by the name of "SVN Server". Now in order to start the service, execute the following command:

    c:\>sc start "SVN Server"

    To verify if the service has been started you can go the services admin control, by running services.msc from the run dialog.

  • Add your code to repository: Now you are all set to add your code to the repository, this code will serve as your initial revision, think of it as your first step in the sand, no matter how many steps you take, you will always be able to come back and see how this looked :). To import code thats say located in c:my_code directory, execute the following command

    c:>svn import c:\my_code svn://youripaddress/ -m "Initial Import" --username youusername --password yourpassword

    Replace your ip address with your actual ipaddress (You can check this by running the command ipconfig), and yourusername and yourpassword with the actual values. This username and password must match one of the entries you created in passwd (in c:my_repositoryconf) file. Once you execute this, you will see a lot of status messages showing the files added, and in the end you will see "Commited Revision 1".

  • Working with SVN: Once you have the repository in place, you are more or less there in terms of getting ready to start utilizing the power of svn. SVN works by every user having their own working copies, and then commiting and updating(these are the 2 most basic and most used operations, you will learn the rest as you get good at the trade).
    A commit sends all local modifications to the repository, and an update fetches the latest code from repository into your working copy.
    Everything you can do with SVN is possible through the command line, but if you are not comfortable using it, you could download Tortoise SVN client. It simplifies working with SVN by integrating with windows explorer, and adding cute icons to folder and files which are under SVN version control.
    Now lets get down to the step by step of working with SVN:

    • Step 1: Checkout working copy: In SVN world every developer has his/her own working copy. This is your playing field, this where you try out that cute new feature that going to change the world :-). Ok now to make working copy you need to get the files from the server. Here is how you do it.

      c:\mywork>svn co [Your SVN Server URL e.g.svn://] [Path where to checkout]

      When you hit enter, you will see a listing of all files being fetched from the server. Once the operation completes you will have a new directory in the folder which you specified as the argument for "path to checkout". This is your working copy.
      If you have "Show hidden files" turned on in you Windows Explorer settings you will see a hidden directory by the name of .svn inside every folder of your working copy. This is svn control area, where you shouldnt, absolutely shouldnt be altering anything.

    • Step 2: Working with the your working copy: Ok now that you have your working copy you can do what you want, ditto for your colleagues, once they checkout using the process mentioned above, they will have their own working copy.
      Working with your working copy is nothing special, SVN doesnt care what IDE you use, or whether you use one at all. Open up your code modify, build, break it :-).

    • Step 3: Commit and Updates: In one line, commit sends your changes to the server, update fetches latest changes from the server. These two operations do just that and nothing else i.e. commit will not fetch anything new, and update will not send anything period. Think of these operations as push and pull. Commit pushes, update pulls. Now lets get into the nitty gritty of commit and Update

      • Commit: The commit command can commit a single file or multiple files or all files in a directory. The syntax is:

        c:\my_work\my_project>svn commit [path...] -m "LogMessage"

        c:\my_work\my_project>svn commit -m "Added calculation for Service Tax"

        This sends the all the modifications that you have made to the files specified in the paths to the server. The log message is meta information which is very useful when tomorrow you want to know "what did I do that day?".

      • Update: The update command can update a single file or multiple files. The syntax is:
        c:\my_work\my_project>svn update [path...]

        e.g. suppose you have directory called unitests.

        c:\my_work\my_project>svn update unittests

        This fetches all updates to files in the unitests directory. When you run svn update along side each file updated you will see a letter (A/D/U/C). Following are the

        A Added - This file was added to SVN

        D Deleted - File was deleted from SVN. Don't panic. This DOES NOT mean file is lost forever. It just means that in revision number, say 10 of this directory this file was deleted. You can get the file from the previous revision.

        U Updated - The file was updated

        C Conflict - A conflict occurred while updating, i.e. some local modifications that you made couldn't not be automatically merged with the latest file from the server. See section below on what to do when a conflict occurs.

        G Merged - Some local modifications and the latest file from the server were automatically merged.

      • I am getting an error!! what do I do?
        Errors messages thrown by SVN in most cases are very informative, and tell you whats wrong. Some errors that you might encounter frequently when you are starting up on SVN are:

        • "Transaction is out of Date": At the time of commiting you might get this error "Transaction is out of Date". This means that the file that you are trying to commit has been changed since you last pulled from the repository, i.e. while you were working with the file, someone committed a new version. To commit your changes you must first get the newest version from the repository, merge your changes into that (more on this later) and then commit thereby creating a newer revision.

        • Conflict: Conflicts might be encountered while pulling changes from the server, i.e. while updating. RELAX, its normal, it does not mean that everything is corrupt now, and you need a major cleanup effort. First of all lets understand what happens when you do an update. For each file that is apart of the update that you are trying to pull, there are two things to consider: have you made any local modifications to the file, and if the file has been changed by anyone on the server since you last updated your copy.
          If the file has been changed on the server by someone and you don't have any local modifications, then an update will just replace you existing copy of the file with the updated file.
          If you have local modifications but the file hasn't been updated on the server, then nothing happens and you know why. right??
          If you have local modifications and the file has been updated on the server, then in the first place SVN tries to merge automatically. For e.g. if the file you checked out had the following content.

          Address=a-236 hill towers wonderland

          Now you the spelling bee, saw the galring mistake in the spelling of "client", so you change it. But in the meanwhile, your friend John updated the address and performed a commit. So now your local copy had the following content

          Address=a-236 hill towers wonderland

          And the latest server copy had the following content

          Address=a-236 high hill towers wonderland

          Now you run the update command. SVN sees that your change, and the change on the server are on separate lines and it merges them automatically. So after the update your local copy is as follows

          Address=a-236 high hill towers wonderland

          Now you can run a commit to make your merged file the latest version.

          But suppose your change was something like this:
          Address=a-236 low hill towers wonderland

          In this case, there is no way for SVN to know whats the correct version (low or high), and now you have to decide whats right. This is reported as a conflict (C) when you run the update command.

          When SVN reports a conflict it creates 3 extra files and puts markers in your existing file. The 3 extra files have the following names.

          • filename.rOLD e.g. Clients.txt.r12 - This is the latest version you were in synch with

          • filename.mine - e.g Clients.txt.mine - This is your file before you ran the command. Look at it this way, you got r12 from the server and you changed it to mine.

          • filename.rLATEST e.g. Clients.txt.r14 - This is the latest file on the server.

          • The markers in your original file are put in the following fashion.

            <your changes in the conflicted area>

            <the conflicted area as per the latest copy in the repository i.e. The changes made by the last author>


            So your file will look like this:


            Address=a-236 low hill towers wonderland
            Address=a-236 high hill towers wonderland

            Now you decide whats right. High or low. Once you make your decision, remove the markers from the file and run the following command.

            svn resolved Clients.txt

            and then to commit the resolved file

            svn commit Clients.txt -m “Merged mine and his changes”

SVN provides a lot of features which you will need as you become a top notch developer. A very good reference for anything related to SVN is

Please contact me (puneet dot lakhina at gmail dot com) in you case find some problems and or have some comments with regards to this tutorial.

Thursday, November 29, 2007

Firefox crashing

I don't know if I can call this an accomplishment, but I have been able to crash firefox in a consistent repeatable manner by following a sequence of steps. The test case goes like this:

  1. Start Firefox - Open firefox. I have 2-3 live bookmarks one of which is My reading list on google reader, now when I initially launch firefox this live bookmark doesn't load as i need to sign into my google account through any of google services.

  2. Log into gmail - My usual routine, I log into gmail to check my mail.

  3. Reload live bookmark - After logging in I reload the google reader, my reading list live bookmark. It loads, no hitches.

  4. Visit problem item - This is where the problem is, I click on the item that leads to this link on lifehacker. After a few status messages on the status bar, FREEZE.
    Then i get the mozilla talk back screen asking me to report the problem, which I did giving full detail. I also get the Windows Vista dialog saying "This program has stopped responding".
    An interesting thing to note is that the bar on the bottom right corner that normally shows progress in terms of page loading doesnt appear. I dont know if its relevant or not, thats how it is.

  • I have the following add-ons installed - Chatzilla 0.9.79, Bookmarks 1.5.44, DOM Inspector v1.8.10, Firebug 1.05, Indic IME 1.6.3 (disbaled), Talkback 2.0.10

  • The problem is limited to this profile. I created a new profile (by running firefox -p) and added just my reading list live book mark and repeated the above steps. It runs without problems, so I am guessing some configuration in my profile is causing the problem.

  • The problem does not occur if I click on any other item of the feed.

  • Other details on my setup: OS: Windows Vista Home Premium, Firefox 2.0.10

If you can help please post a comment. I would be very happy to provide any additional details required. I have the dump generated by the talkback client which it sends back to mozilla.

  • The problem is firebug 1.05 extension. I disabled that extensions and the crash did not happen.

Sunday, November 25, 2007

Earthquake in Delhi

An earthquake shook Delhi and its neighboring areas in the wee hours of Monday morning on 26th November 2007. The earthquake was a relatively strong one and lasted for about 4-5 seconds. I must mention that it was a little scary as earthquakes have a history of widespread devastation in India, and the memories of that poignant republic day in 2001 are still fresh.

Update: The earthquake occurred at exactly 4:43 AM IST and measured 4.3 on the Richter scale. The epicenter as per news reports was in Bahadurgard, although this cant be confirmed at the moment.
The Delhi Met Department website should be able to provide more details in the days to come.
The location in Google Maps (Double click the map to zoom in):

View Larger Map

Friday, November 09, 2007

GMail probable bug

While using the new GMail, which I believe everyone hasn't received as yet, I observed the following behavior. While using the chat, it showed one of my friends as offline even though i was chatting with them and there was no problem in recieving the messages. See screenshot below? Post comments if you have seen this kind of behavior. For the record I run Google sidebar on Windows Vista Home Premium also. My browser is Firefox with only the delicious extension being of note. I also have firebug which was disabled.