Inbox Zero Party

Recently @edrabbit had a great idea: “I want to install a cache of balloons and confetti over my desk for when I achieve inbox zero.”

It was brilliant, so I kludged together the first step: a ruby script that takes an action when you hit inbox zero.  Here’s the code, if you want to play along at home.  You’ll need to edit your username and password; if you’re on Linux, “gnome-open” is probably the right thing to have there.  On OS X, you’ll want “open.”  If you’re on Windows, you have your own little set of special problems.

(Note that this program exits 0 when you’ve got inbox zero, and 1 otherwise, so you can easily put it into a shell script.  In addition to the exec() command in the script, this could be used to trigger a program that pings an arduino to unlatch a box of balloons and confetti.  For my sake, I’ll be thrilled to have “Peanut Butter Jelly Time” pop up when I hit inbox zero.)

#!/usr/bin/env ruby
# You need to add your username and password below!
require 'net/imap'

config = {
  'server' => "imap.gmail.com",
  'port' => 993,
  'username' => "josh.myer@gmail.com",
  'password' => "",
  'action' => "gnome-open http://bit.ly/pbj_time",
}

imap = Net::IMAP.new(config['server'], config['port'], true)
imap.login(config['username'], config['password'])
imap.select('INBOX')
n = 0
imap.search(["NOT", "DELETED"]).each do |message_id|
  n += 1
end

imap.logout()
imap.disconnect()

puts "Your inbox contains #{n} not-deleted messages."

if n == 0
  puts "SUCCESS!  INBOX ZERO ACHIEVED!"
  exec(config['action'])
  exit 0 # superfluous, I know
else
  exit 1
end

Adding unit tests to Write Yourself A Scheme in 48 Hours

I’ve recently been working my way through Write Yourself a Scheme in 48 Hours. This is a guided tutorial through implementing a Scheme interpreter in Haskell. It’s been really fun, and a nice change from my current contract (which involves a lot of screwdriver turning and other sysadmin duties).

That said, there is one big change that I’d like to see made in the text: build it with unit tests! I’m not a total test-driven disciple, but I do believe they’re a fantastic tool, and this is a great place to use them.

Parsing is incredibly test-friendly: you have an input string, and an expected output parse tree. It’s totally deterministic, with no random numbers, no ambiguities, and no pesky humans. There are a lot of interacting components, especially in terms of nesting, which are hard to keep in mind when manually “testing” things.

In addition, the “here’s code, extend it to do X” pattern used in the text benefits from having comprehensive tests. In working the homework exercises, you’re going to refactor big chunks of code. As you do so, you should be worried about breaking the hell out of your existing code (if you’re not worried, you’re either brilliant, inexperienced, or inattentive). There’s no better way to assuage those worries than unit tests, and, as you find broken things, adding regression tests. It gets even better if you add code coverage, guaranteeing that you’re exercising all codepaths via your tests.

Another wrinkle that makes you want tests: as you work through the book, you merge your existing code into the next snippet of example code. This is often an error-prone process, and having tests to catch mistakes is great. This is the reason I broke down and refactored the code for testing. I started getting into the interesting stuff at the end of chapter two, and suddenly my strings weren’t parsing properly. Upon examination, I found I’d merged my code into the next sample code incorrectly, and left my parseString implementation behind.

So, with all that in mind, let’s make Write Yourself a Scheme more test-friendly. The first step is to factor the parser implementation out into its own module. This is really easy: we create WYAS.hs, containing everything but main, and change the module line to:

module WYAS where

We’ll also need to extend LispVal a little bit, too. We want to be able to compare them, so we’ll add deriving(Show, Eq) immediately after the definition:

data LispVal = Atom String
             | List [LispVal]
             | DottedList [LispVal] LispVal
             | Number Integer
             | Float Float
             | String String
             | Char Char
             | Bool Bool
             deriving (Show, Eq)

Don’t worry about what “deriving()” means here; it’s just some Haskell typeclass voodoo that lets us now show (Char 'x') and have it do something useful, as well as allowing us to compare two LispVals for equality. After adding deriving(Show), you can also make readExpr’s Right case return the actual parse tree as a string:

    Right val -> "Found value: " ++ show val

Handy, no?

Then, we add main.hs, containing:

module Main where
import WYAS
import System.Environment

main :: IO ()
main = do args <- getArgs
    putStrLn (readExpr (args !! 0))

Next, let’s compile this, and make sure we get something that acts like our old parser:

ghc --make -o main main.hs
./main 42
./main "#t"

Once we’re convinced that’s all working, save it and commit it to your version control. (You are using version control, right? svn, git, cvs, hg… they’re all great, and totally worth using here!)

Now, we add a test framework. First and foremost: make sure you have HUnit installed (on ubuntu and debian, it should be ‘apt-get install libghc6-hunit-dev libghc6-hunit-doc‘).

Then, we’ll get to using HUnit to write unit tests. I don’t really want to explain HUnit in too much detail, in part because I still don’t fully grok it. Suffice it to say, the following works, and gets good results. If you have better options, please leave them in the comments, as this is one of those things that could always use refinement.

For my purposes, I’m only really interested in running tests on each parse type. That is: I want to put together a bunch of strings representing possible Number inputs, along with their parses, and run them one after the other. I’d like to have a string to tell me the name of the grouping, but, beyond that, I’m not too picky on how much debug output I get. When an input string fails (and it will), I can use the ./main binary to examine the output parse. So, I’m going to write a small templating facility in my test setup. I’ll define a ParseTestSuite, which is a String identifying the group with a list of (String, LispVal) pairs. The String is the input, and the LispVal is the expected parse. Once I have that, add some code around it to turn them into HUnit’s internal Test representation. At the very end, we collect all these Tests, and run them. Here’s the resultant test.hs:

module Main where
import WYAS
import Test.HUnit
import Text.ParserCombinators.Parsec hiding (spaces)

-- A ParseTestSuite is a name, then a list of strings, and their expected parses
-- For instance:
--   ParseTestSuite "testNumbers" [("32", Number 32), ("3.4", Float 3.4), ..]
--
data ParseTestSuite = ParseTestSuite String [(String, LispVal)] deriving (Show)

doParse :: String -> LispVal

doParse input = case parse parseExpr "lisp" input of
    Left err -> Atom ("No Match " ++ show err)
    Right val -> val

-- Convert a ParseTestSuite into an HUnit test suite.
-- This requires extracting the boolean assert, then turning
-- it into a test case.
suiteEntryToAssert :: String -> LispVal -> Assertion
suiteEntryToAssert s p =
assertBool s (p == doParse s)

parseTestSuiteToTest :: ParseTestSuite -> Test
parseTestSuiteToTest (ParseTestSuite name tests) =
    TestLabel name bodies_t where
    bodies_t = TestList $ map (\(s,p) -> TestLabel s (TestCase (suiteEntryToAssert s p))) tests

tests_Number :: ParseTestSuite
tests_Number = ParseTestSuite "tests_Number"
    [
    ("32", Number 32),
    ("3.2", Float 3.2),
    ("0", Number 0),
    ("#d1", Number 1),
    ("#b10", Number 2),
    ("#x10", Number 16),
    ("#o10", Number 8)
    ]

tests_Bool :: ParseTestSuite
tests_Bool = ParseTestSuite "tests_Bool"
    [
    ("#t", Bool True),
    ("#f", Bool False)
    ]

-- lots of other tests elided

all_tests :: [ParseTestSuite]
all_tests = [tests_Number, tests_Bool, tests_Atom, tests_String, tests_Char, tests_List, tests_DottedList, tests_Quoted]

main :: IO ()
main = do
    runTestTT $ TestList (map parseTestSuiteToTest all_tests)
    return ()

Then, we compile this:

ghc --make -o test test.hs
./test

and its output:

0] jbm@density:~/src/wyas/ch2 $ ./test
Cases: 22  Tried: 22  Errors: 0  Failures: 0
0] jbm@density:~/src/wyas/ch2 $

From here, it’s just a matter of adding more of these ParseTestSuite entries and inserting it into all_tests. As we do this, we gain more confidence in the parser we’re building in this process.

There’s one more key consideration in confidence, though: code coverage. Unit tests are great, but they might not test all your code, leaving bugs lurking for some poor soul to find later. The best way to ensure this is to run your unit tests under a coverage tool. GHC comes with one of these, handily enough: hpc.

As with all coverage tools, we need to recompile the program with some new options. And, like many of them, we need to clean up the project a bit first. So, in the name of being lazy, I wrote a Makefile:

# NB: you're going to get this mangled.
# The things under the target names MUST be tabs, not spaces.
# The joys of ancient Unix programs.
#
all: test main

coverage: clean WYAS.hs test.hs
        ghc --make -fhpc -o test test.hs
        ./test
        hpc markup --include=WYAS ./test

test: WYAS.hs test.hs
        ghc --make -o test test.hs
        ./test

main: WYAS.hs main.hs
        ghc --make -o main main.hs

clean:
        rm -f *.tix *.hi *.o main test

distclean: clean
        rm -f *.html

This lets us run ‘make coverage‘ and get an HTML file showing the coverage of WYAS.hs:

0] jbm@density:~/src/wyas/ch2 $ make coverage
rm -f *.tix *.hi *.o main test
ghc --make -fhpc -o test test.hs
[1 of 2] Compiling WYAS             ( WYAS.hs, WYAS.o )
[2 of 2] Compiling Main             ( test.hs, test.o )
Linking test ...
./test
Cases: 22  Tried: 22  Errors: 0  Failures: 0
hpc markup --include=WYAS ./test
Writing: WYAS.hs.html
Writing: hpc_index.html
Writing: hpc_index_fun.html
Writing: hpc_index_alt.html
Writing: hpc_index_exp.html

To get a quick view of how we’re doing, we can use ‘hpc report‘:

0] jbm@density:~/src/wyas/ch2 $ hpc report test.tix
91% expressions used (416/457)
100% boolean coverage (1/1)
100% guards (0/0)
100% 'if' conditions (1/1)
100% qualifiers (0/0)
62% alternatives used (22/35)
100% local declarations used (6/6)
96% top-level declarations used (32/33)
0] jbm@density:~/src/wyas/ch2 $ hpc report test.tix  WYAS
91% expressions used (233/256)
100% boolean coverage (1/1)
100% guards (0/0)
100% 'if' conditions (1/1)
100% qualifiers (0/0)
63% alternatives used (21/33)
100% local declarations used (5/5)
95% top-level declarations used (19/20)
0] jbm@density:~/src/wyas/ch2 $

As you can see, my “alternatives used” is rather low. Looking at the highlighted output, I need to finish up the tests around my R5RS character decoding implementation. Time to go in and add more cases to my unit tests!

I hope this post helps explain the benefits of testing for this project, and helps you convert your copy of Write Yourself a Scheme into something more test-driven. If it saves you time, or you have any other ways to help the rest of us save some time, leave a comment. WYAS is a great resource, and I’d love to collect all the time-savings we can and fold them into the original text.

Heated Fingerless Gloves FTW

Noisebridge is getting pretty chilly lately.  It’s better than it was, but you still want to bundle up a bit to hack there.  Fingerless gloves are a pretty standard part of my wardrobe six months of the year.  Err, to be totally honest, eight months, here in San Francisco.  Anyway, they’re great: I can type, but my fingers are still insulated.  Unfortunately, Noisebridge is so chilly that insulation isn’t quite enough.  Heck, so is my apartment.
That’s where USB comes in. Yeah, USB-powered, heated fingerless gloves.  Of course they exist!  And they’re pretty awesome.  They are reasonably nice fingerless gloves (see above), with little heating pads velcroed in.  The heating pad goes on the back of your hand, and plugs into the USB cord they come with.
Of course, I had to see exactly what the heating pad was made of, so I did a little bit of minor disassembly.  Looking into it: it’s just a little bit of printed (stamped?) resistive foil, which hooks up to the power and gets hot.  Hunh.  It seems pretty simple.
These things are great, and are keeping my moneymakers nice and warm, without having to heat my whole apartment.  If you’d like a pair, let me know.  I got some extras, and would be happy to sell them for $10/pair.  Happy (and warm) hacking!

Morse decoding using Arduino

Here’s a quick hack I keep meaning to release in a meaningful way: a morse code decoder in arduino.  Hook up a button to pin 2 (like you would for the button examples), and then watch the serial monitor.  If you key in SOS (…/—/…), it will light up the LED on pin 13.  My intention here was to use this to buzzy myself into my apartment building’s door, but I still haven’t gotten around to actually putting it inside the box yet(!).

Give it a go, and see what you think of it.  I’d also like to hook it up to an LCD panel and make a proper morse training device out of it, but that’s for another day, I think.

Leave comments here if you make any use of this, I’m keen on seeing what happens with it!

73 de KJ6ANM

Here’s the file: arduino_morse_decoder.pde(.txt to make things happier).

A community funding experiment

You might remember muralizer, a mural drawing robot I was working on at Noisebridge earlier this year.  Things went awry, and the project never really achieved fruition.

I’m starting it back up again; more deatils over at its own blog: Muralizer Project Blog.  In particular, I’m trying to make ends meet for a few weeks with just Muralizer work.  To that end, I’ve started a pledge drive over at kickstarter: Muralizer kickstarter page.  This is something like a PBS pledge drive, with me handing out prizes for different pledge levels, with a big twist: if the funding goal isn’t met, no money changes hands.   This is great, but means that I need to be getting the community behind me.

So, if you’re reading this and can afford to kick in a few bucks to make a really cool open hardware project happen, please, pledge at kickstarter.  I’d really appreciate it, as would the community of artists who will benefit from a friendly kit version of this hardware.  Thanks in advance for your support!

Fair Use Reminder

Fair Use Reminder

Fair Use Reminder

A really nice Fair Use Reminder from the folks at Freedom For IP.  We need a copy of this on the wall at Noisebridge.

(via Serafina Kernberger)

Some process hacks for creative work

When doing creative things, there are challenges at three basic stages: intimidation in starting, getting stuck in ruts while implementing, and chasing my tail while wrapping up.  In this post, I want to share three “techniques” to help get over the intimidation up front, get out of ruts as you’re building, and keep from chasing your tail as you wrap up.

First, a few examples of each problem.  When designing a system, I get intimidated by the openness of the blank page, and don’t want to write down anything until I’m confident that it’s Right (free fourth tip: this is why I always start out in tiny notebooks or on notecards).  It’s also nice to use whiteboards; something about the ephemerality of them is really helpful.  That said, there’s still a lot of ground to cover in getting over that initial hurdle, and Merlin Mann has some great quotes and reassurance to share.

Next up is getting stuck in a rut.  For instance, when designing an architecture, I sometimes can’t decide which component should own a particular piece of functionality.  If I’m not careful, I wind up getting stuck in little mental loops, recapitulating my own ideas over and over.  Once I recognize this, I break out a deck of cards with totally insane advice (think Tarot, but for the creative process), and give it a go.  This usually helps reset my state and reinstate some clarity.

But, sometimes I’m stuck in that rut because I’m simply overwhelmed.  This is most common when debugging a program crash that takes a certain sequence of operations to recreate, it’s hard to keep track of which operations I’ve tried.  In that case, I start taking notes of what I’ve tried, and then look for patterns, especially where I’ve missed some alternative way to go through things.

With those kinds of problem in mind, here’s some techniques (err, process hacks) for getting over each of them.

First up, getting over intimidation: Merlin Mann on Doing Creative Work.  Mr Mann talks at length about the mental hurdles you face in the creative process, and how to overcome/ignore them.  Here are the quotes that really resonated for me; I hope you find them helpful, or at least they help motivate you to spend half an hour listening to someone giving great, free advice.

@17:24  — “Anybody you know who does great work, sit and sweat it: I am a fraud,  I am never going to do anythign good again, and I’m going to die alone, with shit in my pants, watching cable”

@19:00 — “Develop an insane amount of tolerance for having no idea what something is turning into.”

@20:15 –  “If you let your brain give you ideas, you can execute them. You can’t force them out, you can’t think them out.  You think you can.  You think if you buy a  better mind-mapping app, you think if you get a new project management app, you think if you get a really cool pen, it’s gonna get easier, and it’s not.  You’ve got everything on your body right now, with your nerd phone or your space pen… you literally have everything you need right now to get started on that.”

@21:15 — “You’re going to have forgive yourself when it doesn’t work out on the very first day”

If, after all that, you’re not convinced that your fears of abject failure are normal, well, you need to go catch up on who that dude is, and maybe read more about how authors view themselves.  Just sayin’.

As for getting stuck in ruts, I really like Brian Eno’s Oblique Strategies cards.  I like them so much that, if I weren’t a starving entrepreneur at the moment, I might even buy them.  Until then, I’ll use the iPhone or JavaScript versions (search the App Store for the iPhone, JavaScript Oblique Strategies).  They’re a great way to knock yourself out of mental ruts you might get stuck in.  Sure, they’re totally inappropriate for the kind of work we do, but that’s half the benefit: try to make the bizarro-in-context advice (“Change instrument roles”) fit what you’re doing.  If nothing else, the mental exercise clears your mind of the patterns you keep following.  In the same vein, I have a tarot program on my iPhone.  Sure, it was $3, but that’s such a low price for a lifetime of bad advice and creative jostling.

Sometimes, though, that jostling just isn’t enough.  Especially when debugging, I sometimes keep track of which steps I’ve taken, which combinations of techniques I’ve tried, or what order of operations, etc.  In doing this, I can find new patterns to try, and keep from repeating the same steps to no avail.  This is one of those cases where the logbook idea I posted about last time really pays off: when you find a similar crash in the future, you can look back to your repro steps for this time.

All in all, I find myself relying on these more as I’m my own boss.  It’s key to keep myself productive, engaged, and not-frustrated.  A lot of that comes from being able to focus, recognize when I’m stuck in one of the above loops, and grab the right tool to pry myself out.  I hope this helps you, too.

If you have any further ideas or feedback, I’d love to hear about it in the comments.

My penultimate day at Aardvark

Since I don’t remember when, I’ve kept a paper logbook next to my computers.  It’s my lab notebook, where I track what I work on each day, with tables of intermediate results and charts literally cut out of spreadsheet printouts and taped in.  This way, when I go into meetings, I just carry my notebook, and I have immediate access to the process I went through in a given tuning session, etc.  It’s most helpful when I’m coming back to something a week later: I can see what I’ve already tried, so I don’t wind up tuning in circles.  It’s second-most helpful when someone suggests pretty obvious refinements that didn’t pan out: “Shouldn’t we try inverting the score here, then doing this?” is answered with “If we do it that way, the recall goes down by 10% but we get a 0.5% improvement in precision, here’s the data.”  I love these notebooks (I keep nicer ones at home than I do at work, honestly), and find they’re really helpful for keeping me focused when working.  I’d highly recommend

These notebooks are obviously enough chock-full of proprietary information, so I can’t take them with me when I leave.  Therefore, they get handed off to some poor bastard who has to try and decipher my handwriting, process, etc.  It’s mostly a symbolic thing: “My time here is done; I leave these with you because I trust you to carry on what I was doing.”

Today, I handed off my notebooks for Aardvark (3 of ‘em) to my coworker Mike.  Tomorrow is my last day here; after that, I have a half-dozen little projects to chase down, as well as seeing how the world goes for a freelancing jack-of-all-trades.

src parade: marginalia

I recently centralized and tallied up my personal source repository: something like 100kloc and about 80 directories.  This represents around a decade of evenings and weekends spent writing code, in everything from C to Haskell, in environments from my low-level Unix home to PalmOS.  The most recent stuff is arduino and processing, but it also includes OCaml-gtk and a bit of Objective C (written on OS X 10.0).  The common themes through all this diversity?  It’s all hastily written, poorly documented, and nigh-unreleasable code.

That said, my friend Kragen caught wind of this and suggested I release it all.  While I won’t release everything (some of it is still very nascent and/or mostly vapor), I will be working my way through, giving some things Makefiles and READMEs before kicking them out the door.

Tonight is the first installment of this src parade.  It’s actually something I released years ago, which has fallen into a bit of disrepair, but was still pretty cool: Marginalia.  Marginalia was a firefox extension that allowed you to annotate webpages in-place, and see the annotations others had left behind.  Its plugin description was “Collaborative annotation for FireFox,” which pretty well fits.

Viewing an annotation placed with marginalia

Viewing an annotation placed with marginalia

Why did I build this in the first place?

It was meant to allow the disruptiveness of the web to become even more pervasive.  Imagine if citizen journalists could leave links to alternate coverage of stories on CNN.com, or add links to previous statements by politicians to their latest contradictory interview.  It predates youtube; nowadays, it would definitely allow embedding youtube clips for this.

What did I learn in building it?

Javascript is hard.  No, really, it is.  If you want to build something like this, performance matters, and it’s non-trivial to get correct.

HTML/DOM is hard.  It was never intended to do things like this, and you really have to bend over backwards to make it happen.

Don’t give up so soon.  Marginalia was pretty freaking awesome, if I do say so myself.  I didn’t push hard enough for others to adopt it, and I let it die too early and too easily.  It could have been a big deal, but I didn’t care enough to keep at it.  In my defense, I was in the second to last semester of undergrad, which was pretty intense.  I was working 20-30 hours a week and had two majors, so it was either hack on this or spend time with my girlfriend.  (I got to play with marginalia on the clock, but only so far as it didn’t interfere with keeping the lights on.)

Where does it stand today?

Marginalia fell to the wayside at some point.  Most significantly, it needs retouching to work with the latest firefox/gecko.  It currently doesn’t install, but I’m pretty sure it’s more than just updating the compatibility ranges.  If you’re interested in the problem, I’d suggest looking at newer web annotation systems  Wikipedia has a good list at [[Web annotation]].  The hardest technical problem you’ll face is actually kind of silly: figuring out where to attach the note based on the user’s click.  Have a look at how marginalia does it to see one solution; I’m sure there are others which are just as good.  (Hint: marginalia bundles a pure-javascript SHA-1 implementation)

You’ll find more text and a download at the Marginalia homepage.  The source is part of the download, though it doesn’t look like it.  XPI is, like JAR, a strange way to say ZIP.  That is: you can download the XPI file (right-click, save as), then unzip it (you might need to rename it to be a .ZIP file).  The guts of things are in chrome/marginalia/content/marginalia.js

Would I do it again?

Probably not, actually.  This is mostly because others are solving the problem, but also a little bit because solving the problem is incredibly tedious.  Having written a handful of little firefox extensions, I now have zero urge to build on that platform any more.  I still love the idea of marginalia, but I would prefer to leave implementing it to someone else.

oscremoted

My iPhone is gradually becoming a universal remote control, and I love it.  This is the first part of that: how to hook a generic GUI-creation tool on the iPhone up to run arbitrary commands on my Linux box.

One of the peacetime dividends of Perceptron is an awareness of OSC.  OSC is Open Sound Control, a standard for sending, well, sound controls over the network.  If you’re familiar with MIDI, it’s basically MIDI over the network, but with twice the resolution.  Technically, they seem to have made lots of really good design decisions, and it’s been around long enough to have mature tools around it.

Basically, OSC allows you to have volume sliders, arbitrary buttons (play, pause, turn on lights, etc), knobs: just about anything you could use to control music can be put into OSC.  This is great, because it allows a designer to abstract out the interface from their application, and just plug in different physical widgets to implement “volume slider 1″ or “play drum B.”  Or, just as easily, hook those up to software, so they can have a GUI to interface to humans, or pure software control, with a software robot hitting virtual buttons.

While poking around one day, I thought to myself, “Wait, someone has to have done an OSC GUI for the iPhone!”  And, sure enough, they had: OSCRemote.  It’s great fun to play with: you can add little sliders, move buttons around, and even use the accelerometers.  It’s a delight, especially if you’re used to creating GUIs in code.

However, at the end of the day, I’m still a command-line Unix guy.  How do I bridge that gap?  With a control daemon, of course!  There’s a nice C library that implements OSC (liblo) using callbacks; add a trivial config file parser and an exec() implementation, and voila: I can now run set unix commands by hitting buttons on my iPhone.  It’s incredibly configurable and general, while staying pretty straightforward.  Now I can start and stop music, jump tracks, and nudge volume up and down from anywhere in my apartment, using just my phone.

You can get the code for this at oscremoted (creative name, eh?).  It needs to get a proper homepage on my domain; until then, it’s just a tarball with a freshmeat page.  I’m curious if anyone has ideas for refinements or improvements; comment if you do!

ὑπόμνηματα: memoranda, notes, minutes