42

Looking for fun, Feeling groovy…

Category: Rants

I

More than Death, losing my memory scares the shit out of me.
It makes me queasy to think that all the wonderful experiences I had, the secrets in my head, my tough times and failures can go poof; slowly or in an instant without warning.

Doesn’t matter if its due to some fucked up illness like Alzheimer’s or a freak accident from sheer bad luck. It is very possible that I won’t be me one day.

The only bright side is that at least parts of my identity will live on as memories in people close to me if that happens. Coming to think of it, things won’t be that bad after all :) . As they say,

8x10 keep calm carry on gray

 

simplejson’s simple gotcha

I like simple things. Anything more complex more than ‘simple’ is tough to deal with. Therefore it comes as no surprise that I love JSON. Heck, the entire grammar fits in a business card.

If you take a closer look at the spec above, you will notice that the keys for a JSON ‘dictionary’ should be strings. I have a feeling that programmers like me whose language-of-mass-destruction is python are likely to overlook this minor gotcha.

This is where it gets interesting. Python’s json module tries to do something smart when you try to encode a python dictionary into a JSON string. In this case, all the keys are python ints.

In [3]: json.dumps({ 1 : 'Foo', 3: 'Baz'})
Out[3]: '{"1": "Foo", "3": "Baz"}'

When I decode it back to a python object…
In [4]: json.loads(json.dumps({ 1 : 'Foo', 3: 'Baz'}))
Out[4]: {u'1': u'Foo', u'3': u'Baz'}

BAM! The json module silently converts all my integer keys to strings. I, for one, would have preferred an Exception to be raised instead.

Something like this, for example.
In [19]: class F: pass
...
In [20]: f = F()
In [21]: json.loads(json.dumps({ f : 'Foo', 3: 'Baz'}))
... snip errors ...
TypeError: key <__main__.F instance at 0x92b4b2c> is not a string

In this case, I get the desired behaviour where a ‘TypeError’ is raised. Stupid example, but you get the idea.

If I am missing something obvious here please do comment. This particular cheekiness of the json module caught me unawares recently. Or maybe I was wrong in expecting the decode operation to return something that is identical to the source.

Interestingly, the json support modules that ship with TurboGears error out if you try to return a dictionary having non-string keys from your controller methods.

Almost a graduate

4 years ago, I joined a college which had the highest mediocrity rating among the mediocre colleges in TN. To be honest, I didn’t have good academics in my high school, so I must say I was quite fortunate to get an undergrad ‘seat’ for a CS Engineering degree there. Luckily, on the very 2nd day of college, I had enough brains to come to a conclusion that my next 4 years would be spent in an Orwellian Dystopian Parallel Universe where students wore lab coats for CS Labs. (It still beats me, the purpose of a fucking labcoat in a Theoretical Computer Science Lab).

Engineering education in TN is as fucked up as it gets. The fact that Yours Truly will be attending his Convocation ceremony next month and getting a degree certificate is proof enough that its fucked up beyond all recognition.

And did I mention, there will be 50 more new colleges this year in TN alone! Fucking Pathetic…

Lastly,

Thanks to Krish Ashok for making a joke out of us poor zombies..

Nai Sekar, your not-so-friendly translation bot..

SekarRecently I had to make use of Google’s translation engine to translate phrases at work. Given the lazy big bum I am, I found using the Google’s web UI a bit tiresome to use. I thought “heck, why not write a little jabber bot to make things a bit easier..”. (Agreed, writing a bot is nowhere near to the best solution.)

Writing a Jabber bot is incredibly easy with python. You will need the JabberBot package, which offers a really really simple and straightforward way to write bots. The little script below proves how easy it is.

The bot translates phrases/sentences using the python-pygtrans package. I had to name the script *something* and Nai Sekar seemed to be a good idea. Apologies if you just went ‘WTF?!’.  (I am quite lame when it comes to naming code/function/classes)

#
# Released Under WTFPL
# http://sam.zoy.org/wtfpl/
#
from jabberbot import JabberBot
import gtrans
import random

# Gmail uses Jabber, but their TOS doesn't allow automated scripts. So be warned
username = 'yourJabberID@example.com'
password = 'password'

# Just some famous dialogues from Vadivelu comedy tracks. Might not make sense if you
# don't know who or what vadivelu is.
error_dialogues = [
    "Nee yaaru kitta paysikittu irrukaynu theriyuma? Sekar ngara oru TERROR kitta",
    "Saykar settutaan",
    "Tirisa illana Divya",
    "Huh.. yennaku body strong basement weeeku",
    "Naanum rowdy.. naanum rowdy.. naanum rowdy",
    "Shabba... ippovae kannu kattudae",
    "Heloooo.. Ennoda biruther maark irukaara",
    "Don't worry.. Be gaaapy",
    "But andha dealing enaku pudichi irundhuchi",
    "lighta...",
    "Vaynda... Vallikidu.... Azuthuduvane.. Azhuthuduvane",
    "Sing in the raine... I am swoying in the raine..",
    "Helloo.. Prabha wine shop ownerungala? Kadaiya.. yeppo saar tharapeenga?",
    " romba nallavanu enna pathu sollitanmaaaaa..."
]

class NaiSaykarBot(JabberBot):

    def bot_trans(self, msg, args):
       """Translate the phrase/sentence from the source language to the required language
          ex: trans en pl Apples grow in trees
          would translate the above phrase from english to polish
       """
       split = args.split()
       if len(split) == 0:
            return
       src_language = split[0].strip()
       required_language = split[1].strip()
       phrase = ' '.join(split[2:])
       try:
            translated = gtrans.translate(src_language, required_language, phrase)
            return translated
       except gtrans.InvalidLanguage, e:
            print "Invalid args : %s" %(args)
            # Return a random error message
            return random.choic e(error_dialogues)

    # Overridden from JabberBot
    def unknown_command( self, mess, cmd, args):
        print "Unknown Command %s" %(args)
        return random.choice(error_dialogues)

if __name__ == '__main__':
     bot = NaiSaykarBot(username, password)
     bot.serve_forever()

Give your boss the illusion of managing you… with pidgin and dbus

Dilbert.com

Oh yeah!. With the power of DBus and libpurple APIs it is possible to give your boss the illusion of managing you. Just run the following script (under WTFPL). Tested with jabber accounts in a live office environment :P .

#!/usr/bin/env python
# By Sudharshan S, released under WTFPL

import dbus
import gobject
import time

class PointyHairedBoss:

    def __init__(self, boss_id, source, frequency=30):
        self.boss_id = boss_id
        self.source = source
        self.frequency = frequency
        bus = dbus.SessionBus()
        _pidgin_proxy = bus.get_object("im.pidgin.purple.PurpleService", \
                                                       "/im/pidgin/purple/PurpleObject")
        self.purple = dbus.Interface (_pidgin_proxy, "im.pidgin.purple.PurpleService")
        # FIXME:
        account_id = self.purple.PurpleAccountsGetAllActive()[0]
        self.boss_conversation = self.purple.PurpleConversationNew(1, account_id, self.boss_id)
        self.boss_im = self.purple.PurpleConvIm(self.boss_conversation)
        print self.boss_im

    def start_nonsense(self):
        question_list = open(self.source)
        for q in question_list:
            self.purple.PurpleConvImSend(self.boss_im, q)
            time.sleep(self.frequency)

if __name__ == "__main__":
   # Change the jabber id and the path to your questions, with an optional frequency
   o = PointyHairedBoss("foo@gmail.com", "questions")
   o.start_nonsense()

Burn, baby.. Burn

When it comes to fitness, I am one of those nerdy couch potatoes with a rather rotund tummy. Burning away calories has become an important priority now and boy, do I miss those Lays and the local Iyengar Bakery Bun Butter Jam and Puffs. For the last week, I have been waking up early and jogging for 30-40 minutes (I also got a good pair of running shoes). Should increase the workout time as weeks progress.

Oh, I also got a new job :D ….

Why Python?

Ever had that feeling of insignificance? The feeling that your very existence is a microscopic peanut in the grand scheme of things. By grand, I mean the Whole Sort of General Mish Mash. I am going through that right now. We are, according to our own theories an extremely smart species, yet for every answer we discover, 10 more questions creep up like one of those annoying LOLCATS shouting ‘OH HAI’. What the hell is the purpose of life? Why do we exist? What is our place in this infinite Cosmos (See the embedded video)? Its incredibly creepy even to think that our entire life is just a mega-complex probability equation, which most likely is too complex for our puny brains to comprehend.

Yeah, so basically what I am coming at is simple. Party now, Life is too short to be spent over unnecessary complications. Or in other words Frigging Use Python!!!!

(Strip from XKCD)

Thinking inside the “box”

About 10 minutes ago, my brain switched from neutral to first gear and started pondering about ways to teach someone how to program (Not that I am particularly good at programming in the first place :D ).

For example, how would you explain the concept of variables, references, names. etc, which seemingly form the corner stone of programming language syntax. Sometimes this can make you struggle a bit when you are switching languages.

Consider the following,

>>> a = 10
>>> b = a
>>> id(a)
37688272
>>> id(b)
37688272

One teency weency thing I learnt the hardway was the fact that when the interpreter evaluates ‘a = 10′, it creates a “box”, slaps the label ‘a’ on it and puts the integer 10 in it. Consequently, something like swapping of two numbers becomes as easy as,

a, b = b, a

This is actually emphasised on most, if not all Python tutorials I have come across. This didn’t sound all that important when I learnt Python for the first time.

Then I found C to be doing things differently (Am I even right?),
Take this for example,

#include <stdio.h>

int main(int argc, char **argv) {
	int x = 5;

	/* This however creates a new "box"
           containing the value 5 and a name y */
	int y = x;

       	printf("Value of x = %d, Address of x is %x\n" \
	       "Value of x = %d, Address of y is %x\n", x, &x, y, &y);
	return 0;
}
--------------------------

Gives the following output, where x and y are named on different boxes and yet have the same values.
Value of x = 5, Address of x is 98e6cecc
Value of x = 5, Address of y is 98e6cec8

Hmm, This is where I hit it. Suddenly realisation dawned. Sun shone again. Birds twittered. The darkness was gone. I suddenly found myself telling “Its called the pointers.. stupid!”

Now, to mirror the the Python “box” analogy (not exactly) well, a  in a language like C, we have to our disposal the good old pointers.

#include <stdio.h>

int main(int argc, char **argv) {
	int x = 5;

        /* Pointer to the "box" that is name 'x'. */
	int *y = NULL;
	y = &x;
       	printf("Value of x = %d, Address of x is %x\n" \
	       "Value of y = %d, Address of y is %x\n", x, &x, *y, y);
	return 0;
}

This would give me,
Value of x = 5, Address of x is c07ec844
Value of y = 5, Address of y is c07ec844

where ‘*’ and ‘&’ are the de-reference (value-of) and reference (value-at) operators.

So folks, Is it right to think along the lines of “a box at c07ec844 is labelled ‘x’ with the integer value 5″ when I see something as mundane as “int x = 5″ . It did help me to understand pointers better, but are there any better analogies when speaking about variables, references etc. than say, picturing a row of shelves with lots of boxes, each of which can have multiple sticky notes with names at a given point of time.

Zero Productivity

For the last few weeks, my productivity has dipped to an all time low. Progit is to be blamed. Suddenly I find myselves hitting refresh to see what’s ‘hot’ leading to more time reading blogs and articles, and less time actually getting some work done. So, from this point on I am activating a self-imposed ban on progit.

Lets see how long I last urge :D .

EDIT: Bleh…. Gave up, ban lasted 12 minutes

Exams again…:/

Semesters start this friday, Nov 7th. :( . So will be missing in action for the next two weeks…..

Till then,

Ctrl-Z

Follow

Get every new post delivered to your Inbox.