29 December 2011

Predictably Irrational Again - Video

Again, it is predictably irrational. But this time it is video. Watch the following video of Dan Ariely speaking about predictably irrational.

I think, from the whole of this talk, i tend to like the portion he talks about cheating.

Even though we have thousands of mirrors in us (and conscience), we still cheat (for example, how we cheat insurance companies. I think, the insurance companies know this and again they cheat us the following years). We don't bother whether it home, street or work, we are going to fudge to an extent that will make us still have a great self image.



If you have the book, the above video could be a companion and makes the reading/understanding a lot easier. While watching this video, i could recollect whatever i read and i m going to read the book again for the insights.

This is one of the books that i thoroughly enjoyed.


 

27 December 2011

Predictably Irrational - New Perspective

How many of us make decisions everyday and how many decisions we make everyday?

Do we apply common sense before making the decisions and how often we regret for the decisions we make. How many times in our life we fool ourselves that our decisions are in fact correct. How often we justify the decisions we make and why do we want to appear intelligent to ourselves (leave alone trying to be intelligent in front of others). Is there a reason why we want to be a super man in a group and boast about our contributions or things we own.

 The book Predictably Irrational by Dan Ariely talks about the forces that shapes our decisions. The book talks about various factors that shapes one's thinking fully substantiated with a lot of research work conducted on real people. The experiments that are discussed and the conclusion drawn opens up a lot of learning on how we make certain decisions at certain conditions and how quickly we change to a different decision (a true 180 degree) when the conditions are changed only a bit.

I really like the way in which the experiments are presented and the presentation of experiments by itself is a great learning. If you read the book, i feel one will get at least couple of value adds (how to conduct experiments for research, how to present them and how to draw conclusion from the experiments) apart from knowing a bit on decision making.

If you find the book in your library, I would recommend you to give it a glance.

While many of us thinking of starting the new year with new resolution and trying to be better, i feel so happy about reading this book and the way i m bidding farewell to 2011. I think, this book is a good investment i made in 2011.

Wish you a happy new year

.

16 November 2011

Puzzle - Mega Substring

Scenario #1
Given two strings - string1 and string2,  write a program to find whether string2 is a part of string1 (substring of string1). The above puzzle may seem to be very simple as it is. If this sound silly, read on.

Scenario #2
Assume that you have to write above substring program to compare the contents of two files whose sizes put together is more than the size of your RAM + SWAP partition (let us say 10GB of contents). If you feel like you can solve this with bit of try, move on to the next scenario.

Scenario #3:
What if I want to exploit the number of cores? Will it be better if I have few threads to do the job. If i choose to go with multi-threaded way, what are the special conditions that i should take care of?

Watch out this place for answer (probably this weekend - 20/Nov/2011)

05 November 2011

Time Server - Network Programming

Happen to flip first few pages of Unix Network Programming by Richard Stevens. Wrote a simple time server and client.

The server listens to specified port for incoming connections and sends the current time in seconds since Epoch (midnight of 1-1-1970 UTC).

The client is written to connect to the server, gets the time and displays it.

Here is the screenshot of the output (server is started as background process, netstat shows the server is listening in port 12000. The client connects to server and gets the current time).

The source files (with comments, so that one can follow) are uploaded to my Dropbox account. Sharing it here, just in case if you want to look/run the piece of code.

Server Source
Client Source

Compile the above programs (gcc client.c -o client & gcc server.c -o server) and run it as shown in the pic.

02 November 2011

Palindrome in Haskell

This is probably a week after i started to read Haskell (a functional programming language). Having tried few examples from the book and writing few on my own, i feel like it is a different world. If i m successful enough to keep my interest with Haskell and continue to practice, i think it is going to improve my thinking at a very least. I m not so sure of using this language at work (but who knows). More on Haskell later.

Here is the code that says a given String (list) is palindrome. (see, how expressive Haskell (FP) is). The first two line is to reverse the list and the last line is the one that decides whether or not the original and reversed string same (you need to write probably 10 lines in imperative language)

rev [] = [] 
rev (x:xs) = reverse xs ++ [x] 
palindrome x = (x == rev x)
 Here is the sample output (from WinGHCi)


*Main> palindrome "test"
False
*Main> palindrome "madam"
True
*Main> palindrome "123321"
True
*Main> palindrome [1..100]
False
*Main> palindrome "a great good haskell"
False
*Main> 

You can find my Haskell notebook (and my daily progress) here. (thanks to Dropbox)

29 October 2011

Scala - The Scalable Language

I stumbled upon the programming language Scala few months back and haven't got a chance yet to work with Scala (just download Scala last night and installed Eclipse plugin in my laptop this morning). I happen to watch a video on Scala by Martin Odersky. It is a great presentation - both the language and the presenter.

If you are looking for some alternatives for Java, check out Scala. Companies like Twitter and LinkedIn are using Scala in their products and seems like the list is growing day by day.

Scala is both object oriented and functional language and the code compiles into bytecodes which runs on a Java Virtual Machine. The main advantage of writing Scala program is that you will end up writing lesser amount of code as Scala is more expressive than Java. The adoption of Scala is in early stage and i hope (should say, rather want) it replaces Java.

You can find more stuff on Scala from here.

Overview on Scala, might help you to embrace Scala - http://www.youtube.com/watch?v=zqFryHC018k
Geeky Stuff - http://www.scala-lang.org/node/198
Scala Home - http://www.scala-lang.org/

Needless to say, i m so confused on whether i should blog about Java or Scala :-)

28 October 2011

Measuring Time to Minutest Precision With Guava

Other than profiling, have you ever encountered scenarios where you wanted to measure elapsed time from a predetermined past. A simple way of doing is to log the time (milliseconds or nanoseconds) into a long and then find the difference between two points. Here is a simple code.

public static void timer() throws Exception { 
long startMillis = System.currentTimeMillis(); 
for(int i = 0; i < 10; ++i) { 
Thread.sleep(1000);//equivalent to some work/logic 
long endMillis = System.currentTimeMillis(); 
System.out.println("Elapsed Time = " + (endMillis - startMillis));
// if i need to reset the start time, i need to do the following 
// startMillis = System.currentTimeMillis();
}  
}

If you are looking for only time difference between two points, you don't need to actually log the current time. It is enough if you start a clock (your own clock may be) at time t1 and stop it at time t2. If you want to measure time, you end up writing boiler plates. Guava has a little cute API for this.

Stopwatch is a simple API that mimics the functionality of a stopwatch. Here is the reincarnation of above code example.


public static void niceLittleAPI() throws Exception { 
Stopwatch stopWatch = new Stopwatch();  
stopWatch.start();  
for(int i = 0; i < 10; ++i) { 
Thread.sleep(1000);//equivalent to some work/logic  
System.out.println("Elapsed Time = " + stopWatch.elapsedMillis()); 
// if i need to reset the timer/clock, i need to do the following 
//stopWatch.reset(); 
// and my timer resets to zero
                                 // and if you want to stop the Stopwatch, just call
                                // stopWatch.stop();
}
What are the other advantages of using Stopwatch. I think it is an advantage of Stopwatch that it hides completely the mechanism it uses to keep time and in fact the user of the API is free to give his/her own Ticker.

Another nice addon is that you can get the elapsed time in days, hours, minutes, seconds, milliseconds, microseconds and nanoseconds which becomes very handy at times. A word of caution, Stopwatch is not thread safe and you have to figure it out how to make it thread-safe :-).

In order to understand the full power of Stopwatch, you may want to read Javadocs of Stopwatch, Timer and TimeUnit.

In my next post, we will see yet another Guava class and its use.

You may also want to check my previous post on Guava's Postconditions.

27 October 2011

Preconditions - (Java) Guava Collections Library

Fail early. It is applicable in life and programming.

The methods (or functions) are inevitable part of your code. The methods operate on the objects (or state of the system) and has a logic to do. Sometimes, the logic cannot (or rather must not be applied) due to non-availability of data (objects) or data being in an inconsistent state.

Let us take simple IPv4 address validator. Here is the code.

public static boolean isValidIPV4Address(String ipAddress)
{  
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

The above code is potentially dangerous if null is passed into the method. It crashes and brings everything to grinding halt. We can fix this by just adding a null check (and we have been often told to do that but we hardly follow it). The code will look something like this.


public static boolean isValidIPV4Address(String ipAddress)
{
                if(ipAddress == null)
                    throw new NullPointerException();
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

And thats how you fail early. You validate the inputs (irrespective of the number of arguments) and flag/fail early without changing the state if the arguments (inputs) sound weird. If you still operate on the data that is passed and change the state of the system, you add more pain by pushing the system to an inconsistent state. [Read Effective Java by Joshua Bloch if you haven't read it yet and if you want to be told by a Java expert]

If you think above is a good way, hold on. You have better way.

Guava (Google collection library) has a better way to handle this by using Preconditions. Replace the null check with one line statement and bingo Guava helps you to throw the exception.


public static boolean isValidIPV4Address(String ipAddress)
{  
Preconditions.checkNotNull(ipAddress); 
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

If "null" is passed, Preconditions.checkNotNull throws NullPointerException. You can also check for the validity of expression using Preconditions.checkArgument (check out Javadoc). Apart from improving the readability of code (to reduce boiler plates from code), it helps you to fail faster without causing any trouble to the state of the system.

Check out Preconditions. Here is the Javadoc of Preconditions. Don't you think that Preconditions is worth adding in our source code :-)

In the next post, we will see how to measure time with Guava's Stopwatch.


13 August 2011

Effort towards Perfection

Is it possible for a fresher or a newly formed company (any new entrant) to stand out and highly regarded among professionals (even among professionals with few years of experience)? I think, standing out in the crowd is no way related to how old are you. There isn't any age factor involved.

Standing out is the result of an attempt (even a failed attempt) towards perfection. In order to move towards perfection or excellence, you need a thought that perfection/excellence is a necessity (and not a value-add) and once you feel/absorb that the value is inherent in you. Perfection/excellence is not a stretch goal but an action, may be a base thing which you are supposed to do and a thing that you should naturally do.

I can't wait more to write this post after watching this video.


23 July 2011

First Program in Haskell

Recently, I stumbled upon a new programming paradigm - functional programming. Rather than focusing on variables, we define functions that does something. Without much of theory, let us quickly see an example

Write a program that finds triplets (a, b c) such that a, b and c are sides of a right angle triangle with none of the sides is greater than 20. I tried to write programs in Java and in Haskell as well. Here is the code snippet
Java
public class RightAngleTuples {
public static void main(String[] args) {
printTuples();
}
public static void printTuples() {
for(int c = 1; c <= 10; c++) {
for(int a = 1; a <= c; a++) {
for(int b = 1; b <= a; ++b ) {
if(a*a + b*b == c*c && a+b+c == 24) {
System.out.println(a + ", " + b + ", " + c);
}
}
}
}
}
}
Haskell
 Prelude> let triples = [(a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a], a^2 + b^2 == c^2, a+b+c == 24 ]
Prelude> triples
[(8,6,10)]
Initially it may appear that both the programs are different syntactically. But if you really see, while programming in an imperative languages, we need to think a lot of logic and variables (or memory location) that maintains the state of the program. It is programmers responsibility to keep the state sane. But in the case of functional programming, there is no concept of state. Everything is functions (obviously everything is logic).

If you are really interested to learn a new programming paradigm, i recommend Haskell. With my few hours of encounter with Haskell, i feel it changes one's thinking :-) and Learn you a Haskell for Great Good by Miran Lipovaca can be a great resource. (BTW, i copied the above example from the book and i promise that it is in fact last example that i will steal from the book). An heads-up: reading Haskell doesn't increase your value in job market :-), you cannot ask for 40% more hike but just improves your geeky quotient :-)

More stuffs on Haskell in coming weeks/months. Sharing never hurts :-) 

19 June 2011

After a while things go real hard

It appears to me that i stopped blogging forever. I literally can't think what to write. It is over a month i tried to post something here. The past two months have been so engaging and lot of events. I felt that i lost touch and became irrelevant. I needed so much courage to write this post because i honestly think that every post should add value to me and at least to my eyes i should feel that my thinking is slightly getting better. This self imposed exile of keeping away from my blog was not so easy. I m back and i think i should be consistent.

Here comes the real learning. The manager typically delegates work sacrificing hands-on. Though the delegation helps and often needed when one moves up, being hands-on is equally important. I m not here to say that you need to strike balance as i think that such balance never exist in reality. All i m saying is "dont lose touch". Why?

Hands-on experience helps in better abstraction. Abstraction is more meaningful only if one is consistently gets his/her hands dirt. Without hands-on, the abstraction deviates from its course and it turns out to be a poor abstraction. The poor abstraction gives us meaningless decisions and from there the things go real hard. From empowerment, people move towards irresponsibility and abandonment without their own knowledge simply because they are far from reality and most of their decisions/thinking will become outdated.