Modelling Gravity in Scratch

With school holidays upon us, and one week until the next CoderDojo, I thought I’d set a Scratch challenge!

I thought we could create a clone of a game I played and loved when I was 12 – Thrust!

Here’s a video of this awesome game from 1986 – although by modern standards, it’s a bit basic.¬†

(By the way, here’s a JavaScript clone of the game ūüôā¬†

Now the physics going on in this game are a little complex to start with, so maybe we should start with something a bit simpler – maybe… [delves into computer game history…. and picks out…] Tanks!¬†

This might not look like much, but it will get us some of the basics of physics.¬†And show it to your parents, and they might get all nostalgic ūüôā

Let’s get started!

So how do we start modelling this kind of physics in Scratch? There are lots of ways, but let’s start with a simple approach – basically when something falls, it accelerates toward the ground, so it will start at 0 kph, and then speed up, 1 kph, 2kph, 3kph, etc. In real life, it will be travelling around 32kph after one second of free-fall. We won’t bother about stuff like terminal velocity yet (that’s what stops a parachutist from carrying on accelerating much past 200kph, due to air resistance).

We can model this by using a variable, let’s call it vy¬†(for velocity y – you can call it what you like),¬†¬†and set it to zero. Fire up Scratch and start a new project at, select the¬†data Scripts palette, and click¬†Make a variable. Give the variable the name vy, choose¬†For this sprite only, and click OK.

Creating new variable

Creating new variable

Insert a When green flag clicked block from the events palette, and under it we’ll set y = 0¬†(from the Motion palette,¬†and set vy =0 from the¬†data¬†palette. This means when the green flag is clicked, we’ll set the y position (or height) of our cat sprite to zero (this is in the middle of the screen – more on this later), and we set our y velocity variable to zero – e.g. we’re staying still.

Then we’ll create a forever block from the control palette, and inside that block, add a¬†change¬†vy¬†by -0.1 from the data¬†palette. Then we’ll grab a change y by¬†block from the¬†motion¬†palette, and add the¬†vy variable from the¬†data palette. This means we’re decreasing our velocity (increasing our speed downwards), and moving the sprite based on our velocity.

First draft of code

First draft of code

Press the Green flag to give it a go. Try changing the value in the change vy by block Рwhat happens?

Here’s a copy of the code:¬†

But that’s not really what happens when things fall, is it? Things bounce when they hit the ground. So¬†let’s detect when we hit the ground… we need a few new blocks here:

  • an if block from the control palette
  • two less than¬†(<) blocks from the operators palette
  • an and block from the operators palette
  • the y position block from the motion palette
  • and a vy variable from the data palette

Drag the if block onto your canvas, and insert the and block. In the left part of the and block, insert one of the less than operators, and inside this, insert the y positionin the left hand side, and type -130 in the right hand side.

In the right hand side of the and block, insert the second less than operator Рin this one, insert the vy in the left hand side, and type 0 in the right hand side.

if block, and, < operators

if block, and, < operators

So what is this doing? It’s saying, if the y position (or height) of the sprite is less than -130,¬†and vy is less than zero (e.g. we’re moving downwards), then do something. The y value will vary from the bottom to the top of the stage, with the middle being zero. The top and bottom are -180 at the bottom to 180 at the top. Take a look at Scratch’s coordinate system¬†¬†for more info. So if the bottom of the stage is -180, why are we using -130? That’s because we’re checking the centre of the sprite, not the bottom – so if the centre of the cat sprite is at -130, then the cat’s feet are about -180.

Scratch’s coordinate system

So we’ve touched the ground, now what? We need to bounce – and we can do that by changing our speed so the cat moves in the opposite direction. I use the term speed here, but as we’re measuring the magnitude of a speed in one direction (up), we’re actually measuring¬†velocity using a vector.

So if we multiply our velocity by -1, this will change our direction from down to up. It’s also a good idea to set the position of the sprite to -130 – this is in case the sprite has moved slightly below -130 before our check and puts it back at ground level.

Take the whole if block, including the set vy and set y blocks as below, and add it under the change y by block. Here’s our code:


Bouncing of the ground code

Try this out, and see what happens. There’s something wrong with the bouncing though… when did you last see something bounce like that? And how do you think we could fix it? Create a remix and see how you can tweak it.

Here’s a copy of the project:

Next steps

Next step in a couple of days will be to change from a bouncing cat to something more spacey… like a rocket we can steer ūüôā

Further Reading

Here’s a really good, but quite in depth, introduction to Gravity at Khan Academy:¬†

Leave a comment

Filed under Teaching kids to code

Teaching kids electronics using wooden blocks

Here is a great post at makezine, describing how Paul Marlier at the Children‚Äôs Museum of Pittsburgh has put together a “set of wooden blocks with electronics on them that museum visitors can connect up in any way they like”. Inspired by this, I recently put together a similar set of wooden blocks for my son Ethan, aged 5.

I had an electronic set (like one of these) as a kid in the mid-80’s, and it was great fun. But as Paul says in the Makezine article, he “chose this simple design over commercial products because he wanted to emphasize that these are just parts that anyone could find and put together”. I agree, as these commercial sets, like the one I had as a kid, hide away all the bare components, and in the process, add a level of magic, further distancing you from what’s going on under the hood. This subtly further ingrains the belief that what’s going on under the hood is too complicated to understand, and encourages kids to assume that nicely packaged sealed components are better to use that the basic electronic components. (Of course, I’m ignoring the fact that all those “basic electronic components” are themselves often amazingly complicated devices sealed and packaged themselves – but I hope you see the point).

So, did Ethan enjoy it? I would challenge you to find any 5 year old boy who wouldn’t like to pick up a jumble of wires, LEDs and a “missile” switch, and go for it!

Ethan experimenting with LEDs

Some more pictures of my setup, and others of the original setup in Matt Met’s photostream.

Leave a comment

Filed under Uncategorized

Searching for text in MSSQL stored procedures

Simple 5 minute tip here, but I’d done this ages ago and forgotten how to do it.

Suppose you know somewhere in the multitude of stored procedures in the database you’ve inherited that there’s likely a reference to a field or table, and you don’t know where it is. How do you find it without going through each stored procedure and checking it?

Easy. The definitions are stored in the system tables, just like pretty much all structure of a MSSQL database, so we just take a look in those tables, or the INFORMATION_SCHEMA views.

There’s a few different ways of getting at the information, but let’s say you’re looking for references to the field email, and the table Organisation:

SELECT		routine_name, 
FROM		information_schema.routines
WHERE		routine_definition LIKE '%email%'
AND		routine_definition LIKE '%Organisation%'

		OBJECT_DEFINITION(OBJECT_ID) as Routine_Definition
FROM		sys.procedures

or all references to a different email field that include no reference to the Organisation table? This one’s a bit more likely give false negatives – e.g. the procedure may reference the Organisation table in some way not related to the email field. But you get the idea.

SELECT		routine_name, 
FROM		information_schema.routines
WHERE		routine_definition LIKE '%email%'
AND		routine_definition NOT LIKE '%Organisation%'

Leave a comment

Filed under General

IT education in schools

A recent post by Liz Quilty echoed my thoughts, following Google’s Eric Schmidt’s recent criticism of education in the UK. I don’t agree with everything Schmidt says, but I’m surprised that this hasn’t already been addressed if it’s really as bad as I fear it is.

I’ve been getting more and more depressed with what I suspected was happening in IT education – certainly in the UK, and it appears too here in NZ – I recently started looking into schools here for my 6 year old (some years away) – and was saddened, but not surprised, to find a class masquerading as IT but really sounding more similar to the European Computer Driving License, basically teaching office computing skills.

The driving lesson analogy works quite well here – it’s like claiming you’re teaching mechanic and metal work skills, when what you’re actually doing is teaching someone how to drive a car. Both valuable skills, but I wouldn’t like to live in a country that didn’t have any mechanics.

I’ll admit, teaching kids ECDL type lessons may still be useful – I’m sure that there are still a significant (but I suspect continuously decreasing) number of young people who still are intimidated by IT, but realistically, computers are one hell of a lot less intimidating than say even 10 years ago, and I imagine these classes are frankly a waste of time for 80+% of pupils.

I’m one of the generation that benefited from the BBC – I remember programming on Commodore PETs back in the mid 80’s, and then on the ground breaking BBC Master Series – these machines I’m sure encouraged a fair few of us to get really interested in computers.

It seems strange that when comparing how quickly you can both learn how to, and actually implement, vastly more complex and cool functionality than we could dream of 20-25 years ago, teachers seem to be shying away from programming and real IT, which should surely be far more accessible to young kids?

Bruce Clement has posted similar thoughts too.

Tim Foster also pointed me to a great article in the Guardian – Kids today need a licence to tinker

So anyway, I’ve started showing my daughter scratch – it seems to be the Logo of the 2010’s. Although secretly I suspect she’ll be a musician anyway!


Filed under Rant

Moving from VMWare Server 2 to VMWare ESXi 4.1 – a walkthrough

I’m sitting here gradually migrating a bunch of VMs on to our new server running VMware vSphere Hypervisor¬†Based on ESXi. It’s taking a little while, and I got a bit flummoxed at a couple of points so I thought I might document what I had to do in order to get it all working.

There’s nothing really complex here, but I found it confusing in a number of places, so hopefully this may be of use to others – it will certainly be a memory aid for me in the future.


We have an old Windows server the free running VMware Server 2 administered via VMware Infrastrutcure Web Access. There are some peculiarities if you want to run a console window in Firefox, but it generally works well, and is free, so I can’t really complain.

Whilst we’re doing this migration, we’re also looking at consolidating software licenses, an obvious candidate is the host machine running VMs – in this case I could either run VMware Server on Windows or Linux, or look at VMware vSphere based on ESXi. I’ve run VMware Server 2 on Ubuntu before – it was a bit of a nightmare and took a couple of days to get working properly, so I was keen to see if ESXi was any better. ESXi also runs bare metal as opposed to on top of another operating system, so there should be some performance benefits too.

So, VMware vSphere ESXi it is then.

All of the VMware software we’re using below is free, but you’ll have to register in order to download it.

Continue reading


Filed under Virtualisation

Redmine sub project support

One of the things I really like about Redmine (and Git), compared to Trac and Subversion, is the out-of-the-box support for multiple projects.

The web interface in Redmine makes it pretty easy to bulk move issues to new projects, as I was doing earlier today. Whilst it manages issues, relationships between issues, and time entries against issues, one minor thing it doesn’t seem to let me do through the web interface is move time entries that are not associated with an issue/task to a new project (for example, I have certain project management and deployment activities that are not related to a particular issue or task in Redmine).

In order to do this, I had to get into mysql. This is all some pretty basic SQL, but I thought I’d jot it down incase it’s of use to anyone.


First, and it goes without saying, but I will anyway – take a backup!

lhunt@vm-srv052:~$ rsync -a /var/www/redmine/files /backup
lhunt@vm-srv052:~$ /usr/bin/mysqldump -u redmine -predmine redmine > /backup/db/redmine.sql

Now, get a list of Projects:

mysql> select id, name, parent_id from projects;
| id | name                  | parent_id |
|  1 | Project X             |      NULL |
|  2 | Sub project 1         |         1 |
|  3 | Silverlight migration |         1 |
|  4 | Version 2             |         1 |
4 rows in set (0.00 sec)

Then review all those entries without the correct sub-project associated to with them, in this case, everything still associated with the original parent project, Project X.

mysql> select id, project_id, spent_on, comments  from time_entries where project_id =1 ;
| id  | project_id | spent_on   | comments                                |
|  22 |          1 | 2010-10-29 | comments related to ticket...           |
|  27 |          1 | 2010-11-01 | Some more comments related to ticket... |
|  .. |         .. | .......... | ....................................... |
|  .. |         .. | .......... | ....................................... |

In my case, I had a minority of entries that should now be associated with the new Silverlight migration sub-project I’m working on….

You could do this by picking individual entries, or by searching the comments…

mysql> update time_entries set project_id = 3 where id in (102, 106, 109, 110);
Query OK, 4 rows affected (0.03 sec)
Rows matched: 4  Changed: 4  Warnings: 0

mysql> update time_entries set project_id = 3 where comments like '%silverlight%';
Query OK, 5 rows affected (0.03 sec)
Rows matched: 9  Changed: 5  Warnings: 0

And the rest should be associated with a new sub-project for a piece of stabilisation work…

mysql> update time_entries set project_id = 2 where project_id = 1;
Query OK, 38 rows affected (0.04 sec)
Rows matched: 38  Changed: 38  Warnings: 0


Update 24 Dec

Err – I lied – it wasn’t completely done – I had some Documents that were referenced by Title rather than ID, which then failed to link across projects.

Quick fix:

mysql> select id, project_id, title from documents;
| id | project_id | title          |
|  1 |          1 | V1.3.3.3 ..... |
|  2 |          1 | Training Env.. |
|  3 |          1 | V1.3.3.4a .... |
|  4 |          1 | Flow diagram.. |
|  5 |          1 | 20101203...... |
|  6 |          1 | Training Env.. |
|  7 |          1 | V1 3 3 4b UAT..|
7 rows in set (0.00 sec)

All the documents needed to be moved to the Stabilisation project, so again a really simple bit of SQL…

mysql> update documents set project_id = 2;
Query OK, 7 rows affected (0.10 sec)
Rows matched: 7  Changed: 7  Warnings: 0

Leave a comment

Filed under Git, Open Source, Redmine, Uncategorized

Installing a headless GeoServer on Ubuntu 10.4 on Amazon Web Services – part 1

There are a few good articles out there documenting how to get a headless GeoServer box up, and some great documentation out there for Ubuntu on AWS, but nothing covered exactly what I was trying to do in one place, so I thought I’d document the steps necessary to get GeoServer running on Ubuntu 10.4 (Lucid Lynx) hosted on Amazon Web Services.

N.B. At the end of this you should have an Amazon Machine Instance running GeoServer suitable for playing around with. What you will not have is a strongly secured performance optimised GeoServer box – hopefully that will be covered in a following post.

This post also assumes you already have an Amazon Web Services account.

Creating our instance

I’ve tried doing this setup with the default Fedora AMIs from Amazon, but I haven’t used Redhat in a few years, and I’m more familiar with Ubuntu, so the first step is to get a trusted Ubuntu instance to start from.

First step – grab an AMI with Ubuntu 10.4 – Ubuntu’s Public Cloud Deployment documentation lists the Amazon EC2 published AMI’s – I’ll be using the 32bit EBS image on the US West Coast (ami-cb97c68e), as I’m just wanting a small instance (the 64bit are larger, and cost more), I may want to be able to stop the instance without loosing it completely, and as I’m in New Zealand, I suspect the US West Coast will have lower latency than Singapore.

So, let’s create our Instance. Head over to Amazon Web Services EC2 Console Dashboard, and click Launch Instance.

  • In the Choose an AMI tab, click Community AMIs, and enter ami-cb97c68e in the text box next to Viewing / All Images.
  • Press Enter, and the Ubuntu AMI ami-cb97c68e should be listed. Click Select.
  • The Instance Details tab appears, you can leave the defaults selected here. Click Continue.
  • Under Advanced Instance Options,¬† you may want to click Enable CloudWatch Monitoring for this instance, though note that this costs extra – you can leave this unchecked and add it later if you wish. Click Continue.
  • In the Create Key Pair tab, either select a preexisting key pair, or create a new pair. I’ll creating a new key pair called geoserver – enter geoserver in the name for keypair text box and click Create and Download your Key Pair. Save the .pem file to somewhere safe.
  • In the Configure Firewall tab, as we’ll be running GeoServer on top of Tomcat on port 8080, we’ll select Create a new Security Group. Name the Group, and add the following ports: HTTP (TCP, 80), and SSH (TCP, 22). We’ll also need to add Tomcat (TCP, 8080), but we’ll need to set this up as a custom rule later on.
  • Click Continue, and we’ll be at the Review tab. Check everything looks OK, and click Launch. You can now click Close, and click on the x Security Group(s) link under My resources.
  • Select the GeoServer security group we created earlier, and add the Tomcat rule (Connection Method: Custom, Protocol: TCP, From Port: 8080, To Port: 8080, Source (IP or Group): Click Save.

Within a few minutes, the machine should be up and running on the web. Now we need to connect to it and do some installation.First we need to get the public DNS address of the machine:

  • Go back to the EC2 Console Dashboard, and click on the x Running Instance(s) link under My Resources.
  • Right-click your new instance, and select Connect.
  • In the popup that appears, the public DNS will be listed – something like

Depending on what platform you are using locally, there are two ways to connect. (Well, actually there are loads, but I’ll focus on Windows and Ubuntu).

Connecting from an Ubuntu Linux box

  • Locate your private key file, geoserver.pem
  • Use chmod to make sure your key file isn’t publicly viewable, ssh won’t work otherwise:
    chmod 400 geoserver.pem
  • Connect to your instance using instance’s public DNS.
    ssh -i geoserver.pem
  • Answer yes when warned about authenticity of the host and asked if you want to continue connecting.
  • You should see something like this:

leigh@deep-thought:~$ ssh -i geoserver.pem
The authenticity of host ' (184.72.xx.xx)' can't be established.
RSA key fingerprint is f5:f5:0c:2e:77:9f:6a:82:3a:33:8c:99:5a:65:e2:09.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ',184.72.xx.xx' (RSA) to the list of known hosts.
Linux ip-10-160-43-6 2.6.32-305-ec2 #9-Ubuntu SMP Thu Apr 15 04:14:01 UTC 2010 i686 GNU/Linux
Ubuntu 10.04 LTS

Welcome to Ubuntu!
* Documentation:

System information as of Wed Jun 16 21:59:44 UTC 2010

System load: 0.06 Memory usage: 2% Processes: 54
Usage of /: 4.6% of 14.76GB Swap usage: 0% Users logged in: 0

Graph this data and manage this system at
At the moment, only the core of the system is installed. To tune the
system to your needs, you can choose to install one or more
predefined collections of software by running the following

sudo tasksel --section server

0 packages can be updated.
0 updates are security updates.

The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.

To run a command as administrator (user "root"), use "sudo ".
See "man sudo_root" for details.


Connecting from a Windows box using PuTTY.

  • PuTTY doesn’t use .pem files for authentication – instead we need to create a PuTTY private key file (.ppk) using the PuTTY Key Generator (PuTTYgen). A guide to doing this can be found here, but the steps required are.
    • Download and run puttygen.exe from the PuTTY download page.
    • Click Conversions->Import Key Pair, and select your .pem file. Click Save private key. You can password protect it at this point if you like, however in my humble opinion, you probably don’t need to if you treat this file with the same care as you would the .pem file. We’ll save the file as geoserver.ppk.
  • Fire up PuTTY, and enter the public DNS in the (Host Name or IP address) text box.
  • In the Category tree, select Connection->SSH->Auth, and Browse for the Private key for authentication, selecting our newly created.ppk file.
  • Go back to the Session category and save this session if you like, and then click Open.
  • Click Yes when warned about verifying the identity of the server, asked if you want to continue connecting.
  • Login as the user ubuntu.
  • You should see something like the following:

login as: ubuntu
Authenticating with public key "imported-openssh-key"
Linux ip-10-160-43-6 2.6.32-305-ec2 #9-Ubuntu SMP Thu Apr 15 04:14:01 UTC 2010 i686 GNU/Linux
Ubuntu 10.04 LTS

Welcome to Ubuntu!
* Documentation:

System information as of Wed Jun 16 22:32:12 UTC 2010

System load: 0.99 Memory usage: 2% Processes: 56
Usage of /: 4.6% of 14.76GB Swap usage: 0% Users logged in: 1

Graph this data and manage this system at
At the moment, only the core of the system is installed. To tune the
system to your needs, you can choose to install one or more
predefined collections of software by running the following

sudo tasksel --section server

0 packages can be updated.
0 updates are security updates.

Last login: Wed Jun 16 21:59:45 2010 from
To run a command as administrator (user "root"), use "sudo ".
See "man sudo_root" for details.


Installing necessary packages

We’ve now got a vanilla Ubuntu instance running, and we’re connected. Now let’s install the packages necessary to get GeoServer up and running.

  • From the terminal, execute the following:
  • sudo apt-get install unzip lynx tomcat6 tomcat6-admin
  • sudo vim /etc/default/tomcat6
    Find, uncomment and modify the following lines:

JAVA_OPTS="-Djava.awt.headless=true -Xmx512m"

  • sudo vim /var/lib/tomcat6/conf/tomcat-users.xml
    Modify to contain the following, substituting your own super strong password. Be sure to remove any comment block surrounding the <tomcat-users> section if one exists. (Thanks to jvangeld)

<role rolename="admin"/>
<role rolename="manager"/>
<role rolename="tomcat"/>
<user username="tomcat6" password="some super strong password" roles="admin,manager,tomcat"/>

  • sudo /etc/init.d/tomcat6 restart
  • We’re now ready to login to Tomcat’s administration interface and install GeoServer.
  • Download the Web Archive from GeoServer’s Stable download page.
  • Unzip the downloaded file.
  • Browse to your new instance’s tomcat administration interface, e.g.
  • Log in using the tomcat6 and some super strong password username and password combination specified earlier.
  • Under WAR file to deploy, upload the unzipped geoserver.war file you have just downloaded, and click Deploy.
    • This file is about 40-50MB in size, so this step can take a while depending on your connection speed. You’re waiting to see both the message OK in the top of the window, and /geoserver being listed under the Applications list on the Tomcat Web Application Manager.
  • Browse to your GeoServer instance, e.g.
  • To check things are OK, lets do a sanity check by clicking on Layer Preview link in the left hand pane.
  • At the bottom of the list of configured layers, there are some entries named tasmania, spearfish and tiger-ny, next to which are some OpenLayers links. Click the spearfish link, and you should get a simple OpenLayers interface showing some test data.
  • Click on the tiger-ny OpenLayers link, and you should get a simple map of New York…
    • …except you won’t – you’ll get a bunch of blank image tiles in an empty map. This threw me for a bit, so I had to delve into the GeoServer error log. You can skip to the solution below, but if you want to see where some of the error information is logged, see the steps below.
      • Open up a terminal session to the server if necessary, and type the following:

        vim /var/log/tomcat6/catalina.out

        You should see, near the bottom of the log file, some telltale entries like the following:

        16 Jun 23:29:42 ERROR [geoserver.ows] -
        org.vfny.geoserver.wms.WmsException: org.vfny.geoserver.wms.WmsException: Rendering process failed
        at org.vfny.geoserver.wms.responses.GetMapResponse.execute(
        Caused by: java.lang.Error: Probable fatal error:No fonts found.
        at sun.font.FontManager.getDefaultPhysicalFont(
        at sun.font.FontManager.initialiseDeferredFont(

      • Google came to the rescue – this being a headless server, it has no fonts installed.
      • In order to find out what fonts Java is expecting, type the following:

        vim /etc/java-6-openjdk/

      • This yields the following line amongst others:

        serif.plain.latin-1=DejaVu Serif

    • To install the missing DejaVu font:

      sudo apt-get install ttf-dejavu
      sudo /etc/init.d/tomcat6 restart

    • Try the New York map again, and you should get a map of Manhattan.
  • Note that the maps being displayed are non-tiled, and generated every request. Click the small menu icon in the top left of the map to enable tiled mapping (taking advantage of local caching), and change the map canvas size.

Next steps

I’ve kept this short so that it details the absolute minimum steps required to get GeoServer up and running on an AWS Ubuntu instance.

So the next few bits – I need to get working are:

  • Getting some base map data – ideally I’d like to get this from OpenStreetMap‘s OSM export facility, probably using osm2pgsgl. I haven’t got this working yet,¬† so in the meantime, I’ll probably download some Shapefiles from the great koordinates repository, which has loads and loads of data, especially for New Zealand.
  • Running direct from PostGIS is going to be a better solution than from Shapefiles, and more manageable.
  • Then, I need to import some TFW raster files, probably using something like GDAL.
  • Making use of GeoWebCache to pre-render and cache map tiles on the server.
  • Last, but not least, securing and optimising the installation.

Hopefully I will write up these steps in the coming weeks.

Some other useful references:


Filed under Uncategorized