Two Tools for Teaching Children to Code

Why should we teach our children to code?

  • Because it gives them the ability to see what’s going on under the hood.
  • Because it sharpens their logical reasoning.
  • Because it empowers them to create instead of consume.
  • Because they may just like it and someday they might want to make a living out of coding.
  • Because it makes them “cool” among their peers.
  • Because it helps them to work better with computer professionals even if they chose a different line of specialization.
  • Because it is pure fun. Coding gives them instant gratification. Working code can show them magic unfolding in front of their eyes.

I am sure I wasn’t persuasive enough but please give it a try. There are tons of resources out there online to help you choose the right toolkit. It will be a true gift to your children.

To begin with here are a couple of links to checkout. Scratch from MIT is really easy and fun for young kids of age 5-8. App Inventor (created by Google and later donated to MIT) lets you create real Android apps using some of the event driven programming concepts. It is appropriate for ages 9-15. A child who can do Legos can do coding as well with either of these tools. Both are great tools for teaching.

Next Delicacy on the Menu: Python Pickles

Python pickle could be a delicacy that vegans, vegetarians and meat lovers alike might relish. No, I am definitely not talking about the serpentine meat in jars of brine stored for eternity. This pickle is from Python programming language.


Python pickle is an aptly named package that helps us literally “pickle” objects and data from Python code and save it in flat files. This can be reloaded into its original form using the same package. In programming lingo, we call it serialization or marshaling of data, but in simple terms, this is a way of storing data in a format that enables us to resurrect the object if and when required.

Use cases of Pickling
Why we do we need pickling at all in the first place? A few sample uses are listed below:

  • Sending data across a trusted network. You can make data in pickle format and sending through a trusted network, so that the recipient can compose the same objects.
  • If a process takes a long time to do a task, and there are intermittent results available, you can pickle the results into a flat file. If the process goes down for some reason, you could bring up the process, which could reconstruct the object from the pickle file. The process could literally start from where it was left off.
  • Suppose you have a cluster of processes, which work in tandem. One process would take an input, produce an intermittent result and hand off to another process and so on. You could employ pickle to serialize the output objects to flat files and next process in line can pick them up and start processing as if an object that was handed off to it.

How do we use Pickle?

There are inner classes within pickle module and there are many helper functions to dump and load different data types. But essentially there are only two functions within the module. dump() and load(). Using dump() you can serialize data to a file descriptor (an open file, a socket etc.) and load() will help you load the serialized data and return you an object that was dumped before.

Sample Code: Dumping Data

# Dumps a dictionary to a flat file

import pickle
import sys

def main():
    my_data = {"name" : "Python", 
      "type" : "Language", "version" : "2.6"}

    # File opened in binary writable format (wb)
    fp = open("picklejar.dat", "wb")

    # Data is written to the file
    pickle.dump(my_data, fp)

    # As program quits this happens, but just
    # to make code cleaner, we can close the file descriptor.

if __name__ == '__main__':

Let us deconstruct the program. The package pickle is going to do all the heavy lifting for us. We have a little dictionary object that we need to store. First thing to do is to open a file, named as you wish. Remember to open the file in writable binary mode. The data dumped will not be purely printable ASCII format.

Save the code above to and run it.


If you check the file system, you should be seeing a file containing the dictionary.

ls -l picklejar.dat

Sample Code: Loading Data
Now we need to reload the data that was stored previously in pickle jar.dat.


import pickle
import sys

def main():
    # Open the file readonly binary format. Why?
    fp = open('picklejar.dat', 'rb')
    out = pickle.load(fp)

if __name__ == '__main__':

If you execute this program, you will see that the output is written in the same fashion as we had originally saved from our previous example. Cool, isn’t it?

If you have a skeptical mind (that is a good thing) you would be asking questions. It is wonderful to store a dictionary, but I have many data structures, how would I store them? Can we store native data types? What can we store and what we can’t?

One way to store a large number of objects is to create a simple wrapper object – list, dictionary etc – which comprises all the objects that you want to pickle and then dump that wrapper object itself. You can not only store objects, but native variables such as integers and strings can also be stored. But you can’t store methods or classes, obviously. But if you think about it, methods are your logical segments, which comes to life as soon as you instantiate the object itself. The missing element of the puzzle is the data itself, which pickle easily saves and restores.

Like everything else in life, this too comes with a caveat or two.

  • Pickle storage is not secure. If you are planning to send data between machines across a non-trusted network (say internet), never use pickle. There are packages such as Trusted Pickle aka TPickle to help us with this task. It uses public key encryption to sign the pickle data and send. I haven’t used it myself, but here is the link for those who would like to venture out.
  • If you have large number of objects, pickling can be very slow. One reason is that this package is a “pure Python” package. But there is a C implementation of pickle called cPickle, which is a 1000 times faster than pickle itself. If performance is your concern, go for it!

Next time you come across a scenario, where you want to save and recover “states” of objects, give it a shot. Surely worth it.

Photo by Three Points Kitchen

A One-liner Web Server

I have been trying out some mobile web development for practice over the weekend. I have a bunch of HTML files, which I was loading from my main HTML file using AJAX/jQuery load call. The problem with this approach is that jQuery / AJAX prohibits loading a local HTML file from another local HTML file. If you try to access it locally from the file system, you will see a an error similar to what is shown below:

XMLHttpRequest cannot load file://file/path/page.html: 
Origin null is not allowed by Access-Control-Allow-Origin.

One way to resolve this JavaScript error is to host both the files to a web server and access the files from the URL itself. However, for such a trivial task like this, I didn’t want to FTP these files to a remote server or deal with Apache server on my laptop. In any case, once I have the prototype ready, I would be “hosting” these files under the wings of PhoneGap, which is a mobile development framework. (Want to learn more about PhoneGap? Check out “Achieve Mobile Mastery with PhoneGap“)

What is the easiest way to start a web server for this purpose? Well, if you have Python installed in your machine, all it takes to bring up a mini-server is just one line of command. Python comes with an out-of-the-box web server module named SimpleHTTPServer. You can also invoke this from command line. The following steps will help you load your HTML files to an instance of SimpleHTTPServer:

  • From command prompt, change directory to the location, where your HTML files are located.
cd /path/of/the/html/files/
  • Fire up the following command. This will start Python web server, which will be listening to port 8080. You can chose any other available port of your choice.
python -m SimpleHTTPServer 8080
  • Access the URL http://localhost:8080 from a web browser – bingo! you are on the air!

Caution: This solution is only for testing out HTML/JavaScript files. If your involves serious server side programming, you will need a web server like Apache or Tomcat server.

Achieve Mobile Mastery with PhoneGap

If you ever wanted to embark on a mobile development mission and were intimidated by iOS or Android APIs, there is a third alternative. The portable and familiar ground of web programming can bridge the gulf between major mobile platforms. The bridge is called PhoneGap, which I thought would help you develop mobile apps too – with the ease and efficiency of web programming, all the while not losing a lot vitamins from native hardware.

I do not do mobile development for my day job, but I had ventured out a little bit into mobile app development in the past. The main challenge in developing apps for mobile platform is that the platform itself is highly fragmented and the flavors are not inter-operable. For instance, if you would like to develop an app for Apple iOS devices, you need to learn Objective C and iOS SDK to the core. Once you have developed your app from the bottom up, you will realize that not even a single line of code you wrote will ever work for Android, which depends solely on Java language. I am not even daring to talk about Windows Phone OS nor Blackberry but I know just enough to claim that they too use incompatible development frameworks. Each mobile platform created its own ecosystem, in its quest to capture market share by being unique. It appears that the platform independence that we achieved to some extend in the last century with the personal computer revolution was completely erased when we moved forward to mobile computing. A big step back indeed.

A Personal Story
A few years ago, I wanted to develop an iOS app. After many weeks of desperate attempts, I was finally able to get a handle on coding for iOS using Objective C and Xcode. Even though, I was well verse with C coding, I found some of the Objective C features completely non-intuitive. Concepts such as named parameters and SmallTalk-like messages were some what alien to me. Moreover, I found Xcode (Apple’s development environment) as a tool evolved from a primitive era. I am not stating these to start flaming or to create a controversy. It might be purely my inability to get used to different programming paradigms. As a long time developer, who migrated from vi editor to Eclipse IDE, I found it difficult to deal with multiple window system of Xcode (I used Xcode 3.x version or so. Apple somehow glued those Windows up togther when it came to Xcode 4.x) and strange UI development conventions of Interface Builder. After 3 months of intense struggle, I finally shipped my app to the app store. It did not become an instant hit, but it made me feel proud of myself – for a while. In the process, I learned a bunch of things.

I wrote about this experience to point out the struggles of developers to cope with multiple platforms, multiple operating systems and multiple form factors (screen sizes ranging from 3 inches to 10 inches and all possible decimal points in between). If portability were the only determining factor of measuring progress in the world of computing, we would have to admit that “mobile revolution” was a huge step backward, compared to the PC computing. iOS (Objective C/OSX/Xcode/Cocoa touch), Android (Java/Dalvik), Blackberry (C++) and Windows (.NET) chose to travel totally different paths, in their selfish quest to capture their share of mobile market.

Too bad. At least for the mobile developer.

Why Phone Gap?
PhoneGap is a framework that bridges the gap between mobile platforms. It cleverly utilizes web views, which is embedded within a native application. Mobile development for the most part becomes developing a web app using HTML5, Javascript and CSS and package that into a native app (which PhoneGap does semi-automatically).

Exciting benefits of PhoneGap

  • Mobile developers now can develop apps in familiar HTML5/Javascript/CSS platform and PhoneGap compiles them into various mobile platforms. Truly interoperable app development.
  • Obviously time to market is another benefit. As mobile world is evolving quickly, getting apps on the ground as early as possible is critical.
  • Developers can focus on business logic rather than resolving the quirks of OS features.

What is Not-So-Exciting?

  • PhoneGap is a web-based framework. It can do what a browser can do – for the  most part. If your purpose if to build visually jaw-dropping UI experience, go native. HTML is still an evolving platform, but I am sure it will get there in short order.
  • Each mobile hardware has different features. Accelerometer, Gyroscope, camera, NFC, .. the list goes on and on. While PhoneGap has many plugins for some of the hardware features, there are still some gaps. However, you are not entirely out of luck. Developing an OS specific plugin is not out of reach. Such development will be following a hybrid approach – native SDK as well as PhoneGap SDK / HTML, but is surely worth pursuing.

Getting Started
“Okay, I am convinced, what should I do to get started?”. The procedure to get started with your Hello World app is well documented. The following resources will help you to build your first app (how can the first app be anything but “Hello World”?). If you want to develop for iOS devices, you need a MacBook Pro or a similar Apple desktop, Xcode 4.x and a jug of freshly brewed coffee. For Android, you need a PC/Mac/Linux machine. Thats it.

I will write details of how to install and get started with PhoneGap with iOS as well as Android in subsequent posts. I am trying it out myself and I will be glad to share my experiences here. But if you are impatient, please use the link below to dive in.

I believe the mobile holds the key to the future of computing. Pretty soon, computing devices will become wearable too – externally or internally. I also believe that the development platform will go the HTML route as HTML/Javascript platform becomes more mature and become more capable for providing a higher level of user experience.

After a couple of years after my first iOS stint, I am back to trying out something mobile. Things have changed for good in these years. There are more features added to the mobile Javascript libraries. PhoneGap is much more feature-rich than was in 2010. Javascript, especially jQuery, became more mobile friendly. I am on my path to develop another app; this time using Web standards so that I can port it to iOS and Android with ease.

It is going to be entertaining as well as exciting to watch how the mobile landscape evolves.


Path Expansion in Windows Python

One of the issues that I came across while working with Windows is its historical dependency on its DOS legacy. Anyone who tries to get path name from DOS prompt (renamed as command prompt) would recognize rather awkward file names. Path names often return incomplete names. You might often wants to get full expanded file path. For example, if you want to create a temp file with user name expanded. You could use mkdtemp() method from tempfile module in Python, but in Windows, it may return a path such as c:\users\longuser1~n\appdata\local\temp\temp\tmp4567fqx. One way you can achieve is to use ctypes and invoke Win32 APIs. An example code illustrates the concept.

import tempfile
from ctypes import *
tempFile = tempfile.mkdtemp()
buf = create_unicode_buffer(500)
WinPath = windll.kernel32.GetLongPathW
WinPath(unicode(tempFile), buf, 500)
print buf.value

This will return the expanded path c:\users\\appdata\local\temp\temp\tmp4567fqx

Next time, you come across similar problem, give it a try.

Python Unbuffered …

I happen to frequently write many database driven queries embedded within python code. And I love my code to be informative if not interactive. The code should report back to the user the current state instead of putting him / her in a state of software anxiety. You could add many “print” statements in Python, which will print the status at each of the locations. The problem is that Python stdout (sys.stdout) is buffered, which means the output doesn’t come out when you need to see them. Take an example below:

print 'Doing myBigQuery ....',
print 'DONE

One may expect that the code will print Doing myBigQuery .... and once the query is completed, it will append DONE to the same line. On the contrary, most likely, the whole string will be printed after the query is completed. This is the result of buffering of sys.stdout. How to get around this?

There are many ways to do this, but the simplest method is to invoke python interpreter with -u option as in python -u Or, as I would prefer as well, use #!/bin/env python -u at the beginning of code. Alternatively, you can also set the environment variable PYTHONUNBUFFERED. If you really want to flush every time, you can also wrap the print with print() and sts.stdout.flush().

Which ever method you would prefer, this is one simple handy snippet you would find useful, while working with Python.

Available Ports

Often you may want to set up a few servers, which listen to certain pre-defined ports. You may end up searching available ports using netstat. Here is a simple python utility to search and print available ports.

Usage: 1000 2000 will find ports from 1000 to 2000

#!/usr/bin/env python
import socket
import struct, time, sys

def main ():
     start = int(sys.argv[1])
     end = int(sys.argv[2])
     count = 0
     print (‘nn%50s’) % (‘Available ports from ‘ + 
            sys.argv[1] + ‘ to ‘ + sys.argv[2] + ‘:’)
     for port in range(start, end):
          sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
               sock.bind((“”, port))
               if not count % 10:
                    print (‘%6d’) % (port,),
                    count += 1
          except socket.error, msg:
                 sock = None

          sock = None
     return 0

if __name__ == ‘__main__’: