Tuesday, March 27, 2012

Python Decorator – A Syntactic Sugar

Python Decorator - A Syntactic Sugar

Sweet!!! And that's why python decorators are called as syntactic sugar. So what are decorators in python anyway? If you are newbie, it might confuse a lot at first. The idea is simple. To take a function, and return another function. As the name suggests, it decorates a function. Here I am trying to explain only the basic working of the decorators. I ll post a more detailed post on decorator when I find time. So lets consider a baby program to start with: to print the entered string. I think the following program do not need any explanation.

#First Example
import sys

def originalFunction(stringArg):
    print "The entered String is :"
    print stringArg

def main():
    print "Enter a String :"
    strInput = sys.stdin.readline()
    originalFunction(strInput)

if __name__ == "__main__":
    main()

The function does not do much. It just prints the string you entered in the console. The output looks some what like this:

Enter a String :
dhilipsiva
The entered String is :
dhilipsiva

well, that was not so hard. Having done that, now lets dive into decorator and apply it to the first example. As I already said, a decorator takes a function and return another function. A decorator is denoted by a '@' symbol in its beginning. Using the first example, lets consider we have to use a decorator '@CAPITALIZED' which alters the 'originalFunction' so that it prints the capitalized version of the passed string. It is simply done by adding the '@CAPITALIZED' statement just before the declaration of the 'originalFunction'.

@CAPITALIZED
originalFunction():
    ...
which is equivalent to
originalFunction = CAPITALIZED(originalFunction)

An important thing that few newbies might mistake is that '@CAPITALIZED' is some sort of built-in special keyword or has some special meaning. Either ways it is NOT true. It is just a function name. The function that you are going to define. The decorator function. you can keep it anyway you want just like a normal function. I like to be in that way because, it tells exactly what the decorator does. So, let go-a-head and implement it.

import sys
def CAPITALIZED(origFunc):
    def modifiedFunction(strArg):
        origFunc(strArg.upper())
        print "This line is appended from modifiedFunction"
    return modifiedFunction

@CAPITALIZED
def originalFunction(stringArg):
    print "The entered String is :"
    print stringArg

def main():
    print "Enter a String : "
    strInput = sys.stdin.readline()
    originalFunction(strInput)
    

if __name__ == "__main__":
    main()

in the above example, the 'originalFunction' is passed as argument to the 'origFunc' and 'stringArg' is passed on to the 'strArg' in the 'CAPITALIZED'. The decorator returns the 'modifiedFunction' to the 'originalFunction'. And now the originalFunction is modified to print the uppercase-d letters of entered string. the output goes like this:

Enter a String : 
dhilipsiva
The entered String is :
DHILIPSIVA
This line is appended from modifiedFunction
More detailed explanation on decorator is coming soon. Comments and corrections are welcomed.

Sunday, February 19, 2012

Plugin - Architecture : Programming Using Python [Tutorial]


This post will soon be moved to here
This blog has moved to http://dhilipsiva.com/blog/
This post is outdated.

Python!!! She, is a beauty. I have been in love with her lately. At work, I was asked to write an application that supports a plugin architecture. After 4 days of mind-screwing thinking,  I came up with a model that supports plugin architecture. I honestly don't know if this is the efficient way. But, it works. So here is a tutorial for you. This is just a quick tutorial.

Consider an example : you need to write a program that gets a string input from console and perfoms a case-swap and returns back to you. So let us code three plugins for that. First plugin is to get a value from the console, then to swap case and the last plugin to print the result. Therefore let us divide the components into 5 parts.

  1. A Class File : To hold all the data that are shared by the plugins at run-time
  2. Plugin 1 : To get a string from console 
  3. Plugin 2 : To Swap Cases
  4. Plugin 3 : To print the result 
  5. The Main Program

Implementation:

1. You need a class file to hold all the data that are share by the plugins and the main program. so lets deal with that file first. Lets call this file as AppData.py

class AppDataClass:
 global ipString
 global opString

2. The First Plugin : ReadInput.py
from AppData import AppDataClass
def init():
 AppDataClass.ipString = str(raw_input("EnTeR a StRiNg : "))

3. The next plugin : SwapCase.py
from AppData import AppDataClass
def init():
 AppDataClass.opString = AppDataClass.ipString.swapcase()

4.The Final Plugin : PrintOutput.py
from AppData import AppDataClass
def init():
 print AppDataClass.ipString.swapcase()

5. the main program : PluginExample.py
import imp
from AppData import AppDataClass

def main():

 AppDataClass.ipString = ''
 AppDataClass.opString = ''
 ModuleNameList = ['ReadInput','SwapCase','PrintOutput']
 
 for ModuleName in ModuleNameList:
  mFile, mPath, mDescription = imp.find_module(ModuleName,['PLUGINS/'])
  mObject = imp.load_module(ModuleName, mFile, mPath, mDescription)
  mObject.init()
  
    
if __name__ == '__main__':
 main()

Points to ponder :

I have used init() method as an entry point to all the plugins above. So that when we import modules, we know which is the entrypoint of the plugin.

Sunday, February 12, 2012

Stories that helped me grow


There are only a handful of people, with whom I shared this story before. Now, I wanted to share this with the whole world. This story is about nothing but some personal thoughts, which I would love to share with the world. I just want to share 4 small stories. Nothing more, nothing less!

The first story is about - me as a coward.
I hope you all know ‘Valley of death’, a poem, written by Tennyson. Goes something like, "Forward the Light Brigade, charge for the guns he said" and "How can their glory fade?". my favorite stanza in the poem is "Not tho' the soldiers knew, Someone had blunder'd" – The soldiers knew that they are about to die. But not one soldier asked any questions. They just did it and they just died. Against the fact that they are going to die, they had courage to follow their leader’s order. That’s bravery and that’s an Honor. And this poem is beautifully portrayed in the film, ‘The Blind Side’. I just totally fell in love with that film. This created a strong impression in my mind, during my 8th standard schooling. This created an impression that I was a coward. Because, I never listened to my teachers or elders. But, something extraordinary happened last April. It is only from that time, I gained the courage to listen to my elders.

The second story is about - me as a waste paper.
Nothing about me was normal. I learnt everything in a hard way. I fall hard, crashing into core of earth, but always had gathered enough strength to stand quickly back again. I always made a lot of mistakes. and I was happy about it. Because, to make many mistakes, you must have courage to try new things out. I learned from my mistakes. That gave me experience, a lot of experience. Hacking was my favorite. I used to hack a lot of stuffs. Radios, simple mechanical items, simple electrical items, etc. Due to my trail and error type of learning and I never listened to what others said, It always took a lot of time understand things. But I think I understood it clearly, than everyone else. But that was not the case. "If you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid", Well said by the greatest superhero of all times, Mr. Albert Einstein. And I believed that I was stupid because, I always failed in exams. No one considered me. So really felt like a waste paper who was useless for anything. But, my grandpa is a great man. And my uncle is also a great man. Because these were the people who protected me, and stood by my side up until now. I am very thankful to them. Things changed when I joined High School. Because, my trial & error type learning helped me understand writing program. Writing program was like raising my own child. Teaching it what to do. Teaching it how to behave. Taking care that it would survive the task at hand and successfully completes it. It was phenomenal. It was awesome. I was able to write programs even the ones which my teachers felt as difficult. I was able to write programs at an amazing speed than others. My classmates came rushing to me to ask for doubts. I heard my teachers saying they put extra effort in preparing, as I was sitting in class. Not just computer, I was dominating math class, too. Because it was always me who gave answers. As I entered College, I defied just about everything. I felt powerful. For 3 years, I stopped learning because I was under illusion that I know everything. But it all changed when from last April. From April, I am starting over, again.

The third story is about - me as my roll models.
I was raised under very different situation. I hated TV. But I loved to watch discovery channel, Nat-Geo and very few cartoons. I spent most of my childhood thinking. Thinking why the things are in the way that they are. Questioning myself a lot. Hunting answers. Exploring jungle. Exploring bird nests. Exploring animal behaviors. Hacking something. Mostly alone all the times. I felt awesome being me. Its me and my world. I listen to story that my grandpa tells. My Great Great Grand mother ( i.e., Grandmother’s Grandmother was alive when I was born. She used to tell Ramayana n Mahabharata. I loved 2 persons very much. Hanuman and Karna. They are my roll models. Other than that, General Iero and Lord-voldemort also are also my roll models. I love hanuman because he was an unmatched and unparalleled student of Surya Bahvan (The Sun-God). He learns everything at a blazing fast. Undefeatable. And my personal opinion is that he has an awesome leadership quality. Because, even though he was powerful enough to beat a whole army, single handed, he took Ram as his leader and stood by his side. It is a very wonderful quality . Without hanuman, Ram would have died the very moment when he went to battlefield. In fact, he would not have gone even to the battlefield without hanuman. And need I say about karna ? He is an awesome fellow. I just wrote a blog about him last week. Click Here you wish to read it. So I personally hate Krishna a little. He was responsible for karna’s death. So I hate him a little.

The fourth story is about – magic that happened last April.
It has been a fantastic journey last six months . I have been redefining me. If you had met me before April, you would have kicked me out of office . Now it’s completely new me. What happened 6 moths completely redefined me . April was peek of my atrocities. I felt powerful than ever. That took my ego to skies. But as college got over, I realized what I have become . I lost joy in what I was doing, and I enjoyed only when others spoke highly of me. I hated what I loved, if it didn’t make me feel special. I have become the stupid that I wished I should never become. I had 34 backlogs in total. No one hired me. Everybody rejected me, as soon as they saw my marks. Again, learnt my lesson in a hard way. The heaviness of being powerful is replaced by lightness of being nothing. I started everything over again. I feared a lot. But things are getting straight now.

Saturday, February 4, 2012

Karna was not defeated, but betrayed!

Do you think that Karna died because of the arrow that was launched by Arjuna? What happened to karna was a betrayal. That should not have happened to such a generous, skillful and courageous warrior. Karna was actually betrayed. Not once, not twice, but 4 times. How?, This is how:
  1. In the first place, his mom betrayed him. Kunthi, his mother, was stupid enough to “experiment” a boon that was granted to her. The sun-god magically appears, as kunthi wished, and blesses her with Arjuna (with kavasa & kundala, of course). Kuthi then decides to leave him float along the sacred river Ganga.
  2. This one also goes to Kunthi. She requests karna for 2 boons.
    • Hand over his kavasa & kundala
    • And to use the bramahastira only once. That’s not fair, by any means.
  3. The third was by lord Krishna. The big guy lowers height of the surface of earth by stamping on it, and thereby saving Arjuna who is eventually gonna be a tool to kill karna. Well, that’s not warfare. I mean, shifting the position of the earth is by no means, warfare.
  4. This is again by lord Krishna. Even after shot by arjuna’s arrow, karna does not die. His deeds have been saving him. But lord Krishna disguises as a begger and begs for his karma that was accumulated for his good deeds. And Karna even does that.
  5. In addition to these things, karna also gets lots of curses for his guru, a Brahmin, the boomadevi, and a hadful of few others. So, what I see is not an arrow that killed him. But curses of those people and 4 highly damaging betrayal by both his mom and a god. It took this much of betrayals to bring down a warrior. So do you still think that karna was defeated? Think again…

Wednesday, July 27, 2011

My online status

Wow, my 5 years of hard work in the CyberSpace has paid me off very well! Feel like I am an one man army! As a single entity, I managed to gather a potential crowd around me using social media. Not bad, I never spent a dime on this, but many people do follow me.

Twitter Status

Twitter Accounts Followers Tweets Made Listed
       
@DhilipSiva_Tech 711 141,000 13
@DhilipSiva 370 17,584 5
@DhilipSiva_Game 363 92,670 4
@DhilipSiva_Film 332 55,847 4
@DhilipSiva_And 301 50,118 13
@DhilipSiva_Aple 273 86,536 5
@DhilipSiva_linx 111 17,280 3
       
TOTAL 2461 3,34,135 47

 

so, total twitter followers are 2461 across my 7 accounts with a total of 3,34,135 listed in 47 lists.

I sincerely thank all my twitter followers for this. Thank you to all your support!

now lets take a look at search engines

Google Results : 78,700

Yahoo Search : 41,300

Bing Search : 5,100

And the image results of Google was really good. it gave lots photos across all my online profiles.

for comments and suggestions, contact :

dhilipsiva@dhilipsiva.com

dhilipsiva@gmail.com

http://www.DhilipSiva.com

mobile : (+91) 81 97 98 53 97

Wednesday, May 18, 2011

My last week as student!

hi everybody!
this is my last week as student.
now, I am sitting at my system at college lab.
CC1 lab, system number : 17 - the computer that i used for 4 years.
i used to sit in between Devi Priya n Elangovan.
1st year C lab,
2nd Year OOPS lab,
3rd Year Java lab and
final year projects,
all with my sweet friends.
but, today, I am alone. couldn't stop crying.
today, i sit with my ghost of the past !
if i had powers to reverse the time,
I would like to be with all my snsct-07cse'ians one more time! :'( :'( :'(
"TIME" is merciless evil !
"TIME" is merciless evil !!
Miss all you guys.

Thursday, February 3, 2011

Its time to change, India !

Our mother, India, is the seventh-largest country by geographical area, the second-most populous country with over 1.2 billion people, and the most populous democracy in the world. My question is, why in the world is India still developing? Why is our mother not a superpower? Why is our mother lagging behind tech? Why are we like this?

If you ask any average Indian citizen about these questions what would you think his reply would be? Well I myself ask this question to many people. And I am amazed with the replies that I get. Here are few: "Politicians are not good", "Youths are spoiled", "Media is making us dumb" and finally, "All the big brains are moving foreign to make money".

I believe 99% of all persons will just blame some other person. Seriously, do you really think that politicians are impacting the growth that belongs to you and me? no, not at all! Or not much, at most. What did these people do when Dr. APJ Abdul Kalam was president ? Nothing! What did these people so when Dr Rajendra Prasad was our president? nothing! What do we do now? Nothing! Yet, we always blame some other persons.

And, I agree. some traitors are leaving their mother India for their selfish needs. But what about the remaining of us? [Strike-out because I wrote this when I was too young. Now, I take it back! Not everybody is a traitor]. We blame some one else. But, do you ever know where our faults are beginning? Yes, you are right, "we blame others".

Its time to change people. We are responsible for our own growth. If there is somebody to blame, it is upon ourselves. I would blame myself if I had not posted this. I would blame myself if India is not developed. Its time that we took our responsibilities. Blame yourself. Start moving towards your goal. Be focused. No matter how slow you are moving, just don't stop ans keep moving towards your goal. Take your responsibility. If every individual is correct , there is nothing to stop our mother India.

It is time that you paid your duty as a son to our mother, India, back!
Jai Hind!

Monday, May 17, 2010

thedi choru - தேடிச் சோறு

தேடிச் சோறுநிதந் தின்று - பல
சின்னஞ் சிறுகதைகள் பேசி - மனம்
வாடித் துன்பமிக உழன்று - பிறர்
வாடப் பலசெயல்கள் செய்து - நரை
கூடிக் கிழப்பருவ மெய்தி - கொடுங்
கூற்றுக் கிரையெனப்பின் மாயும் - பல
வேடிக்கை மனிதரைப் போலே - நான்
வீழ்வே னென்று நினைத் தாயோ?
-mahakavi Barathiyar

MY ENGLISH TRANSLATION OF THEDI CHORU

Search for food everyday,
Speak of unwanted things through out,
Worry myself with thoughts,
Hurt others in the way of pointless things,
Get old day by day,
Succumb to vileness, die and finally go without a trace.
I will not give up and fall apart like the rest of these people!

[NOTE: I know this is not a good translation. If anyone could help me translate better, I ll be more than happy.]