Some Bits: Nelson's log

57 posts about javascript

Astro static site generator

I took a quick look at Astro, a newish open source framework for building (mostly) static websites. It looks pretty nice but may not be what I want for my current project, (once again) trying to replace my ancient dynamic blog engine with a modern static site.

The big thing Astro seems to enable is Javascript-heavy static sites. If you want to use React, Vue, Svelte, etc to build a complex Javascript site, but you want everything statically pre-rendered, Astro looks to be your choice. There’s a lot of fancy support for dealing with Javascript, CSS, fonts, etc and getting them to assemble to a nice static page for the client. Also integration with GitHub (for code hosting) and Netlify (for site hosting). I think that’s an interesting spot to be in for a framework in 2023. (Also kind of the opposite of another paradigm I think is interesting, very lightweight Javascript and using HTMX to bridge to a dynamic server.)

One minor annoyance: even the very first empty template project loads about 5kb of client side Javascript. It doesn’t seem to be doing anything and I think can be removed. But it says something to me that even the null project already has client side Javascript; this is a tool intended for Javascript sites.

What Astro doesn’t have out of the box is a blog engine. They have a great tutorial that has you create a blog, very nicely written and easy to follow. But along the way you’re writing code like “enumerate all the markdown files for the posts then use that to build an index of my blog posts”. Ie, you’re coding your own blog layout. That’s fine as an example of building your own static site. But I’m just trying to set up a blog, I’d rather have that stuff built in already.

Maybe that stuff does exist. Astro has a bunch of blog themes, perhaps Astro + an off the shelf theme is what I’m looking for. So I gave Blogster minimal a try. It’s kinda nice and has zero Javascript in the built output, a goal I want. But this looks more like another demo of how to build a blog. In particular there’s no easy way to extend this code short of forking the github project and building your own. Which is fine, but more like programming Javascript and less like customizing some static HTML templates. That’s great if you want to really customize but is work I’m hoping to avoid.

I’m left with the impression Astro is a good choice if you are expecting to write a lot of code to build something unique and custom.

Background work in Javascript

I’m writing a little browser toy where I calculate a model in the background and render it frequently. Think something like an animated cellular automaton.

Rendering is easy in modern browsers: you just use requestAnimationFrame and hopefully it’ll call your code once per screen refresh or at least as fast as it can manage.

But how do you do background compute work in Javascript in 2023? I want it to run as fast as possible (ie, 100% CPU for the browser tab) but still be smooth and responsive. I think the right answer is “web workers” but then that requires the overhead of passing the calculations back and forth via messages (and JSON serialization?!).

Here’s some other things I tried for background Javascript work. I tested using a calculate function which executes in well under 1ms.

  • Use setInterval to fire off the calculation: 4ms is the minimum allowed in modern browsers, limiting you to 250 calculations / second.
  • Use a spin loop. This works and I can do but now the main browser thread is blocking everything and it’s a UI disaster. Not feasible.
  • Use a spin loop with a Promise to yield via a short sleep. Still subject to 4ms on setTimeout, but overhead means it’s more like 5.2ms in practice.
  • Use requestIdleCallback. I had high hopes for this but in practice I’m getting called every 11.1ms or 90 updates / second. Turns out that’s my screen refresh rate and the idle callback rate changes if I update the display driver refresh. It’s like VBlank interrupts in 2023 only about nineteen layers removed from the hardware.

I think in practice setInterval will work for me; my calculations are likely to take a few milliseconds and anyway I don’t want it to run “too fast” because it won’t be visible. Still kinda wacky this is so hard in 2023. Web workers are probably the right way if I need faster than 4ms.

// Calculation loop using idle callbacks
function calculate_idle() {
        calculate();
        window.requestIdleCallback(calculate_idle);
}

// Calculation loop using ersatz sleeps. Note 4ms is minimum here.
async function calculate_sleep(interval) {
        // https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
        while (1) {
                calculate();
                await new Promise(r => setTimeout(r, interval));
        }
}

switch (mode) {
        case "idle":
                // Seems to be every 11ms per quick testing in Chrome
                calculate_idle();
                break;
        case "interval":
                // Browsers seem to make 4ms the minimum interval
                setInterval(calculate, 1);
                break;
        case "spin":
                while (1) {
                        calculate();
                }
                break;
        case "sleep":
                calculate_sleep(0);
                break;
}

Ubuntu vs NodeJS versions

Node seems to have some serious stability problems; various apps are sensitive to which version of Node you run. Here’s some recent versions:

  • Ubuntu 22.10 / kinetic: 18.7.0
  • 22.04 / jammy: 12.22.9
  • 20.04 / focal: 10.19.0

Nodesource packages different versions of NodeJS for Ubuntu. It’s basically a PPA but they want you to use their shell script to install them.

I ran into a problem with Nodesource where “apt install” really wanted to keep installing Ubuntu’s 18.7 despite having a PPA. I fixed that with apt install nodejs=14.21.1-deb-1nodesource1 to select a specific version.

I don’t understanding looping with Promises

Did some hair-pulling work with Javascript Promises recently. I’m calling a paginated database API (CloudKit JS), so I want to fetch N results at a time until there are no other results to fetch. In simple synchronous programming you’d do this with a while loop. But Promises can’t be reused or iterated in this way, so instead you do something that amounts to tail recursion. The Cloudkit docs have a handy example:

database.performQuery(query, { resultsLimit: 10 }).then(function(response) {
    if (response.hasErrors) {
        // Insert error handling
        throw response.errors[0];
    } else {
        // Insert successfully fetched record code
        if(response.moreComing) {
            return database.performQuery(response);
        }
    }
});

I use code much like this for real and it works. But it’s complicated! database.performQuery is an asynchronous method in CloudKit JS, it is a Promise. This code creates a new query promise, then chains it via .then() to some synchronous code that processes the response. The last thing the processing code does is check if there’s more results to come (the pagination API) and if so it creates a new Promise and returns it. Which causes the Promise execution framework in the browser to go to resolve that new promise next.

It feels very much like tail recursion. I get conflicting answers on whether it genuinely is recursive, in the sense of some Javascript stack or Promises chain growing larger and larger with each request. It’d be simple enough to do basic tail recursion optimization to eliminate that growth, just no idea if implementations do it.

My problem

So I’ve got code working. My problem is the moment I try to do something more complicated, I get lost. As a practical example; what if I want to inject a one second delay between each call to that performQuery() function? I can make a new promise with setTimeout() and chain it in there, but half the time I type the code to do that I get it wrong. I got lucky and it worked once and I don’t really understand why. Then try passing arbitrary parameters conveniently through the call chain; you can, but it’s hard because Promises only take one argument to pass along so you have to stuff your parameters into a new Object. And I haven’t even tried to reason about getting error handling right, although I think if you’re naive and don’t do much of anything then the default reject/catch behavior will probably work.

async/await

There’s a new hotness coming in Javascript with the async and await keywords along with async interation. Here’s another example of it in use. I haven’t ever used this stuff myself and am not sure if it works yet in browsers.

Update: some advice on Twitter to use async/await, that it has decent browser support.

Thinking asynchronously

This is an unsatisfying blog post where I investigated a problem and don’t really have a solution. Honestly, most of the time I do async programming in any language I feel the same way. Python, Javascript, even select()-based C code back in the day. My model of programming computers is so heavily based on imperative execution I always feel all twisted when I program asynchronously.

I need to do a series of exercises fully in an async model and get comfortable. Either that or find a good Javascript wrapper for Promises that provides higher level components like “iterate this set of promises” and the like.

CloudKit JS: hasErrors vs isError

Well this is a nuisance. A lot of CloudKit requests have two different ways of signaling errors when you make Javascript calls to the iCloud API.

The request can look like it succeeded and returned a Response object of some sort. But instead of the response you want it can have the hasErrors flag set, in which case there’s a whole array of errors objects. This method is what’s shown in example docs.

The request can also just fail and the method returns a CKError object instead. This object has an isError property, also an isCKError. I’m not positive but I think this mostly catches client-side programming errors, like when I put in an integer where a string array was expected.

In neither case does the Promise reject; it resolves with some sort of error status. So for now every call to a Promise in CloudKit JS I make has right after it:

        if (response.hasErrors) {
            reject(response.errors[0]);
        } else if (response.isError) {
            reject(response);
        }

I wonder if there’s a better idiom.

Dismal programming language law: no matter how many language features there are for signaling errors out of band: Exceptions, Promises rejects, etc.. Programmers will ignore those and return error values in-band instead.

noUiSlider, a nice Javascript control

Just wanted to give a shout out to noUiSlider, a nice Javascript library for building slider controls. We just used it to add a time-range slider control to Wanderings, my little location tracker. Now you can restrict what data is shown to specific date ranges. Our control looks a lot like this demo.

There’s a zillion slider controls implemented in Javascript. Most of the well known ones are 5+ years old and require jQuery. There’s some fancy new ones that require React. What I like about noUiSlider is it’s standalone, doesn’t rely on any other frameworks. It’s not tiny but it’s pretty small, about 90k uncompressed or 25k gzipped.

noUiSlider is also remarkably professional. It’s quite flexible; you can have any number of handles, linked or not. It’s straightforward to restyle. It gives off a nice collection of events when the user interacts with it. It works thoughtfully on touchscreens. And it’s all well documented! Nice library.

The one thing I haven’t figured out how to do in my app is add a nice UI for “filter to one month” for “one year”. It’d be easy enough to add buttons but the UI would be so cluttered then. Want something less obtrusive. For now we have a bunch of hotkeys defined on the main window (YQMWD for ranges, also HL to pan back and forth) but that’s pretty mysterious.

New release of Wanderings, in which I learn to love Webpack

Brad and I pushed our first new release of Wanderings since the big release last January. No user visible changes, but we upgraded all the versions of third party packages and build tools we were using.

The real thing is I had to get over being whiny about webpack and npm. Right after we finished 1.0 Brad stepped in and reorganized our code to use fancy web tools. Previously we just had a big ol’ wanderings.js file we imported on every page, along with a bunch of third party minimized redistributables included one after the other in the HTML file. You know, the old school way. Brad redid everything nicely in webpack and npm so that third party modules were fetched from a repository and bundled together. Our code was refactored and then combined into the bundle. All with nice frontend scripts like “test” and “deploy” and “start development server”.

Unfortunately I don’t know anything about these fancy new fangled tools, I live or die by press-F5-in-the-browser. And it was kind of a big hump for me to get over it, learn the tools, and use them. I have a categorical problem any time someone tries to inject a “compile” or “link” phase into what should be simple interpreted code. It always slows me down. npm is very hard to love, too.

But webpack solves a lot of problems too. Managing distributing the right versions of things. Bundling them so they distribute efficiently. Minimizing the code for obfuscation + network savings. Keeping it possible to still run devel versions with source maps, etc for easy debugging.

The fancy devel server we get from webpack is pretty nice too. It seems to automagically arrange for things to recompile and reload when they change. I had a problem with this at first because our devel bundle is like 4.5 megabytes and I was running my devel server remotely, on another continent. That’s a bad idea; once I got the devel server running locally on my laptop it was much better. (We might want to split our bundle into two pieces though, a big one of third party code that seldom changes and a small one of our own code. Just to keep reload overhead down).

I’m still grumpy about some things. I’ve lost all my global variables I used to reach into to inspect the state of the running system in the console. I’m not sure I can get the Firefox debugger working at all, the source maps or something aren’t working. Chrome seems better though.

I still hate imposing any overhead in the “change code, reload, run” loop. But all this build stuff solves real problems in the Javascript ecosystem so I think it’s best to play along.

Notes on Javascript cryptocurrency mining

The new hotness is web sites using visitors’ CPU to mine cryptocurrency. Typically without consent, often via malware, although sometimes as a disclosed alternative to ads. Fuck everything about that.

Still I was curious how this works. Mining most cryptocurrencies requires speciality hardware to be worth the bother. GPUs, at least, and in the case of Bitcoin ASICs. So I’ve been wondering how a Javascript miner would work, surely it’s 100-1000x slower than a native GPU program? Are they using WebGL?

The most popular solution for Javascript mining now is CoinHive. And they mine the Monero currency. Why?  Explicitly for performance reasons. The Monero hash (Cryptonight) is something designed for CPU computing and doesn’t really run better on GPUs. So it’s a reasonable thing to do in Javascript.

BTW I found this CoinHive demo useful for playing around with a Javascript miner in my own browser. Yup, it takes 100% of all 8 of my CPU threads very easily.

(Related: the NoCoin extension is a way to protect your browser from this crap. Ad blockers will typically block them too (uBlock Origin does), but I want to see the icon specifically about whether some website is running a miner.)

Browser unit testing Javascript

I wanted to do some simple unit testing in a Browser context; no NodeJS. I decided to use Mocha and Chai, then found it remarkably difficult to figure out how to just get it working without a bunch of complicated setup.

I finally figured it out: demo here. It’s pretty simple really, grab the CSS and JS from a CDN, then write the tests.

Boy there’s a lot of stuff in these frameworks. Mocha + Chai is literally 26k lines of code, 820k bytes. Minified it’s more like 300k but that’s still huge. I see why folks like tape instead. I wasn’t sure tape really supports running in a browser though.

 

Javascript Promises wot I learned

I program in 2006-era Javascript. But recently I started doing some more modern stuff. Arrow functions, those are great! And easy. Promises! Those are great. And confusing. Here’s some notes about what I’ve learned about Promises.

Warning: I’m a n00b here, some of this info could be wrong.

  • The best single guide to Promises I’ve read is Google’s. The folksy tone at the start is annoying but keep reading. MDN also has a basic guide that’s useful. You’ll want the MDN reference too.
  • The key thing no one explains is that when you create a Promise, it is automatically added to the event loop and will be executed by the browser when it has time. You do not have to schedule a promise or create your own event loop, like you do in Python async programming. It’s all automagic.
  • The exciting thing about Promises compared to other async frameworks is the .then() function, the ability to chain a second promise onto a first one. “First do this thing asynchronously, then when it is completed start doing this second thing. And make this chunk of two things itself a Promise so it runs asynchronously”.
  • You can also combine Promises with all() and race() but I don’t see it being used that way very often.
  • The other neat thing about Promises is it has an API for error handling. I’ve never used this for real (I’m an optimist programmer), so I can’t say more about it, but it seems important.
  • A Promise is a Javascript function that runs like any other function, but will yield control and allow other things to run when it’s blocking on network IO. (At least I think that’s right, I’m not 100% confident.)
  • When I’m sloppy I think of a Promise as basically a Thread. An independent unit of execution that runs in parallel with everything else. That’s not really true; Promises aren’t Threads, in particular there’s no interrupting multitasking. There is co-operative multi-tasking though so as soon as your Promise blocks waiting for network or whatever, something else will happen. Specifically the browser’s event loop will keep running and the page will be responsive, the key reason to be using async programming at all.
  • It’s OK to create Promises that never invoke their resolve or reject functions. That means the Promise won’t ever have a return value to pass on to the next Promise in the then chain, but that’s OK. Maybe you wanted the side effects or something. It’s probably not a good idea though, the promise will stay in pending state forever and nothing chained after it with then() or whatever will ever run.
  • It’s also OK to mix Promises and events for different styles of asynchronous programming. Promise chains let you program in a more or less declarative way: do A then B then C. But it can be tricky to arrange your control flow for a whole page program to make sense this way. Events are nice because the publisher of the event doens’t need to know anything about who might be consuming it somewhere else. It’s fine to have a Promise post an event that something else listens to and acts on asynchronously.

This code is laughably simple, but I found it useful when learning about Promises:

 

var state = 1;

console.log("starting");

console.log(state);

p1 = new Promise((resolve, reject) => {
    console.log("p1 created");
    setTimeout(function() {
        console.log("p1 finished");
        state = 2;
        resolve();
    }, 1000);
});

console.log("made p1");
console.log(state);
p1.then(function() { console.log(state); });
console.log("made p1.then");

Better Jupyter charts: mpld3

As much as I’m liking Jupyter, I don’t much like that matplotlib is the default charting library. I mean matplotlib gets the job done, and it’s powerful and popular. But end of the day you’re rendering raster images with 10+ year old software. (Even if seaborn has made the raster images better.) We’ve got a fancy browser viewer, why not have fancy SVG/Javascript graphs?

That’s what mpld3 provides. Using it is as simple as importing it and calling mpld3.enable_notebook(). All (most?) of your old matplotlib API code will still work. mpld3 emulates that charting API but renders to SVG using D3, instead of rendering to a static image. It’s kinda nutty that it just works. The resulting pixels look good, although admittedly matplotlib’s raster backend (agg?) looks pretty good too. 

The real advantage is the graphs are manipulable with Javascript. Out of the box every graph is now pannable / zoomable, right in the browser window. You can do fancy linked brushes across multiple figures.

There’s also plugins to add more capability. PointLabelTooltip plugin is particularly nice, it adds an easy way to have HTML tooltips on a scatterplot when you hover the points. There’s also MousePosition (useful for images).

And... and that’s about it. After a bunch of work a couple of years ago development seems to have stalled. That’s OK, it’s useful as is. Particularly since it’s such a simple drop-in upgrade for matplotlib.

Probably time to look at alternatives. Bokeh is the “better matplotlib” and includes a bunch of browser / notebook stuff. However it’s still rendering raster images (albeit in an HTML5 canvas). The examples sure are pretty though. I also see frequent references to VisPy, which is GL based, but although there’s some noises made about WebGL and notebooks I can’t find a working demo. Other options I’ve run across are pygal, bqplot and Altair. People also talk about Plotly but it’s a hosted system and costs money.

Some other thoughts on this topic: The future of visualization in Python, In defense of Matplotlib, Overview of Python Visualization Tools

While I’m here, ipywidgets is kind of nutty. It lets you add interactive controls to a notebook like sliders and input boxes, to turn your notebook into an interactive app.

 

Simple Javascript time series charts

I want to draw a time series graph in Javascript. This is one of the simplest kinds of regular data visualizations and all of the libraries I find to do it suck. I looked at this a year ago, is anything better now?

What I want is a library that will automatically assign axes and draw correct time series graphs. The time intervals are not regular. Also sometimes data is missing. Not zero, null. Remarkably, very few charting libraries seem to be able to handle these common requirements. Here is some very quick evaluation, I spent ~3 minutes on each library so may have mischaracterized something or overlooked some greatness.

  • Charts.js: too low level, really a graphics library for drawing colors in canvas
  • Flot: good ol’ flot, just seems too old. Maybe that’s foolish and it’s solid?
  • D3.js: great library but too low level. I don’t want to build my own axis and don’t really want to program at all, just declare data.
  • Metricsgraphics: promising library at the right level, but seemed buggy. I spent about 90 minutes trying to get a time series to render and depending on my Date range, either got a decent graph or got confusing SVG rendering errors involving NaN.
  • Rickshaw, xCharts, Ember, and d3.chart look to all have very slow or no development. Rickshaw was promising, I wonder if it’s just “mature”.
  • Dimple’s time series seems to assume equal spacing
  • NVD3 has been around a long time and is still active. It’s kind of a sloppy project though. The example code on the site doesn’t match what’s live. Some of the examples kill Google Chrome when run. There are no reference docs. I give up.
  • Vega looks too toolkitty and not enough libraryish. It frames itself as an analog to Protovis or D3, and I already know one of those. Also no time series example.
  • new TauCharts looks promising.

I need to investigate Highcharts. It’s not free software, but is free for non-commercial use.

dygraphs is sort of promising. It actually plots my data correctly but the default style is ugly. Also I’m not wild about canvas. It does a lot of fancy time series stuff out of the box though.

dygraph sample

openaddresses-conform Node code notes (plus bonus Python)

I’m working on porting openaddresses-conform from NodeJS to Python. First time I really sat down and read the code from start to finish. It’s remarkably clean and easy to follow, once you read past all the async-back-bending.

The basic flow of the tool is to take arbitrary source files, convert them to CSV files in a schema similar to the source, then convert that source CSV schema to the out.csv schema of OpenAddresses, the one with LON,LAT,NUMBER,STREET. It works by creating a lot of files on disk to hold intermediate results of transformations.

Here’s the core logic, which starts at processSource(). ConformCLI() is the command line tool entry point.

processSource(): download a source from the Internet, conform it, upload out.csv to S3.

conformCache() is the meat of the extract and transform process. It has comments!

  • Convert to UTF8: if source.conform.encoding is set, use iconv to convert source file to a new file with UTF8 encoding.
  • Convert to CSV: turn all types of sources in to a CSV file (see below on convert.js)
  • Merge columns if source.conform.merge is set.
  • Advanced merge columns if source.conform.advanced_merge is set.
  • Split address if source.conform.split is set.
  • Drop columns: prepare a new CSV file with just the core LON,LAT,NUMBER,STREET fields picked out of the processed source CSV.
  • Reproject to EPSG:4326. Only for CSV and GeoJSON files, creates a VRT file pointing at the processed source CSV and uses ogr2ogr to convert it to WGS 84.
  • Expand abbreviations: Fix Capitalization & drop null rows. This code is a bit woolly; it has a comment “I haven’t touched it because it’s magic” and there are no tests.

convert.js has five separate functions for converting different source types to a CSV file in the source schema.

  • shp2csv(): uses OGR2OGR to convert a shapefile to a CSV file. Also reprojects to EPSG:4326. Quite simple code.
  • polyshp2csv(): very similar to shp2csv(), but handles polygons.
  • json2csv(): uses geojson-stream to convert a GeoJSON file to a CSV file. Figure out headers from the first object’s properties. Converts polygons to points with a very simple average.
  • csv(): uses Node CSV modules to read the source CSV file and transform it into a cleaner CSV for further processing. Implements source.conform.headers and source.conform.skiplines.
  • xml(): uses ogr2ogr to convert an XML input to CSV, with reprojection. Very simple code, may not be used yet?
  • there’s code for computing the center of a polygon that’s duplicated in polyshp2csv() and json2csv().

openaddresses-conform has a small test suite. I believe it works on full source files, it’s more like functional tests than unit tests, running big chunks like conform or download and verifying the output is reasonable.

Existing Python port

Machine has its own Python code for doing the equivalent of downloadCache() and updateCache(). It’s quite different from the Node code strategy and is extra complicated because of the way Machine was a wrapper for invoking the Node code.

Very little of the extract and transform logic of conformCache() has been ported to Python but @iandees did some back in November. That code lives mostly in conform.py:ConvertToCsvTask. It works differently from the Node code. It basically takes whatever input file has been downloaded and uses Python OGR bindings to convert it to a CSV file in the schema of the source, plus an extra computed centroid. There’s no code yet to extract attributes or merge columns or anything. It’s streaming code, never loads the whole thing in to RAM.

I’m considering this choice to lean so heavily on OGR to process source files, it’s different from how the Node code is designed. I asked Ian and he said at the time all sources could be processed with ogr2ogr, so no need to write extra code for source CSV parsing, etc.

  • Check the type is .shp, .json, .csv, or .kml
  • Open source with OGR and figure out what field names are in it.
  • Set up OGR to transform the source SRS to EPSG:4326
  • Create a CSV file using csv.DictWriter with headers from the field name.
  • Iterate over features in the open OGR
  • For each feature, write a row to a CSV file with columns set to all fields from the feature. Also compute a centroid column.

I’ve never used the Python OGR bindings before. It’s pretty un-Pythonic and now I understand why Fiona exists. This list of Python Gotchas in GDAL will be a useful reference going forward. Apparently all the calls to Destroy() are unnecessary, but you do need to take care to manually dereference data sources.

Code in The OpenAddress Machine

I’m trying to help with the OpenAddress project, particularly Mike Migurski’s “machine” code for running a full analysis of the data. Particularly particularly the ditch-node branch. Managed to get the tests running after some version hassle.

Now I’m taking inventory of what all code is in the repo to understand where to work. These notes are probably only useful right about now (December 2014) and only for the ditch-node branch.

openaddr/*.py

This is the big thing, about 1700 lines of Python code. The architecture is a bit confusing. I don’t really understand how it’s managing threads / processes for parallelism. Also the actual ETL code is a bit convolved with the download and cache code, including S3.

  • __init.py__: grab bag of top level stuff. Key methods:
    • cache() and conform() are wrappers around Python code to download and process data from sources. This code wraps Python modules and uses multiprocessing.Process to run them as separate jobs. (see also jobs.py) The comments say these are Node wrappers, but they no longer are in this branch.
    • excerpt() pulls bits of data out of source files for user presentation. Contains some logic for parsing CSV, Shapefiles, etc to get a few rows out of them. See also sample.py. Excerpt does not use Process.
  • cache.py: Download from HTTP, FTP, and ESRI sources. I believe this code entirely writes to local disk and does not use S3. The ESRI code has logic about doing database-like queries on URLs and rewriting the ESRI proprietary JSON to GeoJSON
  • conform.py: python code to translate source data to the OpenAddress CSV output schema. Uses the OGR Python bindings, etc. I believe this is not complete.
  • jobs.py: script code to run a bunch of cache jobs, conform jobs, etc as separate threads. I’m not clear how this multithreading interacts with the multiprocessing code in __init.py__
  • process.py: a main program. this invokes all the work described in jobs.py, then does some processing to extract report-like information (like the map). This is doing I/O via S3 and caches, not so much local disk.
  • render.py: Cairo and geo code to draw the map of data sources
  • run.py: a wrapper for running stuff on EC2
  • sample.py: extract some sample features from a GeoJSON file, used for excerpts?
  • summarize.py: produce a report about the job run using an HTML template.
  • template/state.html: the actual HTML file that is visible at http://data.openaddresses.io/. Or rather a Jinja2 template.
  • template/user-data.sh; not sure what this is. It seems to be a templatized “run” script that installs everything from scratch on a new machine. I imagine this is what Mike runs first on a fresh EC2 instance.
  • geodata/*: shape files. I think this is used by render.py to draw pictures of FIPS codes.

openaddr-*

Not part of the Machine repo, these are four small Node projects that contain code for managing OpenAddresses data. This is the code that’s being “ditched” in the branch, and in fact I think it’s no longer used outside the tests.

  • openaddr-source: this is the openaddresses project itself. The main thing is sources/*.json, a bunch of JSON files that describe data sources and their conforms.
  • openaddr-download: code that takes a source URL as input and downloads it. lib/connectors.js has the actual code to do FTP and HTTP requests. Also is able to get data out of ESRI services using esri-dump, another program by Ian Dees that has both Python and Node versions.
  • openaddr-cache: another downloading program, this one is focussed on caching source data in S3.
  • openaddr-conform: the big program, glues together all the other scripts into a single thing that takes a source JSON as input, emits a processed CSV as output. So it has a little download and cache logic in it as well as a bunch of ETL code for extracting data out of source files and emitting it in the simple CSV schema OpenAddresses publishes. it in turn relies on ogr2ogr and other tools for extraction.

test.py, tests/

Test suite for The Machine. All the code is currently in test.py, just 11 tests. tests/ is test data files.

chef/

Scripts to set up an Ubuntu server to run The Machine. I haven’t actually run these on my dev box, just copied out bits of it as necessary. Some of the things it does:

  • run.sh: install Ruby and chef, the invoke chef-solo
  • role-ubuntu.json: spec for The Machine. Installs Python, Node, and four openaddr-* Node modules.
  • **/default.rb: specs for each package. There aren’t many interesting bits here. Node is wired to version 0.10.33. Python installs Cairo, GDAL, and PIP. The openaddr-* modules get installed in /var/opt. Only openaddr-conform is now needed for the tests to run in ditch-node, although I’m not sure about the full machine loop.

Node.js sqlite3: very slow bulk inserts

I’m running into a baffling problem where the straightforward way to use prepared statements in the MapBox sqlite3 Node.js code is super slow. Like inserting 100 rows in a table takes 16 seconds!

Update: found the problem, I wasn’t using transactions right. See bottom. Simple solution for faster bulk inserts in sqlite3: do them with a transaction.

The API docs have a strange note for Statement.finalize() which says “if you experience long delays before the next query is executed, explicitly finalizing your statement might be necessary”. I’m seeing exactly that. But after you’ve finalized it you can’t reuse the prepared statement; what’s the point of using statements at all then?

There’s notes online that naive bulk inserts in sqlite3 are slow, nothing to do with Node. See StackOverflow and Blog::Quibb. The quick fix I learned from both of those is to wrap the insert block in a transaction, because without that sqlite3 treats each insert as a separate transaction and is understandably slow. OK, so we’ll use a transaction.

But even with transactions using prepared statements is still slow in the Node version. I don’t know if this is a bug, me not understanding sqlite3 right, or me not understanding Node right. I am using serialized mode and trying to do simple nonconcurrent programming. The delay only occurs when the database is closed, btw, sqlite3 is accumulating the changes in a journal before committing them.

Three approaches:

  1. Call db.run(‘INSERT...’) a bunch of times. This is fast, but only if I wrap the inserts in a transaction.
  2. Prepare a statement once, then call stmt.run(‘INSERT...’) a bunch of times. This is slow whether I use a transaction or not.
  3. Prepare a separate statement for each row, then call stmt.run(‘INSERT...’) on it and then stmt.finalize(). This is fast.

Sample code is in this gist. “db” and “finalize” both take about 400ms on my Linux box. “reuse” takes 16 seconds to insert the 100 rows.

Update: the problem was I was creating the prepared statement before I did the “begin transaction”. Apparently that means the prepared statement is executed without the transaction context. Beginning the transaction and then preparing the statement, the three methods all run fast. I suspect the call to finalize has nothing to do with it, but I’m not sure.

Here’s the revision view: version one had the begin transaction too late.

Node.js sqlite3 error handling

This post is an exercise in trying to learn how to debug errors in Node.js programs.

Trying to write some sqlite3 code in Node.js. MapBox has a lovely Node module, but the docs are a bit thin and assume Node expertise I do not yet have. This morning’s challenge is trying to gracefully handle an error if database.run(“DROP TABLE”) fails. All work is running after database.serialize, so no concurrency.

By default with no error handling code, an error will cause an Unhandled ‘error’ event that kills the process. But you can’t just catch an exception because this is Node.js and exceptions don’t really work. So instead you need to specify a callback to database.run(), to get the Error (or else inspect the results of a successful statement.) Fair enough.

But what is the Error object in the callback? The sqlite3 docs don’t document this anywhere. In Chrome I’d just console.log() the object and use the lovely inspector. Node’s equivalent to the inspector is util.inspect, and you want to set showHidden to 1 to really see it. And voila:

{ [Error: SQLITE_ERROR: no such table: logs]
  [stack]: [Getter/Setter],
  [arguments]: undefined,
  [type]: undefined,
  [message]: 'SQLITE_ERROR: no such table: logs',
  errno: 1,
  code: 'SQLITE_ERROR' }

So this object looks like an ordinary Error object, with the message property. In addition it has errno and code properties. And now I know.

Another way to have learned all this would be to use the Node debugger. It’s pretty primitive, but you can set breakpoints in your code with the “debugger;” statement or from the debugger command line with “sb(lineno)”. Once it breaks you want to run “repl” to switch to the scope of your running script, then you can inspect objects. It all works but is a bit awkward without a GUI. I miss Chrome’s beautiful debugger; should try out node-inspector or something similar.

The irony of all this is I don’t even need too handle this error; sqlite supports “DROP TABLE IF EXISTS”. But oh well, now I know more about sqlite3 error handling and how to debug Node programs.

D3js mouseover tooltip

It took me three hours, but I added a mouseover tooltip to my LoL netlog graphs. It turns out there’s three ways to do this.

  1. Use svg:title or svg:text and rely on the default browser hover action to show it. Totally ghetto, but it does work.
  2. Catch mouseover events on your actual chart elements. If you bound your data sensibly, the event handler gets the datum that was bound to the element that got the event passed right to it. This works great for bar charts as long as you don’t mind the popups only showing up on the bars, not the whitespace. Not so good for line charts or other things.
  3. Add an overlay to the entire chart area you want to capture events in. Unfortunately no useful data is bound if you do this. So you have to use d3.mouse() to get the relative X,Y in pixels of the mouse position, then shove that through scale.invert() to map that back to data space. Here’s a demo of that technique. It’s a lot more work, but now you have mouse events for the whole chart area, not just the marks.

I went for option #3 and really it looks pretty great. The other tricky part is I was reading the timestamp from the X axis of my time series chart, but then finding the specific row of timeseries data that corresponds to that timestamp is not so easy. I ended up doing a linear search in my data array; not awesome, but will work OK for me.

The other half of the problem is displaying the tooltips. I ended up going with a div element with visiblity toggled by mouseenter/mouseleave. The tooltip is positioned absolutely with CSS, and the mousemove handler positions the tooltip relative to the event pageX and pageY. Important to make sure the tooltip div doesn’t grab the mouse events. I did that with positioning, but probably better to use the pointer-events CSS option.

 

Reconsidering Node

Having done a bit of work deploying a Node server I may not use it afterall. Things I don’t like:

  1. Lack of standard production scripts
  2. Lack of blanket error handling for servers; exceptions kill servers
  3. Difficulty preventing memory leaks in servers. Closures capture memory in complex ways and V8 isn’t always able to GC it.

These are all solvable problems, but I’m not sure I want or need to solve them for my very simple server. The main advantage I get from Node is that I can share some Javascript parsing code between the browser and the server. But I’m not sure I really need that.

Truthfully I don’t need much if any custom server code at all. Just a bucket to post data to and be able to retrieve it again. I wonder if I can do that entirely with client-side Javascript and some basic S3 API.

 

Starting a Node server in Ubuntu

My Node server sort of works and I’m ready to put it into production. I need some sort of start script. What to do? Naturally, the Node world has to reinvent everything and there’s no standard way to do this. But most docs talk about using Upstart (the Ubuntu variant of init scripts), plus monit or forever to keep the Node process running when it inevitably crashes. (Because of course, this is new tech, it’s gonna crash!).

Also some scary notes about catching exceptions globally so your server doesn’t fail simply because of a bug in one user request, but I think Express takes care of that me. Update haha joke’s on me, by default the whole server crashes if you have an unhandled error because “By the very nature of how throw works in JavaScript, there is almost never any way to safely pick up where you left off, without leaking references, or creating some other sort of undefined brittle state.” Apparenly Node domains are the way to deal with this, some notes here.

I ended up just using a trash shell script for /etc/rc.local because it’s too much bother to do it right. I wish that here in 2014 we finally had a basic simple standard way to deploy and run server scripts in production. So many solutions that are either too ad hoc (upstart) or too complex (Puppet and friends)

Some resources:

 

 

My first Node server

I rewrote this Python CGI server in to a Node.js server, or most of one. The main thing it does is accept POST content, writing it to a file and returning a generated filename. (Yes, that’s really a PUT. I know.) The Python CGI is 39 lines, the Node.js is 52 with 12 lines of NPM configuration. But then the Node version is a full server and has fancier message handling. Things I learned:

The Node community and docs are good but nowhere near as mature as Python. Also the Node philosophy is one small stable core, then you download add-on modules. Batteries not included. The core Node API is well documented. Beyond that you’re hunting through npmjs or maybe node.js modules for more.

NPM isn’t so scary. Grab a template, put your dependencies in a packages.json, run “npm install” and it will build a node_modules directory for you with all the dependencies. It’s good that’s a default tool deep in the Node chain. More info on npm.

express is a reasonable webapp framework and has a nice tutorial guide. I like the router style of specifying handlers.

node by default doesn’t do anything with POST body content, you have to install middleware to handle the input bytes. senchalabs / connect seems to be the default choice for doing fancy things like parsing JSON, etc. I just want the plain message text so the raw-body middleware middle is for me. It’s an awful lot of boilerplate to set up.

I’m gonna need a content hash; here’s a pure Javascript implementation of Murmur 128 that’s in npm as “murmurhash3js”. Hard to come by; it’s tricky doing true bit twiddling in Javascript without proper bit types. NPM turns up 10 different Murmur implentations, many of which either require native code or only implement the 32 bit hash.

 

My first Mocha test

OK I’m writing tests in Mocha now! Yay! But what a lot of boilerplate. I want to test a javascript file that works great in a browser. It’s named “lol-netlog-parse.js” and contains a single top level function named parseLolNetlog. Let’s just do a fake test for now.

require('chai').should();
var parse = require("../webapp/lol-netlog-parse")

describe('lol-netlog-parse', function() {
    describe('parseLolNetlog', function() {
        it('Should throw an error', function() {
            "foo".should.equal("bar");
        });
})});

This actually works. But only if I wrap my browser code in some require.js boilerplate to set exports. But then the exports object doesn’t exist in browsers, so I have to do extra work to provide a stub exports object in the browser so that it will still run.

It’s also 7 lines of code for a 1 line test. All test frameworks have their boilerplate, and I understand why this all helps with more complex text harnesses. Still sometimes I think Python doctest had the write idea.. The relative path in the require is a pretty ugly wart too, maybe if I knew more about Node and include paths I wouldn’t have to do that.

I’ve written this in the BDD style, where the function “suite” is named “describe” in some vague attempt at literate programming. I did this because it’s the default style Mocha wants and I don’t want to have to add the “-u” command line flag to use the TDD style. It’s very clever that the code supports 4+ different ways to write unit tests but that’s 3+ more than is necessary. One way to do things; it’s a virtue.

I’m fully embracing the BDD style and using chai’s scary Object prototype manipulation to see if I like it.

Javascript unit testing options

I want to write some Javascript unit tests. I’d hoped Node.js would be mature enough there was one clear answer from that community, but there’s not. This article was useful but two years old. Here’s some options:

  • Mocha: fancy
  • NodeUnit: simple
  • vows: d3js uses this, but I’ve seen some comments it’s not the fresh choice
  • QUnit: been around a long time, browser oriented

I tried looking at most starred modules and nodejsmodules.org to try to figure out what the cool kids were using but it was too much work.

I’ll probably use Mocha unless it seems too hard to do simple things. It seems particularly crazy that there’s not even a consensus assert module. “There’s more than one way to do things” is usually not a virtue.

 

on the idea of reusable D3 chart components

I love D3.js, it’s amazing. But one thing that bugs me is the style it encourages is to write new chart types inline in Javascript. There’s not much in the way for reusable charts, D3’s focus is on making it easier to build your own charts in Javascript. So I find myself painfully rewriting basic histograms and time series and the like. In some sense this is by design; Mike’s style is to parsimonious Javascript and making it easy to actually build charts by hand. And it’s good in that it encourages a diversity of visualizations. But sometimes you just want a simple timeseries, you know?

Of course nothing prevents people from building a chart component suite on top of D3. And lots of people have. Here’s a very quick review of looking at the project web sites for a bunch of efforts. I’m only looking at their ability to produce static visualizations. An API supporting interactions and transitions is significantly more subtle to get right.

The libraries group into two categories. Declarative libraries let you specify a chart simply with a bunch of configuration parameters, no real executable Javascript code. In general, my guess is these are great for doing simple things and hard to customize to go beyond what the library was designed to do. Programmable libraries are more like toolkits on top of D3 that still require some real programming to get results. But then they may give you more access to do complex customizations and interactions.

Declarative libraries

Rickshaw has been around awhile and looks good.

C3.js looks a lot like Rickshaw, see the bar chart example. Seems solid and simple.

Vega is strictly declarative, to the point of emphasizing chart specifications are JSON objects and completely wrapping D3. Has a neat live editor, headless rendering tools, and high-falutin language about “visual grammar”. It’s an impressive package.

Ember Charts by Addepar has some basic chart types. It’s tied to the Ember.js framework and needs Node to develop, also not a lot of activity on GitHub, so I didn’t investigate further.

Tenxer xCharts is declarative but with some programmatic customization. Examples feature using closures inside the chart definitions. Also has notes on customization and extension. Drawbacks are relatively few chart types and that there’s been no code development in eight months.

Programmable libraries

Towards Reusable Charts: Mike’s own opinion on reusability in D3. Advocates encapsulating a chart type in a closure. Doesn’t go much beyond establishing a design pattern. Some of the D3 plugins like Sankey and Horizon are good examples.

NVD3 is a reusable component library that works hard to respect access to underlying D3 design. It’s been around for awhile and seems pretty mature, not many commits in the past few months. The Discrete Bar example is appealingly simple.

Dimple adds chart types on top of D3 that you configure with simple declarative code. But then the advanced examples show you dropping in to the underlying D3 to extend the charts beyond what Dimple provides, which is great.

Bocoup d3.chart is a framework for creating charts, not a chart library itself. Its design is informed by a very thoughtful critique on reusable chart approaches. But it’s pretty early days and it’s aimed more at people writing chart libraries than folks just wanting to draw some charts. Also, I’m bummed the examples aren’t rendering right in JSFiddle. Overall my impression is these guys are pushing on solving the problem I want solved right now.

Summary

I’d use Vega or maybe Rickshaw if I just want some simple graphs. Dimple looks to be the most promising programmable system worth a closer look. I’m stubborn and foolish and like shaving yaks so I’m going to write my own little histogram thing using Mike’s suggested pattern just for the experience. Maybe I’ll end up using Dimple for future projects.

Example

Here’s an example trivial new chart type based on Mike’s proposed format. I’m not very happy with this result.

Update

dc.js is an interesting option. It takes too much programming to really just be reusable chart templates, but it has a nice way of packaging in crossfilter and aiding making basic data charts instead of arbitrary D3 SVG marks.

 

chosen, for Javascript selection

Chosen is neat; it’s a Javascript library that replaces the usual browser form select dropdown with a much more capable version. Check the demo. The only drawback is it requires jQuery or Prototype.

But not anymore! There’s a version that works natively; here’s a pull request for it based on this fork. I’ve built it and it seems to work. 30k JS + 10k CSS after minification. The jQuery version is only 26k JS, but then you also need 80k of jQuery to run it. So big win.

I had a heck of a time building this. Not because it’s complicated, it’s just a few files. But “native” in this case actually means “Coffeescript and Sass with a Grunt build and btw that implies a Ruby dependency”. Bah, kids these days. Here’s a copy of my build, the “public” directory, which contains the minified Javascript, CSS, and a demo that seems to work. I might have built this wrong so better to get it from official sources.

 

d3.js: using CSV for numbers

D3 has two main ways to load data; JSON files or CSV files. JSON is generally better but bloated for long repeated rows of data, for which CSV is better because it only prints the key names once. But CSV has a drawback which is that it’s untyped. So D3 just lamely loads everything as strings. Most of the time Javascript’s automatic string to float conversion lets you ignore that but it fails in some places, like sorting with d3.ascending.

Fortunately D3’s CSV library lets you create an accessor function which manipulates the data as you load it. Here’s a function which will load every row and try to convert things to numbers. I wrote it in very verbose Javascript to make it clear what’s going on. I don’t care about the number of lines, but I do wonder if this is less efficient than possible.

// convert strings to numbers in CSV
function convertNumbers(row) {
  var r = {};
  for (var k in row) {
    r[k] = +row[k];
    if (isNaN(r[k])) {
      r[k] = row[k];
    }
  }
  return r;
}

d3.csv("data.csv", convertNumbers, function(error, inputData) {
  // do work on the data here
}

Note that the accessor function has to create a new object; you can’t just return the one the accessor passes you.

Chrome extension gripes

Working along on my Chrome extension, generally impressed with how well thought out and thoroughly documented the extension support is. That being said, some wrinkles...

There’s no support for reloading extension code when it’s changed during development. There’s some hacks, I’m using Extensions Reloader which gives me a button to press to reload the Javascript code. But it won’t reload the manifest, so it’s not a complete solution. And even then I have to hit the extension reload the button then refresh the page to debug stuff, it’s awkward.

Chrome has adopted an awkward API for signaling errors in the extension API, the variable chrome.runtime.lastError is set. This makes checking for errors a huge nuisance, but maybe it’s the only way to do this given the weird lifecycle of extensions? Good thing Javascript is single threaded :-P. It’s a shame Javascript’s built in exceptions are not very useful. I like the D3 pattern of setting an error object on the callback function, at least it makes the error variable a bit more explicit.

The Chrome extension storage API is fairly capable, I particularly like that it lets you store data in a place that Chrome synchronizes between the user’s browsers. But the API is just enough different from DOM localStorage to be a bit obnoxious. Also the get() method is incredibly slow, like 500ms to retrieve my 10 bytes of state. That means I can’t just store stuff there and fetch it from my content script, too slow for something whose purpose is to modify a page’s presentation. So I have to create a background page and move the config fetching there, an unwelcome complication. Update: it’s not always so slow. Sometimes it’s only 40ms. Sometimes its 200ms. I’m running a bunch of other extensions, should test it more cleanly.

 

Leaflet GeoJSON vector tiles

Half-finished notes, but I don’t want to lose them.

Leaflet doesn’t have a stock plugin for GeoJSON vector tiles. I believe Glen Robertson’s leaflet-tilelayer-geojson is the most complete and correct plugin, but it renders pretty slowly (several seconds for cached data). My river vector tiles tutorial includes a TileLayer.d3_geoJSON.js that renders about 10x faster, but because it uses D3 instead of Leaflet to do the GeoJSON rendering it lacks full Leaflet integration. For instance, there’s no way to bind a Leaflet popup to a LineString.

Over on the Leaflet-js mailing list I started a discussion “GeoJSON performance? River vector tile map, trying to figure out how to make Glen’s approach using Leaflet GeoJSON faster. Norbert Renner responded with some terrific experimental work that made rendering much faster, but it was sort of a one-off spike rather than a reusable improvement. Someone should spend some time with his optimizations and see if they can be ported to work in the general purpose library.

 

SMASH JSON

D3 3.1 includes support for SMASH, a way to make subset builds of D3. One thing I use D3 a lot for is the XmlHttpRequest support, particularly d3.json(). Most people use JQuery for AJAX, but I like D3’s version, but in either case I don’t want a 100k library just for a wrapper for XHR. Anyway..

$ smash src/start.js src/xhr/*.js src/dsv/*.js src/end.js | uglifyjs -c -m | gzip | wc -c
2276

Just JSON support is only 1464 bytes compressed, but it’s nice to bring in the CSV/TSV parsing. It’s 12k unminimized. Nice way to build a minimal XHR library. Didn’t test that it actually works ;-P

Animating CSS class changes with D3

In a previous blog post I discovered that using .style(“fill”, ...) to set colors was way, way slower than using .attr(“class”, ...) to just switch the class. Which is all well and good, but what if I want to animate the color change? Ie: not just switch from white to black but use D3 transitions to show the grey between? Here are some options.

Class hackery: create a bunch of CSS classes “grey0”, “grey1”, “grey2”, ... that are a ramp from black to white. Then set .attr(“class”, greyN) with a tweening function that uses the classes. Seems awfully inelegant and hard to get right, particularly when you consider nonlinear easing functions.

Stylesheet manipulation. You can grab the CSS stylesheet itself and modify it. I found one D3 example. I have read lots of admonishments that modifying the CSS is hacky, flaky,  and works differently in different browsers. No idea if this would be suitably fast; I can’t imagine browsers optimize this usage.

CSS transitions. Nominal support is pretty good, although I’m breaking my rule not to use vendor prefix CSS in my projects (stupid WebKit). Something as simple as rect { -webkit-transition: fill 0.4s } looks pretty good in Chrome. It does not look good in Firefox: it doesn’t seem to actually tween the color so really all you get is a 0.4s delay. No idea how it looks in Opera or IE. Oh well, I design for WebKit anyway.

CSS transitions have nice control over the easing function. However I don’t see any control over the interpolation, something that’s quite important and subtle when tweening colors. The spec says it interpolates in RGBA space which is just about the worst possible choice. Fortunately my example is tweening white and bright yellow, so I can get away with it, but a red to blue tween probably looks awful using CSS.

Optimizing zipdecode

Are there any good tools for profiling rich D3 webapps, testing the changes in Javascript, CSS, and SVG design for how much time it saves? The best I’ve come up with so far is inserting calls to Date.now() in my code and using console.log() to print numbers. It works, but it’s primitive.

Chrome’s Profile tool doesn’t help me much. The Javascript profiler does, actually, giving me detailed analysis of why something is taking so long. But that’s a forensics tool, what I need is a benchmark wrapper around what I’m doing, something like Python’s timeit. But I don’t want to measure just Javascript code; I’m more worried about the CSS selection time, the DOM manipulation time, the browser render time.

Anyway, my Zipdecode thing is too slow. I’d like to optimize it, in particular so the interaction on the user typing a zip code is faster (and ideally, animateable). My original code is intentionally naive: select all 40,000 dots and set their “fill” CSS style to a specific color. It’s bad:

    d3.select("#zipdots").selectAll("rect")
        .style("fill", function(d, i) {
            if (l > 0 && d.zip.substr(0, l) == selectedZip) {
                return selectedColor;
            } else {
                return unselectedColor;
            }
        });

This take 140ms to do the update (and 650ms for the initial render).

Short circuiting the logic test about d.zip.substr() reveals that very little time is spent doing that. Replacing the call to .style() with a call to .each() that doesn’t manipulate the style drops the time down to 6ms; all my time is spent modifying the style, not creating the selection and iterating through it.

So the problem is mutating the .style(); no big surprise, but I can measure it! Let’s see how I can change the code to be better.

The obvious thing to try is to set the CSS class instead of a style property. The drawback with classes is there’s no way to interpolate the color easily. More on this in another blog post. But it works great, dropping the update time from 140ms to 25-30ms. Feels much faster. I tried this two ways

.attr("class", function(d) { return zipSelected(d.zip) ? "selected" : "unselected" })

.classed("selected", function(d) { return zipSelected(d.zip); })
.classed("unselected", function(d) { return ! zipSelected(d.zip); })

The first way using .attr() is 25-30ms; the second way calling .classed() twice is about 40ms, probably all from the overhead of that extra iterative function. I don’t think there’s anything particularly wrong about using .attr() to set classes, and since it’s simpler and faster I’ll stick with it.

A whole different optimization is treating to be smarter about the selection, not select all 40,000 dots every time. The code is not efficient in one important way; if I change the selection from “94” to “941” only 30 dots really need to be updated, but I go ahead and modify all 40,000 dots. But I don’t much care about fixing that because the case I’m most worried about is going from “” to “9”, where a lot of dots need to be touch (at most 1/10th of all zip codes, about 4000 dots).

But apparently I’m wrong. A version of this pull request from Ziggy Jonsson drops my interaction time from 140ms to 20ms, even less if the user is selecting a very narrow range of zips like “9414”. The key improvement is he’s only modifying the dots that are affected. (In addition he’s avoiding some calls to d3.select(), but I think that’s a smaller effect). Works well, but for my tutorial purposes I don’t like how it maintains this giant cached list of  all possible zip selections.

Another way to achieve the same effect would be  to use the hierarchy of the DOM to model the hierarchy of zip codes. Ie: instead of all the dots being top level <rect> elements, have a <g id=”9″> that contains all the 9xxxx zip codes (and in turn a <g id=”94″> inside that, etc. This would allow me to select with precision just the dots that need addressing, and might make the slower .style() method acceptable. But it significantly complicates the code and I don’t feel like doing that now that I’ve got stuff running pretty well. If I do it might be worth not going for the full hierarchical thing, just break zip code dots into the 10 top level categories.

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.

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.

OpenStreetMap iD editor

The new Javascript OSM editor iD is working on live data now. So I made an edit, adding a pond I know is there by tracing it on Bing. Works pretty well, it’s an impressive JS app. Interactivity is not great, need 30fps+ responsive user feedback to really feel right. But it’s an early alpha, I’m sure they’ll get there.

The CSS looks home rolled other than a stock reset. Here’s the third party JS libraries they use:

<script src=’js/lib/lodash.js’></script>
<script src=’js/lib/d3.v3.js’></script>
<script src=’js/lib/sha.js’></script>
<script src=’js/lib/ohauth.js’></script>
<script src=’js/lib/jxon.js’></script>
<script src=’js/lib/d3.typeahead.js’></script>
<script src=’js/lib/d3.geo.tile.js’></script>
<script src=’js/lib/d3.size.js’></script>
<script src=’js/lib/d3.trigger.js’></script>
<script src=’js/lib/d3.keybinding.js’></script>
<script src=’js/lib/d3.tail.js’></script>
<script src=’js/lib/d3-compat.js’></script>
<script src=’js/lib/queue.js’></script>
<script src=’js/lib/bootstrap-tooltip.js’></script>
<script src=’js/lib/rtree.js’></script>

 

Notice what’s missing? A typical slippy map library like Leaflet or OpenLayers. He’s using D3 instead. I hadn’t realized how far along d3.geo.tile has come. Works pretty well on iOS too!

In addition to D3 there’s Lo-Dash (an Underscore alternative), SHA and OAuth (for login), JXON (for XML parsing?), Queue (for async), Bootstrap tooltips, and the RTree data structure for spatial lookups.

HTML5 template with D3 and Leaflet

I’m often making D3 pages, or Leaflet maps, or some fancy Javascript thing. I always start with a blank editor and then have to remember all the HTML 5 boilerplate. So here’s some boilerplate, a template for starting a D3 + Leaflet project. The browser window is filled with the map.

This validates HTML 5. I’m not confident I’m setting the viewport correctly but this looks right in Chrome, Firefox, and Mobile Safari so good enough for me. I hate that HTML has so much boilerplate associated with it. Update: Mike points out HTML 5 doesn’t require so much boilerplate; tags like head and body are now optional. I don’t know what that means for old browser compatibility though so I’ll stick with the extra words. (Useful reference.)

<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0"/>

<title>Leaflet template</title>

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.css" />
<!--[if lte IE 8]>
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.ie.css" />
<![endif]-->
<script src="http://cdn.leafletjs.com/leaflet-0.5/leaflet.js"></script>

<script src="http://d3js.org/d3.v3.min.js"></script>

<style type="text/css">
html, body { height: 100% }
#map { min-height: 100%; }
body {
    margin: 0;
    font-family: Helvetica, Arial, sans-serif; font-size: 12px;
    overflow: hidden;
    background-color: #f00;
}
</style>

</head><body>

<div id="map"></div>

<script type="text/javascript">
var map = L.map('map');
map.setView([37.7504, -122.4425], 13);
var basemap = L.tileLayer('http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png', {
        attribution: '<a href="http://content.stamen.com/dotspotting_toner_cartography_available_for_download">Stamen Toner</a>, <a href="http://www.openstreetmap.org/">OpenStreetMap</a>, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
        maxZoom: 17
});
basemap.addTo(map);
</script>
</body></html>

Javascript string storage

Helping a friend think through a memory leak on his Heroku / Node.js server, he had a problem where nothing was being garbage collected. Big ol’ memory leak. Because NodeJS / V8 is so new as a server environment there’s not a lot of understanding of memory tuning, instrumentation, etc. Java has a lot of sins but after 10 years we all know how to make the JVM perform well; Javascript, not so much.

Anyway, long story short, my friend did some measurement and thinking and realized the problem. His server makes API calls that get a big JSON response from some other server. He extracts some data from that JSON and then throws the rest of the response away. Only it looks like the responses were never getting GCed. Best guess; the data he kept is a substring of the original JSON response, and V8 implements substrings as pointers into memory for the original interned string. So that original string can’t be collected.

His solution was to gzip the data he needed. Which is smaller in memory, but even better means that it’s a real new string and not a copy. It seems to have fixed the problem.

Update: this may not have been the problem or a correct diagnosis at all. He’d been setting  --max_old_space_size incorrectly; fixing that may have fixed everything.

Artisinal integers, part 2

The connoisseurs of fine artisinal integers discovered my blog post about Cantor pairing and asked some questions. Apparently there’s a sudden interest in creating more foundries and my proposal for allowing an infinite number of sequences thanks to the magic of infinity got some reading. However, taking advantage of that infinity requires an O(n^2) generator algorithm, a bit impractical. How impractical?

One reasonable question is “when do we generate integers bigger than 2^64?”, since that’s such an awkward number for our 64-fingered CPUs. With the current simple even/odd split for two foundries, we can generate 2^63 integers before running out of room, so many it’s hard to call them artisinal really. But with the Cantor numbering we hit 2^64 much sooner: it will be site #3,327,948,883 generating its 2,746,052,116th number that is 2^64. Or to put it in plain English, every foundry gets to generate about two billion integers before hitting the limit.

2^53 is another practical limit, since that’s the biggest integer Javascript can handle (and then, only if you’re lucky). Sites can only generate about two million integers before hitting 2^53. That’s low enough to cause a real crisis in artisinal integers, particularly for the Node.js hipsters.

I submit the practical solution is to pick a large fixed number of integer foundries, say 1000, and simply have each foundry agree to generate numbers in the sequence (eg) 1003, 2003, 3003, 4003. It lacks elegance but is probably sufficient to meet demand. It also sets up a perfect excuse for a hipster sellout should the demand for artisinal foundries explode and the number boffins need to start paying for their fixed gear bicycles and ironic bottled beers; simply start charging for those last few valuable foundry IDs. Scarcity is the business model’s best friend.

#!/usr/bin/env python

# Cantor pairing function, a bijection from Z*Z to Z. 
# http://nelsonslog.wordpress.com/2012/07/29/artisinal-integers/
# http://en.wikipedia.org/wiki/Cantor_pairing_function#Cantor_pairing_function

import math

def cantor(x, y):
    return (x + y) * (x + y + 1) / 2 + y

# could cache calculations for efficiency
def _w(z):
    n = math.sqrt(8*z + 1)
    return int(math.floor((n-1)/2))

def _t(z):
    w = _w(z)
    return (w*w + w) / 2

def invCantor(z):
    t = _t(z)
    w = _w(z)
    y = z - t
    x = w - y
    return (x, y)

for i in range(0,10):
    print cantor(0, i),
print

for i in "0 2 5 9 14 20 27 35 44 54".split():
    print invCantor(int(i)),
print

print cantor(18225714/2, 1)
print invCantor(41522085907653)

for power in 64, 43: 
    biggy = 2L ** power
    x, y = invCantor(biggy)
    print biggy, (x, y), (math.log(x, 2), math.log(y, 2))

dynamically loading javascript

As near as I can tell, Javascript lacks a function to load more Javascript from a URL. There’s eval(), but that takes strings so it’s a bit of work. The usual hack is to add a <script> tag dynamically to the document which as a side effect causes the page to load the referenced script. Here’s a wrapper function for that, courtesy of this July 2009 writeup:

function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

It’s overkill, but it’s cut and paste.I needed this to add jQuery to a page so I could then dump the URLs out of it with $("a").each(console.log(this.href))

Mike tells me he uses this bookmarklet to add D3 to pages. Node.js has the require() function. If you’re serious about dynamic code loading in browsers then requirejs looks good.

JSONP Ajax error handling

I’m using the Twitter API for a project. The results it returns are.. awkward. In particular you often get errors for legitimate requests, but if you try the exact same request again a few seconds later it will work. Presumably their internal caching / timeouts.

Anyway, I need a good way to do error handling of AJAX calls in Javascript. But because I’m doing cross-origin stuff (and Twitter doesn’t set the CORS header) I’m stuck using JSONP. And JSONP error handling sucks, presumably because the crazy <script> eval hack that makes JSONP work doesn’t let Javascript code handle errors.

Options:

  1. jQuery Timeouts. Since version 1.5, jQuery will throw a timeout after N seconds if the JSONP call did not succeed. This gives you limited error notification, albeit asynchronously.
  2. suppress_response_codes. This is a special hack to the Twitter API to always have them return HTTP 200 OK, even on errors, and let you figure out the error in the body. Using this lets you bypass the browser’s own handling of, say, a 400 error and let your Javascript code handle it. Ie when I’m rate limited I get a “400 (Bad Request)” from the API which Chrome intercepts and all I see is a timeout. Presumably with this Twitter API setting, I’ll get a 200 reply immediately that contains info on the error I can parse.
  3. Try Zepto. Their JSONP code is different from jQuery and a preliminary look suggests it might have a better error handling strategy. Seems unlikely, but worth a look?

JSONP is such a horrible hack. I wish Twitter would just set the CORS header and I could use a proper JSON call with XmlHttpRequest with proper error handling. I could do that myself if I proxy the traffic on my server, but then it’s my bandwidth and my IP address being rate limited.

Javascript Date sadness

There are many things to dislike about the Javascript Date library, but this one keeps tripping me up so I better write it down:

typeof(Date(1341070612432))
"string"

typeof(new Date(1341070612432))
"object"

The confusing thing is that Date is both a Javascript class that returns Date objects and a convenience function that returns strings. Most of my Javascript programming is in D3’s style which never uses constructors or the “new” keyword; instead its “classes” are functions that return objects. But a lot of core Javascript isn’t like that. Neither is Leaflet; I keep forgetting to say “new” there too.

Javascript data compression

I’m storing 500k blobs in localStorage. I’d like to make them smaller. In any sane platform there’s some compression function in the library: gzip(data) and it’s 30% the original size. But no, not in Javascript. And there’s no clear third party library that everyone agrees is great.

I found a good roundup of compression options from October 2011, it’s a series of 4 blog posts. It has a lot of detail on speed and compression of 11 different libraries. Hilariously, about half of them simply don’t work or are only capable of doing half the compression / decompression. This StackExchange question is good because it’s specific to localStorage.

Part of the problem is just like Javascript doesn’t have an integer type, it also doesn’t have a byte array type. The basic String (DOMString?) is close, but really it’s a sequence of Unicode characters. So to be efficient you really want to use all 16 bits for each character in the String, although that StackExchange question recommends only using 15 bits to avoid issues with UTF-16. And suddenly we’re at awkward storage. And even storing only 8 bits per word in the String, a lot of these compression libraries seem to have problems storing various “special characters”; apparently getting encoding and decoding right is not easy. You see a lot of base64 encoded data in Javascript strings out there, yuck.

Javascript typed arrays look to be the standard solution for binary data; you create a byte array and then get views into it treating each word as an Int8 or Int32 or whatever. I’ve never worked with them and am unsure about compatibility in current implementations. Also I haven’t found an existing Javascript library that compresses using them.

Related: see this discussion of byte array objects. He discards Strings early because they’re immutable and so modifying a single byte requires a full String copy. He compares ordinary Javascript Arrays, typed arrays ArrayBuffer, and (clever), ImageData. He finds the APIs for the fancy array types are unreasonably slow. No evaluation of size efficiency or ease of use, things I care about.

I think my solution is to use some very simple LZW compression or the like, combined with an encoder that uses 15 bits per word in a String. It’s be nice to wrap this up in a simple API, something that takes an Object, stringifies it with JSON, compresses it, and returns a safe String that can later be unpickled back into the Object. Not sure I need it enough to bother.

HTML5 localStorage

I played around with HTML5 localStorage today, a way for Javascript on a web site to store persistent data client-side in the browser with a simple key/value store. It’s pretty neat, works well in modern browsers (IE8+, everything else), but is kind of slow. Here’s what I learned.

Useful docs:

The API is really simple. Boils down to

  • setItem(key, value)
  • getItem(key)
  • removeItem(key)
  • clear()
  • key(index)
  • length

key and value are both strings. If you want to store Object values, as is sensible, you have to serialize them yourself to JSON like this.

length and key(index) let you iterate over the collection in an undefined order. Also it’s undefined what happens if someone asynchronously modifies localStorage while you’re iterating. localStorage is not an Array, so you can’t use modern methods like forEach() on them. Back to the old school for loop.

It all works pretty well and is straightforward. My one complaint is it seems pretty slow, at least in Chrome. I’ve put about 3200 objects in localStorage, about 200 bytes each. That’s not much data, but with it even just iterating over all the keys (doing nothing with the values) is slow, like 400ms. Here’s my code that is so slow:

function getLocalKeys() {
    var localKeys = [];
    var n = localStorage.length;
    for (var i = 0; i < n; i++) {
        localKeys.push(localStorage.key(i));
    }
    return localKeys;
}

Surprisingly, doing real work on the values isn’t much slower. I can parse all the value strings back into Javascript objects and then sort an array of all 3000 objects and it doesn’t add appreciable time to the work. That suggests all the time is spent in the localStorage implementation itself. I wonder if it’s actually going to disk? Need to dig in more.

I could optimize by storing my collection of all keys itself as a value in localStorage, sort of my own index. But that’s brittle if I forget to update it in the code.

Update: some performance notes here and here confirm it’s not just me seeing bad performance. One issue is that localStorage needs to be synchronous across multiple browser tabs, so localStorage may be implemented as purely on-disk to do that easily. Both benchmarks suggest Chrome is uniquely slow and indeed my code runs visibly faster in Safari.

Update 2: I rewrote my code to simply have one object in localStorage, itself a stringified Javascript Object operating as a hash table. That works much, much faster; the storage time is negligible. My data is 500k stringified, btw, uncomfortably close to the 2.5MB limit!

Using the Javascript console to get at image URLs

I wanted to download 1300+ images from a Dropbox gallery. Unfortunately Dropbox’s UI is so dynamic with Javascript there’s no simple list of URLs. So instead of trying to reverse engineer their code I opened up the Javascript console after the page had loaded to extract the dynamically generated HTML links.

 

l = document.querySelectorAll("a.filename-link")
a = []
for (i = 0; i < l.length; i++) { a.push(l[i].href); }
for (i = 0; i < a.length; i++) { console.log(a[i]); }

Pretty straightforward, but a lot more tinkering during the process. Those URLs lead to the image page; to get to the actual JPG you have to append “?dl=1” to the URL.

Serving mbtiles tiles for slippy maps

I’m playing with TileMill (see my blog post here). TileMill publishes to an mbtiles file, a sqlite3 database that contains the rendered image tiles. One simple file, so nice! Now, how to serve it? The simplest solution is TileStream hosting, but I’m too cheap and hackish to pay the very reasonable $50 / month.

So I set up a tile server on TileStache instead, a Python system. You can see the setup on GitHub. It took about four hours to get working, even though none of it is too complex. Here’s my notes.

  1. Install TileStache via Python easy_install and configure. It’s pretty simple, the only subtle thing is that TileStache wants a cache. This may not be necessary with pre-rendered mbtiles bundles but it was easy enough to set up memcached and configure it.
  2. Set up TileStache to render via CGI, with a CGI script and a bit of Apache config. CGI is a bad way to serve things, but I’d hoped it was sufficient and it was easy to get going. Turns out to be unacceptably slow.
  3. I tried a couple of failed approaches for WSGI. First I tried TileStache’s built in WerkZeug server. This works and is faster than CGI, but lacks administrative scripts to wrap it. Then I tried Apache WSGI and ran into an error with no useful debug output. Gave up on that.
  4. Set up gunicorn, the excellent Python asynchronous server for WSGI. It’s easy to set up on Debian if you get version 0.13 from Backports, it comes with nice administration scripts. Just needs a little config file. I also installed python-gevent for an async worker.
Doing all this, my crappy old single CPU server with 1 gig of RAM can handle serving a map to a single user at acceptable speed. It can probably do more than that, I haven’t load tested it.
I left some things not done, this was intended as a quick hack:
  • gunicorn really wants a proxy HTTP server like nginx in front of it. Good idea, but I didn’t want to bother. The bummer is gunicorn doesn’t set any caching headers at all; really need those for a real deployment.
  • The cool kids building TileMill are doing everything with Node.js these days. Their TileStream server would be another option, but getting Node running on Debian was too much work for a quick hack.
It’s a little surprising that MBTiles is so complex to serve. It’s basically just a big archive of JPG images, it’d be nice to have a little C program to serve it blindingly fast. “mbserv foo.mbtiles --port 8989”. TileStache is a big program that does a lot of stuff, but even TileStream is 900+ lines of code and all it does is serve MBTiles.

D3 scales and interpolation

D3 has a notion of “scales”, transformations of data from a domain to a range. Say your data is percentages (0% to 100%) and you want to draw them as bars of length 10-20. You can easily construct a linear scale to map your domain [0,100] to a range [10,20]:

var s = d3.scale.linear.domain([0,100]).range([10,20])
d3.selectAll("rect").data(data)
  .enter().append("svg:rect")
    .attr("height", s)

If that use of s seems magic, equivalents would be

    .attr("height", function(n) { return s(n); })

    .attr("height", function(n) { return 10 + 10 * (n/100) });

D3 provides various useful scales. Numeric scales like linear, log, and pow, also discrete scales like quantize and ordinal.

One thing you can set on a scale is the interpolate function. It’s invoked when mapping the domain to the range and lets you make the range be something other than the usual numeric range.

s = d3.scale.linear()
  .domain([0,100])
  .interpolate(d3.interpolateRgb)
  .range(["#ff0000", "#0000ff"])
s(0) == "rgb(255,0,0)"
s(100) == "rgb(0,0,255)"
s(50) == "rgb(128,0,128)"

There are pre-defined interpolation functions for numbers, colours, strings, objects, etc. I believe they’re also used by D3’s transition animations, specifically to automatically warp complex things like SVG paths from one shape to another.

The application of interpolation in d3.scale.linear.interpolate is pretty simple to follow:

  interpolate = d3.interpolate,
  i = interpolate(y0, y1);

  function scale(x) {
    return i((x - x0) * kx);
  }

In the linear.js code [x0,x1] is the domain, kx is 1/(x1-x0). [y0,y1] is the range. So the above code takes the input x, maps it to the interval [0,1], then applies cached interpolation function i(). By default that function is a linear interpolation in [y0,y1], but the developer can override it.

Building node without SSL

I’m trying to build node.js from source on Debian/wheezy. There’s an RPM but it’s two major versions behind. I got an error about SSL methods not being declared when compiling. No idea why Debian’s dev environment makes node’s configure think it can build SSL when it can’t (I have libssl-dev installed), but a quick workaround is buidling Node without crypto, via ./configure --without-ssl.

[74/75] cxx: src/node_crypto.cc -> build/default/src/node_crypto_4.o
/usr/bin/g++ -pthread -m32 -g -O3 -DHAVE_OPENSSL=1 -DHAVE_MONOTONIC_CLOCK=1 -DEV_FORK_ENABLE=0 -DEV_EMBED_ENABLE=0 -DEV_MULTIPLICITY=0 -DX_STACKSIZE=65536 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DEV_MULTIPLICITY=0 -DHAVE_FDATASYNC=1 -DPLATFORM="linux" -D__POSIX__=1 -Wno-unused-parameter -D_FORTIFY_SOURCE=2 -DNDEBUG -Idefault/src -I../src -Idefault/deps/libeio -I../deps/libeio -Idefault/deps/http_parser -I../deps/http_parser -Idefault/deps/v8/include -I../deps/v8/include -Idefault/deps/libev -I../deps/libev -Idefault/deps/c-ares -I../deps/c-ares -Idefault/deps/c-ares/linux-ia32 -I../deps/c-ares/linux-ia32 -Ideps/v8/include ../src/node_crypto.cc -c -o default/src/node_crypto_4.o
../src/node_crypto.cc: In static member function ‘static v8::Handle<v8::Value> node::crypto::SecureContext::Init(const v8::Arguments&)’:
../src/node_crypto.cc:101:29: error: ‘SSLv2_method’ was not declared in this scope
../src/node_crypto.cc:103:36: error: ‘SSLv2_server_method’ was not declared in this scope
../src/node_crypto.cc:105:36: error: ‘SSLv2_client_method’ was not declared in this scope
Waf: Leaving directory `/usr/local/src/node/build'
Build failed:  -> task failed (err #1):
        {task: cxx node_crypto.cc -> node_crypto_4.o}
make: *** [program] Error 1

D3 selections

The core datatype in the D3 Javascript library is the selection. But what exactly is a selection? What is its type and how do we work with it? It’s possible to use D3 without really understanding what selections are, but it makes a lot more sense if you understand the core type.

D3 selection type

A D3 selection is an array of arrays of DOM elements. That top level array object also has extra methods defined on it, the D3 selection methods like append(), attr(), etc.  Both select() and selectAll() return a 2d array; the difference is that select() only returns the first of the matching nodes. Most of the time your Javascript code won’t ever iterate inside these arrays; D3’s methods themselves implicitly loop over the elements.

Sample document

The rest of these notes will work on a simple sample HTML document that contains two tables each of size 2x2 for a total of 8 td nodes.

<table id="table1">
  <tr id="tr1-1">
    <td id="td1-1-1">1-1-1</td>
    <td id="td1-1-2">1-1-2</td>
  </tr>
  <tr id="tr1-2">
    <td id="td1-2-1">1-2-1</td>
    <td id="td1-2-2">1-2-2</td>
  </tr>
</table>
<table id="table2">
  <tr id="tr2-1">
    <td id="td2-1-1">2-1-1</td>
    <td id="td2-1-2">2-1-2</td>
  </tr>
  <tr id="tr2-2">
    <td id="td2-2-1">2-2-1</td>
    <td id="td2-2-2">2-2-2</td>
  </tr>
</table>

A note on developer tools

D3 selections are basically just arrays and if you look at a D3 selection in a developer tool like the Google Chrome console it only shows the array. See line 2 below. But don’t be confused! The selection doesn’t show up as having a special type or representation, but it is special. It has extra methods assigned on it and you can inspect and call them:

>>> d3.selectAll("table")
[ Array[2] ]
>>> typeof d3.select("table").attr
"function"
>>> d3.select("table").attr("id")
"table1"

Getting a D3 selection

Where does a D3 selection object come from? The select() and selectAll() methods. Those methods return a selection matching the input parameter. Often the developer selects for strings, using the selectors we know and love from the CSS specification. Selectors are a powerful mini-language worth reviewing to get the most out of D3.

>>> d3.selectAll("table")
[ Array[2] ]
>>> d3.selectAll("td")
[ Array[8] ]
>>> d3.selectAll("#td1-1-1")
[ Array[1] ]
>>> d3.selectAll("#broken")
[ Array[0] ]

In addition to strings, select() and selectAll() also work with ordinary DOM elements returned by other Javascript APIs. This capability can also be useful inside D3: inside an iterator function like each() you can use it to elevate the DOM element passed in the this parameter back into a selection object so you can then modify it with D3 methods.

>>> document.getElementById("td1-1-1")
​1-1-1​
​
>>> d3.selectAll(document.getElementById("td1-1-1"))
[ Array[0] ]

>>> d3.selectAll("td").each(function() { this.style("font-weight", "bold") })
TypeError: Property 'style' of object is not a function

>>> d3.selectAll("td").each(function() { d3.select(this).style("font-weight", "bold") })
[ Array[8] ]

Using a D3 selection

Most of your work with D3 is getting a selection and then invoking methods on it. All selection methods except call are implicitly loops, they will operate once per element in the selection.  The methods attr(), style(), property(), text(), and html() allow modification of the selected elements. each() allows you to call arbitrary functions for each element; methods like attr() are implemented by calling each(). append(), insert(), and remove() allow elements to be added to the DOM. on() allows events to be bound to the selected elements.

Subselections

D3 allows you to create a subselection within a selection, to work on a subset of elements from an initial selection. Subselections allow like elements to be grouped so you can process your data in a structured fashion. (This also explains why selections are 2d arrays; they support the nesting). I haven’t needed to use subselections yet: the scatterplot matrix example shows their use.

>>> d3.selectAll("td")
[ Array[8] ]
>>> d3.selectAll("td")[0][0].id
"td1-1-1"
>>> d3.selectAll("table").selectAll("td")
[ Array[4], Array[4] ]
>>> d3.selectAll("table").selectAll("td")[0][0].id
"td1-1-1"
>>> d3.selectAll("table").selectAll("td")[1][0].id
"td2-1-1"

Data

The data() method allows data to be stored for each element in the selection. Data is stored in a __data__ property right on the DOM node. You should normally not access this property directly, but it’s helpful to understand how D3 keeps data associated with your document elements.

>>> d3.selectAll("td").data([1, 2, 3, 4, 5, 6, 7, 8])
>>> d3.selectAll("td").each(function(d) { console.log(d); })
1 2 3 4 5 6 7 8
>>> d3.selectAll("#td2-1-1").each(function(d) { console.log(d); })
5
>>> document.getElementById("td2-1-1").__data__
5

data() returns the updating selection; you can immediately use attr(), each(), etc after calling data().

>>> d3.selectAll("td").data([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
>>>    .each(function(d) { console.log(d); })
1 2 3 4 5 6 7 8
[ Array[10] ]

Note how the array returned by each() is length 10? We bound 10 data items to the selection, but we only had 8 matching td elements. The extra two new elements implied by the data are accessible as the enter selection. This enter selection only has append() and insert() methods defined on it; you cannot call attr(), etc until you create DOM nodes. There is a symmetric exit selection that has the full D3 selection methods, typically used for removing nodes from the DOM.

this in javascript

Trying to understand the this magic variable in Javascript. You’d think it’d be like self or the like in most OO languages. But Javascript is barely OO and everything is so dynamic, it’s confusing. Some useful references: Quirks Mode, MDC this.

My takeaway from reading stuff is that this is generally set to the object the function is defined on. If you’re saying foo.go(), then inside go() this will be set to foo. If you don’t know what object you called a function on, say because you have a naked go() in your code, then this is probably bound to the global window object.

The usual this behaviour can be overridden in various ways. Both call and apply let you invoke a function and explicitly provide a value for this. D3’s each() function does this so that inside each, this is bound to the DOM node for the specific element being manipulated. There’s also a new ECMA function bind that lets you create a function with a new value automatically used for this.

I’m still a bit fuzzy on the mechanics of how this is assigned, in particular when you copy a function from object A to object B. In general this seems to be set dynamically at the last moment before the function is invoked, so it generally picks up the value A or B depending on how the function was invoked.

Headless SVG rendering part 2

I revisted headless SVG rendering and decided to stick with PhantomJS since I already have it working. It’s rendering text poorly and path strokes not at all, probably fixable with some upgrades that are inconvenient in Debian. But I can work around that for now.

Scripting PhantomJS turns out to be pretty easy. Here’s the Javascript program I use to drive it:

if (phantom.state.length == 0) {
    phantom.state = "rasterize";
    phantom.viewportSize = { width: 64, height: 64 };
    phantom.open("vis-phantom.html");
} else {
    phantom.render("out.png");
    phantom.exit();
}

Unfortunately the input and output filenames are hard-coded. Phantom has command line argument support but I can’t figure a way to get that all the way into my HTML file (to load a specific script), so I just went with a hardcoded input file named data.js.

Here’s my shell script to render a PNG, crop it, and optipng crush it. The crop shouldn’t be necessary, but for some reason I’m ending up with 3 pixels below my SVG element.

set -e
# Render a wind rose image for the given datafile
input="$1"
output="${1%.js}.png"

# remove old crap
rm -f data.js out.png cropped.png "$output"
# Symlink the data to the expected place
ln -s "$1" data.js

# Render, crop, and crush
phantomjs/bin/phantomjs render.js
convert out.png -crop 64x64+0+0 cropped.png
optipng -force -quiet -preserve -out "$output" cropped.png

# clean up
rm -f data.js out.png cropped.png

It takes about 300ms to render a single image for my simple SVG based graphics.

Headless SVG rendering

I’m doing an S3/SVG visualization project and want an easy way to generate 3000 static images with a script. I need a headless SVG renderer. Mike suggested a couple of options: Rhino + Env.js + Batik, or maybe using node.js instead of rhino. Apparently the Protovis community does this; need to delve in their mailing list for examples.

PhantomJS happened to float across today, so I tried it out. It’s WebKit based instead of Mozilla based. It was pretty easy to get going. I had to install libqt4-dev libqt4-webkit on my Debian system to build it. I also learned it’s not really headless, requires an X server, so I installed xvfb and ran it via “Xvfb :1”. With all that in place the basic PhantomJS works. Including rasterizer.js, which loads an arbitrary URL and renders it.

To run it:

$ Xvfb :0 2> /dev/null
$ export DISPLAY=:0
$ phantomjs rasterize.js vis-phantom.html out.png

My visualization didn’t work. First I had to remove the Ajax calls from it and statically load the data. (May not be strictly necessary, not sure). Second I had to set the background to white; the default background in qt4-webkit is transparent, which is actually pretty useful. With those changes my rendering sort of worked, but the font rendering is ugly and none of my stroked lines are visible. I’m using libQtWebkit-4.6.3; apparently 4.7 may fix the stroke problem.

I think I could massage this into something usable, but I’ll probably investigate the Rhino/Batik solution or something next.

Javascript dictionary key types

In Javascript, the dictionary type coerces its keys to Strings:

z = { 3: "three", 4: "four" }
for (var x in z) { console.log(typeof x); }

string

This sort of makes sense because dictionaries are really just Javscript objects, and objects are typically accessed by strings. Ie: z.foo is the same thing as z[“foo”]. Worth noting that z.3 doesn’t work, though. It gets spookier when you use null:

z[null] = "foo"

for (var x in z){ console.log(x, typeof x); }
3 string
4 string
null string

Maybe it wasn’t wise to use integers and null everywhere as keys in my JSON dictionaries. In fact the JSON spec says keys have to be strings, and the Python JSON library was already serializing my keys as strings (with None mapped to “null”). Now I know.

D3 and IE9

IE9 is out, and Microsoft finally supports SVG. Early testing with D3, Mike’s new Javascript library good for doing visualizations, is encouraging. All his examples work. My own code worked once I put <!DOCTYPE html> at the start to convince IE not to use quirks mode.

Javascript closures gotcha with loop variables

The way Javascript scopes “var” in loops and how it interacts with closures trips me up every time I go back to writing Javascript code. Here’s a fleshed out example that shows the confusion.

// Demonstrates using closures to capture the value to do what you meant. See also
//   http://calculist.blogspot.com/2005/12/gotcha-gotcha.html
//   http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/

var data = ["a", "b", "c"];
var wrongFunctions = [];
var rightFunctions = [];

function load() {
  console.log("Creating functions");
  for (var i = 0; i < 3; i++) {
    // X will be set to "a", then "b", then "c". But at what scope?
    var x = data[i];

    // The naive way to construction a function that returns X
    // Will not work: X is scoped to the function load() and
    // is being modified in the loop
    var wf = function() { return x };

    // A more complicated way to make a function that returns X.
    // The function execution creates a closure
    // that captures the value during the loop
    var rf = function() { 
      var t = x; 
      return function () { return t };
    }();

    // While the loop is executing and we're building functions,
    // the output of wf() and rf() will match data[i]. No problem!
    console.log ("  ", x, wf(), rf());
    // output is "a a a", "b b b", "c c c". Everything looks great!

    // Let's store both functions away, what could go wrong?
    wrongFunctions.push(wf);
    rightFunctions.push(rf);
  }
}

function play() {
  console.log("Running stored functions");
  // Let's loop through and call our stored away functions
  // and see what happens
  for (var i = 0; i < 3; i++) {
    console.log("  ", data[i], 
        wrongFunctions[i](), rightFunctions[i]());
  }
  // output is "a c a", "b c b", "c c c".
  // wrongFunctions were indeed wrong.
}

load();
play();

Javascript code review

I’m new to Javascript hackery, my little aviation weather hack had me doing a lot of new stuff with Ajax and dynamic HTML. So I asked my friend Mike for a code review. He’s the smartest Javascript hacker I know, and we both worked at Google where rigorous code reviews were a thing.

Here’s some complicated things I learned from him:

  1. There’s ways to create private namespaces for libraries and classes. Douglas Crockford’s “Private Members in JavaScript” is a good introduction, some examples from Mike are kmeans.js and crimespotting.js. The key thing is creating a closure to scope the private stuff, then assigning the public functions to a module object. There’s potential per-instance overhead to doing it this way.
  2. Reassigning the CSS class of a DOM element at runtime is totally OK. In jQuery, it’s like doing foo.attr("class", "someStyle"). It’s a handy way to make the document suddenly look different, but it made me nervous.
  3. Editing the CSS style of a DOM element is also OK. In jQuery, it’s doing foo.css("font-weight", "bold"). Presumably it’s using element.style.setProperty() to do the manipulation.
  4. jQuery.ajax() gives different types types depending on what it thinks the response is. XML gives back a DOM object, HTML gives back a string, JSON gives back a Javascript blob. My code is getting HTML and then uses the magic jQuery(htmlString) capability to parse the HTML into a DOM and then query it. (BTW, turning strings into DOM is not easy in Javascript.)

Also some simple things:

  1. Javascript has Array.join() just like Python. Handy to avoid lots of String concatenation.
  2. Not clear that testing if (foo === 3) is worth typing the extra =. There’s circumstances where it saves you, but in practice may not be a big deal.
  3. Array.push() can take multiple arguments, to avoid repeated calls
  4. return "" + x is an easy way to ensure the return type is always a string
  5. Be sure to use “var” for all local variables. This is rookie Javascript, but I still forget.

I learned a lot. Code reviews are a great way to teach and learn, it’d be nice to have an online community that offered them along the lines of StackOverflow or github. Both for basic education, but also helping clean up important open source libraries. Key tech piece: a really good browser based code annotation tool.

Now as a favour in kind I’m going to try porting my code from using jQuery to using his D3 library. D3 is more of a visualization library than a jQuery replacement, but it happens to have the selectors and Ajax support I need.

AvWx: dynamic HTML aviation forecasts

Yesterday’s hack was finishing up AvWx, a quick Javascript thing I wrote to show me forecast data useful for flight planning. It’s an iPhone friendly web page that shows forecast maps for the next 3 days at 1800Z. 3 images for general weather (from Wunderground) and 3 images for winds (from ADDS). This is the quick and dirty data I look at when planning a multiday cross-country flight.

Like many of my recent hacks most of the work is done client side, in Javascript. Unfortunately I had to have a server-side CGI to work around the stupid same origin policy. There’s a couple of new-to-me Javascript tricks in there.

One is I’m using jQuery and AJAX to fetch a form off of ADDS and parse it to extract the filenames for the wind maps. The image naming was complicated enough it was better just to use the HTML. I’d done AJAX stuff before but always with XML or JSON data, never HTML. It’s not so bad:

    $(data).find('option[value^="ruc"],option[value^=eta]').each(
        function(i, e) {
            var timeString = $(e).text();
            var filename = $(e).attr("value");
            r[timeString] = filename;
        });

The other trick I did was scaling and cropping the wind images client-side. ADDS returns a 680x680 image but I want to scale it to 640 wide, then slice about 450 pixels out of the middle of it to display. I did this with the “CSS background cropping” technique; basically you create an empty div and set its background image property to your image, then use CSS to position, scale, and crop. Total hack, but it looks good in Chrome and the iPhone.

.etacrop {
      display: block;  width: 680px;  height: 452px;
      background-size: 640px 640px;
      background-repeat: no-repeat;
      background-position: 0px -86px;
   }
   target.css("background-image",
      "url(http://aviationweather.gov/adds/data/winds/" + winds[i] + ")");

There was more work involved, but that’s the nut of it. I ended up writing a pretty comprehensive QUnit test suite for the parsing and filename munging. Felt like overkill, but already has paid off in letting me test and improve the code.