C is for Code

I believe that everyone should be able to program a computer! Now I can see you all rolling your eyes but bear with me for a moment.

We live in the Information Age, computers are everywhere and computer literacy is a skill everyone needs. Unfortunately most people stop short, learning to drive a computer but not really learning to use its full potential.

Now don’t get me wrong, I’m not advocating that everyone become professional programmers. We are strange bunch and you really have to love puzzles and think in a particular way to do coding as job, but the number of times I have seen people perform mindless, error prone, tasks on a computer which could be automated by a simple computer program is astounding. For instance re-sizing hundreds of photos or writing 100 personalized letters, one… at… a… time…

Work smarter not harder is the name of the game!

So what is this “code” stuff anyway ? Well, computers are pretty simple devices, powered by electricity everything comes down to whether something is turned on or off. Programming (or coding) is the process of writing out a set of instructions that you want the computer to perform and then en_coding_ them in to a form that the computer can understand.

In early days of computers this meant that a computer program (a group of instructions) would look like this:

10110100 00001001 10111010 00001000
00000001 11001101 00100001 11000011
01001000 01100101 01101100 01101111
00100001 00001101 00100100

Some poor engineer would need to figure out all these 1’s and 0’s (ons and offs) and then enter them into a computer by either toggling switches or feeding it paper tape with holes punched into it. By the way those 1’s and 0’s above display the text  Hello! on the screen when execute by a computer!.

Clearly this wasn’t productive at all. So the concept of an “assembler” was developed. This would allow a program to be written in a human friendlier way which, could then be assembled into the 1’s and 0’s that the computer could understand. So now you could write the following to print Hello! on the screen, instead of coding up a bunch of 1’s and 0’s:

start:
        mov     ah,9
        mov     dx,hello
        int     21h
        ret

hello   db      'Hello!',13,36

This is much better…not! At least it vaguely looks like English but its still not really easy to understand. Luckily 3rd generation “languages” were developed which, meant that programs could be written in English (with a very strict grammar) and then “compiled” into the 1’s and 0’s needed by the computer. Our program to display Hello! on the screen now just becomes:

print "Hello!"

Much simpler!

A crash course in how programs work

A computer program contains 4 different things:

Statements – Instructions to do something. For example the print statement we saw above or

1+1

Which adds 1 and 1. These can be combined, so the following prints out 2 on the screen:

print 1+1

Loops – Instructions to do something a number of times. For example to display the numbers 1 to 10 on the screen:

for count in range(1,11):
    print count

Conditionals – Instructions to do something, if something is true. For example:

if 1+1 == 2:
    print "The answer is 2!"

Variables – Places to store things (data) needed by the program. For example

answer = 1+1
print answer
answer = answer + 40
print answer

Which:

  1. Adds 1 and 1 and stores the result (2) into a variable called answer
  2. Displays the value of answer on the screen (2)
  3. Takes the value of answer, adds 40 to it and then stores the result (42) back into the variable called answer
  4. Finally displays the value of answer again on the screen (42)

Tada! You’re programming

Its remarkably easy and with a little bit of study, you can save yourself hours of time or even write yourself that smartphone app you have also wanted. If you are interested in learning more about programming, the Internet is chock full of resources. I’d suggest you check out the Codecademy or The Khan Academy sites to get started. The examples above were written using a language named Python (named after the Monty Pythons) which is particularly easy to learn, but it is only one of many different computer languages.

Oh yes and those tedious tasks I mentioned at the start of this post, here is how you would solve them in Python:

# Python program that resizes all the .jpg images in a folder named "photos"

# load some "modules" that tell the computer how to manipulate files and images
import glob
from PIL import Image

# we want to resize images to 640 by 480 pixels
size = (640,480)

# grab a list of the .jpg files in the photos folder
photos_to_resize = glob.glob('photos/*.jpg')
print "Resizing: " + str(photos_to_resize)

# resize each photo in the folder and save the resized photo
for photo in photos_to_resize:
    resized_photo = photo[:-4] + "_resized.jpg" # create name for the resized photo
    im = Image.open(photo) # open the photo
    im.thumbnail(size, Image.ANTIALIAS) # resize the photo
    im.save(resized_photo, "JPEG") # save the photo
    print photo + " resized and saved as " + resized_photo

and

# Python program that generates a personalised letter for a list of people
# it generates a word document with one letter per page

# load a "module" to tell the computer how to create word documents
from docx import Document

# the list of people that we want to create letters for
names = [
'Emma',
'Charlotte',
'Ella',
'Sophie',
'Hannah',
'Emily',
'Jessica',
'Olivia',
'Grace',
'Isabella'
]

# create a new word document
document = Document()

# for each name in the list create a letter
for name in names:
    document.add_paragraph( "Dear %s," % name) # add the salutation

    # add the rest of the text
    document.add_paragraph( "Thanks for your interest in the Acme 2001 Widget. We are pleased to announce that these are now available for sale.")
    document.add_paragraph( "As a valued customer you can purchase one with a 25% discount!")
    document.add_paragraph( "Yours Sincerely")
    document.add_paragraph( "Horace P Sweet")

    # add a page break so we get one letter per page
    document.add_page_break()

# save the word document
document.save('Letters.docx')

ScanPaste – My first app released to the Android Market

Last week I released by first Android application on the Android Market. It is called ScanPaste. The application lets you scan barcodes and then  copy the scanned data to the phone’s clipboard for pasting into web pages, emails etc.

I had been looking for a simple app to build, to test out the end to end Android Market publishing process and when I saw this blog post by about populating your Google books list using barcodes scanned with a USB scanner, I figured why not build an Android app to do it.

Now scanning barcodes with a phone’s camera is not that simple but luckily someone else has done all the hard work. The ZXing team have released an excellent barcode scanning application and library. Even better, using a cool feature of Android, integrating barcode scanning into ScanPaste was only a few lines of code!

In an Android application each screen is broken down into it’s own little task called an Activity. If an Activity is correctly “marked” it can be initiated not only by the application owning the Activity but by other applications. This is what the nice guys on the ZXing team have done and with their application installed, any other application can simply use the following code to scan and process barcodes:

...
// start the scan
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);
...
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
  if (resultCode == Activity.RESULT_OK && requestCode == 0)
  {
    Bundle extras = data.getExtras();
    String result = extras.getString("SCAN_RESULT");
    // do stuff with result here
  }
}

The rest of the app is pretty straightforward, a couple of buttons, a text field and some error checking. All up the application is less than 100 lines of code.

In all it took a few hours to put together and test. The bulk of the time was actually spent working on the icon :) The 1.5 Android platform has some pretty clear guidelines and I was trying to adher to them.

Building a signed app for upload to the Market was a snap, just a menu click and a step by step wizard. Actually publishing the application was as simple as uploading the signed .apk file, filling in a form and clicking on upload. Couldn’t be simpler especially when you compare it to the nightmare process of uploading an iPhone app to the iPhone App store and of course the Android Market doesn’t have a vetting process so as soon as the upload was complete the application could be downloaded by anyone.

One of the things that took me by surprise was that within half an hour the application had been downloaded 20 times. A week later it has been downloaded 1849 times and it has 1156 active installs! It also has a 4 12 star rating and all positive comments. From the comments it seems that many people are using the app to scan the barcodes of books that they are selling on Amazon.

Ok the bad stuff….

Firstly, a minor one,  in the developer console of the Market there is no way to see the comments about your application. You can see the rating and the number of ratings but that is it. Instead you need to look up the app in the Market application on your phone or view a 3rd party site like Cyrket (which apparently uses the Market’s own APIs so why the info cannot be surfaced in the developer console is beyond me).

Now for the killer…since I am in New Zealand I cannot sell any Android applications! I need to be in the US, UK or one of a couple of other countries to be able to sign up as merchant. What the heck is up with that? I see that as a major shortcoming of the Android platform and one that Google needs to rectify ASAP.

Hopefully with the imminent launch of the HTC Magic here in New Zealand this will change. Lets wait and see….

XUL the “forgotten” RIA technology

I started building my first Firefox extension last night and as a result I had to dig into XUL (pronounced zool, al la Ghostbusters).

XUL is the “XML User Interface Language” and is technology of the cross-platform GUI used by Mozilla products such as Firefox and Thunderbird.

Now I have been aware of XUL for years but haven’t really thought about it much until I clicked on the XUL Periodic Table example  that I suddenly realized that XUL makes for a pretty swanky RIA platform (not too mention it was around years before the others).

Not only does it use common technologies (XML, HTML, CSS, JavaScript, AJAX) but it “just works’ which I particularly love in a technology and as a bonus it is open source.

Of course if you clicked on that XUL Periodic table example above using Internet Explorer then of course it would not have worked since IE doesn’t support XUL which of course is a bit of a problem.

Having said that there is XULRunner which lets you run standalone XUL based applications (kinda like Adobe Air).

XUL use isn’t limited to Mozilla products check out Songbird (Media Player) , Miro (Internet TV) or Celtx (Script writing & preproduction tool), which all use XUL.

I wonder how hard it would be to get the XUL engine installed as an IE helper application for .xul files? Maybe something else for me to play with :)