Jan 23 2008

You <-> Eliza Google chat program

Today , I have completed one of my dream programs : I never thought that using only this much lines, I will be able to complete that .. Thanks to Python and Unni.
Well, my dream goes like this

” What if I can connect the google chat program with the Eliza program.”  : Which in non technical dream terms,  What if I have a program which helps the Artificial intelligent program called Eliza to give replies to my friends, instead of me. Those who are chatting with me will think that at the other end, there is a human being (in this case, me) who is replying to their chats.
That is my presence is there in google chat but actually I am not there.. A software “Maya”

The eliza_googlechat.py

##################################################################################
#             You <-> Eliza Google chat  program             #
# What:                                         #
#                                          #
# This program will login as you in the google chat and will automagically reply #
# to those who are ‘thinking’ that they are chatting with you using the eliza    #
# AI program.                                      #
# How:                                         #
#                                         #
# The google chat handling/reply part is done using the xmpppy python module     #
# Chats from your friends will be passed to the eliza program and the resulting  #
# output will be returned back to your friends as though you have typed it.      #
# Who:                                         #
#                                          #
# Maxin B. John <maxinbjohn@gmail.com> This code is small and self explanatory   #
# So I haven’t added a single comment in this program.                 #
##################################################################################

import xmpp
import time
from eliza import *

def messageCB(sess,mess):
    nick=mess.getFrom().getResource()
    text=mess.getBody()
    reply = eliza(text)
    sess.send(xmpp.Message(mess.getFrom(),reply))

def LoopyFn(conn):
    try:
        conn.Process(1)
    except KeyboardInterrupt:
    return 0
    return 1
   
def main_process():
    jid = xmpp.protocol.JID(‘maxinbjohn@gmail.com’)
    cl = xmpp.Client(‘gmail.com’)
    cl.connect((‘talk.google.com’,5223))
    cl.RegisterHandler(‘message’,messageCB)
    cl.auth(jid.getNode(),’my_secret_password’)
    cl.sendInitPresence()
    while LoopyFn(cl):
        pass
if __name__ == ‘__main__’:
    main_process()

The eliza.py program to integrate the eliza program with the above program

####################################################################
# This program will talk with eliza, the psychiatrist AI program   #
# By Maxin B. John <maxinbjohn@gmail.com>               #
####################################################################

import httplib
import urllib

#Function that POSTS the string to eliza website and formats the reply
# my_dialog is the string that we POST to the www-ai.ijs.si website
# obtains the reply from eliza scripts and prints it on the screen

def eliza(my_dialog):
    params = urllib.urlencode({‘Entry1′: my_dialog})
    headers = {“Content-type”: “application/x-www-form-urlencoded”,”Accept”: “text/plain”}
    conn = httplib.HTTPConnection(“www-ai.ijs.si”)
    conn.request(“POST”, “/eliza-cgi-bin/eliza_script”, params, headers)
    response = conn.getresponse()
    data = response.read()
    reply_from_eliza= str(data.split(‘</strong>’)[2]).split(‘\n’)[1]
    return “%s\r\n” % (reply_from_eliza,)
    conn.close()

# invoking the eliza function to test it’s functionality in pythonic way
if __name__== ‘__main__’:
    str =eliza(‘I love python’)
    print str

Well, from now onwards, I can dream of other possibilities . So let me sleep  now Cool


Jan 23 2008

A minimal gopher server protocol implementation in python

This is a minimalist implementation of a working gopher server in Python programming language. It is buggy but it works

#!/usr/bin/env python

# gopherd.py – A Simple Gopher Server
# By Maxin B. John (maxinbjohn@gmail.com)
#
# This little program illustrates the gopher protocol implementation
# using python with the help of SocketServer module.
#
# The gopher protocol is a very simple TCP-based protocol;which listen
# on port number 70.The Internet Gopher protocol is designed for
# distributed document search and retrieval.
#
# The Internet Gopher protocol is designed primarily to act as a
# distributed document delivery system.  While documents (and services)
# reside on many servers, Gopher client software presents users with a
# hierarchy of items and directories much like a file system. 

import SocketServer
import string
import os

class GopherHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        # Read a line of text, limiting it to 512 bytes.
        # This will prevent someone trying to crash the server machine
        # by sending megabytes of data.
        searchstring=self.rfile.readline(512)
        print ‘searching ‘+ searchstring
    # Remove any leading and trailing whitespace, including the
        # trailing newline.
        searchstring=string.strip(searchstring)
    # invoking the get_directory_info to get the return string
    info = self.get_directory_info(searchstring)
    # send the data back to gopher client
        self.wfile.write(info)
    print ‘printing the info \n’+ info
    # The following method takes a string containing the searchstring
    # This function will search the directory and provide the information
    # in Gopher Protocol format. Later will be expanded to contain the searching
    # logic based on the searchstring.

    def get_directory_info(self, searchstring):
    info = ”
    dir_path=os.getcwd()
       
    #Testing whether the request is for a particular file or folder
    #if (searchstring == “” or os.path.isdir(searchstring)== 1):
    if (searchstring == “”):
        “Return a string containing the file and directory information in gopher protocol format.”
        file_list= os.listdir(os.getcwd())
        for fileName in file_list:
            if os.path.isfile(fileName) == 1:
                info += ’0′+fileName+’\t’+fileName+’\tlocalhost\t70\r\n’
            elif os.path.isdir(fileName) == 1:
                info += ’1′+fileName+’\t’+fileName+’\tlocalhost\t70\r\n’
            else:
                print ‘This is a link ‘ +fileName
                info += ’2′+fileName+’\t’+fileName+’\tlocalhost\t70\r\n’
        return “%s\r\n” % (info,)
    else:
        fileName = searchstring
        if os.path.isfile(fileName) == 1:
            info = self.handle_file(fileName)

        elif os.path.isdir(fileName) == 1:
            info = self.handle_folder(fileName)
        else:
            info = ‘nothing’
        return “%s\r\n” % (info,)

    # Function to handle the request for a file
    def handle_file(self, fileName):
    fd = open(fileName,’r')
    textcontent = fd.read()+’\r\n’   
    return “%s \r\n” %(textcontent,)        
   
    # Function to handle the request for a folder
    def handle_folder(self, files):
    info = ”
    os.chdir(os.getcwd()+’/'+files)
    file_list= os.listdir(os.getcwd())
    for fileName in file_list:
            if os.path.isfile(fileName) == 1:
                info += ’0′+fileName+’\t’+fileName+’\tlocalhost\t70\r\n’
            elif os.path.isdir(fileName) == 1:
                info += ’1′+fileName+’\t’+fileName+’\tlocalhost\t70\r\n’
            else:
                print ‘This is a link ‘ +fileName
                info += ’2′+fileName+’\t’+fileName+’\tlocalhost\t70\r\n’
    return “%s\r\n” % (info,)
       
# If this script is being run directly, it’ll start acting as a gopher
# daemon. The following “if” statement is the usual Python style for
# running code only as a stand alone script.

if __name__==’__main__’:

    try:
        # Create an instance of our server class
        server=SocketServer.ForkingTCPServer( (”, 70), GopherHandler)
        # Enter an infinite loop, waiting for requests and then servicing them.
        server.serve_forever()

    # For graceful exit when ^c is used. 
    except KeyboardInterrupt:
    print “Received Keyboard interrput: Exiting…”
    exit


Jan 23 2008

A Pythonic evening with Eliza

I have completed one of my dreams today. A day in which I will be able to integrate one of the greatest AI program that is known to the world ‘eliza’ in Python.
Now I can ‘Chat’ with Eliza using this tiny  Python program written by none other than me (Thanks to Unni for his ruby implementation of the same) Cool

####################################################################
# Copied the idea from Unni without shame :)                                                                   #
# This is just a proof of concept that anything in working in Ruby                                     #
# can be implemented in Python with elegance .. :) Python RuleZ..                                     #
# This program will talk with eliza, the psychiatrist AI program                                         #
# By Maxin B. John <maxinbjohn@gmail.com>                                                                  #
####################################################################

import httplib
import urllib

#Function that POSTS the string to eliza website and formats the reply
# my_dialog is the string that we POST to the www-ai.ijs.si website
# obtains the reply from eliza scripts and prints it on the screen

def eliza(my_dialog):
        params = urllib.urlencode({‘Entry1′: my_dialog})
        headers = {“Content-type”: “application/x-www-form-urlencoded”,”Accept”: “text/plain”}
        conn = httplib.HTTPConnection(“www-ai.ijs.si”)
        conn.request(“POST”, “/eliza-cgi-bin/eliza_script”, params, headers)
        response = conn.getresponse()
        data = response.read()
        print str(data.split(‘</strong>’)[2]).split(‘\n’)[1]
        conn.close()

# invoking the eliza function to test it’s functionality in pythonic way
if __name__== ‘__main__’:
        eliza(‘I love python’)

What else to say , Python RuleZ


Jan 23 2008

Dividing Linux , the good old religious way (Now I am sure that people are mad)

Though I have a christian name , I consider myself as an atheist, vegetarian, die hard linux fan and a follower of Bernard Shaw.  I always found Religion as a group of manipulators blocking the ‘real’ good of the people.
I always thought Linux as “Open” and the Linux users won’t fall into the hands of religion which has the hands of an octopus.  But new ‘avatars’ of Linux distros has shaken my mind and I am begining to feel that the real spirit of Linux will  slowly die out because of the dividing  nature of  different religious  forces  just as the British used the Religion to  implement their “Divide and  Rule” style  in  India during the period of “Colonial Rule”.

These distros are a shame to the Linux community :

For the Christians : Ubuntu Christian Edition (Ubuntu CE)  – http://www.whatwouldjesusdownload.com/christianubuntu/splashpage/splash.html
For the Muslims : Ubuntu Muslim Edition (Ubuntu ME) – http://www.ubuntume.com/
For Satan worshippers : Ubuntu Satan Edition (Ubuntu SE) : http://ubuntusatanic.org/news/evil-edgy-is-released/

What we can expect from these two communities..  May be we can expect a Ubuntu JE .- the ubuntu Jihad Edition..  In the past there were “Crusades” and “Jihads” in between these two religions. Now we can expect the second phase of “Crusades” and “Jihads” … a new “Tux war” Innocent


Jan 18 2008

Go Gopher (My experiments with protocol implementation)

For me, Networking was one of the toughest subject that I have ever touched. I kept myself away from that for a long time just because of the ‘initial lag’ of learning and programming in a “New World”.
  But later , I found that using Python , it can be made simple. So I went on experimenting in it.  Lots of people were telling that the protocol implementation is one of the toughest regions in Networking.
So I decided to give it a try, by implementing a good old Gopher server (Grand father of google Undecided) .. Gopher protocol is defined in the RFC 1436. It is a TCP based protocol listening on port 70. So using these , I have decided to give it a try ..  Got a half baked gopher …It is under construction , but being a believer of the the Free Software Philosophy, I am Publishing it (even if it is not complete )..

#!/usr/bin/env python

# gopherd.py – A Simple Gopher Server
# By Maxin B. John (maxinbjohn@gmail.com)
#
# This little program illustrates the gopher protocol implementation
# using python with the help of SocketServer module.
#
# The gopher protocol is a very simple TCP-based protocol;which listen
# on port number 70.The Internet Gopher protocol is designed for
# distributed document search and retrieval.
#
# The Internet Gopher protocol is designed primarily to act as a
# distributed document delivery system.  While documents (and services)
# reside on many servers, Gopher client software presents users with a
# hierarchy of items and directories much like a file system. 

import SocketServer
import string

class GopherHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        # Read a line of text, limiting it to 512 bytes.
        # This will prevent someone trying to crash the server machine
        # by sending megabytes of data.
        searchstring=self.rfile.readline(512)
        print ‘searching ‘+ searchstring
        # Remove any leading and trailing whitespace, including the
        # trailing newline.
        searchstring=string.strip(searchstring)
    # invoking the get_directory_info to get the return string
    info = self.get_directory_info(searchstring)
    # send the data back to gopher client
        self.wfile.write(info)
    print info

    # The following method takes a string containing the searchstring
    # This function will search the directory and provide the information
    # in Gopher Protocol format. Later will be expanded to contain the searching
    # logic based on the searchstring.

    def get_directory_info(self, searchstring):
        “Return a string containing the file and directory information in gopher protocol format.”
    info=”0Sorry, but the requested token could not be found\tErr\tlocalhost\t70\r\n.\r\n\r\n”
        return “%s\r\n” % (info,)

# If this script is being run directly, it’ll start acting as a gopher
# daemon. The following “if” statement is the usual Python style for
# running code only as a stand alone script.

if __name__==’__main__’:

    try:
        # Create an instance of our server class
        server=SocketServer.ForkingTCPServer( (”, 70), GopherHandler)
        # Enter an infinite loop, waiting for requests and then servicing them.
        server.serve_forever()

    # For graceful exit when ^c is used. 
    except KeyboardInterrupt:
    print “Received Keyboard interrput: Exiting…”
    exit

#############################
Though this is far from completion, it will show the gopher’s output :)
Run the program

python gopherd.py

Then just type
gopher://localhost in your favourite firefox browser, you will see the output of a “Gopher Server”. But I don’t know whether the gopher support is present in IE. But who cares Cool


Jan 17 2008

Python v/s Ruby or how I re implemented Unni’s idea

 Today I happen to meet Unni , my hostelmate and a very brillian Linux programmer, in Gtalk. We talked about the job and the current technologies as usual . After some talks about his career move, he showed me what he has done in his first ‘Open friday’ — in his company friday is an open source day.. you can do what ever you want to do except the usual company’s work :)
It was a nice implementation of xmpp chat program used to chat with friends in Gtalk. He used Ruby to implement the program which can send chat messages to your friends and also use the program as sort of bot which will go on chatting with your friends even if you are not there to type Cool

But he implemented it in Ruby .. that was the only thing that I didn’t like..  Being a python lover, I have decided to “port” his application to Python . And before dawn, I sent my pythohic automagic chats to Ciril with his consent :) ( my aim is not to flood somebody’s chat window.. it is just to show that python is not behind Ruby… Embarassed)

First I have installed the xmpppy package from http://xmpppy.sourceforge.net/ .. The usual
python setup.py install  type installation ..
after that tried this program :
####################################
#  Program to send 1 to 100 from my account #
####################################

import xmpp
import time
jid = xmpp.protocol.JID(‘maxinbjohn@gmail.com’)
cl = xmpp.Client(‘gmail.com’)
cl.connect((‘talk.google.com’,5223))
cl.auth(jid.getNode(),’my very secret password here’)
for i in range(1,100):
        text = i
        cl.send(xmpp.protocol.Message(‘ciril4u@gmail.com’,text,typ=”chat”))
        time.sleep(1)
        print str(text)+’sent ‘
#######################################
Well, it just works ..  My wildest dream is to connect the chat bot to Eliza , the AI program and confuse the people who ‘thinks’ that they are chatting with me Innocent

Cheers to Unni


Jan 16 2008

decompiling c and c++ programs in Linux

Suppose you are working on one project and suddenly due to hdd crash you lost all your source code and suppose that you didn’t use any source code management softwares such as subversion or cvs, and all that left is the compiled binary of your project , then what will you do ??
Decompiling is the process of generating the source code out of running binaries (eg. file.c out of a.out) .  I have used the mocha decompiler for my previous java project when the customer just provided us the class files instead of java source code. We decompiled the classes and generated the source code out of it and studied the structure and logical flow of the project. I must say it was a tedious project.
Now , say for example, you have the source code and then you compiled it and later you will extract the source code from the binary , then how the two codes will differ, just let us see..
For this purpose, I am using the well known decompiler boomerang . It is available for both windows and linux. For linux we need to download  it from http://boomerang.sourceforge.net/. As it depends on a seperate libgc, download that too from the same site and copy it to the /lib directory. Then again it depends on the libexpat .. just create a link to the existing expat library in /lib and it won’t complain again :)

My C program to test decompilation using boomerang is
/**************************************************/
/* Program to check the characteristics of malloc */
/*                               */
/**************************************************/

#include <stdio.h>
#include <stdlib.h>
int *fun(void)
{
    int *a;
    a = (int *) malloc(sizeof(int));
    free(a);
    return a;
}

int main()
{
    int *j;
    j = fun();
    *j = 5;
    printf(“%d\n”, *j);
    return 0;
}

Then compile it as
cc test.c  , now we got the much awaited a.out

then run the boomerang on a.out. You will see something like
./boomerang a.out
Boomerang alpha 0.3 13/June/2006
setting up transformers…
loading…
Warning: dynamic symbol table hack used!
decoding entry point…
decoding anything undecoded…
finishing decode…
found 2 procs
decompiling…
decompiling entry point main
 considering main
  considering fun
  decompiling fun
 decompiling main
generating code…
output written to ./output/a
completed in 0 secs.

go to output/a then you will find another test.c
// address: 0x80483d9
int main(int argc, char **argv, char **envp) {
    int local7;                 // r24
        
    local7 = fun();
    *(int*)local7 = 5;
    printf(“%d\n”, 5);
    return 0;
}           
     
// address: 0x80483b4
fun() {
    int local5;                 // r24
   
    local5 = malloc(4);
    free(local5);
    return local5;
}  
   
Well, almost similar without header files and simple changes. But it is exactly what the previous source code meant to do :) ..
I will definitely call it a 90% success.


Jan 8 2008

cgi programming using clisp

Lisp is considered as the language for the creamy layer in the programming world Cool

As I am not “so busy” these days, I have decided to give lisp a try……….. So decided to start with a hello world thing in lisp…
First I have installed clisp in my linux machine…

Then created the file hello.lsp which contains a single line…

(write-line “Hello World”)

Then ran the program :

clisp hello.lsp

Hello World…

OMG, my first program in Lisp works…… 

Then decided to try the same program as a CGI script in Apache to get the feel of web programming using lisp…

test.lisp
 
#! /usr/local/bin/clisp
(write-line “Content-type: text/html”)
(write-line “”)
(write-line “Hello World”)

to /var/www/cgi-bin/test.lisp
chmod +x /var/www/cgi-bin/test.lisp
Restarted apache..
/etc/init.d/httpd restart
Then accessed it like
http://localhost/cgi-bin/test.lisp

Hello World…

It works…

Now just after a hello world, I feel like I became a hacker… as  Eric S Raymond commented on LISP in “How to Become A Hacker” …

” the profound enlightenment experience you will have when you finally get it. That experience will make you a better programmer for the rest of your days, even if you never actually use LISP itself a lot. (You can get some beginning experience with LISP fairly easily by writing and modifying editing modes for the Emacs text editor, or Script-Fu plugins for the GIMP.)”


Jan 7 2008

What George Bernard Shaw thinks about Apple……

If you have an apple and I have an apple and we exchange apples then you and I will still each have one apple. But if you have an idea and I have an idea and we exchange these ideas, then each of us will have two ideas.

George Bernard Shaw

It is quoted at the mklinux web page . Mklinux  is microkernel “Linux” … a project funded by Apple Inc. I have never seen the combination of GBS with Linux  till now…  Seems very interesting …  as  I am  a  self proclaimed  disciple of  George Bernard Shaw and  an ardent lover of Linux…..


Get Adobe Flash playerPlugin by wpburn.com wordpress themes