42

Looking for fun, Feeling groovy…

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..

24camp – Be there

Last week, 24camp started out as a means for people to get together and work on interesting projects/ideas.

Serendio will be hosting one this weekend, 13th February. We have place for about 20 – 25 in our office premises. More information can be found here.

You can also participate virtually by logging on to #24camp IRC channel on the Freenode servers. If you want to start a local, group of your own add your group in the wiki page mentioned above.

Road trip to Yelagiri

I have been a lurker in the forums of xbhp, just gaping in awe as these guys do road trips to far off places complete with triplogs. I knew I wanted to do something like this and was itching to take my FZ for a ride in the great outdoors. The farthest I had been was the trip to A R Rehman’s concert at Swarnabhoomi a couple of months ago.

A road trip was imminent and rallied two of my friends for a trip to Yelagiri, A small hill station retreat near Jolarpet. Nothing fancy like the Ooty or Kodai. Just a group of hills with the tallest point close to 1100m. Middle of December with cool weather was just so irresistible.

Alas, my friends couldn’t make it and I had to go solo, without any company. The tripmeter at the end of the day read 484.5. Also, logged part of the return trip with TangoGPS in my Freerunner. I have uploaded the traces to OSM.

I have written a fairly detailed triplog at the xbhp forums. Do read it :D

Mashing Twitter and FSO

I really love Twitter and it didn’t make any sense to me to shell out a rupee for every tweet sent through my Airtel Mobile. Moreover, I am on one of those monthly booster packs which allows you to send 22000 text messages for free. I simply had to exploit this by setting up my own little ‘OC’ twitter forwarder written in python. (I know of smstweet.in service but I am still charged 1.50 for every tweet I send)

Its insanely simple to write such a ‘forwarder’ in python using the services provided by the FSO (freesmartphone.org) Framework,

  1. Send messages to your old/unused number whose SIM is in the Freerunner (or any other device supported by the FSO framework)
  2. Handle the incoming messages and use python-twitter API (or) raw urllib2 to post updates. Of course, the device should be connected to the internet, you can tether this device to an old unused computer. Simply put, the Freerunner should be able to access the internet.

I know this is dumb given cheap GPRS and all, but what the heck; Sundays _are_ reserved for dumb things and I wanted to show off how easy it is to develop and conjure up simple but powerful scripts using open hackable hardware like the Freerunner. So take off your pedantic hats ;)

Here is the actual python code,

#!/usr/bin/env python
# Written By Sudharshan S, https://sudharsh.wordpress.com

import dbus
import time
import logging
import twitter

import gobject
from gobject import MainLoop

from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop (set_as_default = True)

# Use OAUTH?
USERNAME = "username"
PASSWORD = "password"

log = logging.getLogger("TweetForwarder")

class TweetForwarder:

   """Process Incoming messages and update twitter status
      if the message startswith 'tweet'
   """

   def __init__(self, username, password):
       log.warning("Starting up....")
       self.twitter_api = twitter.Api(username=username, password=password)

       # Get proxies and add signal handlers
       bus = dbus.SystemBus()
       _usage = bus.get_object("org.freesmartphone.ousaged",
                               "/org/freesmartphone/Usage")
       _proxy = bus.get_object("org.freesmartphone.ogsmd", \
                               "/org/freesmartphone/GSM/Device")
       self.usage_iface = dbus.Interface(_usage, "org.freesmartphone.Usage")
       self.usage_iface.RequestResource('GSM')
       self.sms_iface = dbus.Interface (_proxy, "org.freesmartphone.GSM.SMS")
       self.sms_iface.connect_to_signal ("IncomingMessage", self.onIncomingMessage)

   def onIncomingMessage(self, sender, message, kwargs):
       log.warning("Received SMS from %s:%s" % (sender, message))
       # We don't ALL messages to this number to be tweeted
       if message.strip().startswith("tweet "):
           log.warning("Trying to update status : %s" % message[6:].strip())
           self.twitter_api.PostUpdate(message[6:])
           log.warning("Updated Status")

   def run(self):
       loop = MainLoop()
       loop.run()

if __name__ == "__main__":
    logging.basicConfig()
    server = TweetForwarder(USERNAME, PASSWORD)
    server.run()

Make sure you have python-netclient and python-json installed on your Freerunner. These can be installed using the ‘opkg install’ command.

The script and the accompanying dependency can be downloaded from here. Just change the USERNAME and PASSWORD accordingly after scp’ing the tarball to your device.

Some useful links,

[1]: The FSO API reference

[2]: DBus Tutorial

Come.. Let’s Dance

Just another sketch to break the monotony of my life. (Somehow felt good no matter how bad this turned out)

Come... Let's Dance

(My scanner sucks)

Konsole monitoring with twitter and python

This happens to me all the time, especially when running programs that takes hours to complete.

  1. Start the code
  2. Go out for some tea or movie.
  3. When you come back, you find that the program had decided to piss you off by crashing 2 seconds after you went away from the keyboard.

The amount of cuss words thrown at the code/program is directly proportional to the silliness of the cause of the crash or error. Even more, if its a typo. Now that twitter allows tweets to be sent to Bharti AirTel (Boohoo others) numbers, and add Python + python-twitter + konsole (Terminal emulator from KDE) to the mix, you can get a very rudimentary notification system which can DM you when konsole activity changes.

To do this, First Enable ‘Monitor for Silence’ in ‘View’ Menu

Then  ‘Settings’ -> ‘Configure Notifications’. In the dialog that pops us, configure the notifications such that it executes a python script. The dialog should look something like this,

dialog

Notifications

The real deal is in the script. It uses the python-twitter module to send a DM from a dummy account to whatever account you want the notifications to go to.

#!/usr/bin/env python

import twitter

username = "dummy_account"
password = "password"

receiver = "sup3rkiddo"

def sendDM():
    try:
        api = twitter.Api(username=username, password=password)
        stats = api.PostDirectMessage(receiver, "*Done compiling*")
    except:
        print "Error!"

if __name__ == '__main__':
    sendDM()

Thats it! Simple but useful ;p (Of course, change the message according your needs)

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)