Ubuntu insights, Programming in groovy, java, et als!

Tuesday, November 22, 2011

Why Linked List is a Linear Data Structure?

Reminiscing my textbook definitions during graduation, all I ever read about linear data structures was that, they have elements placed adjacent to each other. Now, I curse myself for not being able to understand the inners of the concept rather than trying to perceive the whole thing at superficial level.

As I dig through this, I see that there are two aspects to the term linear. One is at the physical level (in bits and bytes of memory), other at the logical level (concerning the data structures used). At the logical level we talk about data structures as being linear or non linear. But in reality, at the physical level, computer memory is always linear i.e one memory block adjacent to other.

The concept of non linearity is (usually) implemented with the help of pointers that connect other memory chunks by storing their addresses. Technically, implementing pointers at the physical level is somehow helping us to understand non linearity at the logical level implementation of data structures. Assuming so, I was stumped at this point, wondering why a linked list is considered linear in spite of the nodes never being physically adjacent.

After an overwhelming head-breaking session, I started to see this differently. The terms linear and non linear are purely meant to be viewed at the logical level when used along side data structures. If a list is being used, irrespective of whether it is an array implementation or a linked list implementation, it should only be perceived as a data structure that stores elements adjacently (logically, abstract picture) and hence it is linear.

If the confusion still lasts, there is this thumb rule that you can take help of, to recheck if a data structure is linear or non linear. If you are required to sequentially traverse through all the elements of a data structure to access its nth element, then the data structure is linear. Else it is non-linear.

Example : Stacks, Queues, Lists are always linear. Irrespective of whether they are implemented using pointers or arrays, you need to sequentially traverse through the whole data structure to access the nth element which is not so in the case of trees and graphs wherein to access one element, traversing a specific branch might suffice.

Tuesday, November 15, 2011

Solve Graphic Driver Errors & Unity 3D Display Issues in Ubuntu 11.10

Graphic card compatibility issues with Ubuntu are very annoyingly frequent during installation. I've been a sufferer of the same recently when my graphic card drivers crashed and Unity 3D failed to render correctly, Instead it reverted to Unity 2D version which pretty much sucks. Here are some insights into Unity panel issues w.r.t the non-availability or incompatibility of your graphic driver.

Test if unity is supported  :
Type in terminal

/usr/lib/nux/unity_support_test -p 

You need to get an output saying Unity is Supported : Yes. If you don't, there are things that need to be answered which of course will be, in the below steps.

How do you know if Unity 3D is running :
In the terminal, type in

echo "$DESKTOP_SESSION"

If the output of the above command is Ubuntu, Unity 3D is enabled and running.
If the output of the above command is Ubuntu-2D, Unity is running in 2D mode.

PS: Make sure you are logged into Ubuntu and not into Ubuntu 2D. Verify this prior to login.


Test if Graphic card is detected :
In the unity dash, search for system Info. The System info will show you Processor, Memory, Graphics and other details. If the graphics details displayed is empty, it means that either the graphic card installed is not recognized or you might not have installed a graphic driver at all.

Moving On :
There are three ways of looking at any issue relating to graphic driver installation.

1) Install default binaries provided by Ubuntu (FGLRX drivers) (or)
2) Install Open source drivers to get the graphic card detected & running (or)
3) You either install the ATI binaries from the official ATI site.

You must stick to only one among the above three aproaches, out of which the Second option to install third party open source drivers is the best in my opinion. Here I've explained the first two approaches in detail.

Prior to taking any of the above approach, run this command to install dependencies :

sudo apt-get install build-essential cdbs fakeroot dh-make debhelper debconf libstdc++6 dkms libqtgui4 wget execstack libelfg0 dh-modaliases

1) Install FGLRX drivers provided by Ubuntu (I don't recommend)
To install the FGLRX drivers, search the Unity dash for Additional Drivers, Click on the appropriate FGLRX driver suggested and activate it.

2) Install Open source Graphic Drivers (Recommended)
The below command will remove all traces of Ubuntu's default fglrx drivers (if installed).

sudo apt-get remove --purge fglrx fglrx_* fglrx-amdcccle* fglrx-dev*


Remove the existing xorg.conf 
sudo rm /etc/X11/xorg.conf


Reinstall the xorg.conf
sudo apt-get install --reinstall xserver-xorg-core libgl1-mesa-glx:i386 libgl1-mesa-dri:i386 libgl1-mesa-glx:amd64 libgl1-mesa-dri:amd64


Configure xorg

sudo dpkg-reconfigure xserver-xorg

Reboot the system
sudo reboot

The above series of commands are most important, necessary and typically are the installation steps involved in using open source Graphic drivers to detect your graphic card.

PS: These open source drivers worked spot on with my Dell system with an AMD Radeon™ HD 6470M - 1GB (For ICC) video card. And should hopefully do the job for you too :)




Count the Lines of Code in Your Project

I was searching through eclipse if there was an option somewhere within the IDE that could count the total lines of code in my project. After 5 min of Google struggle, I got to know that I need to install a metrics plugin to be able to do so. Reluctant to install any additional plugin, I resorted to groovy, spending an equivalent 5 min of time for this piece of code that counts the total number of lines in all the files within a directory at any depth.

Run the below script with dirPath variable pointing to your project base and addup comma seperated extensions in the filterFileExtensions variable list to specify the filetypes you wish to index , as in java, groovy or any text rendering file extensions like txt, html, etc. 

//------------------- Start Groovy Script --------------->


def filterFileExtensions = ["groovy", "java"] 
def dirPath = 'C:\\VKWorks\\Sampleproject'


def base = new File(dirPath)
def obj = new FileUtil(list:filterFileExtensions)
obj.recurseCountCodeLines(base)
obj.printResult()
//------------------- End Groovy Script --------------->


class FileUtil{
def lineCount = 0
def filesProcessed = 0
def list 


def recurseCountCodeLines(file){
    if(file.isDirectory()){
        file.listFiles().each{recurseCountCodeLines(it)}
    }


    else{
    def fileExtn = file.getName().tokenize(".").last()
    if(list.contains(fileExtn)){
        println "processing file $file"
            file.getText().eachLine{ line ->
            def isCommentedCode = line.startsWith("/") ||
                                  line.startsWith("*")                      
                if(line.size()>0 && !isCommentedCode)
                    lineCount++
            }
            filesProcessed ++
        }
    }
}
    
def printResult(){
    println "---------------------------------"
    println "files processed : $filesProcessed "
    println "Code line count : $lineCount"
    println "---------------------------------"
}
}



PS on performance: 12,000 lines of code in 150 odd files within various depths of the specified directory were retrieved in less than a second. 



Tuesday, November 08, 2011

Design Patterns : A prelude from a learner's viewpoint

“What do you understand about design patterns from the past nine months of code that you've written?”

This was the question put to me by my manager in today's meeting. The question was sudden and to be honest, I fumbled for words. I uttered few random sentences including the phrases “style of programming”, “the best way to apply a logic out of all available ways to do so”, etc. (which were pretty lame of course)


Now, I sit back in peace and try to fathom about design patterns based on my nine months of programming experience in the corporate world. When I try to rephrase the answer for the question, I find that I am really out of words to exactly describe what a design pattern exactly is, which is So in contrast with the ease with which the Gang of Four describes them to be.

From my understanding, I put it this way,

“A design pattern applied is THE possibly best fit (or the most optimized if not the best) approach that you adhere to while programming to find solution to a problem that you are trying to solve.” It is more generic a term and has got to do little or less with the specifics of a programming language used except for that it is widely used within the scope of Object Oriented Programming.

From what I understand, I believe and will continue to believe so, that, a design pattern is not limited to the few available standard textbook patterns like the factory pattern, singleton pattern, et al as suggested by the GoF. There can always be a pattern that is not a standard, is nameless and self defined, yet best suited for the task that you are working on. All the standard textbook patterns available can be safely regarded as hints to the problem you solve. Why I call it a hint more than the solution itself is that sometimes the pattern might just fit in so perfectly to a business scenario but sometimes it might not, Nevertheless it will take you closest to implementing a best solution to that problem.

My experience limits me to very few design patterns that I've worked with till date like the observer pattern, factory pattern, the yuckiest singleton pattern, etc but I guess this is what a design pattern is if you ask me, of course, from a noob's perspective.


Good that this post will not allow me to embarrass myself again by fumbling for words to phrase an answer when asked the same question and hopefully, at least in an year or two, I hope that I'd be in a position to answer any design pattern related question even in the midst of the midnight hour. Amen!


Saturday, November 05, 2011

Automount NTFS drives on Ubuntu

Well, here's for the lazy ones out there. I came across this simple tweak to fix the problem of manually mounting disks (either external/NTFS) on Linux.

If you have frequently accessed files placed on several drives or partitions that are external to Linux, you need to manually mount these partitions manually from Nautilus or terminal prior to accessing files/directories in them. To avoid this, you can change the contents etc/fstab file in such a way that they are auto mounted on startup.

Prior to editing the fstab content, you need to know the partition label of your drive. Partition labeling (alphabets followed by a number) is quite different in Linux when compared to Windows. Your NTFS partition might look something like sda2 or sda3.

For the geek

Step 1: Running the

fdisk -l

command will give you details of all the partitions like the one shown above.

Step 2: If you fail to decipher anything out of the above output, Just run the below command against the device names whose System column of the above output contains NTFS in it.

fdisk -s /dev/sda6

Running the above command will give you the size of the partition sda6 in bytes which gives you a better chance of identifying the drive (presuming that you might at least know the approx size of the NTFS drive you want to mount).

Step 3: Run the below command below 

sudo mkdir /media/Windows
sudo echo "/dev/sda6 /media/Name_of_Your_Partition ntfs-3g defaults,locale=utf8 0 0" >> /etc/fstab
sudo mount -a

which will add up the details of your partition to etc/fstab.

For the noob

1) Install mount manager via Ubuntu software center, open the app and identify the partition label of the drive to be mounted based on the disk size and partition details shown in it.

2) Hit Alt+F2 and type in
    gksudo nautilus

3) Open the file named fstab under etc folder of file system.

4) Add the below line to the file and save. 

/dev/sda6 /media/Name_of_Your_Partition ntfs-3g defaults,locale=utf8 0 0

Note: Replace sda6 by your partition label and Name_of_Your_Partition should be the name of your NTFS drive.