Hiking and Teaching

August 4, 2012 - Leave a Response

Long hikes are refreshing, tiring, and deeply meditative. I hardly remember the names or the trail – only the emotions experienced, landmarks encountered, personal tensions tamed, peaks climbed, and ofcourse, the destination arrived at.

Acquiring knowledge is akin to a long hike. I believe that the best teachers are those who are “closer” (in terms of “recency”) to the material they are imparting than those who’ve been doing it for decades. Thats why students find the Teaching Assistants and Tutorial sessions more helpful.

Our educational institutions make ceremony of a decorated academic’s presentation. Hence defeating its very purpose.

Gentlemen, the experts have forgotten how they got there. Sure, they can make slides and give lectures, but they cannot elicit the EXACT thought process that triggers learning. For they’ve simply forgotten the trail they took… as their hike started 20 years ago.

Violating Liskov substitutability

March 8, 2011 - Leave a Response

A TimeUnit class needs to behave exactly as a datetime object, except it has an additional UUID member which is used for equality comparisons. Thus this class has the following requirements:

  • Preserve all arithmetic and rich-comparisions as defined by datetime objects
  • Ability to construct TimeUnit objects using a) The datetime constructor’s parameters b) Another TimeUnit object itself (ie, copy-construct) c) Another datetime object itself. In other words, the following code should work:

    tu1 = TimeUnit(2011, 1, 25)
    tu2 = TimeUnit(TimeUnit(2011, 1, 25)) #Normal copy-construction
    tu3 = TimeUnit(datetime(2011, 1, 25)) #Superclass copy-construction
    

Now, I almost always prefer composition over inheritance, but I believe in this case the latter would be more appropriate. Additionally, I understand copy-construction is not the most Pythnonic thing but certainly one can see the merit of code like:

timeunit1 + timeunit2

VS

time_unit1.dt + time_unit2.dt #dt is the datetime member object of TimeUnit

And, another example,

previous_time_unit = TimeUnit( start_timeunit - timedelta(days=2) )

VS

delta_tu = start_timeunit.dt - timedelta(days=2)
previous_time_unit = TimeUnit( delta_tu.year, delta_tu.month, delta_tu.day)

I was able to implement this by taking charge of Python’s object creation, the result is quite elegant if I might say so myself.
But there is one caveat, this solution violates Liskov substitutability. I have mulled about this for a while, but sometimes its alright to break the rules, right?…

import datetime
import uuid

class TimeUnit(datetime.datetime):
  def __new__(cls,  *args, **kwargs):
    #Check if the client is trying to copy-construct a TimeUnit
    #using a datetime object or a TimeUnit object itself
    if issubclass(args[0].__class__, datetime.datetime):#Note that a class is considered a subclass of itself
      #copy construction only requires one arguement, so
      #we ensure that the client doesnt provide anything else
      if len(args) != 1:
        raise StandardError("You tried to copy-construct a TimeUnit but provided more than 1 parameter")
      tu = args[0]
      return super(TimeUnit, cls).__new__(cls, tu.year, tu.month, tu.day, tu.hour, tu.minute, tu.second, tu.microsecond, tu.tzinfo)

    return super(TimeUnit, cls).__new__(cls, *args, **kwargs)

  def __init__(self, *args, **kwargs):
    #There is no need to pass the args and kwargs to the superclass because
    #we have already constructed it in the overriden __new__ call
    self.id = uuid.uuid4()

  def __str__(self):
    return str(self.id) + ":" + self.isoformat()

  def __eq__(self, other):
    return self.id == other.id

  def __ne__(self, other):
    return not self.__eq__(other)

  def __hash__(self):
    return hash(self.id)

tu1 = TimeUnit(2011, 1, 25)
tu2 = TimeUnit(TimeUnit(2011, 1, 25)) #Normal copy-construction
tu3 = TimeUnit(datetime.datetime(2011, 1, 25)) #Superclass copy-construction
print str(tu1), "\n", str(tu2), "\n", str(tu3), "\n", tu1==tu2==tu3

Code is Data. Data is Code.

December 1, 2010 - Leave a Response

The animation system of our humanoid robot can be controlled by a readline client. For example,


This will cause certain muscles to move in a certain fashion. In this case, creating a simple smile.


Observe that the syntax for the input also happens to be just Python-tuple syntax! Nonetheless, my code parsed this input as follows:

def msg_to_frame(msg):
  frame_regex = r"\d{1,2}[R|L]?,\s*\d?\.?\d*,\s*\d?\.?\d*"
  triplets = re.findall(frame_regex, msg)
  frame = []
    for triplet in triplets:
      au, target, attack = map(lambda element: element.strip(), triplet.split(","))
      frame.append((au, float(target), float(attack)))
return tuple(frame)

Which I simply refactored using eval()!:

def msg_to_frame(msg):
    frame = ast.literal_eval(msg)
return frame

Conventional programming languages treat “code” and “data” separately. But in a LISPy language, “code is data and data is code”… essentially this boils down to exploiting the power of eval(). Pragmatism steers me away from LISP, towards the more familiar, albeit muddled, territory of Python.

Thought-for-the-day

September 15, 2010 - Leave a Response

In school, the morning assembly had the same routine: The UAE national anthem, Indian national anthem, thought-for-the-day, news.

The thought-for-the-day section involved a volunteer (in his early to mid-teens) sharing a wise quote with the audience.
“A stitch in time saves nine.”
“There is light at the end of every tunnel.”
“Peace comes from within.”

I thought I understood the meaning of these. Unfortunately, it has taken me over a decade to really understand them. But then again, how would I know? I was wrong the first time, so how can I be certain now?

Reflecting on life’s moments, with some courage, gives meaning to previously encountered wisdom. Immature young adults shouldn’t be exposed to such phrases; for it only illudes them and gives them the illusion of wisdom.

Less is More – but why?

August 3, 2010 - Leave a Response

It’s harder to keep things short than make them longer. Way back in school, we never had a problem answering essay-type Sociology questions. In fact, longer essays were considered “better” (horrible horrible school).

From a programming standpoint, it takes equal effort to “remove things” than to add new things. Ironically, the more I remove the easier it is to add things later.
Simple code, elegantly short formulas, potent proverbs, beautiful art, and even shorter emails, reports and presentations are much harder to create if we endeavor to keep it short. Heck, they say even women prefer men who talk less!

Dare I say, it requires artistic precision, almost a philosophical understanding of one’s domain in order to maintain expressiveness without compromising brevity. As Einstein said,
“Make things as simple as possible, but not simpler”

So short is sweet; but why? I believe it has to do with the instigation of emotions. When exposed to less words, our brains “fill up” the gaps with imagination. On the contrary, the more words there are, the more we are “fed” and this leaves our imagination undisturbed – thus bored. Additionally, being short means we expose the crux of the situation.

My 2 cents.

Python – achieving Semantic Portability

June 20, 2010 - Leave a Response

This is a poorly titled post. It is meant to document some nuances I recently came across whilst dealing with Python threads. Yes, yes, I know; Python threads are a bad idea but we had “reasons”. Anyway, lets look at some code:

import threading
import time

class Parent():
  def __init__(self):
    self.child = ChildThread(self)
    self.child.start()
  
class ChildThread(threading.Thread):
  def __init__(self, parent):
    threading.Thread.__init__(self)
    self.parent = parent
    
  def run(self):
    while True:
      print "Child thread doing work!"
      time.sleep(0.5)

def main():
  p = Parent()
  
if __name__=="__main__":
  main()
  print "EXITING"

Output:
Child thread doing work!
EXITING
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!

First thing we see is that the child thread keeps running even after we have seemingly reached the end of our program. The issue here is more subtle that it appears, but for the time being we will fix this quite simply by changing our loop condition in the ChildThread

import threading
import time

class Parent():
  def __init__(self):
    self.stop_requested = False
    self.child = ChildThread(self)
    self.child.start()
  
  def stop(self):
    self.stop_requested = True
    
class ChildThread(threading.Thread):
  def __init__(self, parent):
    threading.Thread.__init__(self)
    self.parent = parent
    
  def run(self):
    while not self.parent.stop_requested:
      print "Child thread doing work!"
      time.sleep(0.5)

def main():
  p = Parent()
  time.sleep(2)
  p.stop()
  
if __name__=="__main__":
  main()
  print "EXITING"

Output:
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
EXITING

Ok, now the output makes more sense. All good, but there is an enhancement we should make. Now, I also code in other languages, and in C++ for example, bool primitives are not thread-safe (yes, even if you declare them volatile)
So, we will replace our boolean with an Event.

import threading
import time

class Parent():
  def __init__(self):
    self.stop_requested = threading.Event()
    self.child = ChildThread(self)
    self.child.start()
  
  def stop(self):
    self.stop_requested.set()
    
class ChildThread(threading.Thread):
  def __init__(self, parent):
    threading.Thread.__init__(self)
    self.parent = parent
    
  def run(self):
    while not self.parent.stop_requested.is_set():
      print "Child thread doing work!"
      time.sleep(0.5)

def main():
  p = Parent()
  time.sleep(2)
  p.stop()
  
if __name__=="__main__":
  main()
  print "EXITING"

Output:
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
EXITING

As you’d expect, the output remains the same. But this is a better because an Event indicates to the OS scheduler that you are waiting on a condition. Admittedly, we’ve only used the event object here as a glorified boolean flag, but it is capable of a little more than that.

Thread death upon scope exit
Here’s a thought. why is the stop() call necessary in the first place? Ideally, I would like the Child thread to automatically die when the Parent goes out of scope. There are two ways to do this; the easy-but-wrong way, and the right-but-slightly-harder way.
Lets see what the easy-but-wrong way is:

self.child.daemon=True

Output:
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
EXITING

All we do is set the child thread as a daemon thread. The docs state; “The entire Python program exits when no alive non-daemon threads are left.” In other words, by marking our ChildThread as daemon we relinquish control away from the interpretor and to the OS.

The reason why this isnt the Right Solution(TM) is simply because our ChildThread is NOT supposed to be daemon (at least for this use-case). In fact, while monitoring the output of ps -aux, I often see the following:
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
EXITING
Exception in thread Thread-1 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
File “/usr/lib/python2.6/threading.py”, line 532, in __bootstrap_inner
File “./example4.py”, line 29, in run
: ‘NoneType’ object has no attribute ‘write’

Ok so whats the right way? Well ofcourse, we should implement parent’s __del__ method!, right?

import threading
import time

class Parent():
  def __init__(self):
    self.stop_requested = threading.Event()
    self.child = ChildThread(self)
    self.child.start()
  
  def stop(self):
    self.stop_requested.set()
    
  def __del__(self):
    print "Inside __del__"
    self.stop()
    
class ChildThread(threading.Thread):
  def __init__(self, parent):
    threading.Thread.__init__(self)
    self.parent = parent
    
  def run(self):
    while not self.parent.stop_requested.is_set():
      print "Child thread doing work!"
      time.sleep(0.5)

def main():
  p = Parent()
  time.sleep(2)
  #p.stop()
  
if __name__=="__main__":
  main()
  print "EXITING"

Output:
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
EXITING
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!

Whats going on here? why wasn’t the __del__ method called? First of all, the __del__ method is NOT the destructor of a class.
Now look carefully at the Parent and ChildThread classes, you should notice a classical case of circular referencing. Both Parent and ChildThread have references to each other. What we really want to do is tell the child thread to die if the Parent is no longer alive, but Parent will not die (specifically, never get garbage collected) since the ChildThread is always holding a reference to it.

The solution? The weakref module.

import threading
import time
import weakref

class Parent():
  def __init__(self):
    self.stop_requested = threading.Event()
    self.child = ChildThread(weakref.proxy(self))
    self.child.start()
  
  def stop(self):
    self.stop_requested.set()
    
  def __del__(self):
    print "Inside __del__"
    self.stop()
    
class ChildThread(threading.Thread):
  def __init__(self, parent):
    threading.Thread.__init__(self)
    self.parent = parent
    
  def run(self):
    try:
      while self.parent and not self.parent.stop_requested.is_set():
        print "Child thread doing work!"
        time.sleep(0.5)
    except (ReferenceError):
      print "Parent is dead. ChildThread will now also die"

def main():
  p = Parent()
  time.sleep(2)
  #p.stop()
  
if __name__=="__main__":
  main()
  print "EXITING"

Output:
Child thread doing work!
Child thread doing work!
Child thread doing work!
Child thread doing work!
Inside __del__
EXITING
Parent is dead. ChildThread will now also die

A weak-ref is best explained by the docs themselves:

A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else

We only pass a weak reference to our ChildThread – this allows the Parent to die. Subsequently, the ChildThread now has the option to also die if its parent is dead.
NOTE: In this example, I am using a weakref.proxy() instead of weakref.ref() – the former just makes the code slightly easier to read.

Also notice that this time the __del__ method was called. With this setup, the ChildThread will die when the client calls stop() on the Parent, or even if the Parent goes out of scope. Cool.

BTW, inspite of the usefulness of this module, it is worth mentioning that this is a result of circumventing a minor nuance of the language implementation. Ideally, one shouldn’t need to modify code based on the underlying algorithm used for garbage-collection. Nonetheless, that is wishful thinking… besides, I am sure there are compelling reasons for things to be the way they are.

A Final note – Semantic Portability:
I like Python, and I like my code to be as Pythonic as possible. Nonetheless, I also write a lot of code in other languages so I prefer to invest in concepts rather fully devote myself to a dogma. Thus; the term “semantic portability”.

Semantic portability, or semantically portable code, refers to code that embraces well understood concepts instead of unique language/library features; thus facilitating the reader to easily understand and implement in another language.

Where am I going with this? Well, Event() is a great abstraction, however, it doesn’t have consistent support across various threading libraries. For example, the popular C++ Boost.Threads doesn’t support them.
Additionally, the Event abstraction is made redundant by Condition variables. So we should re-write a part of our code using them. You will lose some of the cleanliness, but thats the price to pay for correctness and semantic portability.

Getting the perspectiveId for Perspectives in Eclipse

March 17, 2010 - Leave a Response

While working on multiple projects, it is useful to have scripts that setup your environment. These scripts, among other things, might need to launch Eclipse; and being able to specify the Perspective during launch is a cute time-saver.

Eclipse accepts a command line parameter, -perspective [perspectiveId], to launch with a certain Perspective. However there is no documentation on how to retrieve these internal perspectiveIds. Well, here’s a way…

1) Open Eclipse normally and export your Eclipse Preferences.
File > Export > General > Preferences > Save “eclipse_preferences.epf”
2) Now grep this file:
grep –color=auto -e “<perspective.*id" eclipse_preferences.epf
You will see a bunch of yucky XML output, but it should be pretty easy to extract the perspectiveIds from there.

Here are some examples with common Perspectives:
eclipse -perspective org.eclipse.jdt.ui.JavaPerspective
eclipse -perspective org.eclipse.jst.j2ee.J2EEPerspective
eclipse -perspective org.eclipse.cdt.ui.CPerspective //Assuming you have the CDT plugin
eclipse -perspective org.python.pydev.ui.PythonPerspective //Assuming you have the PyDev plugin

Nostalgia2

February 25, 2010 - Leave a Response

I dont follow Cricket anymore, but I still dont turn down an offer to play when the student roster needs a warm body. I am not a student, but the lure of some physical activity suffices.

For a weeks tho I haven’t felt like playing with this team. You see, I tell one of the players “.. oh yea, but one of the greatest moments in Cricket history was Shahid Afridi’s fastest century“, to which he replies, “I’ve heard of that one!”

You’ve heard of that one?
“How old are you?”
“17″, he replies.

It hit me. Its been 14 years since that historic moment; most of the kids I was playing with could barely walk then.
Like a brick; it hit me – I am getting old.
There actually exist adults on this planet who have never witnessed Shahid Afridi’s fastest century, or used a pulse-dial phone, or watched Ninja Turtles, or edited their CONFIG.SYS to run Commander Keen or Duck Hunt, or wore a T-shirt that doesn’t says something ironic, who dont get it when I say “its RoboCup, not RoboCop! haha.. ha…uhm“.

hmph.

Build system dilemma

February 22, 2010 - Leave a Response

Getting a grad student up-to-speed on our system is something we do from time to time. In order to perpetuate good research, one needs to be easily leverage existing work.

For one of our projects, we wrote a build system (using SCons) a while back. I made the conscious decision to only compile *.cc files thus establishing a standard. Unfortunately, one of our students (who is still learning C++), wasn’t quite able to figure out why the newly added files weren’t being compiled. Turned out she had named them .cpp instead of .cc.

At this point, one of my co-workers exclaimed that the build system should’ve take care of that. This is a noble though, but a build system ought to enforce standards.

Nonetheless, this is an interesting dichotomy that has left me pondering… what would’ve been ideal in this case?

  • Should the build-system have quietly compiled the file? but then risk littering the codebase with mixture of different file formats?
  • Should the build system violent throw up like it did? thus leave the new engineer wondering why the hell he is getting linking errors
  • Should the build system have been printed a courteous message, “hey, I see you have some .cpp files there, I am not going to compile them”.

Whats up ol’ friend?

February 15, 2010 - Leave a Response

I’ve been buried in C++ for the last year, but lately I’ve been doing some Java again (for the Android) and it feels refreshing. I dont have to concern myself with:

  • Is that operator overloaded?
  • Does this class have a default ctor?
  • Who controls the lifetime of the object? Should I expose a pointer or a smart pointer?
  • Did I mark my functions virtual? what about my dtor?
  • Should I expose the pointer or the reference?
  • What kind of copy semantics do we have here? should I make this non-copyable?

etc, etc..

This reminds me why I disliked C++ in the first place – you need to think too damn much! Specifically, the cognitive overhead is not worth it (in most cases). In fact right now, I find Java (with Eclipse!) more appealing than Python even.
Though I do miss C++’s “const”ness (in ALL its forms). That is the one C++ feature I wish Java had. And, of course, C++ also makes you a more cautious.

I am certified in CPR

February 5, 2010 - Leave a Response

Cardiopulmonary resuscitation. The maneuver you see in the movies with chest-pushing and mouth-to-mouth – I can do that now. I am grateful to have learnt this life-saving technique. The training was given by Hamad International Training Center, and the instructors were quite effective. Total 8 hours of training with a theory and practical test at the end. If my memory serves me right, here are the things we did/learnt:

  • A relevant-but-not-boring amount of theory.
  • How to administer first aid
  • How to treat burn and shock victims
  • How to conduct CPR
  • How to use a defibrillator.

Dubai Islamic Bank reduced to “junk” status

January 21, 2010 - Leave a Response

Today my grandfather informed me that Dubai Islamic bank was reduced to “junk” status. I wearily opened my first bank account with them when I was 19.

I remember my family’s words, “.. but its an Islamic bank! its clean money“, “Its profit sharing, not interest. So its not sinful“, “Imran, you dont understand…“.

Fuck it, I told myself. I wasnt depositing a million dollars. But I started using the bank regularly, and here I am, several years later at high risk of having a LOT my money simply vanishing. The kicker is when my mother recently said, “Imran, I’ve been asking you for months to transfer your money out of there…“.

And these are the same people who want to take responsibility for finding me a life partner.

PS: Admittedly, Dubai Islamic Bank still has excellent customer support (offline, online and phone). I hope they survive this mess.

Boost Indirect Iterator

January 5, 2010 - Leave a Response

Its amazing what you can find in the deep annals of the Boost libraries. It’s authors are dark wizards of modern times wielding grotesque magic with great elegance. Anyway, before I get carried away…

So, we’ve all stored heap-allocated objects in containers. But since the container is holding raw pointers, we cant use any functions that work on iterator ranges (like the ones in algorithm.h). For example eventhough your heart is in the right place, the following code would fail:

find_if (myVec.begin(), myVec.end(), someFunction);

Wouldn’t it be cool if there was an iterator that did double dereferencing? Well, there is. Enter the Indirect Iterator. You can now do the following:

find_if(make_indirect_iterator(myVec.begin()),make_indirect_iterator(myVec.end()),someFunction)

Of course, you could’ve also used Pointer Containers to begin with. Which btw, is one of the few Google “approved” Boost libraries – I guess even Google is weary of their dark magic.

When it doesn’t feel right…

December 30, 2009 - Leave a Response

When a solution doesn’t smell right, doesnt feel right, it probably is not right -¬† eventhough It Works. Ignore this feeling for too long and you end up with a house of cards…
So whenever I get this feeling, I either try to fix it right away or make a note of it. In fact, I always arrive at better solution if I pursue it.

For example, for the last few months I’ve been working on deploying a live scenario to demonstrate TraderBots. TraderBots is a market-based technique for efficiently allocating “tasks” to “agents”. In our case, these these agents happen to be robots (Pioneers and Roombas).

Since I am using an older version of the library, it has some bugs. This requires me to mutex protect the TraderBotsPlanner instance (think of the TraderBotsPlanner as the main interface to the library).
Anyway, some of my functions end up looking like this:

void foo()
{
   mutex.lock()
   //do stuff with the TraderBotsPlanner
   mutex.unlock()
   bar(); //This function also uses the mutex
}

Note that the call to bar() will deadlock if I dont explicitly unlock() the mutex. There is nothing wrong here; except it doesn’t “feel right” because these RIAA based mutexes dont need to be explicitly unlock()ed in the first place.¬†This is a classic example of “doing something you shouldn’t really need to”. Afterall, the best kind of code is the one that isn’t written.
So the fact that my design requires this suggests that there is some flaw not yet apparent to me (as of mid November).
But last week (around Christmas) I completely did away with it by doing my auctioning in a separate thread. So foo(), bar() and their ilk run concurrently.

The slightly more elegant solution I arrived at inadvertently removed the kludge elsewhere. Cool. In fact I am certain that this approach is relevant, and can be adopted to any discipline (certainly math).

Why your project should always have a Ticket tracking system

November 10, 2009 - Leave a Response

At my current job, we use a mixture of Google docs and Wikis to maintain a TODO list. This has worked out OK, Trac would’ve been ideal – because it is so much more than merely a task tracking tool.

How so, you ask? Well, a colleague recently asked me the same question.. “why are you still using this Trac thing?”. After pondering that, I organized my thoughts enough.. so here they are.

1) Writing tickets is a good habit. I dont have too many good habits, so I’d like to retain the few that I do have.

2) Posterity. Almost all my tickets begin with the phrase “Recall that..“, “First of all..“, etc. It is critical to establish context, and then dive in to the nitty gritty. Merely dumping your thoughts, or a stack trace, does not qualify as a well written ticket.

3) Lets say you are writing a bug report. Now, the very practice writing down your thoughts in a natural language, forces you to take a step-back from your “code muddled” thinking. I usually enact a short story that exposes my train of thought, and while doing so, I often figure out the solution along the way. Yes! Thats right; simply writing a grammatically correct, and concise ticket actually helps arrive at a solution for the very problem you are documenting. Sometimes tho, the reverse also holds true.. just when you think that you’ve fixed a bug, you realise you have’nt.

4) It feels good to close tickets! A nice morale boost.

5) Forces you to break down a composite task into bite-sized chunks that can be digested and assigned easily. Of course, this means that tickets ought to be as granular as possible. For example, “Change Roboceptionist UI” is not a good ticket; instead reduce this task to a set of specific tickets, such as, “Add Stop and Start buttons to UI“, “Research Qt’s widgets for a replacement to the mouth UI“, “Fix threading issue when the startSpeaking() function is called while initiating text-to-speech“.

Who are these thieves?

August 6, 2009 - Leave a Response

Fran Allen, in her interview in Coders At Work, briefly hints at thieves in academia. Here are a couple of excerpts:

Allen: “… Edith Schonberb, who is a great computer scientist… She’s had work stolen – absolutely brutally stolen. She wrote a paper on debugging of parallel code, which is a very hard problem. It was not accepted at a conference and somebody who had been on the program committee made three papers out of it… He was a famous thief, known but nobody dares touch it”

Allen: “… There was a woman who essentially was the inventory of multiprogramming and credit was taken by somebody who eventually became a Turing Award winner”

Who is she talking about?

Nostalgia1

June 22, 2009 - Leave a Response

I am sucker for nostalgia.

So long ago, late 80s probably, we only had 2 channels on TV in India, Doordarshan and some other channel; Zee TV was still very new. Anyway, there was a cartoon that ran at the same time as another show (Gul, Gulshan, Gulfam). My mother and grandma wouldn’t let me watch the cartoon, inspite of the tantrums I threw. What I found terribly concerning tho, was that in this particular case my tantrums were rendered ineffective. Even my 100% success rate “bang head on the wall” tantrum didn’t make them budge! So I figured this show must be really good, and just gave up. Probably the first time in my life I experienced the concept of “futility”.

Speaking of Zee TV, our receiver would sometimes catch the transmission and I’d get excited AND NEVER change the channel. But Zee TV had a really loud and obnoxious intro theme, so I would run towards the TV and lower the volume (no remote control back then), so that the neighbours wouldn’t hear it and get all nosy. (“Oh my god! You get ZeeTV, can we come watch!?“).

I haven’t watched TV in maybe 10 years.

Triangle numbers

June 6, 2009 - Leave a Response

There’s an old tale where a German math teacher asked his students to sum all the numbers between 1 to 100. One of the students, Carl Friedrich Gauss, finished the task in only a few minutes by calculating 100(100+1)/2

Anyway, it turns out that a triangle number is the sum of n natural numbers from 1 to n. So for example, the 5th triangle number is 1+2+3+4+5 = 15. Pretty simple.

Here’s a toy experiment to compare a some techniques that generate a sequence of the first 10,000,000 (10 million) triangle numbers.

Here I dont use Gauss’s trick. This technique is significantly better than the naive and most obvious solution.

def genTriangleNumbers1(n):
sum_till_n = sum(i for i in xrange(1,n+1))

triangle_nums=[0 for i in xrange(n)]
triangle_nums[-1] = sum_till_n
for i in reversed(xrange(2,n+1)):
  triangle_nums[i-2] = triangle_nums[i-1] - i

return triangle_nums

Time taken: apprx 7.3 secs

Here I use Gauss’s trick:

def genTriangleNumbers2(n):
for i in xrange(1,n+1):
  yield i*(i+1)/2

Time taken: apprx 6secs

And finally, here’s a hybrid style:

def genTriangleNumbers3(n):
sum = n*(n+1)/2
yield sum
for i in reversed(xrange(2,n+1)):
  sum -= i
  yield sum

Time Taken: apprx. 3.3 secs.

Leaf Coders.

March 21, 2009 - Leave a Response

Leaf Coders. That’s a cooked-up term I came across recently, it describes programmers who merely stitch APIs together without necessarily understanding what goes beneath the surface. The term certainly has a negative connotation to it. All programmers would like to believe that they aren’t leaf coders, and their knowledge is more than skin deep.

But you see, Programming is all about abstractions. These abstractions start from your IDE, and go all the way down to silicon in your CPU. I like to stay closer to the metal and leverage abstractions when appropriate, but that is totally subjective. One man’s “closer to the metal” is another man’s “floating on the clouds”. It is not uncommon to feel guilty while working at high abstraction levels (at least I do), one may feel as if all the work has been done by others and they are merely stitching APIs (ie, Leaf coding). Sure, you are more productive, but you certainly dont feel manly (“manly” by programmer standards, not Macho Man Randy Savage standards).

I have battled with this feeling for a few years now – the feeling of unease and guilt. I have tried going deeper, but at some point you have to find solace in what you know (and more importantly, in what you dont) – just how far down the rabbit hole will you go? Nonetheless, I am happy to say I’ve won the battle:

“While working at abstraction n, understand n-1 well, and the basic principles of n-2″

What a remarkably profound quote! Very peaceful. I wish I had read this years ago. If you take this proverb to heart, you realise that exploiting abstractions is akin to “standing on the shoulders of giants” (of course, in the software world it’s more like “standing on the wobbly stomachs of many a Mountain-Dew drinking programmers”).

Being able to settle on an abstraction is actually the Step2. Step1 determining what level of abstraction is suited for the problem at hand – this is one of the most keenest challenge a programmer faces. I dont think there is an exact science to it, it’s mainly intuition, art, and a good sense of design.

So yes, “Leaf” coding is fine as long as you know your n-1 and your n-2… because hey, sometimes those abstractions can leak.

Installing Colorgcc

February 2, 2009 - 2 Responses

Colorgcc is a little perl script that colorizes output of gcc. The goal is to redirect every gcc call to the colorgcc script. In other words, when run “gcc“, you actually call the colorgcc script. Output will look something like this:

Here are the instructions (because I haven’t found them anywhere else on the net!):
1)
Place the colorgcc script in the /usr/bin directory. Remember to chmod it as an executable (chmod +x colorgcc)

2)
Do an echo $PATH and “cd” into the first directory in the path list. For example,
$> echo $PATH
"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
$> cd /usr/local/sbin

2)
Create symlinks for gcc,g++ or any other gcc-bundled compiler inside /usr/local/sbin
$> ln -s /usr/bin/colorgcc /usr/local/sbin/g++
$> ln -s /usr/bin/colorgcc /usr/local/sbin/gcc

We create these symlinks inside “/usr/local/sbin” because it is the first directory listed in $PATH; hence, it is searched first. In other words, when we call “gcc” (in the terminal), we want our symlink to be accessed before the real gcc binaries inside /usr/bin

That’s it!

What to do when you have multiple versions of gcc?
In situations where you have more than one gcc version installed, you need to explicitly specify which compiler to use. For example, instead of g++ foo.cc, you will have to say g++-4.2 foo.cc. In such a case, colorgcc will not intercept the call to g++-4.2, and hence not colorize the output. But you can easily add this behavior yourself..

1)
We create another symlink inside /usr/local/sbin, but this time we specify the name of the compiler.
$> ln -s /usr/bin/colorgcc /usr/local/sbin/g++-4.2

2)
Edit the colorgcc script (probably in /usr/bin), and add the following line inside the initDefaults() function:

$compilerPaths{"g++-4.2"} = "/usr/bin/g++-4.2"

Importance of Education.

January 2, 2009 - Leave a Response

There is a monumental difference between good education, and just education. At a lower level, education is all about having good teachers/mentors. Bill Gates highlights this in one of his TED talks.

A recurring pattern I see amongst those who are tremendously good at what they do, is that they started early. The experiences of youth mold us uniquely; somewhere along this journey, some get lucky (or maybe its a calculated approach adopted by the parents — but that’s still luck) and acquire skills that give them a huge headstart in life. Some of these skills have direct monetary value (whether the child exploits this is another story), while most don’t.

Nonetheless, everyone has to play some sort of catch-up if they need to go anywhere in life. But unfortunately, it takes 10,000 hours to catch up to a Master. I can resonate with that number. There are “activities” I’ve been involved in since youth that surpass that amount. One of these days I’ll figure out how to monetize it…

Follow

Get every new post delivered to your Inbox.