Some Bits: Nelson's log

10 posts in February 2013

Fuck browser keyboard events

In the HTML5 era programming in Javascript with browser APIs is mostly a joy. But sometimes you find a rough edge, in particular keyboard events. My zipdecode example had a simple problem: ordinary number keys worked, but not the numeric keypad. Because I was using the event.keyCode field, this ancient bit of savagery that tells me what button was pressed as opposed to what the user typed and both 48 and 96 mean 0. So I thought I’d try to update my code to the modern HTML5 way. Some things I learned:

  • Here’s a very simple tool for exploring keyCode.
  • String.fromCharCode() sometimes works for translating keyCodes to strings, but not always.
  • Here’s a very detailed guide to keyboard event behavior in various browsers. A bit outdated. The QuirksMode guide also has useful info but doesn’t cover what’s inside the event objects. Also maybe this StackOverflow question and this one.
  • keypress is the synthetic event fired off indicating “a user meant to type this thing”. If you can use it, use it. However it’s not always fired off, depending on the browser. (Ie: no left arrow in chrome). Also you can’t use it to suppress default behavior like backspace navigation.
  • keydown is the low level event fired when the switch is depressed. if you preventDefault() the event, in Chrome it means keypress is never fired but in Firefox it is fired anyway. (I think; didn’t test carefully.)
  • Any of the following fields of the event object may contain what button was pressed: char, charCode, key, keyCode, which. Most docs say “which” is the reliable choice (except for IE), but MDN notes it’s deprecated and says you should use key instead. Only “key” is not implemented in Firefox. Ha ha! Also while these fields are likely to be fileld out in a keypress event, they’re less likely to be present in a keydown event.

I was going to finish this blog post with a summary of the right modern way to do things, but I don’t think there is one yet. Then I was going to say this is a temporary state of affairs, but most of the HTML5-era questions I’m reading date back to 2010 so, um, not new.

I suspect the browser API mavens are scared to touch keyboard events. Partly it’s hard to specify because of internationalization, and partly it’s hard to implement because of cross-OS compatibility issues. I’ll note that jQuery apparently doesn’t have a library to solve this once and for all, either.

Update consider the d3.keybinding.js library from MapBox, for the iD editor.

Extracting features from shapefiles

I tend to forget that ESRI shapefiles are more like databases than just bags of geometry. ogrinfo can extract features.

ogrinfo -geom=no -sql "select HUC_12,HU_10_NAME,HU_12_Name from WBD_Subwatershed" WBD_Subwatershed.shp

unfortunately the output is some terrible text format.

OGRFeature(WBD_Subwatershed):3
  HUC_12 (String) = 180703030303
  HU_10_NAME (String) = Lower San Luis Rey River
  HU_12_Name (String) = Pilgrim Creek

However it turns out using GDAL/OGR’s bindings to Python is relatively straightforward, even if the API is basically a straight-up rip of the C API. Decent tutorial is here.

import ogr

shapefile = ogr.Open("NHDPlusCA/NHDPlus18/WBDSnapshot/WBD/WBD_Subwatershed.shp")
layer = shapefile.GetLayerByName("WBD_Subwatershed")
for feature in layer:
    featureDefinition = layer.GetLayerDefn()
    for i in range(featureDefinition.GetFieldCount()):
        fieldDefinition = featureDefinition.GetFieldDefn(i)
        print fieldDefinition.GetName(),
        print "%s" % feature.GetFieldAsString(i)

curl / wget and gzip encoding

I had no idea that neither curl nor wget will accept gzip encoding. They’re totally ignorant of it! You can set an Accept-Encoding header manually to tell the server to compress, but then you’re on your own to decompress.

wget --header="Accept-Encoding: gzip" 
curl -H 'Accept-Encoding: gzip'

Update curl does have a --compressed flag that does the decompression for you.

Capturing backspace in D3 / Javascript

I wanted to bind backspace on a web page, for a special UI. Had a hell of a time; the default behavior of backspace is to navigate the browser back a page in the history and it’s not easy to override. but long story short:

// Interaction: handle keyboard events (keydown to capture backspace)
d3.select("body").on("keydown", key);

function key() {
    if (code == 8) {
        // Prevent the browser from going back in the URL history
        d3.event.preventDefault();

        // Do your thing here.
    }
}

Some things that don’t work: returning false in the event listener (it’s ignored), calling stopPropagation(), or binding keypress instead of keydown. Browser keyboard events are a total mess.

More TopoJSON / watershed maps

I played more with the California watershed boundary data and TopoJSON. Two nice treatments, online at least temporarily. A full-state static map in D3 with some mild interaction letting you change the depth of HUC codes used in coloring. And a zoomable map written with Leaflet that while HUC colored, emphasizes watershed boundary details over the hierarchical HUCs.

The Leaflet implementation went pretty well. The one thing that tripped me up is my watershed boundaries are stored as bunch of Geometry objects in a GeometryCollection, instead of Feature objects in a FeatureCollection. Leaflet’s GeoJSON support does nice things with FeatureCollections, letting you change the style and bind a popup for each Feature. It doesn’t seem to do that with GeometryCollections. I worked around it by just iterating through the GeometryCollection and adding each Geometry manually. But I wonder if TopoJSON should be emitting FeatureCollections instead? ogr2ogr on my source .SHP data emitted a FeatureCollection, but topojson generated a topology with an embedded GeometryCollection.

I had to regenerate the TopoJSON for the zoomable map with less simplification. 2.2 MB vs 1.4 MB, and it looks good at reasonable zoom scales. I realized too late I really should have changed the quantization from 10,000 to 100,000; but at this simplification level I can get away with it.

So that’s the result. It’s OK and a useful tool for exploring watersheds, but it’s not awesome. The file size and render times are awfully big. And the presentation is clumsy, I should do more.

Screen Shot 2013-02-19 at 6.01.27 PM Screen Shot 2013-02-19 at 6.01.45 PM

TopoJSON notes, watershed boundaries and HUCs

I played around with Mike Bostock’s TopoJSON today, a file format + Javascript library for efficiently encoding maps. It basically does the same thing as geojson, but gets amazing compression in part by identifying common line segments between polygons and only encoding them once (ie: draw the border just once) and in part by quantizing and simplifying all the data. It’s quite clever!

My test data is the Watershed Boundaries from NHDPlusV2; the California-only NHDPlusV21_CA_18_WBDSnapshot_01.7z (89MB) and the national NHDPlusV21_NationalData_WBDSnapshot_Shapefile_01.7z (1.7GB).

Converting

Converting the smaller file to TopoJSON was a snap, just

topojson WBD_Subwatershed.shp -p HU_10_NAME -p HU_12_NAME --id-property "HUC_12" >| ~/src/huc-map/WBD_California.geojson

The flags are to add some GeoJSON properties to the resulting data file.

Simplifying

Taking the default arguments, TopoJSON reduced my 89MB SHP file to a 9.3MB TopoJSON file. Not bad, particularly since the straight GeoJSON is 257MB. A lot of compression thanks to shared boundaries. But also quantization; by default the topojson tool quantizes data to 10,000 values; I’m not sure but I think that means “it’ll look right if your map isn’t more than 5000 pixels wide”.

But topojson doesn’t do any simplification by default. What if we add the -s flag to simplify? Here’s the file size for variants of the -s parameter (in steradians):

0.0001         1.0 MB
0.00001        1.0 MB
0.000001       1.0 MB
0.0000001      1.1 MB
0.00000001     1.4 MB
0.000000001    2.2 MB
0.0000000001   5.8 MB
0.00000000001  5.8 MB
0.000000000001 5.8 MB

To my eye, the 1.4 MB 0.00000001 version looks about right, at least on my 800x800 map. I’m not surprised simplifying to a gross accuracy like 0.001 doesn’t add much; the objects themselves are pretty small. Not sure why it tops out at 5.8 MB or almost half the size of no simplification; maybe the source data has some really silly little details?

Querying the JSON

Quick diversion; I wanted to query my JSON object, to see what the properties and stuff inside it were. Someone’s finally built a decent “grep for JSON”, jq, the “keys” function is particularly useful for exploring a JSON file. Some quicky bits:

# get all HUCs:
jq '.objects.WBD_Subwatershed.geometries[].id'

# get all properties:
jq '.objects.WBD_Subwatershed.geometries[0].properties | keys'

Big data

I foolishly spent half my afternoon trying to convert that 1.6 GB file for the whole country. TopoJSON is memory-hungry; the optimization it’s doing is global so it really wants to read everything in to RAM. Long story short, the main thing I learned is that just like a Java VM the V8 VM has a fixed memory pool that’s like 1 GB or something by default. The magic flag to node is ” --max-old-space-size”. If I set it to 5000 (MB) then the whole process seemed to want to take 10 GB and made my 8GB machine thrash. Unfortunately smaller numbers like 4000 or 3500 resulted in an out-of-memory error. Mike guesses I’d need 16 gigs of RAM to do the conversion. All sort of silly anyway; I’m not sure what I’d do with the giant resulting file.

On the way I learned a lot of ugly things about Mac memory management:

  • Activity Monitor reports an “inactive memory” number that’s complete nonsense. It’s supposed to be RAM available for other processes but it sat at 3GB while my user process was thrashing the swap. So either the VM is not letting me use memory, or else it’s not really inactive afterall. The “purge” command doesn’t really help here, btw.
  • The page ins / page outs numbers on Activity Monitor are hugely helpful. When it’s paging in at 30 MB/s (hard drive rate) you know something is bad.
  • The %CPU number is also useful. When thrashing my topojson process dropped to 25% CPU (from 100).
  • If you double click on a process you get some detailed data. The “memory” page is confusing; I kept ignoring the “virtual memory size” of the process when that turns out to be the most relevant number. That was the 10 GB that resulted in thrashing. The Real Memory Size never got over 6 GB despite having 8 GB of RAM; guess MacOS overhead is 2GB now.
  • The geniuses at apple renamed “vmstat” to “vm_stat” and made it work differently. But it’s somewhat adequate.

Drawing Maps

Haven’t gotten very far for actually making maps yet. I followed Mike’s Let’s Make a Map tutorial and got a maplike something up pretty quickly. Counties in red, watersheds in black outline. My main goal is to add some color interaction around the hierarchical HUC coding.

Screen Shot 2013-02-17 at 6.19.46 PM

Python 3 success

Wrote my first Python 3 program. I was trying to get a Python 2 program to read a CSV file and write it to sqlite3. Difficulty level: Unicode. After reading all the nonsense about how the Python 2 CSV module doesn’t really do Unicode but hey it’s OK it’s bytes and here’s a wrapper you can paste in your code, I got fed up and installed Python 3.

So far so good. My 20 lines of code ran exactly fine in Python 3 first try, with the benefit that Unicode didn’t suck. The only thing that really tripped me up doing things is that print is a function, not a statement, and that’s a very good change. I even tried out the new string formatting system, here’s an idiom for using locals() for quick debug printing:

print ("{date} {asin} {title}".format(**locals()))

My one concern is Python 3 co-existing with Python 2. The Homebrew install seems to name things “python3” and “pip3” and the like, so all is well? But the recommended “pip3 install --upgrade distribute” didn’t work; that fetched some version of distribute that’s not Python 3 compatible.

Now that I’m over this hump I hope to use Python 3 for more things.

IP address 0.0.0.0

The IP address 0.0.0.0 is often used to mean “all a machine’s IP addresses” or “all network interfaces”. If you configure a server to listen to 0.0.0.0 it listens on everything. If you specify 0.0.0.0 as some sort of IP restricting filter it usually applies to all addresses.

But what does 0.0.0.0 mean to a client? Surprisingly, connecting to http://0.0.0.0/ seems to work on both my Macs and Linux. On my Mac “route get 0.0.0.0” shows me it’s going to use my Ethernet interface, with a real IP address. On my Linux box “ip route get 0.0.0.0” shows it using the loopback on 127.0.0.1.

Looking at this because I need a shell script that prints out an IP address that is likely to work even if I’m remotely shelled in to something. Here’s a script I use to launch test web servers for webapp development:

function pws {
  PORT="$1"
  [ -z "$PORT" ] && PORT=$[RANDOM%1000 + 9000]
  IP=`ifconfig | awk '/inet / { if ($2 != "127.0.0.1") { print $2; exit 0; } }'`
  python -m CGIHTTPServer "$PORT" >> /tmp/pws-"$PORT".log 2>&1 &
  echo "http://$IP:$PORT/"
}