Caesar cipher in one line

Can we create an encrypt and decrypt using Caesar cipher in one line? I’m sure you can. Here is one way to do it in Python. This assumes the text is typed in English (or where the lower() function on a string can work).
Encrypt
import sys;print ''.join([chr(x) for x in [x if x else x+ord('a') for x in [ (ord(x.lower())+1)%(ord('z')+1) for x in sys.argv[1]]]])
Decrypt
'import sys;print '.join([chr(x) for x in [x if (x%(ord('a')-1)) else ord('z') for x in [ (ord(x)-1) for x in sys.argv[1]]]])
So, now you can send your next missive in shift+1 cipher ! Of course, you are not going to send trade secrets that way, would you? 🙂

Install Python-MySql on Windows 7 64-bit

Install Python-MySQL on Windows 7 64-bit

I’ve been wanting to try my hand at SQLAlchemy for a while now. No particular reason other than checking how the APIs for the ORM are. To decide on the database to use, I thought MySQL might be a good idea because most of the OSS libraries support MySQL. But the catch was that I wanted to do all this on Windows 7 and that too a 64-bit Windows 7. So, this was a bit tricky. I couldn’t do something like easy_install MySQL-Python on Windows. So, here is a step-by step guide to install MySQL 64-bit, Python-MySQL on Windows 7. The steps might work with Windows Vista too.

Pre-requisites

  1. Python 2.7 – might not work with Python 3
  2. Visual Studio 2008. The Visual Studio express edition will also work. Essentially, a C++ compiler is required
  3. Access to modify the registry
  4. MySQL DB 5.5 on Windows

Installing Python-MySQL

  1. Download the combined installer of the MySQLDB on Windows from MySQL. The current version is 5.5
  2. Download the Python-MySQLDB library here – Python-MySQLDB. The current version is – MySQL-python-1.2.3
  3. You need to have the Microsoft Visual Studio installed on your machine. I had Visual Studio 2008 installed, but this can work with the Microsoft Visual Studio Express edition too
  4. Install the MySQLDB – select the ‘developer’ configuration during install. This will install the required libraries and the header files for the C connector- these are important. Note the directory that you are installing the MySQL
  5. This will install MySQL 64-bit on the machine. I am running Windows 7 64-bit and hence I installed the 64-bit version of MySQL
  6. Extract the MySQL-python-1.2.3 into a directory
  7. Open the site.cfg and make the following modification
    -registry_key = SOFTWARE\MySQL AB\MySQL Server 5.0
    +registry_key = SOFTWARE\Wow6432Node\MySQL AB\MySQL Server 5.5

    Based on the version of the MySQL server, change the 5.5 to whatever is the version you installed. On Windows 7 (and I think on Vista too) 64-bit, the registry key is changed to this location during installation. This took me a long time to find. This has been documented here too – MySQL-Python forum (check for the comment no. 13)
  8. Then modify the setup_windows.py by adding the lib_dirs and include_dirs. Here we add the directories for the C connector that was installed as part of the installation of MySQL. I could not locate the registry key for the connector, so I added the directories for the headers and the libraries to the compiler parameters. Note that I added the opt-imized library directory. If you are debugging the MySQL connector, you will want to include the debug version of the libraries
    library_dirs = [ os.path.join(mysql_root, r'lib\opt'), "C:\Program Files\MySQL\Connector C 6.0.2\lib\opt" ]
    include_dirs = [ os.path.join(mysql_root, r'include'), "C:\Program Files\MySQL\Connector C 6.0.2\include" ]
  9. One final step and you are ready to go. As documented – here, you need to modify the msvc9compiler.py. Look for the line containing
    ld_args.append('/MANIFESTFILE:' + temp_manifest) and add a new line – ld_args.append('/MANIFEST')
  10. Now install the python library using – python setup.py install in the MySQL-python-1.2.3
  11. This will use the Visual Studio compiler and the file mentioned in the include_dirs, library_dirs to build the .egg file for the MySQL-Python libraries
  12. Some more help here
  13. Also can check this on SO though for the 64-bit windows, I found that this solution did not work

Howto use implements in Jython

If you are a Jython beginner and were wondering how to use the implements of Java, then it is very simple. Both extends and implements are part of the inheritance list of the class. For example, if your class extends JFrame and implements an ActionListener, then you can write code like this in Jython. Also look at how the super (the superclass) is invoked. The super is replaced with the name of the base class whose super we are trying to invoke:


class MyClass(JFrame,ActionListener):
def __init__(self):
JFrame("Test title")
....
def actionPerformed(self,ae):
actionCommand = ae.getActionCommand()
//do something based on the actionCommand

If you see the above code, MyClass has the code for both the JFrame and the ActionListener. The actionPerformed method is invoked for any events within the MyClass object.

Pygene howto

PyGene is a genetic algorithm framework in Python. It is a very simple framework with support for multiple classes of algorithms. The examples are very straightforward to understand and one can start off with writing implementations very fast. I suggest looking at the demo_string_char.py file in the distribution. This has a very simple GA implementation to construct a string out of random characters. Even though one can understand from the code, there might be some places where a little more explanation would help.Here is the test client with the appropriate comments (hosted on my site, till I find out how to upload text files on weblogs.us).

Multicast server and client in Python

Python has complete support for sockets. Some of the APIs though have a different signature than the POSIX equivalents. It is therefore possible to write multicast servers and clients in Python. Multicasting is the ability to send data to select set of hosts. Broadcasting in a network is to send data to all the hosts, unicast is when data is transfered between two hosts (typical one-one communication). Multicasting is the ability to send data to a multicast address and the clients are provided the data. Now that an introduction to multicasting is complete, lets look at how to write a simple multicast server and a multicast client.

Multicast servers are written very similar to a standard unicast server, its the clients who have a slightly different code. The major change is made in setting socket options on the socket transmitting and receiving data.
Continue reading “Multicast server and client in Python”

Building PyMedia on Windows

PyMedia is a Python module to enable one play various audio and video formats. Apart from playing the files, one can perform manipulations on the media files too. PyMedia can be used within Kamaelia to test the multicast and brodcast capabilities. I wanted to test these features and so set out to build the latest version of PyMedia. PyMedia, like most of the open source packages, is easy to build on Linux (and may be the other *nixes too). On Windows, its a different story altogether. Below is the description to build PyMedia from the source on Windows. *Beware*, there is a simple Exe installer of PyMedia which works fine, but I wanted to figure out how to build it from the source. So, unless and until you really want to build PyMedia from the source, don’t venture ahead. If you prefer a point and click installer, head to PyMedia on Windows.
Requirements:

  1. Python 2.4 or above
  2. Microsoft Visual Studio .NET’s VC7 compiler. I have tested with VC7 compiler.
    Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.00.9466 for 80×86. Copyright (C) Microsoft Corporation 1984-2001. All rights reserved.
  3. Devenv for opening the solution files and building the dependencies
  4. Download the source files for faad,lame,ogg,vorbis,pylame,pymedia. I have tested with the following versions of the files:
    • faad2-2.0.zip
    • lame-3.97b2.tar.gz
    • libogg-1.1.3.zip
    • libvorbis-1.1.2.zip
    • pymedia-1.3.5.0.tar.gz
  • FAAD2 (Freeware Advanced Audio Decoder) is a MPEG-2, MPEG-4 AAC decoder.FAAD2 is a ISO AAC audio decoder and has a slew of other features. You can download it from here
  • LAME (Lame Ain’t a MP3 Encoder) is used for encoding MP3s. You can download LAME from here.Vorbis is a patent-free lossless audio codec, and Ogg is the container for the Vorbis files. You can read more here and here. You can download the source for the ogg and vorbis here :Ogg, Vorbis
  • Then download the PyMedia source. PyMedia is a Python module for wav, mp3, ogg, avi, divx, dvd, cdda etc files manipulations. You can play these files, do manipulations on them. Get PyMedia PyMedia. Download the PyMedia source and that should be good enough.

Continue reading “Building PyMedia on Windows”

Psyco internals oversimplified

I chanced on Psyco when searching for something on Partial Evaluations. And Psyco is similar to one – but does a lot more. It is, very simply put, a JIT specializer of Python code. Or, more simply put, it compiles python code into assembly code. What differentiates Psyco from the standard JIT environments is its memory. Psyco remembers the code that was generated for certain Python function, for a certain datatype (this is an important thing to note, as explained further) and when the same function with the same datatype is invoked again, Psyco knows that the machine code for this particular datatype was already generated, and uses the machine code, modifying the data value. A simple illustration will look thus:
Python –> Psyco compiler –> Assembly code –&gt Execute –&gt Psyco compiler
Of course there is more to Psyco than this, and I will try to write about it as I understood (thanks to Armin Rigo on #psyco).
Standard disclaimer: I haven’t looked / debugged the code yet, I am still reading the theory behind psyco – so, some of the things might sound vague / incorrect. Please point me to the mistake(s) and they will be corrected. Also there might be lots of other JIT environments for various languages which use this approach. Please point them, and I will be glad to write about them in a different post.
Continue reading “Psyco internals oversimplified”

Python and Oracle connectivity

I wanted to write some test scripts for work. I needed a DB-Agnostic wrapper library for Python. Looking around, I found that SQLObject is a well respected and well used DB access library. This was an interesting lead for me, as using this would have helped me reduce the amount of work to be done. My happiness was shortlived, as I found out, that the support for Oracle is missing in SQLObject. Too bad 🙁 A little more digging did reveal that there is some kind person is working on it. But that, I guess, is going to take a while. Till that time, for me to do anything with Python and Oracle is cx-oracle, which I haven’t explored (and might not) and pymssql for MS-SQL. This might not work out for my requirements – so am dropping the idea of using Python 🙁
Continue reading “Python and Oracle connectivity”

Bangpypers – motm 21st May’05

First things first – always check your mail before you go to any user group meeting. I didn’t and had to travel half way around Bangalore!! I assumed that the meeting was at the ThoughtWorks office on Airport road, and merrily wheeled there, only to find the man at the security desk giving me strange looks. I tried to explain it to him, that there indeed is a meeting and he clearly said saab andhar koyi nahin hein. I thought I will wait, but somehow logic got better of me, and I started looking for a browsing center to check my mail. The darn folks there charged 10 bux for 2 minutes of browsing time, hmmph X-( And when I check my mail, I see that the meeting was rescheduled to Yahoo!. Darn, from Airport Road to MG Road, Saturday evening traffic. All I could do was chal meri luna 🙂
Continue reading “Bangpypers – motm 21st May’05”

Kamaelia – pipe using Python

There is a new category that I have added – Python. Off late I have been spending sometime on this language and I must say, this language is indeed very interesting. Putting aside the arguments about what it is useful for, whether it is ready for ‘enterprise level’ yada yada.., I think this language is a definite plus in your skillset. At least it will let you think about a good design for the data structures you use (in whatever language) and at best – well, errr, go figure out yourself. And drop me a mail if you think you have done real cool things.

Now onto Kamaelia. This is a collection of Python generators, more here and here.

Continue reading “Kamaelia – pipe using Python”