One night in Toronto

A few years ago, Chrissy and I took our first trip to Toronto. We were there to see Christopher Moore at a book signing. We had arrived in the very early morning, so the owner of the guest house where we were staying had left us a key and a note on how to find our room. We followed the instructions and went up two flights of stairs before making our way through what we thought was our room door.

Upon unlocking and opening the door, we discovered a narrow, creaky staircase lined with some interesting paintings. At the top of the staircase was a bathroom with a large, old jet tub, a toilet by a window (where nothing could be left to the imaginations of the neighbours), and a large, terrifying clown behind a plant. The bathroom looked like it could have been a happening place for swingers some time in the seventies.

We continued past the bathroom along a short landing, strange paintings and knick-knacks surrounding us. On the back of the door hung a small pair of children's fairy wings from a costume, along with some bridal equipment. Dust covered everything and the air smelled of musty books. We opened the door.

The bedroom was packed with stuff. In the words of Stefon from SNL, this place had everything: creepy paintings, old woolen blankets, VHS tapes, CRT TV, sixties furniture, orange shag-pile carpet, and a horizontal head rush. What's a horizontal head rush? It's that thing where the floor slopes inward such that the head of the bed is lower than the foot.

Chrissy wanted to immediately head back out and find a different hotel. I, however, was exhausted and wanted to sleep, even if it did mean ignoring all the signs that we had entered the Twilight Zone. I persuaded Chrissy to stay and we went to bed. As the blood rushed to our heads and our feet became icy cold, little flecks of dust and paint rained down on us from the paintings above us and we did our best to fall asleep.

The next morning, we went downstairs to the dining room. A large round dining table was beautifully laid out. It felt like we were staying at the house of an eccentric relative. The room had a high shelf that was lined with teapots of varying shapes, sizes and colors. It was there that we ate a delicious breakfast cooked by the proprietor and one of his friends. We also got to meet some of the other guests who were staying; they seemed equally as eccentric as the house.

From the dining table, we could see the kitchen. Actually, that's a lie, we could see some of it. The bits that were not underneath something else. It was no place for the squeamish and I decided it would be best to just not look, that way we could enjoy the food.

In fairness to our host, we had a wonderful stay thanks to their courtesy and hospitality, and that of his friends and guests, but there is no way my words, nor the photos below can do justice to the wonderful time capsule in which we stayed. The house could have served well as the backdrop to a Dickens adaptation or perhaps a Hammer Horror. It will stay with me for a long time.

Controlling a bot using node.js and express

Last week was our work hackathon. During these events we get to spend a day hacking around with something fun, whether it is work related or not. Thanks to my friend and colleague, Brian Genisio, this time around we got to tinker with hardware and build some bots.

Using node.js, johnny-five, an Arduino Uno board and a bunch of additional components, teams created their own sumo bots. At the end of the day, we competed to see who had the best bot. Ours was the only bot that walked instead of using wheels and we were confident our design could have won. Unfortunately,  we faced some technical difficulties and a couple of design issues that prevented us from achieving our full potential. You can see our bot (it's the large gold one that lumbers in from the bottom) take on all the others in this video and slowly start pushing them all out of the way.

http://youtu.be/pW6t5qfsc4g

As I am sure you can tell from the audio, this was a thoroughly enjoyable and highly competitive hackathon. There were a variety of problems to address as we developed our bots. Some of them were unique to the bot being created, others were comment to all. One such problem was how to control the bot. Regardless of how the signal got to the Arduino board (Bluetooth, RF and USB were available), we had to command our bots to move forwards, backwards, left and right (and in some cases, to deploy an extensive range of weaponry and distractions).

After some trial and error, I settled on using a simple web server and web page front-end that made API calls to the server. The server would then map these API calls to bot controls. This provided a way for us to use mouse, keyboard and touch input to control our electronic sumo minion. You can see the very basic user interface1 in this Vine that I took during our build.

https://vine.co/v/Ounjjiu6Br5

Using AngularJS, the buttons in the web page were connected to API calls. By clicking buttons in the web page, using the numpad or AWSD keys, or touching the screen of my laptop, we could control the robot. The API itself was implemented using the Express package in node.

Express

I installed express into our node application, using npm:

npm install express

Then I added express to our bot code and defined a simple API to process web requests:

var express = require("express");

var app = express();

app.post('/move', doMove);
app.post('/rotate', doRotate);
app.post('/stop', doStop);

app.use(express.static(__dirname + '/public'));

app.listen(4242);

This snippet of code has been edited down to show the pertinent details; you can view the real code on GitHub. First, we require the express module, then we use it to create our server app. The three calls to post set up our three API methods and the handlers for those methods. Using the post method defined these as POST endpoints, we could have used put, get or delete, if it were appropriate. The use call sets up a redirect for static page requests so that those requests are satisfied from our public directory. Finally, we tell the app to listen on port 4242.

Each request that matches one of the three calls I have setup will be sent to the appropriate handling methods. These handlers each take a request object and a response object, which they can use to get additional information about the request and craft an appropriate response.

Here is an implementation of the doRotate method:

function doRotate(req, res) {
    var direction = req.param('direction');
    var rate = req.param('rate');
    drive.rotate(direction, rate);
    res.send();
}

In this handler, we get the direction and rate parameters from the request and pass them to the code that does the real work. At the end, we respond to the request. We could provide data in our response or even send an error if we wanted.

This allowed me to host a local website and API for controlling our bot. It was that simple.

Conclusion

Hacking a robot using node.js was a great way to delve into a new facet of JavaScript programming; hacking hardware. Not only that, but it allowed me to discover some of the cooler things that can be done quickly and easily using node.js, such as setting up a web server using express.

Have you hacked a robot with node? How did you implement control? Please leave a comment with your experience or any questions you may have. And if you are interested in hacking a bot of your own, watch this space.

  1. and an early prototype of our robot []

Getting posh-git in all your PowerShell consoles using GitHub for Windows

If you use git for version control and you use Microsoft Windows, you may well have used posh-git, a module for PowerShell. For those that have not, posh-git adds some git superpowers to your PowerShell console including tab completion for git commands, files and repositories, as well as an enhanced command prompt that tells you the current branch and its state1.

PowerShell console using posh-git
PowerShell console using posh-git
GitHub for Windows
GitHub for Windows

GitHub for Windows includes posh-git for its PowerShell console, if you choose that console when installing or later in the settings. It even adds a nice console icon to the task bar and Start screen2. Unfortunately, posh-git is only installed for the special version of the console that GitHub for Windows provides and you cannot make that prompt run as administrator, which can be useful once in a while.

Now, you could install a separate version of posh-git for all your other PowerShell needs, but that seems wrong. Especially since GitHub for Windows will happily keep its version up-to-date but you'd have to keep track of your other installation yourself.

Faced with this problem, I decided to hunt down how GitHub for Windows installed posh-git to see if I could get it into the rest of my PowerShell consoles. I quickly discovered ~\AppData\Local\GitHub containing both the posh-git folder and shell.ps1, the script that sets up the GitHub shell. The fantastic part of this script is that it sets up an environment variable for posh-git, github_posh_git, so you don't even need to worry about whether the folder changes3.

Armed with this information, you can edit your PowerShell profile4 and edit it to call both the GitHub shell script and the example profile script for posh-git5.

# Load posh-git example profile
. (Resolve-Path "$env:LOCALAPPDATA\GitHub\shell.ps1")
. (Resolve-Path "$env:github_posh_git\profile.example.ps1")

cd ~/Documents/GitHub

Once the edits are saved, close and reopen the PowerShell console to run the updated profile. Posh-git should now be available and all you have to do to keep it up-to-date is run the GitHub for Windows client once in a while.

  1. such as if there are any unstaged or uncommitted files and whether the branch is behind, ahead, or diverged from the remote []
  2. or menu, if you're pre-Windows 8 or installed something to bring the Start menu back []
  3. and if you've seen the folder name for posh-git in the GitHub for Windows installation, you'll see why that's useful []
  4. just enter `notepad $profile` at the PowerShell prompt []
  5. you may want to do the same thing for the PowerShell ISE, as it uses a separate profile script []

Learning Poetry: Exercise 4

It has been over a year since I last ventured into the world of poetry on this blog as I slowly make my way through The Ode Less Travelled by Stephen Fry. In each entry, I have posted my attempts at the exercises in the book and today, we'll look at Exercise 4 (Exercise 5 in the book).

If you are interested in the previous posts in this series, please check them out below:

I am not reiterating the content of the book here, merely the exercise, my attempt at it, and perhaps some notes. You may want to get your own copy of the book to follow along in more detail1.

The Exercise

Write your own verse of shorter measure. Give yourself forty-five minutes.

  • Two quatrains2 of standard, eight-syllable iambic pentameter.
ti-TUM ti-TUM ti-TUM ti-TUM
ti-TUM ti-TUM ti-TUM ti-TUM
ti-TUM ti-TUM ti-TUM ti-TUM
ti-TUM ti-TUM ti-TUM ti-TUM
  • Two quatrains of alternating iambic tetrameter and trimeter.
ti-TUM ti-TUM ti-TUM ti-TUM
ti-TUM ti-TUM ti-TUM
ti-TUM ti-TUM ti-TUM ti-TUM
ti-TUM ti-TUM ti-TUM
  • Two quatrains of trochaic tetrameter: one in 'pure troche' and one with docked weak endings in the second and fourth lines
TUM-ti TUM-ti TUM-ti TUM-ti
TUM-ti TUM-ti TUM-ti TUM-[ti]
TUM-ti TUM-ti TUM-ti TUM-ti
TUM-ti TUM-ti TUM-ti TUM-[ti]

 The Result

This morning we are flying home-
Detroit awaits our restless feet.
The cats await our fuss and food,
Perhaps a tasty little treat.

Some sleep would also be quite nice
to rest my weary head and dream.
An hour or two, that would suffice
between the sheets, the sandman's seam.

Tomorrow must I work all day?
I hope that I must not.
If I could only have my way
I'd dream away the lot.

Alas, I have to go to work
and concentrate on code.
Keep focused, calm, not go berserk
Till I can hit the road.

Taking flight; Atlanta's waiting,
Soon we will be landing safely,
Stepping off the plane and skating
Off to catch the next one, waiting.

Home awaits me bed and bathroom,
Nothing could mean more right now.
First, we have to drive the vroom vroom,
If I can remember how.

The Score

Unlike previous exercises, there is no scoring. However, I think I did well at this exercise. The verses seem less forced and meet the requirements laid out in the instructions.

As implied in the words, I wrote these verses while journeying back to Michigan from a vacation somewhere. I cannot recall the exact trip at all, but I think the words conjure up the hope and fatigue of travelling. What do you think? Have you tried this exercise? Post your attempts in the comments, if you'd like.

  1. Try Nicola's Books in Ann Arbor []
  2. a stanza of four lines, especially one having alternate rhymes []

Testing AngularJS: $resource

This is the fourth post taking a look at testing various aspects of AngularJS. Previously, I covered:

In this installment we'll take a look at what I do to isolate components from their use of the $resource service and why.

$resource

The $resource service provides a simple way to define RESTful API endpoints in AngularJS and get updated data without lots of promise handling unnecessarily obfuscating your code. If you have created a resource for a specific route, you can get the returned data into your scope as easily as this:

$scope.data = myResource.get();

The $resource magic ensures that once the request returns, the data is updated. It's clever stuff and incredibly useful.

However, when testing components that use resources, I want to isolate the components from those resources. While I could use $httpBackend or a cache to manipulate what results the resource returns, these can be cumbersome to setup and adds unnecessary complexity and churn to unit tests1. To avoid this complexity, I use a fake that can be substituted for $resource.

spyResource

My fake $resource is called spyResource. It is not quite a 1-1 replacement, but it does support the more common situations one might want (and it could be extended to support more). Here it is.

spyResource = function (name) {
	var resourceSpy = jasmine.createSpy(name + ' resource constructor').and.callFake(function () { angular.copy({}, this); });

	resourceSpy['get'] = resourceSpy.prototype['get'] = jasmine.createSpy('get');
	resourceSpy['$save'] = resourceSpy.prototype['$save'] = jasmine.createSpy('$save');
	resourceSpy['$delete'] = resourceSpy.prototype['$delete'] = jasmine.createSpy('$delete');

	return resourceSpy;
};

First of all, it is just a function. Since it is part of my testing framework, there is no need to wrap it in some fancy AngularJS factory, though we certainly could if we wanted.

Second, it mimics the $resource service by returning a function that ultimately copies itself. This is useful because you do not necessarily have access to the instances of a resource that are created in your code before posting an object update to your RESTful API. By copying itself, you can see if the $save() call is made directly from the main spyResource definition, even if it was actually called on an instance returned by it because they share the same spies.

To use this in testing, the $provide service can be used to replace a specific use of $resource with a spyResource. For example, if you defined a resource called someResource, you might have:

describe 'testing something that uses a resource', ->
  Given => module ($provide) =>
    $provide.value 'someResource', spyResource('someResource');return
  ...

Now, the fake resource will be injected instead of the real one, allowing us to not only spy on it, but to also ensure there are no side-effects that we have not explicitly set up.

Finally…

I have covered a very simple technique I use for isolating components from and spying on their usage of AngularJS resources. The simple fake resource I provided for this purpose can be easily tailored to cater to more complex scenarios. For example, if the code under test needs data from the get() method or the $promise property is expected in get() return result, the spy can be updated to return that data.

Using this fake resource instead of $httpBackend or a cache to manipulate the behavior of a real AngularJS resource not only simplifies the testing in general, but also reduces code churn by isolating the tests from the API routes that can often change during development.

As always, please leave a comment if you find this useful or have other feedback.

 

 

  1. API routes can often change during development, which would lead to updating `$httpBackend` test code so that it matches []