J Vision

February 9, 2009

Why we need functions as first class citizens?

Filed under: coding

I had been following the debate on inclusion of closures into Java for a long time. And I used to wonder, why do I need them. I understand that functions are important, but cant we achieve that almost entirely though the use of interfaces. I think I have realized why we need functions to be first class citizens, and it has more to do with restricting scope over which the function will be available.

Lets start with a simple scenario highlighting the need for data to be a first class citizen. You are doing some complicated calculation which takes time and is error-prone to write. In most cases, if you need to repeat it exactly, you would store it in a local variable, so that it can be reused. This comes very naturally to us, and most of the times we dont notice what we have exactly done. We have restricted the scope of the partial calculation by declaring a local variable, and we can further restrict its access by defining a logical block. This would not have been possible if data was not a first class citizen. We would have had to rewrite the whole calculation again or we could define a function for the calculation. But if we define a function for it, then it is almost impossible to restrict the scope of the function.

Now consider the dual of the above situation, we wrote some functionality which is totally local to a function and needs to be repeated a couple of times. We cannot use interfaces for it, as then we can’t restrict the access to that method. Moreover, we can’t define a function locally inside the existing function since that would make function a first class citizen which it is not. Hence, the need for closures or the need for acknowledging the functions as first class citizens. As in that case, we can simply declare function in restricted scope and enable code reuse while abstracting away local implementations to avoid contaminating the namespace.

January 8, 2007

Life is a TMS

Our life is a knowledge base, in which we are constantly dumping new rules. For example, we started our lives with a fundamental axiom that zero is the smallest number. Given, it was a wierd idea to quantify something which does not exist, but we coped with it. Fast forward a few years we find the existence of negative numbers. It is interesting to note that in spite of knowing this fact for more than a decade of my existence, I still subconsciously discount their existence. I almost implicitly believe in

This expression is only true if all the numbers are non-negative and atleast one of them is positive. Well the reason I am bringing this up is that recently, I spent quite a few days figuring out the reason a limit was not holding before I realized this expression to be at the heart of the problem. So once again, our life is a knowledge base. The only issue here is that knowledge base is not monotonic and requires the use of some TMS (truth management system) to handle the exceptions. However, we always tend to think monotonically making it difficult to incorporate the exceptions at a subconscious level. A plausible solution to this problem is to avoid the formation of faulty beliefs in the first place, especially for non-bleeding edge stuff like negative numbers or existence of kiwis(birds which cannot fly). I get that it is difficult to expose a lot of new ideas at once but we can clearly work towards avoiding the corner cases till the brain is mature enough to assimilate the advanced information.

April 10, 2006

Architecture Design through Dia

Filed under: productivity tools

Architecture design forms the foundation of any good OOPs program. I used to draw my class diagrams on paper, but it has an issue that it does not extend endlessly on all sides. In addition to that I could not make sense of it after a few modifications. I preferred a whiteboard to the paper but I was actively looking for alternatives. So I tried out “dia”. I always knew that dia supported UML diagrams and had a section of UML symbols, what I did not know was the amount of UML support it had. Not only does dia provide one with the symbols but unlike most editors, it does not force one to write the method names n properties in the symbols. It provides an alternative input source in form of dialog boxes, which are then shown in the box diagrams. This completely abstracts all the hassle of resizing classes, folding method names, from the designer. Of course, you can optionally enable and disable which parts of the class diagram you wish to show. I was just blown away with the amount of options one could provide and play with in rendering the designs although I found the default template good enough. Here is a screenshot of the input dialog for a class and the final structure. Click on the thumbnails to enlarge.
screenshot of options under dia class diagram

Respect the Javadocs

I know this is a very redundant and obvious comment. But sometimes, even knowingly I try to cross Java with not so nice results. The recent addition from the list of recommended practices which I had been flouting and which got me is the comparison of two doubles. I know we should never compare two doubles directly, the recommended practice has always been to have an error margin based on the calculation that you are performing. I tried to follow it when I could but who knows what is the correct or accepted level of error say when you are trying to find out which side of the line a point lies ( I am referring to the case when it is REALLY close to the line). I was writing a very simple piece of code to segment an area based on probability masses ( the actual purpose of the code was to decide good positions to segment the region for observing it). It is pretty straightforward, except for the fact that the segmentation has a radius around a central point which can be covered by that point. And just to make the matters a little bit more interesting there are obstacles which mutates the nice circular structure of the selected region. Of course, I tried to make my life easier by putting it over a grid so that I am in the discrete world. But right here lay the trap which i fell into. In order to find out whether a grid cell was viewable from another point I had to decide whether all the vertices were in its line of sight. But the comparison were doubles and I had taken signum since i cared only of the sign. Now I noticed that when I ran the code I was getting leaky probabilities. That is even if I selected all the regions my total probability distribution was not summing up to 1. Now this is a MAJOR flaw, after much headbanging I found out that the problem lay in my double comparisons. I just had to replace my double comparisons (a op b) with Double.compare(a,b) to get the complete probability distribution. But this experience has reinforced that one should follow the recommended practices even if sometimes we find that we can work happily and get the correct result without following them. When u least expect it, they will come and bite you. And in this case Javadocs are just saying like Eric Cartman, ” Respect my AUTHORITY”. (In case you didnt follow the last comment eric cartman is a south park character)

March 28, 2006

Extending display to external monitor for Lifebook n3410 under FC4

As i mentioned in my last post I had crashed my system while trying to get the desktop extension to work on my laptop. I figured this was the perturbation I needed to get out of the local optima of being able to see display only on my laptop screen. So after further study, I am pleased to announce the successful desktop extension of my laptop screen to another monitor under FC4.

I was right in assuming that I was getting most of my stuff right but messing up in some key parameter which was keeping the goal just out of my reach. The magic ingredient was Xinerama. Xinerama is the open source driver for extending the output to multiple monitors and has been compiled into the X server. It has support for all major graphics cards including Nvidia and ATI Radeon. I was already configuring Xinerama in my xorg.conf but had forgotten to enable it by placing an option under the serverflags section. The relevant portions of my current Xorg.conf have been given below. Once correctly configured I am able to view the desktop extended over two monitors with different wallpapers and movable windows. In order to mirror the desktop the Cloneable option has to be enabled which I have commented out in my current configuration. Screenshot:
twinview

Xorg.conf
Section "ServerFlags"
Option "DefaultLayout" "twinview"
EndSection

Section "ServerLayout"
    Identifier     "twinview"
    Screen         "Screen0" 0 0
    Screen             "Screen1" LeftOf "Screen0"
    InputDevice    "Mouse0" "CorePointer"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Synaptics" "AlwaysCore"
    Option               "Xinerama" "true"
EndSection

Section "Monitor"
    Identifier   "Monitor1"
    VendorName   "Monitor Vendor"
    ModelName    "CRT 1600x1200"
    HorizSync    31.5 - 90.0
    VertRefresh  60.0 - 60.0
    Option      "dpms"
EndSection

Section "Device"
    Identifier  "Videocard0"
    BusID       "PCI:0:2:0"
    Driver      "i810"
    VendorName  "Videocard vendor"
    BoardName   "Intel 915"
#   Option "VideoRam"    "131072K"
    Option  "MonitorLayout" "CRT,LFP"
    Option  "DevicePresence" "true"
    Screen 0
#   Option "Clone" "true"
EndSection

Section "Device"
    Identifier  "Videocard1"
    BusID       "PCI:0:2:0"
    Driver      "i810"
    VendorName  "Videocard vendor"
    BoardName   "Intel 915"
#   Option   "VideoRam"    "128000"
    Option   "MonitorLayout"  "CRT,LFP"
#   Option "Clone" "true"
    Option  "DevicePresence" "true"
    Screen 1
EndSection

Section "Screen"
    Identifier "Screen0"
    Device     "Videocard0"
    Monitor    "Monitor0" 
    DefaultDepth     24
    SubSection "Display"
        Viewport   0 0
        Depth     32
        Modes    "800x600" "640x480" "1200x860"
    EndSubSection
    SubSection "Display"
        Viewport   0 0
        Depth     16
        Modes    "800x600" "640x480"
    EndSubSection
    SubSection "Display"
        Viewport   0 0
        Depth     24
        Modes    "1280x800" "1280x1024" "1152x864" "1024x768" "800x600" "640x480"
    EndSubSection
EndSection

Section "Screen"
    Identifier "Screen1"
    Device     "Videocard1"
    Monitor    "Monitor1" 
    DefaultDepth     24
    SubSection "Display"
        Viewport   0 0
        Depth     32
        Modes    "800x600" "640x480" "1200x860"
    EndSubSection
    SubSection "Display"
        Viewport   0 0
        Depth     16
        Modes    "800x600" "640x480"
    EndSubSection
    SubSection "Display"
        Viewport   0 0
        Depth     24
        Modes    "1280x1024" "1024x768" "800x600" "640x480"
    EndSubSection
EndSection

March 20, 2006

Hackers Anonymous ….

Many of us have inadverently done things which we regretted later on… The wierd thing in all these experiences is that there is always a voice at the back of our heads asking us not to do it, very much like a guardian angel. But we do it nevertheless. If there is a pattern among the mistakes, it can be many times attributed to an addiction. The addiction is defined as Compulsive physiological and psychological need. I have recently come to terms with my addiction for hacking my system. I have an unending urge to mess with things which are much beyond my understanding. I can hear my guardian angel telling me that now is not the time, you dont have another computer to do your work. But without paying any attention, i hack away changing my xorg files for things which i dont really need and i know to be in a very experimental state. i managed to extend my display to two desktops without cloning of the X server. i was ecstatic and totally in bliss once i got tht up n running … but i soon found that my X server had crashed on both screens and i had filesystem corruption in my home folder…. there were signs….. my vim became corrupted first… then my display became fuzzy … but like an addict doped on hacking i continued… modifying the configuration and testing it out… the end result as i said my home partition became corrupt…. i dont think i am alone in this behavior… i fall into the group of ppl who need help from themselves for their own sake (read their computers, their life)….. but i think the realization tht i have this issue is the first step towards controlling it…

March 17, 2006

Social Analysis, subject: research community

A recent mention about the social characteristics of people made me ponder on the social characteristics of a researcher. The basic aim of the analysis was to find a suitable social model for people doing research and I think that researchers can be classified as belonging to the Formicidae family. in other words, a research community resembles an ant society.
There is a hierarchy in social status, workers (read graduate students) at one end and the queen (read pioneer or current reigning authority) at the other end of the spectrum. To an uninformed eye both societies seem to be highly organized. They follow paths to their goals which are highly sophisticated. In addition to this, the number of ppl taking those paths is directly proportional to the expected reward. In case of ants, this is the size of food store while for researchers it is an approach. While in reality both the species are following the basic instinct of randomly choosing between the expected goal (for ants this is the smell, n u know the equiv for research community). So basically, a common observation that research community doesnt have a social life is not very accurate, a better version of conveying the sentiment will be tht research community basically treats every other species as a potential threat and is indifferent to it … (hmm maybe like ants)…

March 12, 2006

Power of being stationary

Filed under: techi thoughts

Sometimes you keep on using a property or assumption without realising its true potential and implications, and then it just hits you… One of the things which just hit me is the property that a markov distribution becomes stationary. I always knew that a markov process becomes stationary after which it will not change anymore… but what this actually means is that if you ever want to analyze such a distribution , you do not have to take time into account…. it just makes the analysis so much simpler… instead of thinking how a distribution will change from one time step to another, it is just one static list of numbers which shows the probability distribution of the process which will not be effected by time.

transferZen V2

Filed under: linux

I own a Creative Zen Neeon, and as Creative does not support linux and neeon does not allow one to make playlists on the player itself I had written a script for flattening out directory stuctures when the songs are transferred to the player. Recently, I had to reinitialize my player, so I wrote the base names of directories which I needed to copy, feeling nice and happy about the flattening feature as neeon does not recurse the directories in directory shuffle mode. once the file was made it was simple to write a one line script for reading it and putting the value in transferZen. Obviously, along the way I found some bugs and had to correct my script but the working and output was awesome… I am specially a sucker for progress bar which I have integrated thanks to my percent script….chk out the cool screenshot…. transferZen working screenshot
The transfer script is shown below:

#!/bin/bash

if [ $# -ne 2 ] ; then
    echo "Usage: $0  ”
    echo “Only .mp3 files will be copied”
    exit
fi

srcDir=$1
tarDir=`dirname $2`;
tarDirD=`basename $2`;
echo ${tarDir}/${tarDirD};

if [ ! -d “$srcDir” ] ; then
    echo “Base directory : ($srcDir) not found”;
    exit
fi
#cd “${srcDir}”;
numFiles=`find “${srcDir}/” -iname *.mp3 |wc -l`;
curr=1;
find “${srcDir}/” -iname *.mp3 |while read; do 
    cp “$REPLY” “${tarDir}/${tarDirD}”; 
    percent 0 $curr ${numFiles} 40;
    curr=`expr $curr + 1`;
done
echo -e “\n”;

Multiple Gmail accounts

So I have been keeping two gmail accounts for sometime. The sad part is that in order to switch between them without entering passwords I had to use separate browsers. In addition to this, since I dont use windows I was running multiple instances of gmail-notify. But now give way to Gmail Manager a firefox extension capable of handling multiple accounts. The manager takes care of logging u out from one account before opening the other account. So now, just keep a firefox window open somewhere on some desktop to monitor ur gmail accnts. The best part is that since it is a firefox extension it works everywhere.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham