20091010194338

- Finally relieved from my job at D.E. Shaw & Co. 16th is the last day I shall use Altova Mapforce ever again. Hopefully.
Hope the grass is greener where I’m off to.

- Been way too long since I’ve watched a movie. Going for Inglourious Basterds today ( if I get tickets ).

- Have to pack. Oh wait – Unpack. No – pack. Arrrrrrrrgh. I guess three cycles of packing and unpacking are due on me.
Good thing they begin anew everytime you pack. Room looks like I was robbed and then a tornado hit it.

- Another Diwali gone for a toss. Last diwali I woke up at 4:30 in the evening only to find myself alone at
home – my roommate had silently slipped off to Delhi. It was one of the blackest and dullest days ever. Or maybe second
to last Holi. That was just a mess. So while everyone else is bursting crackers, I’ll be off to Delhi – beginning my
career afresh. I just hope a stray rocket doesn’t come and hit the aeroplane I’m on.

That’s all I guess

Abhinav

Erlang basics | Sorting. BubbleSort, InsertionSort and Quicksort.

~/sortlist.erl.html


1 % WAP to sort a list using different techniques of sorting.
2
3 -module(sortlist).
4 -export([bubblesort/1, quicksort/1, inssort/1]).
5
6
7 %% Method that inserts an element into a list in its proper ascending order position.
8 %% This is basically the inner loop of a bubble sort expressed in functional programming terms.
9
10 insertintolist(X,[])->[X];
11 insertintolist(X,[H|L])->
12 if
13 X>H->[H|insertintolist(X,L)];
14 X=<H->[X,H|L]
15 end.
16
17 %% Bubblesort – This is basically the outer loop of the conventional imperative language bubble sort
18 %% That calls the inner loop ( insertintolist()) over and over again, for each element in order to sort the list.
19 bubblesort([H|L])->bubblesort(L,[H]).
20 bubblesort([],Accumulator)->Accumulator;
21 bubblesort([H1|L],Accumulator)->
22 [A1 | _] = Accumulator,
23 if
24 A1>H1->bubblesort(L,[H1|Accumulator]);
25 A1=<H1 ->
26 bubblesort(L,insertintolist(H1, Accumulator))
27 end.
28
29
30
31
32 %% Trying to write a declarative version of quicksort.
33
34 partition(Pivot, [], Left, Right)->{Left, Right};
35 partition(Pivot, [H|Tail], Left, Right)->
36 if
37 H<Pivot->partition(Pivot, Tail, [H|Left], Right);
38 H>=Pivot->partition(Pivot,Tail, Left, [H|Right])
39 end.
40
41
42 quicksort([])->[];
43 quicksort([X])->[X];
44 quicksort([H|L])->
45 {Left, Right} = partition(H, L, [], []),
46 lists:append(quicksort(Left), [H|quicksort(Right)]).
47
48 % Holy Fuck – it’s done ! Erlang FTW !!
49
50
51 %% OK, now trying to do an insertion sort.
52 %% Logic .. maintain a sublist within the list at the beginning of the list, i.e: [[],,,,]
53 %% that holds the sorted A1…Ai-1 at the beginning of each reduction. ( iteration in imperative languages).
54 %% At the end of this function, [[Sorted A1..AN]] will result.
55
56 insertionsort([[]])->[];
57 insertionsort([H|[]])->[H];
58 insertionsort([H|Tail])->
59 [TF1|TT] = Tail,
60 insertionsort([insertintolist(TF1,H)|TT]).
61
62 inssort([])->[];
63 inssort(L)->
64 [H|_] = insertionsort([[]|L]),
65 H.
66
67 % Done too ! Whoa. Now for some tree based stuff.
68 % To see the number of reductions ( function calls ) made by a given function, we can use the BIF()
69 % statistics/1 as in : {_,Reductions1} = statistics(reductions).
70 % Then Reductions1 will give us the number of reductions in the previous/last function call.
71

Tsar Bomba !! 20091004

So it’s my last day at home. What a whirlwind 2 weeks ! Resignation, Interviews, Festivities, Scary conversations.

- As of 10th October, I’ll officially be Jobless. And not the engineering student kind. OMG ! Jobless!!!11
Paapi pet ka kya hoga ? But the shit had hit the fan, bored a hole through the ceiling and was flying out the hole !
To read about why I quit my job, and why you should quit a similar high-salary-negative-work-experience one too,
read more by Paul Graham, and the first blog entry at AnonymousCowherd .
No worries though, as of the 12th I’ll be a software Mazdoor(Labourer) once again :D, hopefully lifting higher quality
software bricks and laying thicker and richer software mortar on the information superhighway.

- Erlang much ! This language is the rocks much lot !!! Functional programming ftw. A good programming course should
entail a course on a low level ( C/ASM ) language as well as that on a functional one(Haskell, Erlang).
Once the concept of a ’state’ is out of the window, and you’re no longer bothered about the chores of imperative
programming, the true swordsman in you is awakened. Ok, the true nerd programmer. But how different are the
two anyway ? :P

- Father : “So, when will you marry ?“.
Son : “:O :o) *runs*

Father = My father, Son = Me.

He might as well have said “Son, Tsar Bomba for you.” I swear to god I heard lightning strike outside the moment he
said this. Maybe Thor wanted to know too, and the strike was him chiming in – “Yes, when?” Ok, so I live in a place where 10-20 people die an year from lightning strikes. But this was out of the blue.
Both the lightning strike and the bomb my father dropped on me.
Then he started giving me deadlines. “You’re 23, another 3-4 years I guess – and then we’ll start looking!! Become
someone in this time ! And mail me your preferences if you’re too shy to say it to my face. Hahahahaha
“.

And … Aneurysm ! Take a shovel and knock my fuckin’ head off, someone. Of all the lows we’d
had in all the years, I think this takes the cake.

It was scary ! For sometime now, I’ve been thinking that the marital/domestic urges in me have been satisfied, without
me ever having as much as an affair. Or atleast I’ve deluded my brain into thinking they are. Yep, pathetic. I’m aware. But like some Smart Alec on a train put it to me – “Kya karein, Majboori ka naam Mahatma Gandhi hai.“. Haha wtf ??
That doesn’t even make sense, but it’s a nice sound byte when you have no logical reasons to offer.
Call me deranged, but everyone makes do. I’m not cut out for romance or liaisons, and the one attempt I’ve made
at achieving one has been an epic fail much. It’s not that I’ll be shy in approaching a girl that I like now, it’s
just that it’s been so long – 2 years since that fiasco – since I’ve seen someone I’ve liked.

And while working and cultivating love in an ersatz relationship _could_ be fun, I’m not sure that’s what I want to work at in life. I’d rather have the love from the moment I enter into a relationship. Which doesn’t really seem feasible at the
moment. So, I’ve kinda made peace with the fact that I might have to stare celibacy in the eye at some point in my life.
Or add a few dubious contacts to my phonebook, for some hook–err–(Yeah, I win with this.)…. escort supply. :D

20090915 Updates

20090915 updates :

- Slept soundly. Fell asleep with the lights on, which is a good thing – since with my brief
medicine induced insomnia, I had to turn off even the small laptop adaptor light
in order to cut off all distractions that kept me from even catnapping at night. Woke up
after 11 hours. WOO HOO ! My sleep’s back !! Which also means that I don’t have fatal
familial insomnia caused by the mutation of proteins through mercury causing the formation
of plaques that go and settle on your thalamus – the regulator of sleep and other things
mighty. You don’t know how much of a relief it is to get my sleep back !

- Gymmed today – after some 20 days ? The first 7 were because I was sick, the next 7 were
because I wanted to give my body time to rest and repair itself from the sickness and
the next 6 were because I wasn’t really sleeping a wink for around 5-6 days
and hence getting no rest – so exercising on top of that the way I do would definitely
have led to a cardiovascular collapse within 3-4 days.

- The last 10 or so days have been good, academic wise. -1 for sleep equals +1 for academia.
Life mostly is a zero-sum game. Learnt some cool stuff and cleared up several long-standing
doubts. It’s only so long you can go about being a fraud before your conscience gets the
better of you. But now it’s all good.

- Finally, my leave to home for a whopping 15 days has been approved ! Damn I needed this
respite ! It’s a little sad when you think how you’d get bored of being at home for around
2-2.5 months when you were at college, and now you have to literally pester and fight your
way to get a measly 15 day leave approved, when you’re working.

That’s all Folks !!

Abhinav

Public service Announcement

Hey guys

Just a few public service messages based on personal experiences.

1. Never, ever just break a mercury thermometer and try to just dust away the mercury
globules that form when you break one. Mercury vaporises at room temperature, very very
slowly. SO, especially when you’re in a small room – never, ever do that. The thermometer
you broke 2 years ago, might still be giving off mercury vapors, since they vaporize,
condense on cooler surfaces – and basically go away really slowly.

If that’s not enough, consider the fact that mercury is the second most toxic element
there is.

2. Never take a quinone based antibiotic with an ‘ox’ in its name. e.g: LevoFloxacin.
The darling of most practitioners, LevoFloxacin is a biochemically altered ( you
probably guessed because of the Levo- which means left, which means they just
just used the chemically altered counterpart to the normal ‘dextro’ floxacin ).

It causes severe CNS damage when continued for months. – For major infections like
after a surgery, or for major organ infections. I was given this for a sinus infection for
a mere 5 days, and had insomnia for 3 days. Even now, my sleep is only partially returning
back, day by day.

I was lucky to get away with a minor side effect. People have not been this lucky. Many
have started getting tics, tremors, insomnia, tendon rupture, weakness, fibromyalgia,
chronic fatigue syndrome – all immune and CNS diseases.

In short – stay away from LevoFloxacin. It comes under several brand names, the most
popular of which are Levaquin, Levoflox, etc.

Thank much :D

Abhinav

Been awake for holy fuck 48 hours

48 hours since I slept soundly.
The ass outside my room keeps chattering something in telugu. Bloody ass.
Feel like smacking his nose in.

I lie on my bed in wait of sleep but it doesn’t come. Second night in a row.
Am I turning into an insomniac ?

Is it the levofloxacin dosage ? Is it mercury poisoning ?

Only one thing is for certain. The guy outside my room is going to get his butt whoopped. Pretty soon.

- Abhinav

Pearls after Swine

~/Untitled.html


 1 So, I caught the flu. Swine/Vanilla, I know not – but I’m kinda hoping it was swine, since I’d have immunity now.
 2 It’s day 5 and I’m feeling much better than days 1 and 2, which are better left undescribed. Ah well, I’mma do it
 3 anyway :
 4
 5 - Day 0 : Aggravated feeling at the back of the bridge of my nose. Weirdly, only the left nostril. I ignore it, (mis)taking
 6           it for a post-nasal drip or something.
 7
 8 - Day 1 : Epic nasal blockage. Sinuses feel like bombs waiting to go off. I constantly feel like taking a chainsaw
 9           and sawing off my head from the forehead up to feel better. Runny nose every 5 minutes, low-grade fever.
10           When I thought it couldn’t get worse, headaches steps it up a notch at night. I cringe, twist, turn,  backflip
11           to no avail. Finally, one posture seemed to relieve the pain a bit, so I stick to that posture and stay.
12
13 - Day 2 : YSR dies of a freak helicopter crash. The entire city comes to a standstill. No food, no water, no hospitals.
14           I call up Apollo, some one on emergency duty replies – "sar! YSR <something><something> today close sar"
15           WTF? Why should a hospital shutdown because some politician is dead ? Thankfully, some restaurant called
16           "Greens" didn’t catch the news and were the only open restaurant in nearby localities, so I had two bowls
17           of soup while the others stared at my distressed state and peculiar culinary choice.
18
19           Low Fever, Headaches still continue, although the sneezing from all the post-nasal drip was irritating.
20           I could also have died of boredom if it were possible, since it seemed like there was nothing to do.
21           However, I found something on YouTube I could pass time with, and after 24-30 hours of watching it,
22           lying in a vegetative position with my mouth open ( courtesy blocked nostrils ) staring at the laptop
23           screen, I could not figure out what the show was about. Perhaps that’s the beauty of it – they yapped
24           on about topics ranging in frivolity from "Kim Kardashian’s lingerie" to some serious Liberal material about
25           American Healthcare involving heavy duty political terms I cared too little about.
26           But I have to give it to them for keeping me entertained while I was sick – TheYoungTurks .
27           That’s the name of the YouTube channel for you – TheYoungTurks
28
29
30
31 - Day 3 : Another YSR city-wide Bandh. Ok, maybe the guy was an honest politician so he deserves two days of mourning.
32           Today I’m feeling a little better, no headaches, an oh-so-slight fever, but I am still under threat from
33           the usual viral pneumonia that follows such influenza infections. I hope I don’t get it, but here’s what I
34           find the most irritating about this.
35
36
37
38 In an attempt to spread information about swine flu, people have literally swamped the internet with all sorts of
39 informations, a major percentage of which is their own ‘intelligent’ guesses. The most scary thing I’ve come across
40 is that about ‘Cytokine storms’, that cause you to die of a pneumonia within a couple of days.
41
42 So, I can prevent it by eating ‘right’, right ? No, you can’t. Infact, the same ‘right’ things that you thing might
43 save you, would kill you and are the causes of cytokine storms.
44
45 What are cytokine storms – these are nothing but an all-out response from a healthy immune system to eradicate that which
46 it doesn’t recognize. Since the swine flu virus is new, in people with strong immune systems, a lot of cytokine is released
47 to destroy it since it’s not really recognized. Now, since viruses infects your lung cells, this ends up destroying your
48 lung cells too, thereby suddenly diminishing the lung’s capacity and killing the patient.
49
50 This is weird because it’s a phenomenon described in people aged 15-40, with strong immune systems. Ah, alright. So I
51 just have to make my immune system strong, and yet not too strong at the same time ? Wtf.
52
53 So, by the point I am all freaked about what to eat and what not to eat. Apparently, everything that’s normally healthy
54 for your immune system will cause a cytokine storm and kill me, so I’m stumped.
55
56 I ended up eating plain slices of bread for the day since there was nothing available anyway. I hope the cytokine
57 doesn’t storm in me, since I’ve longed believed myself to have a dysfunctional immune system anyway, what with the
58 stray twitches (autoimmune response ?) and tics – but that’s a story for another day.
59
60 Will write again if I live,
61
62 Abhinav
63

Illusion of choice

What the fuck kind of a choice do we have when it’s a choice between wearing surgical masks and getting infected with flu ?
When it’s a choice between starving and eating contaminated food ?

It’s a sad day for humanity when we have 100 different antiviruses for computer viruses but a mere 2 for swine flu
– that don’t even work properly, and are in a majority of cases, contraindicative.
When a person’s death triggers a statewide ‘bandh’ ( shutting down ) of all shops, hospitals – leading to more deaths.

Just feeling a little angry at the state of affairs.

My could-be Last Blog Post ever ? *shudder* | Probably not !!

This time, I’m hoping it’s Sinusitis – ‘coz the symptoms are really resembling those of a brain tumour :D
On second thought, It’d be fun to have one though, finally _something_ exciting in life.
‘Drab’ wouldn’t come close to defining this pathetic existence.

Oh and I got another lymph node swelling in my armpit ( eww ) because of some wrong and over-exertion at the gym. :(

So, health-wise, life pretty much sucks. :(

Will update this if I don’t die shortly :D

- Abhinav

Yay ! Woke up today with no headache, but then my right cheek was oh-so-slightly swollen, which when take together with all the other symptoms,  suggested another acute ENT Infection. Bloody hell. This ENT infection thing is such a pest :(

Haiku Moment – Rain :D

walking in the rain
splashed a puddle
mud on my clothes

My first attempt at a haiku :P. Requires a little more discipline than I’d imagined. And also noticed that my syllables are a little screwed up :D

Helplessness ?

It’s important to realize that we’re never really helpless.
We’re only unwilling to make large enough sacrifices to help ourselves, because our goals or targets do not really inspire us enough to do so.

My hands are officially alcoholics !

Strange things force people into alcoholism. The economy, peer pressure, girls, guys, etcetera.   H1N1’s forced my hands into alocholism – I can’t touch a material object and then touch my face unless my hands chug down a helping of alcohol-based sanitizer named Viroff 753 – like smirnoff, but for viruses !. Brings back memories about 6 years ago when everyone in my family was catching viral conjunctivitis, and I was so scared of it I didn’t talk to anybody or touch anything that’d been touched for about 4-5 days. And of course there was the sanitizer. I finallly made it through the family-wide pandemic without contacting it !  I hope history repeats itself.

It really angers you when you hear compelling news about how swine flu might have been manufactured in a laboratory and not naturally. If this is true, then I’d rather be swine than human.  I mean what the hell. I understand this might be an attempt at doscouraging social gatherings that promote freedom of speech and disburse knowledge and breaking news to the people of the world ( read Zeitgeist )  – but do people really have to go this far as to kill other people in order to stay on top ? I do enjoy conspiracy theories, but I won’t accept stuff that’s absolute hokum.  However, this one does seem to have some amount of truth to it – when you look at the H1N1 virus, it seems to have been the result of an experimental vaccine trial error – it contains :

  • 1 strand of human influenza virus
  • 1 strand of Bird flu virus
  • 2 strands of different swine flu viruses.

combined into one.  Now, what are the odds that a human, two animals and a bird – each a carrier of  influenza virii particular to its own species – slept together in a horror of an orgy ?  1/1048576  at best – taking into account each participants’ prejudices or predilections  against/for each other participant.

It’s more likely ( 1/2 :P ) that the virus was put together by a lab experiment – purposely or otherwise.  My hands are never forgiving these biochemical renegades for turning them into alcoholics. I hope they don’t involuntarily grab and strangle the pharmaceutical tycoons’ necks if and ever we come face to face.

Checking Gmail from Vim – A small exercise in python and Mechanize

Hi !
Today we learn how to scrape Gmail in order to get your email from the command line, or in this case - while working from Vim.

The code given below has a method called getMail(username, password), which when called with the right username and password, will fetch your unread emails and display them for you in a Vim split-screen.

I realise I could have just used Google's RSS Atom feed, but then this was so much more fun :D - plus I got a little bit of a hang of mechanize. 
I used mechanize since urllib[2] would have been a little more tedious - I'd have to either go through
the convoluted Google Javascript code or use wireshark , which would have taken more time.

 I plan to do this someday, just not today.
So here's the code. To use this, follow the following steps : 
 1. Save this code in a file gmail.py ( or a file name of your choice ) 
 2. open ~/.vimrc, and type these 2  lines in there: 
pyfile path_to_the_above_python_file ( e.g: pyfile ~/gmail.py )

command! -nargs=0 Gmail python getMail('your_gmail_username', 'your_gmail_password')
 3. Save ~/.vimrc and close. 
 4. open Vim
 5. Press Escape, and type :Gmail  to fetch your email from Gmail.
Have fun ! 

Setting your currently playing rhythmbox song as your pidgin status message.

This script will set your pidgin status message as the song that’s currently being played by your Rhythmbox.
It’s a simple process – save it to a file, and run it. i.e:

1. Save it to a file – say status_changer.py
2. Run it : python status_changer.py & ( the & is optional. I think you’d like it to run in the beckground, hence the & )

3. Stare in Awe for as long as you like, as your status message gets changed with the change of every song :D


#!/usr/bin/env python

import dbus, gobject, dbus.glib

# A function to change the status Message on Pidgin without changing the status itself.
def set_message(message):
        # Get current status type (Available/Away/etc.)
        current = pidgin.PurpleSavedstatusGetType(pidgin.PurpleSavedstatusGetCurrent())
        # Create new transient status and activate it
        status = pidgin.PurpleSavedstatusNew("", current)
        pidgin.PurpleSavedstatusSetMessage(status, message)
        pidgin.PurpleSavedstatusActivate(status)

# A callback for when the song changes.
def status_changer_func(*args, **kwargs):
    mydict = rhythmshell.getSongProperties(rhythm.getPlayingUri())
    set_message("Now Playing: " + mydict['artist-folded'] + " - " + mydict['title'])

# Don't need the system bus for this. Connect to the per-Session Bus
bus = dbus.SessionBus()

# Associate Pidgin's dbus interface with Python objects
obj = bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
pidgin = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")

# Associate Rhythmbox's dbus player and shell interface(s) with Python objects
# Shell is needed for getting info about the song being played - the Artist, etc.
rhythm_obj = bus.get_object("org.gnome.Rhythmbox", "/org/gnome/Rhythmbox/Player")
rhythmshell_obj = bus.get_object("org.gnome.Rhythmbox", "/org/gnome/Rhythmbox/Shell")

rhythm = dbus.Interface(rhythm_obj, "org.gnome.Rhythmbox.Player")
rhythmshell= dbus.Interface(rhythmshell_obj, "org.gnome.Rhythmbox.Shell")

# Add handler for when the song changes.
bus.add_signal_receiver(status_changer_func,dbus_interface="org.gnome.Rhythmbox.Player",signal_name="playingChanged")

#begin the loop that checks for signals being generated and calls the registered callbacks.
loop = gobject.MainLoop()
loop.run()

Why Love ?

This is in attempt to answer one of the questions that baffle me, and expectedly a few others – why love ? That is, why do we fall in love ? The kind of love I’m talking about is  love at first sight. Those who think such love doesn’t exist are merely lucky or unlucky enough not to have experienced it. However, it does exist. But why ? First, a little about evolution.

Like it or not, we have all evolved. From stuff that came from some star. In the words of Carl Sagan, “We’re star stuff, harvesting star light.”. There’s absolutely nothing special or divine about us, except that we might be able to prolong our survival through our developed brains.

Has it ever occurred to you why we find certain things repulsive or scary while certain other things attractive ? We’re instinctively disgusted by the smell of rotting flesh, scared by the sight of a snake, but charmed by flowers. Why ? The answer lies in evolution.

Throughout evolutionary stages, our ancestors roamed the African plains, hunting and gathering. In the course of their lives, they encountered various stuff. Like rotting flesh. To the first human tribe, rotting flesh probably did not smell ‘bad’. It probably didn’t smell at all.  It was like all flesh, except that it had harmful bacteria that made the person who ate it, sick . Unaware, they ate it. And fell sick. Some died. The ones that survived, made a note of this in their brains. Over generations, this piece of information about rotting flesh being bad, got converted into a series of chemical reactions in the brain that developed a ’smell’, which is essentially a flow of hormones to your body that made the smeller feel nauseated. Thus, the smeller became averse to the rotting flesh, through the ‘bad’ smell. Chances are that the rotting flesh does not smell bad to a dung beetle, since they thrive in Hydrogen Sulfide.

Similarly, other things. If the number of things our ancestors came across in their hunter-gatherer lives were more dangerous than useful, the generations following them would be averse to any new things they encounter. And likewise for the other case. This is why some kids are instinctively afraid of snakes – or pretty much anything they see for the first time, while some, would gleefully play with anything unless warned by their parents.This is a classic example of ‘Convention over configuration‘ , a popular practice in the Sofware Industry Sector.

What this practice means, is that unless something is configured otherwise, the convention(the default value in the limbic portion of the brain) would take over. As in the example of the little baby and the snake, the ‘Convention‘ ( the baby’s natural instinct ) is to not fear the unknown, while the ‘Configuration‘ ( what his parents tell it ) is to fear the snakes. Over a period of time, the Configuration overrides the Convention in case of snakes, and the baby starts fearing snakes.

Similarly for a baby that instinctively fears snakes, the Convention is to fear the snake, while if tried, he can Configure his brain not to fear it.Why these two kinds of babies occur is again because the first baby is the product of a lineage in which people encountered more useful things than dangerous things while hunting in the African plains, while the second baby is the product of a lineage which encountered more dangerous things than useful or benign things during the course of their hunt. This led to the brain having a ‘default = negative‘ flag in the latter, and a ‘default=positive‘ flag in the former.

Now how does all this add up to love at first sight ? This is how.

What is the face ? It’s merely a collection of contours that might or might not appeal to you in the same way it does to another. Why ? Because of evolution. If your ancestors, ( not just your parents, but 10s or 100s or 1000s of people above you in your hierarchy ) found a great degree of success in producing kids with a female having a given kind of face, their brain stored this information. Passed on over generations, if each of the people along that path found great success of producing healthy offspring in the same kind of face, the feeling that the bearer of that given kind of face will help you produce an offspring better than the bearer of any other kind of face, intensified greatly.

This is where the intensity of love that people talk about comes in. How can love at first sight be so intense if you don’t even know the person ? Modern social dynamics requires that people get to know each other over a period of time and then, your love could be called intense. Most people would rubbish Love at first sight as mere lechery or weakness of character, without even looking into what causes it. So now, we have two kinds of love -

1. The cultivated love, ( the one that grows with companionship, trust, etc. )

2. Love at first sight.

Let’s dissect both of them with the perspective that we’ve held up until now – evolution.

1. The cultivated love between Male M and Female F

From an evolutionary perspective, this kind of love would occur when the  males, say

M[i],  where i belongs to  the time  period  ( first human generation to  today’s generation ) picked  females F[i], where i belongs to  the same time period, but all these females had very little similarities to each other.

This would mean that the attraction to no particular common facial/physical trait in females was amplified over generations in the male brains to produce an amplified effect of attraction (interpreted as ‘love’ ) on the male inheriting this generation today. However, throughout the generations, one thing was common – the chances of bearing healthy young would increase if the couple formed a bond of trust and affection with one another, preferably for life.  Hence the ‘Cultivated Love’.

Now let’s move to the more interesting case -

2. Love at first sight between Male M and Female F.

From an evolutionary perspective, this kind of love would occur when the  males, say M[i],  where i belongs to  the time  period  ( first human generation to  today’s generation ) picked  females F[i], where i belongs to  the same time period, but these females had a lot of similarity in their facial/physical features.

For example, if the first generation male picked a female that had narrower eyes, a pug nose, large shoulders, a small chin, etc. and if he was able to produce healthy offsprings with her ; this would get persisted into his memory. But this attraction  was still not written in stone. The next generation ( his offspring ),  found a female that had similar features, and was once again able to produce healthy offsprings with her. The genetic persistence into his limbic brain got a little stronger. Some 50 generations of similar females later, the rule of attraction was that much closer to being  written in stone. How ? The limbic portion of the brain of the 51st generation kid was imprinted with brain code telling it – “This kind of face/physique is right for you. If you copulate with her, your kids will be strong. Go for it ! “.  When the kid actually sees a girl with a similar face or physique,  his brain tells him – “Hey, that girl is so pretty ! Go for it !“.  How ? Once again, through a rush of hormones, that give the kid a high. The kid of course, interprets this as love, and goes for it. The female agrees, and they have healthy offspring. Now, this feeling is intensified over generations. We’re probably into 10000s of generations, maybe more, since humans developed the brain. Imagine the intenstity of this love at first sight, if most of our ancestors reproduced with similar girls.

This is why Love at first sight is not balderdash. And is probably more intense than Cultivated Love, atleast at first.

Now, what happens when the female you have fallen in love with at the first sight, refuses your advances ? Is it doom ? Does it mean your genes will end with you ?

Hardly. Even ignoring the wrong  assumption that there’s only a single female with the approximate facial/physical characteristics that your brain has been told is good for you, there’s the option of using that which makes us human – the frontal cortex. I.e: Cultivated love, through conditioning. Without the frontal cortex, and our control executive, we would have been left at the mercy of our ancestors’ experiences. However, with the inclusion of this newly evolved brain, we get to cope with constantly changing surroundings. It’s like the inclusion of a RAM chip and a hard drive  over a ROM chip – the latter is read only, while the former are configurable.

This is where the ‘Convention Over Configuration‘ paradigm kicks in. The configuration and the convention refer to two different areas of the brain. The ‘configuration‘ is concerned with the non-limbic, or the executive area of the brain, while ‘convention‘, is the limbic portion – which retains all the evolutionary persistence. All our  ‘basic instincts’, come from the latter. While our more ‘educated’  and learned behavior, comes from the former. The brain evolved inside out. That is, the brain stem came first, and then the limbic portion, and then the executive portion, the cerebral cortex, etc.

While making a choice, the executive area of the brain is consulted first. The limbic portion usually comes into play during emergencies, or when the executive area is too swamped, or resting (like when we’re daydreaming ), or when we’re intoxicated ( alcohol, lack of sleep ) .So, for the most part, you can configure your executive brain to trigger the release of the same hormones that get triggered when love at first sight occurs. This means that cultivated love can be just as fun as love at first sight, since the same hormones get released with both of them.

However, since your limbic portion still has some other, possibly conflicting, information about the person you’re supposed to be with, you will have to lead a life of slight  subconscious conflict ( which you’ll probably never realize anyway.) All it will mean is that your offspring will not feel AS attracted to the girl that you fell in love at first sight with, since you were not able to produce offspring with that girl. If this continues, the rule written in stone might get erased and 1000 generations later, your descendant might find another kind of girl attractive.

Conclusion  (and some fundae :P ):

There is nothing divine or pure about either us or love. No Cupid, nothing.  The ability to feel loved is but in your own hands. And the best way is to love everyone, like the sun – the object all gods are based on. The sun gives warmth to one and all without distinguishing between people, and without asking for anything in return. If we, are able to achieve such a level of giving love, it must mean we have love. For, in the words of John Marks Templeton, “How can you give love if you don’t have love ?” .

So, if you’re feeling piqued because some girl dumped you, don’t ! Mainly because you’ve got other options, and secondly, because you’ve got company !! :D

Read More »

The Mighty Ant

Something really strange happened today. I was just watching a video on YouTube about how tiny our earth, our sun and the planets really are when compared to other celestial bodies. After watching it, of course, I felt utterly negligible and insignificant. It occurred to me that this is what insects must feel like when they see us towering over them through their mosaic vision.

And then I fell asleep.

On waking up, I found something tickling on my face. On rubbing it, I found it was a small red ant. Dunno what attracted it there, there was no food lying around. Suddenly, I felt something prick behind the back of my nose. I panicked – I knew an ant had gotten there. I feared the worst, but I’m still alive after an hour or so, so I’m hoping a few last bites was the most damage the ant did before it died.

However, the fact that I ridiculed the Ants’ existence, although mentally, and then this event that made me panic, made me realize that maybe _we_ stood a chance against the biggest of the stars, even if it was only giving it a panic attack. Maybe we were meant to expore the universe rather than grow comfortable out here on earth.

Love when stuff connects :D

Cognos | The cognos #prompt()# macro

Here’s another bitch. The Cognos #prompt()# macro.

In case you’re wondering about giving a default value to the prompt, here’s how you do it :

#prompt(‘prompt_name’, ‘prompt_type’, ‘default_value’)#

However, there is a catch. The prompt won’t accept just anything as its default value – the third argument can only be a column name in case of strings. However for numbers, it accepts numeric constants. For example :

#prompt(‘id’, ‘INTEGER’,'-1′)# is correct,

but

#prompt(‘name’, ‘STRING’, ‘HELLO’)# is wrong. It will have to be :

#prompt(‘name’, ‘STRING’, column_name)#

Weird. I’m not very sure about this, but After a lot of hit and trials on it, where there is no documentation available on this particular topic, I think this is correct.

Please let me know if this is correct/wrong, if you, like me are fedup with the lack of documentation too.

PERL | DBI | Batch Upload/Insert – Row wise vs Column Wise binding.

Today’s topic is Bitch uploading. Oops – Batch Uploading. Using Perl DBI. Into SQL Server. It’s hard to believe that anything perl is poorly documented. Well, atleast non-intuitively documented. How else am I supposed to find out how to bind row-wise instead of column-wise to a prepared statement ? You would think that `perldoc DBI` would help, but it has but one nondescript line about row-wise binding.

Anyway, since I am documenting anything that people might find useful in their lives, here’s what I have found about row-wise binding in DBI as opposed to column-wise binding ( which is easy, well – better documented ). I show you examples of both.

To bind column-wise, use this :

$sth = $dbh->prepare(“insert into database..table values (?, ?, ?)”);
@array1 = ( 1, 2, 3 ) # array that contains the values of column1 across all the rows.
@array2 = ( 1, 2, 3 ) # array that contains the values of column2 across all the rows.
@array3 = ( 1, 2, 3 ) # array that contains the values of column3 across all the rows.

$sth->execute_array({}, \@array1, \@array2, \@array3); # {} is on purpose, not a typo. Read the perldoc for more.

—————————————–

To bind row-wise, use this :

$sth = $dbh->prepare(“insert into database..table values ( ?, ?, ?)”);
$sth->execute_array({ArrayTupleFetch => sub { return_a_referecnce_to_an_array(a row)_with_three_columns }});

what the second statement does is that it calls the subroutine repeatedly over and over ( by itself, without you specifying a loop ) till it returns an undef.

e.g:

$sth->execute_array({ArrayTupleFetch => sub { return shift @array_of_row_references }} );

so, when called repeatedly, the code will keep shifting an array ( thereby returning its first element ) till it runs out, in which case it will return undef.

Have fun with bitc..err..batch uploading !

—-

All this info is courtesy the Author/Architect of the perl DBI – > Tim Bunce ( or something to that effect, apologies to him – a great guy, ubiquitous with his help ).

Sex | The Irish Elks and the Gibraltar Macaques

Once upon a time, there lived an Elk in Ireland, we shall refer to it as the Elk. Now, Ireland being a male place, there were all of  6 female elks left. These female elks were not very attractive elks, but had the female reproductive organ nevertheless, which sanctioned unto them the right to being called female. Now our Irish Elk was good and all, but was faced with the challenge of trumping the remaining 659 of his elk brethren in the battle for one of the 6 female reproductive organs. This was not just his plight, mind you, for scroll back through the annals of Irish elk history, and you’d see a similar pattern emerge across several pedigrees.

But first, a few things about Elks.

The Elk. This animal,

1. Has terrible eyesight.

2. Will dive more than 2 feet underwater if it sights food there.

3. Is herbivorous.

Ok, enough random Elk trivia. If you had to relate them to another animal, you’d probably name them the nordic cousins of the moose, or a reindeer. They are nice animals overall, but in all their nobleness, they are, still, animals. Now elks, as all other animals, have this read-only chip branded into their limbic brain, which renders them helpless when it comes to reproduction. They get bent out of shape, desperate to impregnate their way  into the future.

So, with 6 females and 659 other males, our elk was in trouble. He was, after all, an average elk, with average-sized antlers. And antlers, as the cruel times would have it,  were the currency for copulation with the female elks. He tried every way in the book of increasing the size of his antlers, but the elk books weren’t so anatomically advanced yet. He did finally copulate though, but it was with a female who several elks had already copulated with, and the chances that his sperm would make it through now, were one in a googol. Frustrated, our elk passed away bearing the same complex that had plagued his lineage and several more in different lineages – small antlers.

Despite all our efforts however, randomness prevails, and our elk’s sperm fight their way,  through zillions of other elk sperm cells – cheesy inspiring background music playing all the while – and impregnate the female elk. A healthy young elk is born, and has substantially bigger antlers than that of its biological father.  Now I know what you’re thinking, “Ah everything’s fine,  the story has a relatively happy ending – the young avenges the deceased. ” .

But no, that’s not what happens.

The newborn  looks around, only to find  tens of other fledgling elks, with antlers bigger than its own. Another generation of inferiority complex sets in. The story repeats, and fortunately, this time around too, our second-generation elk manages to impregnate a female elk before dying a sad death after a life filled with want of bigger antlers.

Fast forward to 2008 antler-obsessed generations later, a young elk is born – for the 2008th time,  in our original Elk’s hierarchy. Punch drunk from the bloody, roller-coaster transport from the elk uterus into a soft tuft of grass on the ground, the elk opens its eyes and is instantly in awe. It looks at the vast blue canvas littered with cumulo nimbus like bales of cotton in disarray. It looks around, awestruck at the vastness of the meadow and the enormity of the horizons. It’s this elk’s time to shine, to leap into these horizons that seem to challenge its gallant leaps.  Carpe Diem time !

It rolls its back sideways , two tiny paws touch the grass, the stomach and the back get off the wet meadow grass and the two other paws follow suit.

“Wow, that’s hard! “, it thinks.

CRACK .

The last thing the elk sees before the lights go out on him is the other side of the meadow, littered with baby elks, mostly dead, the alive ones trying to get their giant antler heads off the ground, and its mother – smeared in her own blood and in her death throes, still bleeding from the lacerations caused by the young elk’s huge antlers. And then, all goes black.

Meanwhile, two random macaques in Gibraltar have sex.

Not a single Irish Elk has been sighted since mid-2007. The Gibraltar Macaques continue to flourish.

Go ahead, get huge antlers.

*This post was inspired by a documentary on eovlution. And how evolution and survival are more often than not,  trade-offs.

Audacity | Country Roads vs The Undertaker

Hi,

Here’s another (mis?)adventure with audacity. Tried mixing country roads – ( originally by John Denver , this one by hermes house band ) with the undertaker’s wwe entrance theme. The result is OK, not too shabby. Here it is :

Country Roads – Undertaker Remix

Loving audacity !

Tuning Ant and Seb

Ok, so here are Ant and Seb auditioning for the X-factor. The audition was the most hilarious one I have seen, ( apart from Donald Bell-Gam’s audition in Britain’s Got Talent, 2009 ). But this was one of those where it is soo bad it’s genius. Have a look, and then I’ll proceed with what I’ve got to do with this.

So, as you would know by now, the rapper ( Seb ) will never have a music career, so I decided to do my bit to help him : Digitally insert him into two songs : 1. Jennifer Lopez – Love don’t cost a thing and 2. Peter Andre – Mysterious Girl ( which they sang during the audition ) .

It’s a shitty job, but I hope I was able to keep beat and sync for the most part :P. So here you go :

R.I.P., Michael Jackson.

It’s actually taking time to sink in, this news. The guy was a childhood hero, after all. His ‘Heal the World’ shared the status of  almost being the school anthem, with ‘Eye of the Tiger’ breathing down its neck.
Some 13-14 years later, I woke up, with a terrible headache, a blocked nasal bridge and painful throat ( The dreaded pharyngitis strikes again. Damned cold drinks. )
Drag myself to work, and open up GTalk. Here’s how I got this news :

Friend 1’s GTalk Status Message : ‘Adieu, King of Pop !’
Friend 2’s GTalk Status Message:  MJ had racked up $500 million of debt.

My head’s chock-full of trash (that I’m going to forget in 2 weeks anyway), so the term ‘King of Pop’ didn’t really ring any bells for me, although I’m pretty sure I knew MJ was the king of pop.
However, on reading the second status message, the math had pretty much done itself. And the first Google Suggestion “Michael Jackson dead” confirmed it for me.

It was kinda sad and as besmirched as his credentials were in the past few years, I liked some of the guy’s music, and his style. I guess his death pretty much underscores the end of the era that had begun quite sometime ago. It still hasn’t sunk in for me – it’s like Amitabh Bachchan dying ! You don’t expect these guys to die !

But I guess they do. RIP, MJ.

Adding Robotic/Vocoder effect to your song using Audacity.

Have you heard songs where it appears as if a robot is singing a line instead of a person ? Want that effect for your songs ? Now you can.

You will need Audacity ( comes for windows/Linux/Mac – I use the linux one, pretty much the same as the others ) , the vocoder plugin ( which will automatically be there if you install the latest audactiy version. ) Here’s what to do :

1. Load up your song.

2. If your song is stereo ( has two tracks, Left and right, ), split the track into left and right, by clicking on the small arrow that is there in the control box to the left of the track.

Once the track has been split into left and right tracks, select  the entire right track, and then replace it with a sound that has a high amplitude to it, like a synth lead or a rave lead . Or, for experimenting, just with noise. To generate white noise, Click Generate -> Noise -> White.

3. Then recombine the left and right tracks to form a stereo track. Do this by again clickin on the small arrow to the left of the lef track, and selecting ‘Make stereo track’.

4. Now, in Effects->Plugins, select Vocoder. You might want to play with the settings a bit, but a higher number of vocoder bands mean a higher quality of robotic sound, and a lower value would mean more noise.

Apply the effect and enjoy a slightly robotic voice ! To get a more robotic voice, you would like to have a sound with more energy in it. If I had to exemplify, it would be something like a lot of synth organs playing. Like a cathedral noise with lots of strings ( cello/violins/hurdy-gurdy ) but synchronized. Luckily, I had such a song, ( The Undertaker’s WWE entrance theme played using a synth organ kinda instrument ), so my effect sounds realistic. With white noise, it won’t sound very robotish, so you need a proper sound which is in tune, unlike noise, as your carrier ( more on carriers below ).

Basically, how is works is that to vocode, the plugin needs two signals – one is the carrier signal ( the synth lead sound or the noise – in the right track ), and the other is the main sound that we want to vocode ( your song – in the left track ).  The vocoder  does the rest.

It was good for playing around, so I thought I’d let everyone know – there’s a tonne of cool plugins for audacity and it’s fun to play around with them, so by all means experiment !!

Next time, I’m trying the Pitch Snap effect ( commonly known as the T-Pain effect ? )

BTW, if you have windows and FL Studio ( Fruity Loops), you might want to visit www.warbeats.com , an awesome site for people interested in composing/mixing/merging music. Some really nice music stuff out there !

Metal/Flute effect

Here’s a cool effect I tried out using audacity on linux – remixing The Reason, by Hoobastank. The flute portion is taken out of ‘Kaisi Hai Yeh Rut’ from Dil chahta hai. I always wondered how flute would sound together with rock, 2 eluveitie songs later, I decided to give it a shot myself. So here’s the result of about 1 hour of cutting/pasting/shifting/magnifying on audacity :D

Dcac – Reason Flute Download listen lyrics MP3 FREE MP3 Downloads

Shared via AddThis

Transparent Yakuake for GNOME. Goodbye, buggy tilda !

A small piece about enabling real transparency in linux with a drop-down terminal ( tilda like ) called Yakuake(Better than Tilda and Guake).

So, I found about this great drop down terminal for KDE called Yakuake ( all of tilda, Guake and Yakuake are modeled after Quake’s drop down chat/command terminal. I miss my Quaking days T_T ).

The problem with most KDE apps (amaok, Yakuake) on Gnome is that they don’t have a lot of their KDE specific eye-candy(transparency, etc). However, with ccsm ( compiz ) , you can correct this. If you install Yakuake on Gnome ( because tilda is too buggy and Guake looks like a cross between tilda and Yakuake gone wrong ), you’ll find that the terminal works fine and everything, but doesn’t detect transparency. Here’s how to fix it, and add fancy effects to it as well -  : ( You can use this for adding highly customized open/close effects to any window type) :

1. type ccsm on your terminal, – this will open up the compiz configuration settings manager.

2. Go to Effects -> Animations, and make sure it is checked.  Then click on ‘Animations’, and in the ‘Open Animation’ tab, click New.

3. In the popup that appears, choose an effect, then in the ‘Window Type’ input box, type class=Yakuake.

4. Press OK.

5.Repeat for the ‘Close Animation’ tab.

This is for adding an effect to Yakuake when you press the key that activates/hides it. Then, in ‘effect

Press Close.

Now, in System->Preferences->Appearance, click on the ‘Visual Effects’ Tab, and check the highest effect one. These steps will enable transparency in your terminal. If you still need a testimonial to what Yakuake does, and does so much better than tilda, here’s a screenshot of a ‘grid’ feature in Yakuake, that you would otherwise need GNU Screen or Terminator along with Tilda for :

http://yfrog.com/14screenshotcrqp

Happy Yakuaking !

Downloading music from IMEEM on Linux.

Allo !

So I have been looking for this song http://www.imeem.com/abelandel/music/rewVAnNK/sawt-el-atlas-mama/ all over for quite sometime now, and have been unable to find it :(

Finally, I find it, and also that Imeem doesn’t allow downloads. Just great! After streaming a couple of times I decide this was just ridiculous. It’s streaming shit to my computer, so it’s got to be in my computer somewhere ! I was prepared to join files and stuff, but turned out it was easier than that.

Here’s what to do :  Play the song once in firefox via streaming, and then do this little bash-fu that’ll let you download the file ( On Linux . This won’t work on Solaris – you’ll have to change the options to ps (ps -eaf ), lsof and the numbers in awk):

cp `lsof -p \`ps aux | grep firefox | grep “?” | awk ‘{print $2}’\` | grep Flash | awk ‘{print $9}’` ~/media

^ that’ll copy the song files ( beginning with Flash ) to ~/media ( change th directory name to wherever you want to copy the song ) , and you’ll be able to play them using mplayer ! BTW, those files are there in FLV format even though they are songs. To change to MP3, use either of ffmpeg/mencoder/mplayer.

All the best !

Restoring/Moving a process from one terminal to another

Today we learn how to restore/move/shift a process, even from one terminal to another.

There’s a useful utility installed on your linux box called ’screen’

so, if you think a process would need to be restarted on another terminal, don’t just type the command, prefix it with screen.

e.g:

if normally you’d begin the program as : program -option1 argument1 -option2 argument2

do it as : screen program -option1 argument1 -option2 argument2

Now you can logout, close the terminal and do whatever. When you want to check on the process later, just do a screen -r

It will restore your process and let you see how far it’s gotten. Have fun !

——

Here’s why I needed this :

- I use Tilda, the terminal without a titlebar or a menubar, kinda like the FPS shooter dropdowns where you type stuff.
- But this one time, the terminal went all white and I was unable to see anything.
- This made me want to start another terminal and bring a process that was downloading videos on this new terminal.
- So I learnt about screen. It can do a lot more !

Download YouTube Vids Using Python.

Download YouTube videos, and/or their related videos ( and their related videos and so on ) in one go.

1. Download this file : http://www.easy-share.com/1905456105/youtube.py

2. Run it as

python youtube.py -v youtube_video_link -r ( will download all the related videos as well )

python youtube.py -v youtube_video_link          ( will download only the video whose link you give it. )

e.g: python youtube.py -v http://www.youtube.com/watch?v=zXDHEY5BocM

Have fun !

- Abhinav

Download TwitterKun – Twitter/WordPress/Google Words Plugin for Vim

1. Download the .bz2 archive from http://www.easy-share.com/1905507985/twitterKun.tar.bz2

2. Extract it wherever you want to ( and have permissions ) ( e.g: your home directory )

3. Run the setup.py file using the command python setup.py

You will be asked for your twitter username, password, wordpress username, wordpress password and wordpress blog url.

You will be told the location of the file in your computer where they will be stored for your convenience.

4. Now, open your vim editor by typing vim

5. Once in vim, press the Escape key, then type

:FriendStatus to see your contacts’ twitter statuses, or

:PublicStatus to see the general public’s twitter status, or

:Tweet Message to tweet a message on Twitter, or

:Follow username to follow a user on twitter, or

:Unfollow username to unfollow a user on twitter, or

:Sync comma_separated_list_of_users_you_don’t_want_removed_even_if_they_don’t_follow_you to sync your following/followers list.

:GetFollowing to get a list of users following you

:GetFollowers to get a list of users you follow.

:Define Word to get the definition for the word. or

Type something in your vim window, by pressing Escape and then the key ‘i’, and then typing whatever you want in the vim editor window. When you’re done typing, press Escape again, and then type

:BlogThis Title to publish to your wordpress blog whatever you have just typed in your vim editor window, with title as Title.




Python | Webserver

# For a server to be a web server, it must understand HTTP requests.
# HTTP request = header\r\n\r\nbody ( \r\n  = newline in HTTP )
# HTTP response as well. So, a response header can be :
# HTTP/1.1 200 OK\r\n Content-type:text/html\r\n\r\n
from socket import *
import threading
# So here's a web server, that's good for one connection.
# Open http://127.0.0.1:10000/ in your browser after running
# this and you will see a page saying 'Hello'.
# Server - socket, bind, listen, accept, send
# Client - socket, connect, send/recv
# C ---ISN---> S
# C <---ISN+1|J---S
# c ---J+1----->S
class serverthread(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
	def run(self):
		sd = socket(AF_INET, SOCK_STREAM)
		sd.bind(('127.0.0.1', 10000))
		sd.listen(5)
		sockconn, caddr = sd.accept()
		sockconn.send("HTTP/1.1 200 OK\r\n Content-type:text/html\r\n\r\nHello")
		sockconn.close()
srvr = serverthread()

srvr.start()


Posted using TwitterKun

Python Threads

import threading
import time
# A counting semaphore. Allows 2 threads in at once.
# A semaphore is implemented as a non-negative integer
# So its value can't drop below 0. If its value is 0
# and another thread tries to acuire it, ( decrement its value )
# the thread is put to sleep till a thread already holding
# the semaphore releases it ( thereby incrementing its value )
sema = threading.Semaphore(2)
# To create a new style thread in python
# Subclass threading.Thread
# Override the run method with your thread logic
class myThread(threading.Thread):
	count  = 0
	def __init__(self, name):
		threading.Thread.__init__(self)
		self.name = name
	def run(self):
		sema.acquire()
		self.__class__.count += 1
		print "Thread %s running. Count = %d " % ( self.name, self.__class__.count )
		time.sleep(50)
		self.__class__.count -= 1
		sema.release()
mt1 = myThread("One")
mt2 = myThread("Two")
mt3 = myThread("Three")
mt4 = myThread("Four")
# thread object.start() starts your thread ( executes the run() method )

mt1.start()

mt2.start()

mt3.start()

mt4.start()


Posted using TwitterKun

cStringIO – lower memory overhead.

from cStringIO import StringIO as stringIO
# since strings are immutable in python
# normal string concatenation wastes memory.
# use stringIO or cStringIO ( c Implementation )
# to concatenate strings with lower memory usage.
strS= stringIO()
strS.write("Blah\n")
strS.write("Blah2\n")
strS.write("Blah3\n")
strS.write("Blah4\n")
print strS.getvalue()


Posted using TwitterKun

Python Subprocess Module.

import subprocess
# subprocess.Popen - meant to replace os.popen[2|3] and os.system
# pipe_object = subprocess.Popen(command_line_string, stdout = , stdin = ) - in case the process does not have args.
# pipe_object = subprocess.Popen(command_line_as_comma_separated_list, stdout = , stdin = ) - in case the process has args.
# the stdout and the stdin arguments represent the stdout and the stdin of the new process to be created.
# subprocess.PIPE means a pipe has to be created to the process's stdout or stdin.
# (stdout, stderr) =  pipe.communicate(info) - sends 'info' to stdin of pipe and returns a tuple of the stdout and the stderr of the pipe.
# e.g: implementing `ls /u/jhaab/.vim` using subprocess:
print subprocess.Popen(["ls", "/u/jhaab/.vim"], stdout = subprocess.PIPE).communicate()[0]
# e.g: implementing ls | sort using subprocess:
p1 = subprocess.Popen("ls", stdout = subprocess.PIPE )
p2 = subprocess.Popen(["grep", "txt"], stdin = p1.stdout, stdout = subprocess.PIPE)
print p2.communicate()[0]


Posted using TwitterKun

Python Exceptions

# Format of exception handling in py :

# try-except*-else-finally

# To throw an exception : raise

import sys

d = dict(a=10, b=20)

try:

	print d['c']

except KeyError:

	# tb = traceback object - used  by debuggers.

	(t,v,tb) = sys.exc_info()

	print dir(tb)


Posted using TwitterKun

Python – Super in New style classes

# super - super(name_of_the_class, class object passed )
# or
# super(class object, object instance )
# Used to improve the MRO for new-style classes ( a BFS algo instead of
# the DFS algo that caused the diamond problem -
# A<-B->D<-C->A
class superex(object):
	def __new__(cls, x):
		return super(superex, cls).__new__(cls, x)
	def __init__(self, x):
		super(self.__class__, self)
		print x
superex(10)


Posted using TwitterKun

Python – Properties New-Style Classes

class propertytest(object):
    def __init__(self):
        self.__x = 0
    def setx(self, x) :
        self.__x = x
    def getx(self):
        return self.__x
    x = property(getx, setx) # property(getter_function, setter_function)
ct = propertytest()

ct.x = 100

print ct.x


Posted using TwitterKun

Python – Iterators and Iterables

# An iterator is a class whose __iter__() method returns
# the iterator itself and whose next() method returns the
# next value in the sequence it is iterating over
# useful for one time itertaion over a sequence using the same iterator instance.
class myiterator:
	def __init__(self):
		self.count = 0
	def __iter__(self):
		return self
	def next(self):
		if self.count < 10 :
			self.count += 1
			return self.count
		else:
			raise StopIteration
#an iterables __iter__() method returns an iterator.
# useful for more than one pass over the same sequence,
# using the same iterable instance.
class myiterable:
	def __init__(self):
		self.count = 0
	def __iter__(self):
		return self.iterator()
	def iterator(self):
		current  = 0
		while current < 10 :
			current += 1
			yield current
			#return myiterator() - this could have been used as well.
                        # Instead, we're using a generator - a function that has
                        # the keyword 'yield' instead of 'return'. Such a function
                        # on being called, returns a generator object, which is an
                        # iterator, so we can call generator_object.next() to get the
                        # next value in the sequence - current in the above case, which
                        # has the next value in the sequence from 1 to 10.
                        # for automatically keeps calling the next() for an iterator placed
                        # in the position where x is -> for val in x, until StopIteration is raised.
mit = myiterator()
mi = myiterable()
# Trying to re use the iterator
# Won't happen.
for x in mit:
	for y in mit:
		print x, y
print "=" * 30
# Trying to reuse the iterable
# Works.
for x in mi:
	for y in mi:
		print x,  y


Posted using TwitterKun

Python – pyodbc

# Documenting this simple api for connecting to SQLServer 2005 using python

# pyodbc > others for me.

import pyodbc

dsn = "BACKUPSERVER" # Your server name

username = ""

password =""

database = "sandbox"

connstr = "DSN=%s;UID=%s;PWD=%s;DATABASE=%s" % \

        (dsn, username, password, database)

cnxn = pyodbc.connect(connstr, autocommit=True)

query = """

	select * from sandbox..table1

	"""

cnxnCursor = cnxn.cursor()

result = cnxnCursor.execute(query)

myDict = {};

for (k,v)  in result:

	#Do your thing


Posted using TwitterKun

Unbesiegt

They’ll never break me,

Never bribe my mind!

Never I will bow,

never show humility to them.

Never they shall catch me,

never grind my fortress.

See, I am, be my witness:

Bleeding but unbowed!

-

LearnerKun v1.0

So I began going through twisted’s documentation, after reading this awesome article  a few days ago. What struck me most about it was how it was similar in more ways than one to an entire framework I’d written up for a simple task of automating a crucial firm procedure . I’d almost written a neonatal version of twisted myself ! And while writing it, I had this inkling about making the framework similar to this game I was playing at that time – Tremulous. Awesome game, and it became even more awesome to me because of the overmind-spawn-reactor concept. I’d almost written half my stuff to mimic the game’s architecture when I decided it would be too frivolous for a professional environment, and gave up. The code is now biting dust.

Anyway, I was going through twisted, and another thing that struck me about it was that how simple it makes things once you’re through with the design. It was kinda bumming, since I’m already fed up with the extra-collegiate world’s ( read firms’ ) preference of scripting languages over C. I  personally love python, but it just hurts to see C being ignored in favour of newer, hotter and simpler languages. Well, given this article , I’m one to talk. *Slaps himself twice*

Anyway, what better way to learn something than to begin writing something. As it does  everyone, the question of ‘what to write’ plagued me. Taken together,  I’d estimate I’ve wasted about an year’s worth of time chatting on internet rooms. It was about time something good came of it. So, after some googling on the subject,  I decided to develop a bot that would be able to sense the context of a chat topic going on. and be able to reply or converse along, given time. I’m close to releasing a v1.0 of what I’ve christened LearnerKun :D

Here’s a beginning : D -

# The protocol is the class where we implement protocol specific details, on a per-connection basis.
# The factory is the class where information that needs to be persisted throughout connections is stored.
from twisted.internet.protocol import Protocol, ClientFactory
#twisted's main event loop - the reactor :D sounds like a nuclear device 
from twisted.internet import reactor
# supports most chatty protocols, like xmpp, irc, etc.
from twisted.words.protocols import irc
import sys
# This is our protocol class.
# We subclass the IRCClient class and override the methods
# for events like when a user enters a chatroom, when a user renames itself
# or when a user leaves, when we receive a message, etc.
# There are 20-30 such IRC events, in case you want to know more, 
# please RTFM. :D
class learnerKun(irc.IRCClient):    
    def get_nick(self):
        return self.factory.nickname
    def set_nick(self, nickname="LearnerKun"):
        self.factory.nickname = nickname
    def get_channel(self):
        return self.factory.channel
    def set_channel(self, channel="#india"):
        self.factory.channel = channel
    nickname = property(get_nick, set_nick)
    channel = property(get_channel, set_channel)
    def signedOn(self):
        print "Joining %s" % (self.channel)
        self.join(self.factory.channel)
    
    def joined(self, channel):
        print "Joined %s" % (channel)
        self.msg(channel, "Hello from Learner-Kun :D")
    
    def privmsg(self, user, channel, message):
        if channel == self.factory.nickname:
            self.msg(user, "Sorry, Learner-Kun doesn't accept private messages !")
        else:
            print '33[94m' + user +'33[0m' + '33[92m' + message + '33[0m'
            if self.factory.nickname in message :
                self.user.msg(user, "Hi %s, how've you been ?" % ( user ))
            else:
                self.humanize(user, channel, message)
    def userLeft(self, user, channel):
        reactor.callLater(5, self.userLeftDelayedCallback, user, channel)
        
    def userLeftDelayedCallback(self, user, channel):
        if user in self.factory.friendlist:
            self.msg(channel, "Nooooooo")
    def userJoined(self, user, channel):
        reactor.callLater(5, self.userJoinedDelayedCallback, user, channel)
    def userJoinedDelayedCallback(self, user, channel):
        if user in self.factory.friendlist:
            self.msg(channel, "Hey there, %s" % (user))
    def userRenamed(self, userOld, userNew):
        reactor.callLater(5, self.userRenamedDelayedCallback, userOld, userNew)
    
    def userRenamedDelayedCallback(self, userOld, userNew):
        if userOld in self.factory.friendlist:
            self.msg(self.factory.channel, "Nice nickname, %s" % (userNew) )
            dummy = self.factory.friendlist.extend([userNew]) if userNew not in self.factory.friendlist else 0
    def humanize(self, user, channel, message):
        pass

# Our Factory class. We set the protocol attribute to be the protocol we want to use this
# Factory class for. In this case, the protocol = learnerKun ( our protocol class Above )
# It internally sets an attribute named factory in our protocol class, which is what we access
# above in the protocol class as self.factory. This is done so as to allow the protocol logic
# to be able to modify the persisted data in the factory.

class learnerKunFactory(ClientFactory):
    protocol = learnerKun
    def __init__(self, channel="#india", nickname="learner-kun" ):
        self.channel = channel
        self.nickname = nickname
        self.friendlist = ['Ashok', 'Ram', 'John']
    def clientConnectionLost(self, connector, reason):
        print "Lost connection, %s" % (reason)
    
    def clientConnectionFailed(self, connector, reason):
        print "Could not connect, %s" % ( reason )
try:
    channel = sys.argv[1]
except IndexError:
    channel = "#india"
try:
    nickname = sys.argv[2]
except IndexError:
    nickname = "learnerKun"
# The reactor.connectTCP() connects a factory instance to a server.
reactor.connectTCP( 'irc.dal.net', 6667, learnerKunFactory(channel, nickname))
# Starting the  event loop
reactor.run()

And that’s it ! You have a basic irc bot ! Now for the intreresting part – adding intelligence to it. Still working on that :D Torn between using a homegrown, intuitive method and some boilerplate code using markov chains:D Ah, the antinomy.