Some Bits: Nelson's log

18 posts in May 2012

Shape Blizzard’s bittorrent client

Blizzard uses BitTorrent for distribution of their game clients and patches. Great idea, but their BitTorrent client lacks any user controlled bandwidth settings so it totally saturates your home network. And thanks to the combination of bufferbloat and 100+ active streams, TCP congestion control doesn’t much help.

What does help is router QoS. I use Tomato firmware and it has a very nice little QoS setting. The key classifier for Blizzard traffic is Source or Destination Port: 6881. That catches most of the TCP streams starting on your PC downloading the game client. I set it to Low priority, which gives my ssh, HTTP and DNS traffic at the router a fighting chance.

While I’m here, the most valuable router QoS setting is “prioritize ACK packets”. That helps stop large uploads from an ADSL line prevent simultaneous fast downloads.

Here’s a graph of my router outbound traffic while I’m busily downloading Diablo III to my laptop (class = Low) while simultaneously uploading a big file via ssh (class = Medium). The graph shows a lot of Highest priority traffic; I’m not sure, but I assume that’s ACK packets. I’m a little sad that low priority gets 50% of the bandwidth whereas medium only gets 25%: I don’t know if that’s how the QoS works or if it’s an artifact of Bittorrent using so many simultaneous streams.

Here’s my router QoS settings:

Match Rule Class Description
UDP
Port: 123
Highest ntp
TCP/UDP
Dst Port: 53
Transferred: 0 - 2KB
Highest DNS
TCP
Port: 22
Transferred: 0 - 1024KB
High ssh
TCP
Dst Port: 80,443
Transferred: 0 - 512KB
High WWW
TCP
Dst Port: 80,443
Transferred: 512KB+
Low WWW (512K+)
TCP/UDP
Dst Port: 53
Transferred: 2KB+
Lowest DNS (2K+)
TCP/UDP
Port: 119
Low NNTP
TCP/UDP
Port: 563
Low NNTP (SSL)
TCP/UDP
Port: 6881
Low Blizzard BitTorrent

And for lolz, I’ve discovered my iMac + router + modem  has 2 megs of upload buffer. Boy that’s a lot. I should look into tweaking Tomato to lower the buffers. Or maybe find whatever the new hacker hipster router firmware is.

Update: the graph above was when I only identified source port 6881 as Blizzard traffic. Catching destination 6881 as well seems to help things a little.

Layout trick for filling to browser height

When putting maps on pages I often want the map to take the full browser height, not some fixed pixel height. That’s easy, just set height: 100% and the map fills the browser. But what if you want to reserve some space at the bottom, say for a text display? I don’t think any flavor of CSS lets you set height to “100% - 100px”, and I don’t know of a way to trick the box model of CSS alone to say “reserve 100px and then fill the rest with this thing”. It may be doable in pure CSS, but I don’t know how.

However it is doable with a bit of Javascript. In this case we have a map that fills all of the window but the last 150px, then a time series graph in that last 150px.

<!-- The map itself. Height set by Javascript. -->
<div id="map" style="width: 100%;"></div>

<!-- Divider -->
<div id="divider" style="background-color: black; height: 1px; width: 100%"></div>

<!-- Time series graph at the bottom -->
<div id="graph" style="width: 100%; height: 150px; background-color: white"></div>
// Resize the map so that it's the height of the window minus the graph
function setMapHeight() {
    var graph = document.getElementById("graph");
    var divider = document.getElementById("divider");
    document.getElementById("map").style.height = window.innerHeight - (graph.offsetHeight + divider.offsetHeight);
}
window.addEventListener("load", setMapHeight, false);
window.addEventListener("resize", setMapHeight, false);

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.

San Francisco centerlines

More on Skunk Alley; I was talking to Eric F and he was saying it was a shame that this path wasn’t already in OSM. San Francisco publishes a shapefile of street centerlines; apparently when that was imported via TIGER into OSM they filtered out stuff that wasn’t quite a street, like unimproved rights-of-way. And indeed my second, southern segment of Skunk Alley is in that shapefile, as “UNNAMED 025” with CNN 19211000.

So that begs the question; what’s in the SF shapefile that’s not in OSM? Answering that question correctly requires a bit more geometric fiddling in PostGIS than I know how to do yet, but I did get a quick and dirty picture by using QGIS by drawing the OSM data in black on top of the SFData shapefile in purple. Anything purple peeking through is in the difference (roughly)

Lots of little snips and bits in the SF shapefile that aren’t in the OSM. Interesting! I should figure out how to use PostGIS to give me the actual difference.

While preparing this map I had to fix it so that Church street showed up. I used to draw everything with “railway is null”, but somehow that leaves out Church St. Maybe because it has a Muni track running down it? But with railways turned on you get things like underground subways (BART), the old abandoned track snaking through the Mission, etc. Haven’t found a reliable way to filter all that out yet; need to revisit HighRoad’s canned queries for that.

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!

Walks map looking pretty

I’m liking how my map of walks is turning out. It’s now useful to me in that I can see what streets I’ve walked on and what I haven’t. It’s also sort of pretty. I particularly like how the GPS error gives a random smudge effect to the paths. Transparency for older tracks works nicely. I’ve tried to induce some hue variance just to let the eye pick out individual tracks, but the orange->red scale is a bit lipsticky and seems to demand the question of exactly what hue represents (track length).

Twitter API headers

I’m dorking around with the Twitter API, public calls like http://api.twitter.com/1/statuses/user_timeline.json?screen_name=nelson&count=100&page=3&include_rts=1&trim_user=true&include_entities=false. Here’s the HTTP headers that returns:

  HTTP/1.1 200 OK
  X-RateLimit-Limit: 150
  X-RateLimit-Remaining: 112
  X-RateLimit-Reset: 1337888547
  X-RateLimit-Class: api
  Content-Type: application/json;charset=utf-8
  Last-Modified: Thu, 24 May 2012 19:26:16 GMT
  Expires: Tue, 31 Mar 1981 05:00:00 GMT
  Pragma: no-cache
  Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
  Set-Cookie: guest_id="v1:133788757695829242";Expires=Sat, 24-May-14 19:26:16 GMT;Path=/;Domain=.twitter.com
  Status: 200 OK
  X-Transaction: a990ed040a2ffcdd
  X-Frame-Options: SAMEORIGIN
  Date: Thu, 24 May 2012 19:26:16 GMT
  Server: tfe
  Content-Length: 86940

Sadly, there’s no Access-Control-Allow-Origin header there to allow CORS. The Twitter API does support an optional callback= paramter to get them to emit JSONP instead. I was trying to use D3’s AJAX library to make the calls, but it only supports CORS and not JSONP.

Walkways in OSM (San Francisco)

I added a walkway to OSM today, Skunk Alley, a funky little path between two houses with a hand painted sign. It’s on land that’s not part of a house lot and goes through a convenient location, so I think it makes sense to have it marked in the map as an actual walkway.

Skunk Alley is tagged “highway=track, surface=dirt”. I’d never seen the surface tag before, it’s not a column in the SQL version of the OSM Metro extracts I’m using. But highway=’track’ is a useful clue. Here’s all the various kinds of highways that look to mean “a way you walk on but can’t drive”.

select highway, count(*) as n
from planet_osm_line where
"highway" IN ('pedestrian', 'track', 'path', 'footway', 'bridleway')
group by highway
order by n desc;

"footway";5252
"path";1063
"track";959
"pedestrian";116
"bridleway";2

I gather from stuff I read that highway=path is not loved in the OSM community.

Here’s a map of most of SF with those 5 types of highway coloured. Purple is “footway” and seems to apply both to walking tracks in parks and the occasional street-type walkway (like along San Jose Avenue, bottom middle). Light blue is “path” and has useful walkways. Brown is “track” and dark blue is everything “pedestrian” and “bridleway”. The distinction between them all seems entirely arbitrary. Fort Funston is all “tracks”, the zoo and Golden Gate Park is all “footways”, and the greenspace west of Stanyan & 17th gets “paths”.

SQL vs NoSQL

Quick thought.. Mongo is awesome for quickly hacking up a persistent data store where you’re not quite sure what data you’re storing. Schemaless = fast storage coding. But then Mongo is bad at letting you do complex queries, because you have to do all this hand rolled mapreduce crap. SQL = fast query coding. It’s an interesting tradeoff; I want the best of both worlds!

 

Leaflet thoughts

I’m liking Leaflet. It’s got all the great flexibility I love in Polymaps, quickly compositing various layers of raster and vector data into one fancy map. But unlike Polymaps it runs well on iOS devices. And it’s got an active community; Polymaps feels like a dead end.

A few things are missing:

There’s no way to specify the z-ordering of layers, it’s all just in whatever order they are. The developers have said they’re working on this. (Z ordering basically doesn’t exist in SVG, it’s all document order. That’s dumb.)

Scaling transitions aren’t beautiful. Leaflet animates the raster layer but hides my vectors and then has them blink back into place. Bah.

Screenshot of work in progress. Lots going on here... Purple is steps. Orange squiggles are my walks. Faded = older walks. Redder = longer walks. There’s some interaction, too. Click on a track to highlight it and get a popup showing length and age.

Identifying Windows code page 1252

A blog post I wrote on a foreign laptop ended up with byte values 0x92 for apostrophes and 0x93 and 0x94 for quotes. This is an old Windows “smart quotes” and makes sense in Windows code page 1252. It is not valid ISO-Latin-1; that encoding doesn’t have typographical quote marks in it.

Easy enough to fix once the encoding is identified: “iconv -f windows-1252 -t utf-8”

I should make a website that has one web page per code point. So you could go to a page named “0x92.html” and see what all it translates to in the world’s various codecs. There’s a bunch of one-page-per-Unicode-character sites out there, but I don’t know of a resource that lets you easily guess a mystery encoding by a few examples.

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.

GeoJSON for the steps of San Francisco

I keep playing with this dataset of all the steps of San Francisco from OpenStreetMap. I made a GeoJSON file with all the steps of San Francisco. It’s a snap to add to a Web map with Leaflet. A few thoughts:

GeoJSON is a good format for geodata when you’re working cross-language. PostGIS can emit it, Python and Javascript can easily parse it, Leaflet can easily draw it. Half the time I just get a string from PostGIS and never even parse it in Python, just pass it along.

The Python geojson library doesn’t really help very much. If you’re using geopy already to work with geodata, then maybe it’s helpful. But if you’re just building up arbitrary JSON blobs with some geodata it’s not needed.

The world could use a GeoJSON validator. Extra credit if it rendered the GeoJSON blob on a map, wouldn’t be too hard. I should set this up as a web service.

JSON float precision continues to contribute to file bloat; Python’s default 15 digits precision translates to subatomic location positioning. Fortunately in Python 2.7 it’s pretty easy to round off numbers, you just have to do it.

The GeoJSON format I settled on was a FeatureCollection. Each feature has the name, length (in metres), and OSM ID of one set of steps. Then two geometries: the centroid of the steps and the path of the steps. Example:

{   "type": "Feature",
    "properties": {
        "id": 8916413,
        "length": 146.58,
        "name": "Harry Street"
    },
    "geometry": {
        "type": "GeometryCollection",
            "geometries": [
            {   "type": "Point",
                "coordinates": [ -122.431219, 37.740099 ],
            },
            {   "type": "LineString",
                "coordinates": [
                    [ -122.430741, 37.740424 ],
                    [ -122.43075,  37.740351 ],
                    [ -122.431759, 37.739803 ]]
            }
]}}

Here’s the SQL query for all the steps I’m using. There’s more Python code than I’d like to collect all these rows and emit the GeoJSON, but I’m not pasting it all here.

select
    planet_osm_line.name,
    ST_Length(planet_osm_line.way) as meters,
    ST_AsGeoJSON(ST_Transform(ST_Centroid(planet_osm_line.way),4326), 6),
    ST_AsGeoJSON(ST_Transform(planet_osm_line.way, 4326), 6),
    planet_osm_line.osm_id
from planet_osm_line
    inner join planet_osm_polygon
    on ST_Intersects(planet_osm_line.way, planet_osm_polygon.way)
where
    planet_osm_polygon.osm_id = '-111968'
    and planet_osm_line.highway = 'steps'
order by meters desc;

Quick Leaflet with GeoJSON demo

I’m exploring Leaflet as an alternative to Polymaps, mostly because Leaflet has some momentum and is faster to render on iOS. here’s a quick demo of drawing a raster map with a GeoJSON overlay.

var map = new L.Map('map');
var rasterLayer = new L.TileLayer('http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.jpg', {
    attribution: 'Stamen Terrain',
    maxZoom: 18
});
var view = new L.LatLng(37.75, -122.43); // geographical point (longitude and latitude)
var trackLayer = new L.GeoJSON(track);
map.setView(view, 14);
map.addLayer(rasterLayer);
map.addLayer(trackLayer);

“track” was preloaded as a JSONP script. ogr2ogr barfs on converting my GPX files from Runkeeper directly to GeoJSON, so I exported them out of PostGIS instead with

select ST_AsGeoJSON(wkb_geometry)
from tracks
where name like '%4/21/12%'

Leaflet uses SVG for the GeoJSON layer. Pretty simple structure, svg > g > path, I think one per GPS track.

With just a bit more work it was easy to load 65 walking tracks via Ajax (165k data total) and plot them all in a browser. Performance is pretty good on iOS; the main thing I don’t like is the way the GeoJSON layers disappear during a resize.

Bashing Unicode in Python

My whole work environment is UTF-8. Except Python. Python’s “print” will encode in UTF-8 if its printing directly to a tty. But as soon as you pipe that tty to something Python reverts to ASCII. And it’s a real PITA to overcome that.

Here’s one ugly kludge to make Python always treat stdout as UTF-8. It causes problems with some tools, but is sufficient for hacking around:

import sys, codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

Uploading OSM changes with JOSM

I moved a road. OpenStreetMap had one path for an obscure little road in Nevada City, CA called Woodwardia Place. I was curious about the exact path so I drove down it twice with a GPS logger, then used JOSM to upload a change. It’s cool how fast the upload took effect; the raster tiles for the map were generated anew within 30 seconds of my upload. JOSM is a bit confusing, and I never could figure out how to upload the GPX track for OSM’s records.

Here’s the edit; old road is in grey, new road is in yellow moved slightly north.

Image

Then I split the road. There’s a segment that’s a bridge, so I made a change that split the road into two ways and then tagged the short bridge segment with bridge=yes.

Finally I went to a different part of the map and removed a road segment. I’d driven blind down that road expecting it to go through, but the map was wrong. Never again! Removing a road segment is a bit tricky; I had to select the node on the western (non-existent) T intersection, “unglue it”, delete the incorrect line segments, then “merge nodes” to reglue the now-T intersection that does exist on the map.