Some Bits: Nelson's log

118 posts in 2012

Ubuntu resolv.conf

In the old days setting up DNS was easy. You edited /etc/resolv.conf, put your nameservers in there, and you were done. Sadly it’s gotten more complicated as time goes on; DHCP provides nameservers, computers have multiple network interfaces, you want different DNS servers on a laptop depending on where you are.

But the resolvconf(8) system in Ubuntu is impenetrably complex to configure. I’ve found a bunch of random places where name servers are stored or written. I thought that /etc/network/interfaces is canonical. But there’s stuff in /etc/resolvconf/ too, and things cached in /run/resolvconf/, and I have no idea how to just add a name server. Various “obvious” things fail with old configs coming from some cache.

AskUbuntu has a decent answer that while it may not be correct, works. Edit /etc/resolvconf/resolv.conf.d/head (ignoring the warning about autogeneration), add your entry, then run resolvconf -u. I just tried it and it worked, even put my entries first in the list.

My real goal was to replace my ISP’s flaky DNS server with Google’s 8.8.8.8. It’s stupid in the modern era that DNS is still a sequential operation with a 5 second timeout. This Ask Ubuntu answer suggests installing a fancy caching DNS server like pdns.

Playing with WebSockets

I’ve never used the WebSockets API, so thought I’d try it. My goal: try to get arbitrary binary data chunks from a server as an ArrayBuffer. XMLHttpRequest can do this with the newish responseType property but I’m told it’s awkward, particularly if the data is gzip encoded. Also WebSockets sound like fun.

WebSocket support is sketchy: it’s supported in some modern browsers but not Microsoft’s; IE10 may support it. (To be fair, MS isn’t just dragging their feet, there’s security issues they were concerned about.) Also the Mozilla docs talk about things being prefixed like MozWebSocket; not sure if that’s still the case and if I need an API wrapper. I’m only using Chrome as a client for now.

Docs

Doc quality is a bit frustrating; the MDN docs are incomplete and the W3C Browser API is hard to read and takes a lot of filling in the gaps to understand. Feels like an incomplete spec to me.

Server

Lots of options for implementing the server. All the cool kids are doing Node.js no doubt. I decided to stick with Python and try ws4py (github) on top of gevent.

  1. brew install libevent  # MacOS: it’s half a Unix!
  2. pip install gevent
  3. pip install ws4py

The ws4py docs have a trivial EchoServer implementation in gevent. I started there and added some basic message handling for a couple of commands (Echo and bytes).

from gevent import monkey; monkey.patch_all()
import gevent

from ws4py.server.geventserver import WebSocketServer
from ws4py.websocket import WebSocket

# Construct an array of 256 bytes, 0x00 to 0xff
bytes = b""
for i in range(256):
    bytes += chr(i)

class MyWebSocket(WebSocket):
    def opened(self):
        print "Socket opened"

    def received_message(self, message):
        "Handle requests. Echo is echoed, bytes is a request for binary data"
        print "Received message of length %d" % len(message)
        if message.data.startswith("Echo"):
            self.send(message.data, message.is_binary)
        if message.data == "bytes":
            self.send(bytes, True)

    def closed(self, code, reason):
        print "Socket closed %s %s" % (code, reason)

server = WebSocketServer(('127.0.0.1', 9001), websocket_class=MyWebSocket)
server.serve_forever()

Client

The HTML5Rocks docs have some very simple client Javascript that talks to the server they host. I started there and added some special message logic. Basically the client requests a special byte array consisting of 0x00 .. 0xff and then verifies it
actually received those numbers in an ArrayBuffer.

var connection = new WebSocket('ws://127.0.0.1:9001');
connection.binaryType = "arraybuffer";

connection.onopen = function () {
    // When the socket opens, log it and send two messages"
    console.log("socket opened, sending echo request");
    connection.send('Echo this');
    connection.send('bytes');
};

connection.onerror = function (error) {
    console.log('WebSocket Error ' + error);
};

connection.onmessage = function (e) {
    console.log('Message from server');
    if (e.data instanceof ArrayBuffer) {
        // If it's ArrayBuffer it must be the binary array 0x00 .. 0xff we're expecting
        var byteArray = new Uint8Array(e.data);
        if (byteArray.length != 256) {
            console.log("Error; didn't get expected length 256");
            return;
        }
        for (var i = 0; i < byteArray.length; i++) {
            if (byteArray[i] != i) {
                console.log("Error; got " + byteArray[i] + " at position " + i);
                return;
            }
        }
        console.log("Received expected 256 byte array");
    } else {
        // Print out any other message from the server
        console.log(e.data);
    }
};

Followup

I’d take a long hard look at browser compatibility and the future of WebSockets before building a serious product on it. The docs and sample code don’t give me a warm fuzzy feeling, and there’s been definite issues with IE support, etc in the past.

I have no idea what the state of the art is with respect to gzip encoding on WebSockets. There’s nothing in the spec I can find; maybe it’s up to the server? That’d be fine except AFAIK there’s still no browser-friendly zlib.decompress implementation, no way to decompress standard gzip data. It’s baked in to the browser but not exposed in a Javascript API, unless something’s changed since I last looked.

Apparently WebSocket is not subject to same origin policy. Yay! My Javascript client file at http://192.168.0.5:8989/ is happily getting data from ws://127.0.0.1:9001 and Chrome isn’t complaining. I haven’t done any sort of CORS thing and I don’t think any is baked in to ws4py. Worth investigating more later, particularly in the context of all the WebSocket security tsurris.

For basic hacking it’d be nice if the same server can serve ordinary resources via HTTP and special stuff with a WebSocket server. I think the protocol can do it and there’s a way to get ws4py to allow it (see UpgradableWSGIHandler) but I haven’t tried. For a serious deployment there’s an argument for keeping the two kinds of serving separate, particularly if you’re using WebSocket for long lived persistent connections.

MacOS bullshit

I just had to reboot my Mac because a remote filesystem mount failed. I mounted a disk on my iMac via AFP from another Mac last night, over my WiFi network. Then my iMac went to sleep. This morning the remote disk was still mounted, so I went to open it and then Finder locked up, the lovely spinning wheel of death. (Do they still say “beachball”?) But at least all my other apps were working. Then I tried to force quit Finder (er, relaunch), and the entire fucking Mac locked up.

The big fail here is that Finder still has its talons in the graphical shell of the Mac, and file system browsing can lock up the whole machine. The small fail is it’s nearly 2013 and we still don’t have remote filesystems that are robust to failure. I miss the async option on NFS; it caused some problems, but at least it didn’t lock up your whole computer.

Update: after rebooting I remounted the file system and then copied a single 800 megabyte file over by dragging it in finder. I then tried to drag a second file over and had to wait, mouse button held down, for 45 seconds while Finder’s little wheel spun. Because apparently the entire UI locks up while waiting for some buffer to drain in a bulk, low priority file copy. Apple’s handling of remote mounts, even AFP mounts from other Macs, is absolutely terrible.

 

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.

Hexbin map of my tweets

Twitter published user archives, hooray! I cargo culted some code together off of Mike’s Walmart map to show a little histogram of where I tweet. Two maps with different projections and different visualization of magnitude (size vs color)

Screen Shot 2012-12-19 at 4.45.34 PM Screen Shot 2012-12-19 at 5.07.15 PM

Some things I learned:

  • Hexbins can be brittle. If I change the scale of the map or the hexes just a bit the qualitative shape of the connected objects changes radically.
  • Scaling and centering a projection to a dataset is a little tricky. d3.geo.projection() has you doing the scaling and translation in screen coordinates by default, need to do it in geo coordinates to make more sense. (Mike says to use the center() method.)
  • D3 projections are fun! The second projection is a kavrayskiy7, whatever the hell that means, borrowed from this example.

File corruption on my web server

Got a bug report for windhistory.com that I traced back to the main JSON database I’m serving being corrupted. The file hasn’t been touched since September 2011 and I know it was working correctly as of December 1. Needless to say this is very disturbing. Files shouldn’t go bad like this. The pattern of corruption doesn’t suggest malice, just a bug. It makes me wonder what else is corrupted. None of the other datafiles for that project have changed but I can’t easily audit the entire system.

My backups didn’t capture the corruption. But I got clever and realized I could pinpoint when the file changed by looking at the compressed size that Apache was serving; even though the file itself wasn’t truncated, the data changed so the compressed size changed too. It’s typically 369275 or 369276 bytes (why the inconsistency?) but starting at 11/Dec/2012 18:25:58 (UTC) the length 370464 or 370465 started showing up. At first it was really inconsistent, it didn’t stabilize on this new length until 12/Dec/2012 01:05:25.

Nothing obvious in the syslog around that time. Munin graphs show some other weirdness; Munin processing time went up to timeout levels for awhile, HTTP loadtime stopped being reported, NTP briefly went from a 40ms delay to a 90ms delay from true time. A disturbance in the force. But no temperature or voltage spikes, no heavy load, nothing major.

I flushed my filesystem caches via echo 3 >| /proc/sys/vm/drop_caches and now the file is correct. So at least the disk didn’t get corrupted, just the cached copy in memory. Still disturbing, this is way more than a single cosmic ray bit flip. But it does look like a systemic modification of the old bits, not completely overwritten with  new ones. Very weird.

Here’s the output of cmp -b -l; index, then good data on the left, corrupted data on the right. There’s some mild pattern to it, it looks in general like bits are being flipped to 0. But not entirely. And why is the corruption scattered around the file? Very weird.

 188486  71 9     41 !
 188494  54 ,     44 $
 188502  63 3     41 !
 188510  54 ,     44 $
 188518 135 ]      5 ^E
 188526  62 2     40
 188534  54 ,     44 $
 188542  62 2     40
 188614 133 [      1 ^A
 188622  62 2     40
 188630  62 2     40
 188638  54 ,     44 $
 188646 133 [      1 ^A
 188654  61 1     41 !
 188662  54 ,     44 $
 188670  60 0     40
 188742  61 1     41 !
 188750  54 ,     44 $
 188758  61 1     41 !
 188766  54 ,     44 $
 188774  54 ,    144 d
 188782  60 0     40
 188790  64 4     44 $
 188798 135 ]      5 ^E
 188870  54 ,     44 $
 188878  54 ,     44 $
 188886  63 3     41 !
 188894  63 3     41 !
 188902  62 2     40
 188910  54 ,     44 $
 188926  63 3     41 !
 188998  54 ,     44 $
 189006  54 ,     44 $
 189014  65 5     45 %
 189022  60 0     40
 189030  66 6     44 $
 189038  70 8     40
 189046  54 ,     44 $
 189054  71 9     41 !
 189126  54 ,     44 $
 189134  54 ,     44 $
 189142  63 3     41 !
 189150  63 3     41 !
 189158  61 1     41 !
 189166  62 2     40
 189174  54 ,     44 $
 189182  54 ,     44 $
 189254  66 6     44 $
 189262 120 P      0 ^@
 189270 122 R      0 ^@
 189278 105 E      5 ^E
 189286 122 R      0 ^@
 189294  60 0     40
 189302  66 6    144 d
 189310  61 1     41 !
 189382  54 ,     44 $
 189390  54 ,     44 $
 189398  54 ,     44 $
 189406  54 ,     44 $
 189414  54 ,     44 $
 189422  54 ,     44 $
 189430  54 ,     44 $
 189438  63 3     41 !
 189510  64 4     44 $
 189518  54 ,     44 $
 189526  61 1     41 !
 189534  66 6     44 $
 189542  54 ,     44 $
 189550  54 ,     44 $
 189558  54 ,     44 $
 189566  63 3     41 !
 189638  54 ,     44 $
 189646  54 ,     44 $
 189654  54 ,     44 $
 189662  54 ,     44 $
 189670  54 ,     44 $
 189678 113 K      1 ^A
 189686  61 1     41 !
 189694  54 ,     44 $
 189766  71 9     41 !
 189774  63 3     41 !
 189782  54 ,     44 $
 189790  54 ,     44 $
 189798  66 6     44 $
 189806  64 4     44 $
 189814  61 1     41 !
 189822  54 ,     44 $
 189894  70 8     40
 189902  67 7     45 %
 189910  61 1     41 !
 189918  54 ,     44 $
 189926  54 ,     44 $
 189934  54 ,     44 $
 189942  67 7     45 %
 189950  64 4     44 $
 190022  63 3     41 !
 190030  61 1     41 !
 190038  67 7     45 %
 190046  60 0     40
 190054  62 2     40
 190062  61 1     41 !
 190070  54 ,     44 $
 190078  54 ,     44 $
 190150 117 O      5 ^E
 190158 125 U      5 ^E
 190166 101 A      1 ^A
 190174  54 ,     44 $
 190182  60 0     40
 190190  54 ,     44 $
 190198  63 3     41 !
 190206  54 ,     44 $
 190278  64 4     44 $
 190286  63 3     41 !
 190294  66 6     44 $
 190302  54 ,     44 $
 190310  54 ,     44 $
 190318  54 ,     44 $
 190326 135 ]      5 ^E
 190334  62 2     40
 190406  60 0     40
 190414  62 2     40
 190422  64 4     44 $
 190430  54 ,     44 $
 190438  54 ,     44 $
 190446  61 1     41 !
 190454  67 7     45 %
 190462  64 4     44 $
 190534  63 3     41 !
 190542 135 ]      5 ^E
 190550  42 "     40
 190558  65 5     45 %
 190566  67 7     45 %
 190574 141 a     41 !
 190582 145 e     45 %
 190590  54 ,     44 $
 190662  54 ,     44 $
 190670  54 ,     44 $
 190678  65 5     45 %
 190686 133 [      1 ^A
 190694  61 1     41 !
 190702  61 1     41 !
 190710  64 4     44 $
 190718  63 3     41 !
 190790  63 3     41 !
 190798  54 ,     44 $
 190806 135 ]      5 ^E
 190814  54 ,     44 $
 190822  54 ,     44 $
 190830  64 4     44 $
 190838  54 ,     44 $
 190846  61 1     41 !
 190918  67 7     45 %
 190926  67 7     45 %
 190934  54 ,     44 $
 190942  54 ,     44 $
 190950  54 ,     44 $
 190958 135 ]      5 ^E
 190966  42 "     40
 190974  65 5     45 %
 191046  60 0     40
 191054  60 0     40
 191062  60 0     40
 191070  60 0     40
 191078  60 0     40
 191086  60 0     40
 191094  60 0     40
 191102  60 0     40
 191174  54 ,     44 $
 191182  54 ,     44 $
 191190  54 ,     44 $
 191198  63 3     41 !
 191206  54 ,     44 $
 191214  54 ,     44 $
 191222  54 ,     44 $
 191230  64 4     44 $
 191302  61 1     41 !
 191310  61 1     41 !
 191318  54 ,     44 $
 191326  62 2     40
 191334  54 ,     44 $
 191342  54 ,     44 $
 191350  54 ,     44 $
 191358  62 2     40
 191430 101 A      1 ^A
 191438  42 "     40
 191446  64 4     44 $
 191454  61 1     41 !
 191462  65 5     45 %
 191470 135 ]      5 ^E
 191478  54 ,     44 $
 191486  54 ,     44 $
 191558  61 1     41 !
 191566  61 1     41 !
 191574  54 ,     44 $
 191582  70 8     40
 191590  67 7     45 %
 191598  54 ,     44 $
 191606  54 ,     44 $
 191614  54 ,     44 $
 191686  54 ,     44 $
 191694  54 ,     44 $
 191702  60 0     40
 191710  70 8     40
 191718  61 1     41 !
 191726  54 ,     44 $
 191734  70 8     40
 191742  66 6     44 $
 191814 130 X      0 ^@
 191822  71 9     41 !
 191830  64 4     44 $
 191838 117 O      5 ^E
 191846 111 I      1 ^A
 191854 133 [      1 ^A
 191862  62 2     40
 191870  63 3     41 !
 191942  61 1     41 !
 191950 135 ]      5 ^E
 191958  71 9     41 !
 191966  63 3     41 !
 191974  54 ,     44 $
 191982  54 ,     44 $
 191990  54 ,     44 $
 191998  54 ,     44 $
 192070  61 1     41 !
 192078 133 [      1 ^A
 192086  61 1     41 !
 192094  62 2     40
 192102  60 0     40
 192110  63 3     41 !
 192118  54 ,     44 $
 192126  54 ,     44 $
 192198  61 1     41 !
 192206  62 2     40
 192214  54 ,     44 $
 192222  54 ,     44 $
 192230  71 9     41 !
 192238  54 ,     44 $
 192246 133 [      1 ^A
 192254  64 4     44 $
 192326  54 ,     44 $
 192334  54 ,     44 $
 192342  64 4     44 $
 192350  54 ,     44 $
 192358  61 1     41 !
 192366 135 ]      5 ^E
 192374  54 ,     44 $
 192382  60 0     40
 192454  54 ,     44 $
 192462 133 [      1 ^A
 192470  60 0     40
 192478  71 9     41 !
 192486  62 2     40
 192494  62 2     40
 192502  54 ,     44 $
 192510  54 ,     44 $
 356422  54 ,     44 $
 356430  61 1     43 #
 356438  54 ,     44 $
 356446  54 ,    144 d
 356454  60 0     40
 356462  71 9    141 a
 356470  54 ,     44 $
 356478  54 ,     44 $
 356550  54 ,     44 $
 356558 135 ]      5 ^E
 356566  61 1     41 !
 356574  61 1     41 !
 356582  54 ,     44 $
 356590 133 [      3 ^C
 356598  61 1     41 !
 356606  54 ,     44 $
 356678 135 ]      5 ^E
 356686  61 1     41 !
 356694  61 1     41 !
 356702  54 ,     44 $
 356710 133 [      1 ^A
 356718  60 0     40
 356726  54 ,     44 $
 356734  54 ,     44 $
 356806  54 ,     44 $
 356814  54 ,     44 $
 356822  62 2     40
 356830  54 ,     44 $
 356838  54 ,     44 $
 356846  64 4     44 $
 356854  64 4     44 $
 356862  65 5     45 %
 356934 105 E      5 ^E
 356942 116 N      4 ^D
 356958  54 ,     44 $
 356966  54 ,     44 $
 356974  54 ,     44 $
 356982  54 ,     44 $
 356990  54 ,     44 $
 357062  54 ,     44 $
 357070  54 ,     44 $
 357078 133 [      1 ^A
 357086  64 4     44 $
 357094  61 1     41 !
 357102  54 ,     44 $
 357110  54 ,     44 $
 357118  54 ,     44 $
 357190  66 6     44 $
 357198  61 1     41 !
 357206 135 ]      5 ^E
 357214  65 5     45 %
 357222  66 6     44 $
 357230  61 1     41 !
 357238 135 ]      5 ^E
 357246  63 3     41 !
 357318  54 ,     44 $
 357326  63 3     41 !
 357334 135 ]      5 ^E
 357342 117 O      5 ^E
 357350  60 0     40
 357358  64 4     44 $
 357366 105 E      5 ^E
 357374 114 L      4 ^D
 357446  54 ,     44 $
 357454 135 ]      5 ^E
 357462  66 6     44 $
 357470  61 1     41 !
 357478  54 ,     44 $
 357486 133 [      1 ^A
 357494  64 4     44 $
 357502  54 ,     44 $
 357574  64 4     44 $
 357582  54 ,     44 $
 357590  54 ,     44 $
 357598  54 ,     44 $
 357606  54 ,     44 $
 357614  70 8     40
 357622  65 5     45 %
 357630  54 ,     44 $
 357702  54 ,     44 $
 357710  54 ,     44 $
 357718  63 3     41 !
 357726  70 8     40
 357734  54 ,     44 $
 357742  62 2     40
 357750  54 ,     44 $
 357758  60 0     40
 357830  67 7     45 %
 357838  62 2     40
 357846  54 ,     44 $
 357854  71 9     41 !
 357862  65 5     45 %
 357870  61 1     41 !
 357878  63 3     41 !
 357886  54 ,     44 $
 357958  54 ,     44 $
 357966 135 ]      5 ^E
 357974  62 2     40
 357982  62 2     40
 357990  63 3     41 !
 357998  67 7     45 %
 358006  54 ,     44 $
 358014  54 ,     44 $
 358086  70 8     40
 358094  62 2     40
 358102  61 1     41 !
 358110  63 3     41 !
 358118  54 ,     44 $
 358126  54 ,     44 $
 358134  54 ,     44 $
 358142 133 [      1 ^A
 358214 154 l     44 $
 358222 164 t     44 $
 358230  54 ,     44 $
 358238  54 ,     44 $
 358246  54 ,     44 $
 358254 133 [      1 ^A
 358262  54 ,     44 $
 358270  54 ,     44 $
 358342  54 ,     44 $
 358350  54 ,     44 $
 358358  54 ,     44 $
 358366 133 [      1 ^A
 358374  54 ,     44 $
 358382  54 ,     44 $
 358390  54 ,     44 $
 358398  54 ,     44 $
 358470  54 ,     44 $
 358478 133 [      1 ^A
 358486  54 ,     44 $
 358494  54 ,     44 $
 358502  54 ,     44 $
 358510  54 ,     44 $
 358518  67 7     45 %
 358526  71 9     41 !
 358598 163 s     41 !
 358606 141 a     41 !
 358614  61 1     41 !
 358622  54 ,     44 $
 358630  61 1     41 !
 358638  54 ,     44 $
 358646 133 [      1 ^A
 358654  62 2     40
 358726  54 ,     44 $
 358734  54 ,     44 $
 358742 133 [      1 ^A
 358750  62 2     40
 358758  61 1     41 !
 358766  54 ,     44 $
 358774 133 [      1 ^A
 358782  63 3     41 !
 358854  60 0     40
 358862  64 4     44 $
 358870  54 ,     44 $
 358878  65 5     45 %
 358886  54 ,     44 $
 358894  54 ,     44 $
 358902  64 4     44 $
 358910  62 2     40
 358982  54 ,     44 $
 358990  64 4     44 $
 358998 125 U      5 ^E
 359006  56 .     44 $
 359014  54 ,     44 $
 359030 164 t     44 $
 359038 156 n     44 $
 359110  54 ,     44 $
 359118  54 ,     44 $
 359126  54 ,     44 $
 359134  54 ,     44 $
 359142 135 ]      5 ^E
 359150  60 0     40
 359158  54 ,     44 $
 359166  54 ,     44 $
 359238  54 ,     44 $
 359246  54 ,     44 $
 359254  60 0     40
 359262  60 0     40
 359270  54 ,     44 $
 359278  54 ,     44 $
 359286  54 ,     44 $
 359294  54 ,     44 $
 359366  63 3     41 !
 359374  60 0     40
 359382  54 ,     44 $
 359390  54 ,     44 $
 359398  54 ,     44 $
 359406  54 ,     44 $
 359414  60 0     40
 359422  61 1     41 !
 359494  54 ,     44 $
 359502  54 ,     44 $
 359510  67 7     45 %
 359518  62 2     40
 359526  54 ,     44 $
 359534  63 3     41 !
 359542  66 6     44 $
 359550  54 ,     44 $
 359622  54 ,     44 $
 359630  62 2     40
 359638  64 4     44 $
 359646  54 ,     44 $
 359654  60 0     40
 359662  64 4     44 $
 359670  54 ,     44 $
 359678  54 ,     44 $
 359750  54 ,     44 $
 359758  67 7     45 %
 359766  54 ,     44 $
 359774  54 ,     44 $
 359782  54 ,     44 $
 359790  61 1     41 !
 359798  54 ,     44 $
 359806  54 ,     44 $
 359878 164 t     44 $
 359886 101 A      1 ^A
 359894 106 F      4 ^D
 359902 162 r     60 0
 359910 133 [      1 ^A
 359918  54 ,     44 $
 359926  54 ,     44 $
 359934  63 3     41 !
 360006  66 6     44 $
 360014  62 2     40
 360022  66 6     44 $
 360030  66 6     44 $
 360038  67 7     45 %
 360046  65 5     45 %
 360054  54 ,     64 4
 360062 135 ]      5 ^E
 360142  62 2     40
 360158 133 [      1 ^A
 360166  54 ,     44 $
 360174  66 6     44 $
 360182  62 2     40
 360190  66 6     44 $
 360262  54 ,     44 $
 360270  71 9     41 !
 360278  65 5     45 %
 360286 113 K      1 ^A
 360294  67 7     45 %
 360302  56 .     44 $
 360310 165 u     47 '
 360318 122 R      0 ^@
 360390  54 ,     44 $
 360398  63 3     41 !
 360406  54 ,     44 $
 360414  54 ,     44 $
 360422  54 ,     44 $
 360430  54 ,     44 $
 360438  60 0     40
 360446  54 ,     44 $
 548934  61 1    163 s
 548942  61 1    163 s
 548950 133 [      1 ^A
 548958  65 5     45 %
 548966  54 ,    166 v
 548974  54 ,    166 v
 548982  54 ,     64 4
 548990  54 ,    144 d
 549062  60 0    172 z
 549070 135 ]    127 W
 549078  54 ,     44 $
 549086  61 1     41 !
 549094  65 5    167 w
 549102 135 ]    127 W
 549110 124 T      4 ^D
 549118  61 1     41 !
 549190  61 1    163 s
 549198  54 ,    166 v
 549206  60 0     40
 549214  63 3     41 !
 549222  54 ,    166 v
 549230  54 ,    166 v
 549238  60 0    140 `
 549246  54 ,     44 $
 549318  54 ,    166 v
 549326  66 6    166 v
 549334  54 ,     44 $
 549342  54 ,     44 $
 549350  54 ,    166 v
 549358  61 1    163 s
 549366  54 ,     46 &
 549374  54 ,     44 $
 549446  54 ,    166 v
 549454  61 1    163 s
 549462  71 9     43 #
 549470  63 3     43 #
 549478  62 2    172 z
 549486  61 1    163 s
 549494  61 1     41 !
 549502  64 4     44 $
 549574  62 2    162 r
 549582  40      162 r
 549590  54 ,     44 $
 549598 124 T      4 ^D
 549606  70 8    162 r
 549614  62 2    162 r
 549622  63 3     43 #
 549630  63 3     43 #
 549702  67 7    167 w
 549710  54 ,    166 v
 549718  54 ,     44 $
 549726 135 ]      7 ^G
 549734  61 1    163 s
 549742  54 ,    166 v
 549750  54 ,     66 6
 549758  63 3     41 !
 549830  54 ,    166 v
 549838  54 ,    166 v
 549846  54 ,     44 $
 549854 135 ]      5 ^E
 549862  54 ,    166 v
 549870  54 ,    166 v
 549878  62 2     40
 549886  54 ,     44 $
 549958  65 5    167 w
 549966  62 2    162 r
 549974  63 3     41 !
 549982  54 ,     44 $
 549990 133 [    123 S
 549998  67 7    167 w
 550006  67 7     45 %
 550014 156 n     44 $
 550086  54 ,    166 v
 550094  54 ,    166 v
 550102  54 ,     44 $
 550110  54 ,     44 $
 550118  62 2    162 r
 550126 133 [    123 S
 550134  66 6     44 $
 550142  65 5     45 %
 550214  54 ,    166 v
 550222  61 1    163 s
 550230  62 2     40
 550238  71 9     41 !
 550246 135 ]    127 W
 550254  62 2    162 r
 550262  61 1     43 #
 550270  61 1     41 !
 550342  61 1    163 s
 550350  61 1    163 s
 550358  61 1     41 !
 550366  61 1     41 !
 550374  54 ,    166 v
 550382  54 ,    166 v
 550390  65 5     45 %
 550398 135 ]      5 ^E
 550470  54 ,    166 v
 550478  61 1    163 s
 550486  54 ,     44 $
 550494 135 ]      5 ^E
 550502  65 5    167 w
 550510  54 ,    176 ~
 550518  62 2     40
 550526  60 0     40
 550598  54 ,     66 6
 550606  61 1    163 s
 550614  54 ,     44 $
 550622 133 [      1 ^A
 550630  64 4    166 v
 550638  71 9    163 s
 550646  61 1     41 !
 550654  63 3     41 !
 550726  65 5    167 w
 550734  54 ,    166 v
 550742  54 ,     44 $
 550750  64 4     44 $
 550758  54 ,    166 v
 550766  64 4    166 v
 550774  65 5     45 %
 550782  54 ,     44 $
 550854  67 7    167 w
 550862  64 4    166 v
 550870 162 r     40
 550886 133 [    123 S
 550894  62 2    162 r
 550902  62 2     42 "
 550910  61 1     41 !
 550982  62 2    162 r
 550990  61 1    163 s
 550998  54 ,     44 $
 551006  54 ,     44 $
 551014  54 ,    166 v
 551022  54 ,    166 v
 551030  60 0     40
 551038  61 1     63 3
 551110  54 ,    166 v
 551118  70 8    162 r
 551126  54 ,     64 4
 551134  54 ,     44 $
 551142  54 ,    176 ~
 551150  60 0    162 r
 551158  61 1     41 !
 551166  64 4     44 $
 551238  54 ,    166 v
 551246  61 1    163 s
 551254  70 8     42 "
 551262  66 6     44 $
 551270 103 C    123 S
 551278  62 2    162 r
 551286  67 7     45 %
 551294 102 B      0 ^@
 551366  54 ,    166 v
 551374  61 1    163 s
 551382 133 [      1 ^A
 551390  61 1     41 !
 551398  54 ,    166 v
 551406  54 ,    166 v
 551414  54 ,     44 $
 551422  54 ,     46 &
 551494  66 6    166 v
 551502  63 3    163 s
 551510 135 ]      5 ^E
 551518  63 3     41 !
 551526  63 3    163 s
 551534  65 5    167 w
 551542 135 ]      5 ^E
 551622  65 5    167 w
 551630  54 ,    166 v
 551638  54 ,     44 $
 551646  54 ,     44 $
 551654  63 3    163 s
 551662  71 9    163 s
 551670 135 ]      5 ^E
 551678  61 1     41 !
 551750 151 i    163 s
 551758 141 a    163 s
 551774  63 3     41 !
 551782  66 6    166 v
 551790  54 ,    166 v
 551798  62 2     40
 551806  64 4     44 $
 551878  54 ,    166 v
 551886  63 3    173 {
 551894  65 5     45 %
 551902  67 7     45 %
 551910  63 3    173 {
 551918  54 ,    166 v
 551926  54 ,    144 d
 551934  54 ,     44 $
 552006  61 1    173 {
 552014  65 5    167 w
 552022  63 3     43 #
 552030  54 ,     46 &
 552038  61 1    163 s
 552046  63 3    163 s
 552054  70 8     40
 552062  64 4     44 $
 552134  65 5    167 w
 552142  71 9    173 {
 552150 154 l     66 6
 552158  40       60 0
 552166 154 l    166 v
 552174 151 i    163 s
 552182 160 p     40
 552190  61 1     43 #
 552262  54 ,    166 v
 552270  54 ,    166 v
 552278  54 ,     44 $
 552286  63 3     61 1
 552294  54 ,    166 v
 552302  54 ,    166 v
 552310  64 4     44 $
 552318  54 ,     44 $
 552390  61 1    163 s
 552398  54 ,    166 v
 552406 133 [      1 ^A
 552414  65 5     45 %
 552422  70 8    162 r
 552430  66 6    166 v
 552438  54 ,     44 $
 552446  54 ,     44 $
 552518  61 1    163 s
 552526 135 ]    137 _
 552534  62 2     42 "
 552542  61 1     41 !
 552550  61 1    163 s
 552558 135 ]    127 W
 552566 117 O      5 ^E
 552574  65 5     45 %
 552646  61 1    163 s
 552654  67 7    167 w
 552662  54 ,     44 $
 552670 135 ]      5 ^E
 552678  62 2    162 r
 552686  61 1    163 s
 552694  54 ,     46 &
 552702 135 ]      5 ^E
 552774  61 1    163 s
 552782  67 7    167 w
 552790  54 ,     46 &
 552798  63 3     61 1
 552806  54 ,    166 v
 552814  70 8    172 z
 552822  54 ,     44 $
 552830  60 0     40
 552902  71 9    163 s
 552910  61 1    163 s
 552918 133 [      1 ^A
 552926  61 1     41 !
 552934  62 2    162 r
 552942  54 ,    166 v
 552950 133 [      3 ^C
 552958  62 2     40

Notes on vector rivers

Playing around with a vector river map of California. Some notes.

Datasets

The Natural Earth major river dataset is pretty good. Not quite detailed enough for the Dreamflows scale map. Also everything looks to be about 2000m north of the natural boundaries defined by counties, other river datasets, etc. Maybe I screwed up a projection?

After a 3 day delay the NHD finally gave me back a shapefile with detailed flowlines for Nevada County. It’s very detailed data but it still has fewer small creeks on it than Google Maps or Stamen Terrain Maps. It might just be seasonal data, or maybe someone has a more detailed set. I need to explore NHDPlus.

Nick was kind enough to give me a shapefile of major rivers in California; 5 meg shapefile, 648 objects. It looks like about the right level of detail for the Dreamflows map, I’m working with it now although I want to circle back to NHD or some other primary source.

Massage

To convert a shapefile to GeoJSON:

ogr2ogr -f GeoJSON -t_srs EPSG:4326 dest.json source.shp

This converts the projection to EPSG:4326, the GeoJSON default. It contains ridiculously precise floating point numbers so could use some rounding with LilJSON or the like.

-simplify is useful to minimize the detail in the geometry. The tolerance parameter seems to be in the source CRS, so with this dataset in meters I’m trying “-simplify 100” or the like. 200 meters rounded to 4 digits of lat/lon seems like a good compromise; the rivers aren’t too janky at the scales I care about.

ogr2ogr -f GeoJSON -t_srs EPSG:4326 -simplify 200
python liljson.py -p 4

The resulting GeoJSON file is 200k compressed. Sure takes a long time for Leaflet to draw. For this kind of application I really want tiled, variable resolution vector data. Polymaps supported that years ago but it was complicated and underutilized. I wonder if anyone’s done it in Leaflet? May be overkill if I can make a Dreamflows-specific vector dataset.

Pictures

Here’s a QGIS image of a bunch of different data sources showing northwestern Nevada County. Pink dot is my house, center of the map is Deer Creek running west of Nevada City down to the Yuba. This data set is missing local reservoirs and ponds. Thick green line is Natural earth data, thick blue line is Nick’s rivers, and spidery blue lines are the N HD detailed data. Black line is the county border.

Screen Shot 2012-12-06 at 3.24.17 PM

 

And here’s a snapshot of the Dreamflows map I made a few days back with vector rivers overlaid. I like how it highlights the river flows to put the gauge dots in context. But I need a better data source; this one has many rivers that aren’t relevant to the map, and other rivers like Cache Creek and Antelope Creek are missing. I probably should cherry-pick just the rivers that I have gauge data for.

Screen Shot 2012-12-06 at 3.57.50 PM

Dreamflows Map

For the Nevada City Hackathon last weekend I built a map of river flows. Just in time for the torrential rains! All of the data comes from DreamFlows, a kayaker site. They collect real time river flow data from other sites, then process it and present it in a handy table format showing where the rivers are running high for good kayaking. Great site. What I couldn’t find at DreamFlows was a map of all the gauges, showing a picture of the whole state. So I made one!

Screen Shot 2012-12-03 at 9.22.56 AM

DreamFlows is kind enough to publish a CSV file of the aggregated real time data. My code takes that CSV data and draws it on the map via Leaflet. There’s a bit of extra work in geocoding the station IDs; I had to scrape station locations out of the site pages and put them in a JSON database. As is my way these days all my code runs client side; the only code on my server is a tiny shim working around Same Origin policy for the CSV file.

The resulting map isn’t bad for just a few hours work, but there’s a lot of things I’d like to do better. Some ideas:

  • Get data directly from the sources at CDEC and USGS. Mostly for historical data; DreamFlows only publishes current readings. Nick Santos at the Hackathon just wrote a USGS access library which could come in handy.
  • Visualize flows on the map. Right now I’m just drawing dots colored by DreamFlows’ classification. I’d like a more dynamic view, one that conveys the volume of water moving at each site more viscerally. I’m not sure whether to try to put a little historical graph right in the map, or maybe go for an animated presentation so you can watch flows come and go like a little movie.
  • Highlight rivers on the map. It’s hard to follow the courses of rivers on the terrain map I’m using. My thought is to produce a GeoJSON file of river flowlines and draw it with vectors on top of the map to highlight rivers. NHD is the canonical source for river map data in the US but it’s a hard site to work with. Nick pointed me to NHD Plus which augments the NHD data and makes it easier to work with.

Update: Chris at DreamFlows was kind enough to point out that his site has a Google Map like this too. It’s available under the Custom flows options and requires a login and a little setup, but you can end up with a dots-on-a-map almost exactly like mine.

Screen Shot 2012-12-04 at 6.16.25 PM

msgpack for topojson

Mike Bostock has published topojson, a clever variant of GeoJSON that more efficiently encodes toplogies. For a map of US counties, for instance, the GeoJSON approach is a bunch of LineStrings or Polygons that define each state boundary. There’s a lot of redundant line segments; TopoJSON eliminates those by encoding the line segments separately and then referencing them to define each state boundary. Also TopoJSON uses a relative integer representation instead of absolute floating point geocoordinates, greatly reducing size.

But is it as small as possible? There’s a lot of pairs of small integers like [-1,0],[1,-20],[-14,10],[-27,-9]; roughly 8 bytes for what could fit in 2. I took a quick crack at using msgpack to encode the JSON for us-counties more efficiently, this is what I learned:

 Source 668312
 Gzip 175895
 Msgpack 344208
 Msgpack gzip 166761

Msgpack is about half the size of JSON, but after gzip that difference goes away. That’s what I found last time I looked at msgpack, too.

Some custom encoding could make the TopoJSON format smaller still, but I’m not convinced that after gzip it will make much difference. Probably not worth the complexity. The one thing I’d consider is recoding the list of pairs of integers  just as a list of integers, so instead of [[-1,0],[1,-20],[-14,10],[-27,-9]] you have [-1,0,1,-20,-14,10,-27,-9]. That removes 2 bytes per pair, although after gzip that may be negligible. (update: Mike tried it. 552K (vs. 656K) for uncompressed 164K (vs. 172K) for compressed)

 

#!/usr/bin/env python

import msgpack, zlib, sys, json

text = file(sys.argv[1]).read()
data = json.loads(text)
msgpackText = msgpack.packb(data)

def log(s, d):
    print "%20s %s" % (s, d)

log ("Source", len(text))
log ("Gzip", len(zlib.compress(text)))
log ("Msgpack", len(msgpackText))
log ("Msgpack gzip", len(zlib.compress(msgpackText)))

Tomato (Toastman) router config

Here’s some of the config I give my Tomato (Toastman flavor) router:

Basic / Network: DHCP is 192.168.0.2 - 192.168.0.63. Lease 1440. Wireless is WPA2 Personal security, Encryption is TKIP/AES. Wifi is currently auto channel, 20MHz wide. 40MHz is an interesting 802.11n option I’ll play with later.

Advanced / DHCP/DNS: I have “Use internal DNS” checked on. Not sure if this is wise, particularly since I can’t figure out how to override what DNS servers the router uses (presumably the ISP’s advertised on DHCP?) I mostly tell my computers to use Google DNS anyway, so maybe this doesn’t matter.

Advanced / Firewall: respond to ICMP ping. Not responding to ping is just stupid; it offers no meaningful security and makes diagnostics harder.

Port Forwarding / UPnP/NAT-PMP: enable both UPnP and NAT-PMP

QoS: enable QoS, this is the best feature of all of Tomato. It makes things work well if you can estimate your bandwidth limits. Note that “Outbound” refers to upload speed, packets leaving your house and going to the Internet. That’s the slow side on a DSL line. Also I turn on prioritize ACK packets (why isn’t this on by default?!)

Administration / Admin Access: enable SSH at startup. (No remote access, of course.) Save my SSH key.

Administration / Bandwidth Monitoring: enable, save to JFFS every 24 hours. Screw it if it’s not recommended.

Administration / IP Traffic Monitoring: enable, save to JFFS every 24 hours.

Administration / JFFS: enable, format.

Some settings to do once the router is installed:

Basic / Network: is 40Mhz channels wise?

Basic / DDNS: this is very useful, I’ve been using dyndns.com for years and it works great via Tomato.

Basic / DHCP/ARP/BW: another useful option, give static IP addresses to known computers.

Advanced / Conntrack: the default Toastman timeouts for NAT tracking seem awfully short, we’ll see how that works.

Advanced / Wireless: Transmit power was only 17 mW on this router. My old WRT54GL defaulted to 42mW. These may or may not be directly comparable numbers. Some discussion on this setting is here and here, no one seems to have any idea what they’re talking about.

Update I tried changing this from 17mW to 100mW and saw no measurable difference in RSSI on my laptop, or throughput, or anything. I only tested with a laptop very near the router already enjoying -55dBm (as measured via the Mac’s Wi-Fi diagnostics). So if the setting is most useful for distance I wouldn’t notice it. I left it back at 17mW. I am a bit peeved that my 802.11n laptop can only do 10mbits/sec to an 802.11g Mac Mini, despite a theoretical 54mbits/sec connection. Update 2: getting 22mbits/sec now, after rebooting the Mac Mini. Now it’s in 802.11n mode as well. But all on a mixed mode 2.4GHz network and with 20MHz wide bands.

Port Forwarding / Basic: haven’t set this up yet. I’m discouraged that it’s displaying an error “iptables-restore: line 39 failed”

QoS: check caps for the live network and set in place

QOS / Classification: Toastman has enabled a bunch of service classes. Would be nice to check if they are reasonable.

USB and NAS / FTP server: enable on LAN only. (Geez!)

Administration / Logging: remote log to syslog, particularly DHCP traffic. Big help for narrowing down problems.

Update 2: someone named “vibe666” commented “I saw your post about your router and that you are using TKIP/AES.  drop TKIP and just use AES on it’s own as TKIP is both a) not very secure, and b) pretty much obsolete anyway, and c) likely to be slowing down your wifi speeds overall to keep (potential) backwards compatibility with stuff almost nobody has anyway. :)”

Router notes

The Internet router continues to be the most important computer in a house. It’s also the most likely to be garbage. For a long time I’ve done well with Tomato firmware on a WRT54GL, but that config is starting to get long in the tooth. Tomato hasn’t been updated in a couple of years, the WRT56GL doesn’t do 802.11n, and in general the world has moved on.

After some research I settled on what I think is the new consensus setup, confirmed in part by Jeff Atwood’s suggestions.

Router hardware: ASUS RT-N16. It’s the popular hacker router now and at $80, a reasonable price. The big drawback is it’s 2.4GHz only, no 5.0GHz. I don’t much care about 5GHz. If I did, I’d consider an ASUS RT-N66U instead. But that’s $160 and at that price you start wanting a real PC, not a router appliance. My understanding is 802.11n will work on 2.4GHz co-existing with 802.11g and 802.11b, albeit at reduced performance.

Router software: a TomatoUSB variant, the Toastman builds. TomatoUSB is the continuation of Tomato but it itself stopped seeing development about a year ago. Toastman has picked up the mantle. The key feature he added that I need is per-IP bandwidth monitoring. Another popular choice is Tomato by Shibby, an alternate TomatoUSB variant. It looks good too. (Aside: it’s a shame none of these firmwares are nicely packaged. Half of what made Tomato so good is it was a very professional release with a great manual and UI. Very unusual for fan-produced hackerware.)

Toastman releases a zillion different builds. The one I picked was tomato-K26USB-1.28.7500.4MIPSR2Toastman-RT-Ext. Note the file is hosted at some ghetto download service you have to register for free with. Ugh.

First installation is a challenge; the stock ASUS firmware doesn’t like the build and ASUS’ software to reflash a router is Windows only. These TFTP instructions seem reasonable and mostly worked on my Mac. The weird thing is the ping to the router sort of failed before the tftp; first 10 packets didn’t come back. I just left the ping running and the tftp magically worked.

After the tftp there’s no visible sign anything’s going to work. So I held my breath and rebooted, and there’s a stock Tomato/Toastman router. Hooray! Next blog post will be about configuration options; there’s a lot. The default config is reasonable except there’s a typo in the DHCP range and some dumb things like an FTP server running on the WAN port.

Converting ALAC Apple Lossless to 128kbps AAC m4a

I’ve got all my music in fancy Apple Lossless files. CD quality, but big; 500 megs a CD? I’m importing to a small hard drive and need to resample to 128kbps m4a. I looked at a lot of options, including shell scripts and ffmpeg. But I decided to just let iTunes to do the work; I trust it to handle metadata and album art better than something I cobble together myself.

I ended up following these instructions more or less. Here’s what I did:

  1. Start with an empty iTunes library
  2. Choose a new directory for my iTunes Media folder location in Advanced Preferences
  3. Make sure “copy files” and “let iTunes manage library” were unchecked in Advanced Preferences
  4. Open all my ALAC files from a read only remote file server, so iTunes now knows where all my music is.
  5. Go to iTunes preferences and change the CD import options to AAC encoder. Despite the horrible UI, that’s the option used when encoding all music, not just CDs.
  6. Select all my music. Right click, choose “Create AAC Version”
  7. Wait patiently for conversion.
  8. Press “delete”; this will remove the selection from my library, which still points to all the ALAC originals and not the AAC copies.
  9. The AAC copies are now in the folder I specified in step 2. I think these are safe, complete versions, although I haven’t verified that metadata (particularly album art) is in those files and not just in iTunes’ database. (Update: the album art does seem to be in the new files.)

The main problem with this process is step 7 needs to work correctly. If it’s interrupted then just resuming what wasn’t finished is a PITA. Not great when it will take many hours. Also step 4, the initial import, takes a very long time. I don’t think iTunes is actually reading the entire file, at least I hope it only reads a metadata header, but I’m not positive.

Update guess what, step 7 didn’t work correctly! The machine went to sleep on me, and between that and the Screen Sharing login I was using I ended up having to reboot. It wasn’t too hard to figure out where to resume encoding; you can quickly tell from the Bit Rate column which songs haven’t been re-encoded (or spot the dupes) and I hadn’t changed the sort order. So now I’m encoding the second half of my library. Step 8 won’t work now, no selection intact, but I think I can either use Bit Rate to find the original ALACs to remove or else unmount the disk and have iTunes remove the missing songs.

Update 2 36 hours of conversion later and it’s close to done, but not complete. I think it’s getting slower as time goes on but I’m not positive. There’s no major memory leak, don’t know what’s up. iTunes is a piece of garbage. One more problem with letting it do the work; iTunes names files its own way, it doesn’t copy the source filename. So there’s no real way to just diff directories to see what’s incomplete. I finally had to abort the import about 3% from complete; I may have to write a custom tool just to find what’s missing :-(

Update 3: I decided to redo the conversion and asked on Stack Exchange how best to do it. Glad I did; someone pointed me to Max and it’s doing the job well. It handles all metadata correctly (including Unicode) and it’s fast thanks to being multithreaded. I’ve got 8 encoding threads running on my iMac and have maxed out the hard drive bandwidth. Still no solution for resuming an incomplete batch job but since the whole thing only takes 3.5 hours now, I can live with it.

Preview.app’s signature capture system

I love how MacOS’ PDF viewer has the ability to add images of signatures to documents. I’ve been signing a lot of forms with it lately and it’s great.

The capture algorithm is interesting. Here’s a “signature” it generated when it had a view of the other side of my office, with a desk and a bunch of crap piled on it. Heavy edge detection! The cylinder just to left of center is a metal water bottle; can also see some electronic equipment (the box on left) and standing file folders (right).

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))

nmap scan options

I’m trying to learn something about the quality of a wireless Internet link in a house in Nevada County. Unfortunately the last couple of hops are invisible; my guess is the ISP is blocking all ICMP and other stuff at the boundary between their wired network and wireless network. Fair enough, but I really want to see inside that wireless link.

Sadly everything I’ve tried has failed, they’ve really got the link buttoned down. An ICMP traceroute does show me some promising looking networks before my destination but the latency seems too low to be wireless and there’s not much I can learn. Anyway, here’s some notes on using nmap’s more exotic options for probing a network.

nmap has a rich variety of host discovery options. Here’s some notes on various probe options. You have to be root to do a lot of this. In most cases nmap’s strategy is to send a packet hoping to get any sort of reply, it doesn’t care what the reply is, just something that verifies the host exists and is running an IP stack. It seems to send the probe twice, at least in some cases

  • -Pn: no discovery, just assume the host is up.
  • -PS: TCP SYN. Tries to open a TCP port; getting back an ACK or RST will both confirm the host is online, so it works whether the port is open or not. Default is port 80, do “-PS99” or whatever to change the port number.
  • -PA: TCP ACK. Sends a bogus ACK, expecting a RST back.
  • -PU: UDP. Should get an ICMP port unreachable response.
  • -PY: SCTP INIT. Similar to -PS, but tries to open an SCTP connection.
  • -PE: ICMP echo. Good ol ping
  • -PP: ICMP timestamp. One of those tech dead ends that should be removed or disabled (indeed, it’s not present in IPv6). My Linux server seems to respond with the correct time!
  • -PM: ICMP address mask. A way to query the subnet mask. Kind of a useful thing really, but Linux doesn’t seem to answer it. Maybe disabled for security?
  • -PO: IP protocol ping. Sends unusual IP protocol requests; ICMP, IGMP, and IP-in-IP by default. My Linux datacenter box doesn’t respond to IGMP or IP-in-IP probes.
  • -PR: ARP ping. For local ethernets only, bypasses the kernel’s ARP handling and handles ARP itself.  Any ARP reply implies the host exists. Note this is on by default for local networks and short-circuits other types of requests.

The default is -PE -PS443 -PA80 -PP: ping, TCP probes of HTTPS and HTTP, then ICMP timestamp. The default is also to do -PR when scanning ethernet local addresses.

Some other useful flags:

  • -sn: don’t scan ports, just probe to see if the host exists
  • -n: skip DNS and reverse DNS
  • -v: verbose output
  • --send-ip: send IP packets (rather than raw ethernet). Has the side effect of bypassing ARP ping. There’s supposed to be a “--disable-arp-ping” option but it’s not in nmap 6.0.1.
  • --traceroute: uses an existing probe method to do a full traceroute. Very clever way to map a network even when most stuff is shut down; if you can get a response from, say, ICMP timestamps you can use that to do the traceroute.

Here’s a screenshot of Wireshark after a bunch of probes to my remote Linux box.

xxxtreeeem power savings

Following on my last playing around with Intel power stats, I tried Powertop to further reduce my lightly loaded server’s power usage. Powertop watches the kernel to see when interrupts wake the system from idle, then gives you hints on how to turn those power drains off. I turned on a bunch of their power saving tips to see what would happen. Honestly, not much, < 5 watts or 10% of my server’s power usage. And some of what I did was pretty aggressive, like disabling system backups and databases and email that I can’t do for real. Other things were more benign, tuning various parameters (like a 15 second disk flush instead of 5 second) but given how little benefit it has I’m not making changes permanent.

The changes I made are easiest to see in the INdividual interrupts graph, around Sun 16:00. You can see we go from 150 interrupts / second to about 50. Fewer interrupts = more idle time. It’s also sort of visible in the CPU scaling graph. But it’s not meaningfully visible in the UPS power graph.

There’s a bigger change in these graphs, around Sat 20:00. That’s when I shut down mongodb. Mongo seems to constantly be doing something even when sitting idle. I wasn’t seeing the 15% CPU some users report, but it’s a lot more than zero. Still has no meaningful impact on power consumption so it’s probably not relevant.

Intel power state measurements

While reading Etsy’s excellent performance tuning blog post I learned about i7z, a nifty little tool for showing you Intel CPU states. It gives details on clock speed, turbo mode, and just how deep an idle power saving mode it might be in. Fun stuff, but I like graphs in Munin! How to do it?

The i7z author was very kind to give me some suggestions and before too long I had a hacky Munin plugin to display the data. Image below. Unfortunately it requires running i7z in the background and writing to a logfile, not a great match for Munin. I think it’d be better to go back to the source for the data and craft a Munin plugin from the low level CPU info. That being said, i7z does a fair amount of nice work in interpreting things. It knows about different states in different CPU models, can interpret turbo frequencies, etc. It may be a lot of work to do a good general purpose Munin plugin.

Another program that gives similar info is Intel’s PowerTop, part of their awesomely successful effort to bring better power management to Linux. They’re responsible for a lot of savings, I’d guess 20-50% power (and heat!) for a server since the Linux-2.2 era. While looking through its code I learned there’s a lot of detailed info in /sys/devices/system/cpu/cpu*, including power states! Lots of files there, only a little documentation, here’s some of the fun stuff

cpufreq/time_in_state: histogram of clock speeds over the system’s life

cpuidle/: info on power saving. My CPUs have 4 states, the “name” file tells us they are POLL, C1-SNB, C3-SNB, and C6-SNB. cpuidle/usage and cpuidle/time seem to be counters for how often they’ve been in those states. Quicky monitoring

while :; do
  for f in state?; do
    cat $f/usage | tr '\n' ' ';
    echo;
  done;
  sleep 1; echo;
done

For posterity, here’s the hacky plugin I wrote to read the logfile that “i7z -w l” writes. Graph, then code. The graph here is spiky because I’m only sampling every 5 minutes, not taking the 5 minute average. Not sure it’s very interesting info anyway.

#!/usr/bin/env python

"""
i7z - Wildcard plugin to monitor CPU states

by Nelson Minar <nelson@monkey.org>, placed into the public domain

This plugin relies on i7z running in the background and writing
data to a file.

Valid names: c0 c1 c3 c6 c7
"""

# Sample input
# 1344980274.830075945 [1.000000,3.628642,1.000000,95.207611,0.000000]   [1.000000,-0.456208,1.000000,99.314697,0.000000]    [1.000000,-0.737858,1.000000,99.645119,0.000000]    [1.000000,0.956179,0.000000,98.813507,0.000000]
# timestamp [c0, c1, c3, c6, c7] x4 (for 4 CPUs)

import sys, subprocess, os

# Figure out the mode from the name the program was invoked with
mode = os.path.basename(sys.argv[0])[4:]
# figure out which array index of data we want
modeMap = { "c0": 0, "c1": 1, "c3": 2, "c6": 3, "c7": 4 }
dataSlot = modeMap[mode]

# config
if len(sys.argv) > 1:
    if sys.argv[1] == "config":
        print """
graph_title i7z status mode %(mode)s
graph_category system
graph_vlabel percent
graph_scale no
graph_args --upper-limit 100 -l 0

cpu1-%(mode)s.label CPU1
cpu1-%(mode)s.min 0
cpu1-%(mode)s.max 100

cpu2-%(mode)s.label CPU2
cpu2-%(mode)s.min 0
cpu2-%(mode)s.max 100

cpu3-%(mode)s.label CPU3
cpu3-%(mode)s.min 0
cpu3-%(mode)s.max 100

cpu4-%(mode)s.label CPU4
cpu4-%(mode)s.min 0
cpu4-%(mode)s.max 100
""" % { "mode": mode }
        sys.exit(0)
    else:
        sys.stderr.write("Unknown argument %s\n" % sys.argv[1])
        sys.exit(0)

# fetch data for munin

fp = file("/home/nelson/src/munin-i7z/cpu_cstate_log.txt")
data = fp.readline()
cpus = [1,2,3,4]
(ts, cpus[0], cpus[1], cpus[2], cpus[3]) = data.split()
for i, cpu in enumerate(cpus):
    cpus[i] = [float(n) for n in (cpu[1:-1].split(','))]
    print "cpu%d-%s.value %.2f" % (i+1, mode, cpus[i][dataSlot])

sys.exit(0)

A friendlier PostGIS

Nathaniel Kelso has an awesome post about how to make PostGIS more friendly for users. I mostly agree with his points, it’s a friendly todo list, although there’s always the question of who has time to do the work. Some specific thoughts (I can’t figure out how to comment on his blog):

  • 1 Installation: I’d love updated Debian/Ubuntu packages. But it’s a lot of packaging work, I could see why PostGIS would rather defer to some third party to do the packaging. But someone’s got to do it! Upgrades are particularly hard to get right; Postgres and PostGIS mostly leave it up to users to figure out how to do upgrades right now.
  • 2.1 imports: is ogr2ogr any better than shp2pgsql in general?
  • 2.1g importing shapefiles: yes, absolutely, automatic inference of SRID from PRJ files. Is that a solved technical problem though, or is it arbitrarily difficult?

The #1 thing I want to make PostGIS easier is some better graphical query tool / front end to explore geometry queries. I’m used to being able to experiment with SQL in something like pgAdmin to build up my complex queries, but you can’t do that meaningfully with spatial data. I’d love a geo-aware SQL tool, one that draws geometries and stuff. I use QGIS like this a little bit but the UI for refining queries is awful. TileMill is a little better for query tinkering, but still awkward. Wouldn’t it be awesome if Induction were geo-aware, maybe using GeoJSON as a lingua franca?

shp2pgsql and .prj files

Shapefiles have a .prj file which is a text description of the projection used in the shape. For some reason shp2pgsql ignores this and inserts things with the SRID 0 unless you explicitly set one with a -s flag. Maybe it’s because it’s hard to reverse the text description in the .prj and turn it into a simple SRID that PostGIS already knows about?

Update: yeah, it is hard to do the mapping of .prj -> EPSG. The .prj may even describe some weird projection not in EPSG. But for many cases it should work. The website prj2epsg.org does a best effort match.

Anyway, trying to add Mike’s metro extracts coastline to my SFO Bravo airspace database, for another lasercut with a map superimposed. Sort of have it working, but need to clean it up to remove the annoying vertical and horizontal lines: shp2pgsql -s 900913 sf-bay-area.shp | psql faa

archive.org and HTTP seeded BitTorrent

archive.org announced BitTorrent support for downloads of their 1m+ files. The way they’re doing it is interesting, with HTTP seeded BitTorrent, a widely supported BitTorrent extension. In addition to normal torrent chunk downloads from peers, the BT client can also fetch ranges of bytes from an HTTP or FTP URL that’s published in the torrent. So archive.org doesn’t need to do anything too complicated with seedboxes; they just publish .torrent files that reference their existing HTTP resources, and BitTorrent clients will be able to download them. Only the BT clients can also do the P2P thing to download chunks, helping take some bandwidth off of archive.org and solving flash crowd problems.

There’s an impedance mismatch between BitTorrent and HTTP. HTTP is for downloading single files, ideally all in one stream although with Range requests you can get chunks from the middle. A single torrent has multiple files in it, and it’s natural to download chunks out of order. The BEP explains how the chunk stuff works for HTTP serving.

The other mismatch is that the HTTP contents located at a particular URL can and do change. The file contents located in a particular .torrent can’t really change; they are named by a checksum of their content, so if you change the content then the torrent is invalid. archive.org punts on this problem and just says that sometimes they change the HTTP contents and so you need to use a fresh/up-to-date .torrent. Expedient, if not particularly clean.

 

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.

SFO Bravo cut back

I got my SFO Bravo airspace lasercut back. It’s pretty good, but not awesome. A great prototype.

Some thoughts on what to change for a second run:

  • It’s big! 9″ diameter, 2″ thick. It’s just a little too big for me, hard to comfortably hold in the hand. I think I could use the P2 Ponoko sheets and get a 6″ diameter object that felt better in the hand. OTOH that screws up the scale even more; the actual airspace has a 30:1 ratio (60nm diameter, 10,000′ thickness). Maybe I could drop to thinner sheets too, 3mm instead of 4.5mm
  • I don’t love the material (4.5mm light blue acrylic). The translucency is visually distracting and hard to photograph. It’s reflective and a lot of live light inside. And the mirror surface shows fingerprints and smudges from the paper backing glue like you wouldn’t believe. I’m wondering if this wouldn’t work better as a flat white solid material. Or maybe wood, or even metal.
  • After I took the photos I realized I kinda prefer it upside down. Ie: put the surface ring on the top of the object, the 10,000′ ring at the bottom. You can’t just flip it over, you half to flip each sheet (mirror image) to keep east/west correct. But looking top down all you see is one big sheet, no detail. You have to look from the ground to see the detail.
  • Assembly is a little challenging, particularly the 4000′ ring which has almost no detail, just symmetry. If I’m making these as kits I should engrave some notes on each disc. That’d work even better if it’s opaque material.
  • The square spindle hole in the middle with a lasercut matchstick to hold it together doesn’t work well. Has about ±5° of wiggle, either from imprecision in the hole or flex in the stick itself. Really needs to be glued together, I suspect, need to read up on that.
  • The actual cut lines are great. Really worked out well. I don’t think I need to do anything more with the geometry, really.
  • I should engrave a map on the top of the biggest disc. Coastline + airports + major roads, maybe. It’d be neat to engrave some map stuff on the bottom of the discs, too, but it’s a bit tricky with the overlaps.
  • Took about 45 minutes to put together, most of that time peeling the backing off the discs. Would take longer if I cleaned each disc properly and even longer if they’re glued.

Ken suggested making a shape that’s more like a bowl; just the hull of the object. That’d be neat because you could see inside it, too. 3d printing would be the natural way to do that.

Setting default print options on a Mac

My mostly-nice color inkjet has two tanks of black ink; a big one for B&W documents, a small one for color documents. By default my Mac sends all its jobs in color and the printer isn’t smart enough to realize that the whole document is monochrome so really, the cheaper big tank will work just fine. I want to default printing to grayscale.

Irritatingly, you can’t do this with the obvious way in a Mac. You can create new printer option sets and save them as new profiles, but there’s no way to change the default profile.

But there is a way, via the CUPS web interface hiding underneath MacOS. It never occurred to me that this would be there! The instructions in the linked blog post worked just great for me, I even have the same kind of printer. Two wrinkles.. I had to choose the second of the two printers, the first had no print options associated with it. And the “Greyscale Printing” option appears twice, I had to set both to make it work.

This may save me literally dollars a year.

 

sources.list.d

I love apt, the binary package manager for Debian and Ubuntu. It is fantastic. The only drawback is it’s always a bit scary to add extra repositories to the sources that it draws from. In particular I don’t care for editing the single global file /etc/apt/sources.list.

There’s a better way! In addition to /etc/apt/sources.list, apt will also read files in /etc/apt/sources.list.d. It only loads files named *.list for some reason, but it will append all those files to its group of sources. So you can keep the main sources.list file pristine from the distro and then add your custom repositories as separate files. Yay!

There’s also an extra tool for managing apt repositories from the command line, add-apt-repositories (aka addrepo). It has shortcuts for adding PPAs, also seems smart about getting signing keys.

Walks cut back from Ponoko

 

I got back my second Ponoko cut of my walks. It came out pretty well. The etching of my most popular tracks came through really nicely; can’t see it in the photo but the burnt area in the middle is also quite deep. Could be deeper actually. And I love the ragged outline of the shape, it’s quite nice.

What didn’t work well is the burning of the wood on the edges of the cut, like around the bottom edge. That’s a common enough problem when lasercutting wood and in some cases it can be quite pretty. But here its uneven and blotchy and distracts from the fine line cuts. I suspect there’s no way to control this through Ponoko and I’d be better served with some other material.

Artisinal integers

Mission Integers and Brooklyn Integers are hipster web services that generate unique integers. Cleverly, they cooperate so the integers are unique across both sites. They did it the easy way; Mission returns even numbers, Brooklyn returns odd ones. I wanted to add a third site but there’s no way to do that, they’ve claimed all of the integers already.

So... can you generate integer sequences such that there can be an infinite number of generators with no collision? Supporting any predetermined number N of sites is easy; have site S generate s + n, s + 2n, s + 3n, s + 4n. But what if you don’t know N ahead of time? Yes, with maths!

Let’s say the Nth number that site S generates is the pair (S, N). We need an algorithm that creates a bijective mapping between (S, N) and the integers. Ie, for the current setup, Mission, even numbers, is site 0. Brooklyn, odd numbers, is site 1. The algorithm for number (S, N) is currently return n*2 + s

The trick is creating a bijection from the set of all integers to the set of all pairs of integers. I remember from college math this is possible (the cardinality of the set of all integers Z is the same as the cardinality of the cross product ZxZ) but I’d forgotten the constructive proof. Happily, Wikipedia remembers: something like the Cantor pairing function. http://en.wikipedia.org/wiki/Cantor_pairing_function

And the function for (s, n) is...

return ((s + n) * (s + n + 1))/2 + n

The picture is the useful intuition; basically you’re laying the tuples down on a square, then counting off cells.<

This kind of bijection comes in handy as a way to code large 2d spaces into 1d. I feel certain there’s an application for maps.

Here’s my implementation.

The drawback to this approach is the size of the Nth integer is O(N²). Mission integer 18,225,714 is 41,522,085,907,653 or about 2⁴⁵ in the cantor numbering.

See also Part 2

OpenPaths passive location tracking

There’s a bunch of passive location trackers out there. Mobile phone clients that watch your location all the time and upload reports of where you are every 15 minutes, hour, whatever. Three I’ve tried are OpenPaths, Google Latitude, and Geoloqi. Of the three I like OpenPaths the best. It’s by Jer Thorp, a very smart information visualization guy. It’s simple and does its thing well and nothing more. And it has the right goals and attitude. Google Latitude is opaque, corporate, and seemingly abandoned; it also has a terrible UI that only lets you get 30 days of data at a time. Geoloqi is nice but the tracker is more of a demo for their very capable platform. So OpenPaths is the one I’ll keep around.

 

That’s about three months of data, my travels around California. I like how the data shows all the different roads I’ve drive on my trips out of SF, particularly highway 12 across to Lodi. The couple of points east of Concord make me laugh, that’s when I was in Ken’s airplane and forgot to turn off my cell phone.

I’m not sure what I will end up doing with this data, but I intend to keep collecting it.

Simple XMLHttpRequest

I’ve never written my own XMLHttpRequest; I’ve always used jQuery or D3’s libraries. I had some sneaking suspicion one could do better than those wrappers in a modern HTML 5 setting, particularly for error handling, so for this project I wrote my own XHR code.

And turns out, nope, I’m not doing anything clever that those other libraries doesn’t. I’m doing less, really, my error handling is just as bad and there’s some clumsy stuff. Also this code only handles a really well behaved service; hasn’t been battle hardened against perverse replies or old browser versions. It does work for me though.

// Make AJAX calls, assuming JSON replies
function jsonRequest(url, callback) {
    console.log(url);
    var req = new XMLHttpRequest;
    req.open("GET", url, true);
    req.onreadystatechange = function() {
        if (req.readyState === 4) {
            if ((req.status >= 200 && req.status < 300) || req.status == 304) {
                var d = JSON.parse(req.responseText);
                callback(d);
            } else {
                // Bogus error handling
                callback(req);
            }
        }
    }
    req.send();
}

GeoNames web services

I always forget about the GeoNames web services. They’re awesome, a set of very simple REST like services for geodata. They also distribute a database. I don’t really understand the business, but they’ve been around some six years and seem to do their thing right. I used them for my WikiHere hack a few years ago and am about to use their elevation service for another quick hack.

They publish things right. Data is available in XML or JSON or JSONP formats and they set the CORS header so you can do cross-site javascript with no drama. I was originally going to use Google’s elevation service but they have no cross-site solution, not to mention my use would be unlicensed. So screw em.

Geonames asks for you to register and pass a user name on requests, they have a credit limit on requests. It’s 30,000 credits / day for free, most requests are a single credit, goes from 0.1 to 4 credits / request.

Their primary value add seems to be a broad database of place names, postal codes, etc. International. I don’t know how it compares to competing offerings or indeed if there even are any competitors. They also have time zones, wikipedia, some OSM data searches, etc. I’m using the elevation service, they have three to choose from: GTOPO30, SRTM3, and Aster. Too bad there’s no NED 1/9 for the US, but that’s a lot of data.

$ curl -D - 'http://api.geonames.org/astergdemJSON?lat=37.7383&lng=-122.4531&username=nelson'

HTTP/1.1 200 OK
Date: Tue, 24 Jul 2012 22:37:18 GMT
Server: Apache/2.2.17 (Linux/SUSE)
Cache-Control: no-cache
Access-Control-Allow-Origin: *
Transfer-Encoding: chunked
Content-Type: application/json;charset=UTF-8

{"astergdem":257,"lng":-122.4531,"lat":37.7383}

It’s a shame they refuse to allow caching.

Finishing the SFO Bravo lasercut

I finished up my lasercutting project, a model of SFO Bravo airspace. It’s a stack of 11 roughly circular objects, one every 1000′, that when stacked should be SFO bravo. It was a total pain finishing this out from the rough SVGs, but I think I’m there. It will be about 7in in diameter and 2in thick when assembled.

I ended up doing most of the finishing work in Inkscape. I never could get the SVG objects to scale correctly; the SVG viewpoint and scaling model is really confusing. And after calling ST_Union on the shapes I still had some interior lines I had to delete manually. But I got it close enough and could then paste all 11 objects into the Inkscape template, scale and style afterwards.

I got clever and cut a square hole in the middle of the airspace to insert a spindle. Hard to find that position, btw, it’s not really the center of any of the objects. It’s implied by the radii of the circles. Anyway I figured it out (it’s the VOR location, as expected) and added a rectangle to cut. I think I managed to make the holes 4.5mm wide, the width of the material I’m using, and even cut a 4.5mm long rod elsewhere on the sheet to use as the spindle. But it’s hard to get precise measurements out of Inkscape; it seems to be using the line width as part of the size of the object or something. And I’m in the habit of making the lines 1mm thick while editing so I can see them, then rescaling to 0.01mm for the final cut, which seems to throw off all the sizes. Oh well, if the spindle’s not perfect it’s OK.

It’ll cost of $37 + shipping in blue acrylic. Amazing how much cost depends on thickness. 4.5mm acrylic = $37, whereas 3.0mm is $20 and 5.6mm is $51. Most of that is laser time.

 

quickie VPN notes

I looked quickly into setting up a VPN server on my Ubuntu box in a datacenter, for use with MacOS and iOS clients. Unimpressed with what I learned. Here’s some options. They all suck.

  • PPTP, the venerable Microsoft protocol. Relatively easy to set up on both server and client, but has a reputation for being insecure. Plus it’s PPP and old and has a bad smell to it.
  • L2TP over IPSec. Apparently the server is doable on Ubuntu, but a bit wonky. MacOS and iOS both have clients. I probably should try this, I just don’t like the description of how it works. Update: Josh J. suggested this guide for setup (site down; Google cache).
  • Cisco IPSec. Proprietary? End of life from Cisco? Seems like a road not worth looking down.
  • OpenVPN. This is Ubuntu’s recommended server. Naturally, MacOS has no client for it; people like Tunnelblick. There’s no iOS client either other than GuizmOVPN which requires a jailbreak. I briefly tried following Ubuntu’s guide for installing OpenVPN which starts with “copy these config files and then edit some stuff”. Only the list of things to configure is incomplete, the template config files have errors in them, and after setting it all up I’m told “No /etc/openvpn/easy-rsa/openssl.cnf file could be found. Further invocations will fail”. I imagine I could power through all this stuff but it’s clear OpenVPN is not ready for casual users.

Why is this so damned hard?

Setting up to lasercut Bravo airspace

Another Ponoko project, making a 3d model of San Francisco’s Bravo airspace. It’s a bunch of roughly circular slices, should be great cutting a disc every 500′ or 1000′ to the outlines of the bravo. Some first steps to getting there, from raw data to basic (not finished) SVG files.

1. Download the FADDS database to get the FAA’s shapefiles of airspace. It contains some shapefiles for airspace.

2. Identify the coordinate reference system because shp2pgsql isn’t smart enough to guess. Class_b.prj says:

GEOGCS["GCS_North_American_1983",DATUM["D_North_American_1983",SPHEROID["GRS_1980",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]]

A quick lookup lets me know this is NAD83, EPSG:4269. That’s what I would have guessed, it’s quite close to WGS84, the GPS reference everyone sane uses. US government prefers NAD83 for some complex historical reason.

3. Load a database.

createdb faa -T template_postgis2
shp2pgsql -s 4269 class_b.shp | psql faa

4. Try loading the data into QGIS and see if it looks right. This is where projections start to matter. The Project Properties dialog lets you reproject the data on rendering; you have to check “Enable on the fly CRS transformation”. The SF bravo looks wrong when projected to WGS 84 (EPSG: 4326), too squashed. They should look like circles, using some projection local to San Francisco. There’s a few NAD 83 / California Albers projections that do pretty well, like EPSG: 3310.

Even better is grab Aeronav’s GeoTIFF for San Francisco and see what they use; pilots expect the airspace to look like it does on the chart. Here’s what gdalinfo and QGIS identify it as:

+proj=lcc +lat_1=45 +lat_2=33 +lat_0=37.6 +lon_0=-122.25 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs

PROJCS["San Francisco TAC",
    GEOGCS["NAD83",
        DATUM["North_American_Datum_1983",
            SPHEROID["GRS 1980",6378137,298.2572221010002,
                AUTHORITY["EPSG","7019"]],
            AUTHORITY["EPSG","6269"]],
        PRIMEM["Greenwich",0],
        UNIT["degree",0.0174532925199433],
        AUTHORITY["EPSG","4269"]],
    PROJECTION["Lambert_Conformal_Conic_2SP"],
    PARAMETER["standard_parallel_1",45],
    PARAMETER["standard_parallel_2",33],
    PARAMETER["latitude_of_origin",37.6],
    PARAMETER["central_meridian",-122.25],
    PARAMETER["false_easting",0],
    PARAMETER["false_northing",0],
    UNIT["metre",1,
        AUTHORITY["EPSG","9001"]]]
Origin = (-144533.795827518420992,71334.980332990919123)
Pixel Size = (31.819676000000001,-31.819676000000001)

Here’s a gallery of what the airspace shape looks like in WGS 84 (the squished one), that California Albers, and the “correct” Lambert projection the FAA uses (with the raster backdrop). The latter two are pretty close, but I could make things hard for myself and use the custom Lambert projection. Instead I’m going to use EPSG:26942, a Lambert that’s centered more or less on San Francisco. Visually the result looks very similar to the FAA’s projection, with the advantage I don’t have to figure out how to add a custom CRS to PostGIS.

5. Create an SVG file with some code. Naively this is as simple as ST_AsSVG(geom) and pasting the path into a skeleton SVG document. This actually works, but is a bit awkward since without reprojection the coordinates are all lat/lon values and stuff’s in a box from 37, -115 to 40, -118 or so. Quick workaround for that in Inkscape: select all (Ctrl-A) then zoom to selection (3). Also need to set the stroke width to something sensible for the coordinates.

 

Having to stop work on this here; I’m now generating reasonable SVG files, one per chunk of Bravo. Two main things left to do. First, use SVG transforms to scale the shapes from the default extent numbers like x=2,000,000 y=464,000 to something like 7cm square Ponoko uses. And second, do some topology calculations with ST_Union or the like so I render each slice of the airspace cake for every elevation.

A second try at Ponoko for my walks

Giving a second try at using Ponoko for my walking tracks after this moderate success. Sha and Rachel of Meshu suggested etching the actual GPS traces on top of the blob, which I thought was clever. So here’s what I’m doing step by step.

1. Create a view for my tracks with simplification

CREATE OR REPLACE VIEW simple_tracks AS
 SELECT tracks.ogc_fid, st_simplify(tracks.wkb_geometry, 0.0002) AS wkb_geometry, tracks.name
   FROM tracks;

2. Use QGIS to make a map of all those tracks, then use “Save as Image” to get a PNG raster image. I made the lines of the tracks be 1mm solid black and zoomed in. Note QGIS exports the image at the size visible on screen, so make that window big first!

 

 

3. Use Pixelmator as a paint program to calculate the concave hull of all my walks. Basically I did a flood fill of the background of the image to some random color, then selected all the pixels of that flood fill color, then inverted the selection. Now my selection is my concave hull! I then used a black brush to fill in the selection so I have a basically monochrome image, also erased some hanging bits to have a cleaner shape. This is the step I wish I could just use ST_ConcaveHull() in PostGIS to do, or some other topology algorithm.

4. Convert the raster blob into a path. Load the painted image into Inkscape, choose Path / Trace Bitmap, and use the default Brightness cutoff. Click “OK”. Nothing visible happens, but now if you move the raster out of the way you’ll see there’s a second black shape. This one is a vector object. Edit the style so it has no fill and a black outline, just to make it obvious.

5. Create a new Inkscape document from the Ponoko starter kit.

6. Copy and paste my outline from step 4 into the new document, then update the stroke style to a cutting line (0.01mm, #0000ff). Note the caution about XQuartz and the Mac clipboard not copying vector objects.

7. Reload my GPS tracks into QGIS. Be careful to load the simplified tracks, for fewer points. Then use the QGIS Print Composer to save the map as an SVG. That tool is really confusing, basically you use the “add map” button to swipe out a rectangle on the page. Scale and centering doesn’t much matter, all we really want is the SVG bits.

8. Load the QGIS generated tracks SVG into Inkscape. Break the group and select the hairball of individual tracks. Copy and paste it into the main document from step 6. Adjust the style of the track hairballs to a light engraving line (0.01mm, #ff00ff). Then, the sadness, scale and align the track hairballs so they just match the outline from step 6. Visual process, non-exact, we’ll see how it looks.

9. Save the SVG and send to Ponoko!

This took me a couple of hours. All this paint program fiddling is terrible; the right thing is to do this all with code. Calculate that concave hull, dump it as SVG. Calculate the union of simplified tracks, clip it to fit inside the concave hull, dump it also as SVG. Combine with the same reference and done! PostGIS has an ST_AsSVG that helps, but until I can get it to calculate the outline of my tracks the way I need there’s not much point.

Ubuntu upgrade to PostGIS 2 with data preservation

I thought it’d be “fun” to upgrade from PostGIS 1.5 to 2.x on my Ubuntu box. I forgot how byzantine Postgres extensions are and the fundamental rule of database upgrades; you have to take a dump with the old version first. I didn’t take careful notes, but here’s what sort of worked for me.

  • Read the PostGIS instructions on upgrading, in particular the notes about doing a “hard upgrade”. Create a dump before changing PostGIS 1.5.
  • Follow these instructions on installing PostGIS 2.x from sharpie’s PPA. You really need postgis-nightly; he has a PPA called postgis-stable too but I don’t think it’s fully populated.
  • Restore the dump with pg_restore, to a new database name. Pay close attention to stderr.
  • I got an error about ST_* functions being “not unique”. This report suggested that the restore brought over some 1.5 versions of functions and the solution is to run postgis_upgrade_20_minor.sql. Running that threw errors because I had a view depending on some of the functions; I ended up just dropping the view.

Honestly this is all pretty messy and I don’t have full confidence that PostGIS 2 is really installed properly. There’s too many spooky places PostGIS stuff gets loaded into the database. But all my old code still seems to work and gives the same results (at least, visually) so maybe it worked out.

I tried playing with ST_ConcaveHull that I wanted. It’s very, very slow on a GPS track with 50 points in it. Like 1.5 seconds to do a single track to a target percent of 0.5. I guess it’s doing some optimization algorithm? target percent of 0 doesn’t even work, throws a TopologyException. This function may not be what I need to do my calculation.

select
ogc_fid,
ST_NPoints(ST_Simplify(wkb_geometry, 0.0002)),
ST_ConcaveHull(ST_Simplify(wkb_geometry, 0.0002), 0.5) as wkb_geometry,
name
from tracks
limit 1;

visitors apache log analyzer

It’s irritating but there’s still no great solution for analyzing Apache log files. webalizer and analog both suck. One nice lightweight tool is visitors; it’s simple, fast, and mostly stateless. sample output, sample usage:

grep tweetchive /var/log/apache2/access.log{,-20120715} |
visitors -A -r 100 /dev/stdin
>| tweetchive.html

(cat /var/log/apache2/access.log{,-20120715};
  zcat /var/log/apache2/access.log*gz) |
visitors -A -r 100 -p 100 --prefix http://www.somebits.com --prefix http://somebits.com /dev/stdin
>| vis.html

# 4432363 lines processed in 41 seconds

Here’s some six years of weblog traffic. The breakdown reports are surprisingly uninteresting. I did learn my top Google search phrases: [chiller], [python xpath], [bash read], [spidermangame], [nelson minar], [bash read command]. I could make an SEO fortune!

tweetchive in IE9

Cross-platform Javascript has gotten a whole lot better in the HTML5 era. I developed all of Tweetchive without testing it at all in anything other than Chrome. It just worked in Firefox and Safari and Mobile Safari. IE9 still takes a bit of work, had to make two changes:

  • Added <!DOCTYPE html>. Other browsers don’t care, but IE9 runs in quirks mode without this and leaves out useful things like the JSON functions.
  • Dropped in Moment.js to parse dates. new Date(“some random localized string”) does a good job of parsing dates in most browsers, but not in IE.
    moment(fullTweet.created_at, “ddd MMM DD HH:mm:ss Z YYYY”).valueOf()

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.

Alternate way of filling browser with a div

A few weeks back I wrote up a trick for making a div fill the remaining browser height using Javascript to calculate a pixel height for the div on resize events. That seemed clunky to me and I just stumbled on a StackExchange question with an alternate method that’s CSS only using absolute positioning. Basically you create a box with top/left/right/bottom set to 0, then save a fixed amount of space at the top. The example uses padding-top, but I found I had to use margin-top instead, at least for a Leaflet map.

In retrospect I should have thought about this absolute positioning idea before! it makes much more sense. And it’s simpler not running any event code.

Animated temperature map

It’s hot. Here’s an animated map of temperatures for the day, from the aviation forecast. Normally this kind of angry rainbow palette is the worst sort of visualization sin, but it’s sort of appropriate for a hot day like today.

Making an animated GIF well is harder than I remember if you care about filesize.

#!/bin/bash
# Source: http://weather.aero/tools/weatherproducts/windstemps
for n in 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18; do
    wget -O $n.gif "http://weather.aero/data/winds/ruc"$n"hr_sfc_temp.gif"
done
gm convert -filter box -resize 315x -loop 0 -delay 25 ??.gif animation.gif

Lasercutting results

I got my lasercut test back. It worked out pretty well.

I was surprised at how well the fine detail came out on the GPS track. One blob is missing; I had a widowed little lozenge at bottom right that was detached. Fair enough. But all the fine details came out surprisingly well on the cardstock. The letters came out great too; all I did was convert some Postscript font text to a path and it came out fine.

The thing that didn’t work was the SF Bravo space (see earlier post). Entirely because of the double lines; Ponoko warns against doing that and they’re right. I also didn’t like the cardstock itself, particularly the burnt edges from the laser. To be expected, and no big deal since this was just a test cut, but unappealing. The solid grey areas came out surprisingly well; they sort of half burn it with the laser and it looked OK. Surprisingly the results came back glued to a wax paper back that I think was attached during the burning. Nice for not losing small parts, and frankly I’m amazed they can tune the laser so it cuts through the material but not the paper backing. I wonder how well that works with something like plexiglass.

Next project will be to re-do the Bravo, but do it right this time. First, use the right projection so the circles aren’t ovals! Second, create a series of stacked objects, one layer for each 1000′ of altitude. That’ll require some union magic in PostGIS. My goal is to get a stack of plexiglass layers with a hole in the middle so I can make a proper 3d object.

 

bash function for launching a web server

I’m doing a lot of AJAX development lately so I have to serve my HTML via HTTP, because AJAX just won’t work with file: URLs. There’s a lot of ways to launch a simple HTTP server in your current directory, here’s a handy bash function to do it (using Python)

pws ()
{
    PORT="$1";
    IP=`ifconfig en0 | awk '/inet / { print $2 }'`;
    python -m SimpleHTTPServer "$PORT" >> /tmp/pws-"$PORT".log 2>&1 &
    echo "http://$IP:$PORT/"
}

There’s a bogus bit here, using “ifconfig en0” to try to guess the right IP address to show. On a Linux box that’d be “eth0”, and in general it’s hard to know which of a machine’s IP addresses you really should use.

Update: I’ve tinkered with this script a little bit. It’ll supply a random port number if one isn’t given. And it’s a bit smarter about figuring out a likely IP address.

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

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.

Lasercutting foray

I’m playing with doing some lasercutting, using Ponoko and their Inkscape starter kit to do the cutting. I gave myself just a few hours to prepare a single test file to send off for fabrication, just to get my feet wet. First time using Inkscape, and first time in over 10 years to try to drive a laser cutter.

Inkscape is sadness on a Mac. It runs in X11 which is mostly intolerable. It’s unaware of the Mac file system. But the worst thing is the rendering is just really ugly. It’s a shame there’s no Cocoa native port of Inkscape, although realistically that’d be a lot of work to do right. BTW is it just me or if you copy a path from one Inkscape window and paste it to another, does it get converted to a bitmap?! I had to save the thing to a file and then import it to preserve the vector data.

Ponoko’s use of Inkscape is quite simple. Basically just make a bunch of blue lines 0.01mm wide for cuts. Some extra options for engraving, fills, etc. I made some circles and an outline of my name in Futura as test objects. But on to the more interesting things.

First, my walks tracks. Converting my complex walk shape to a cuttable SVG was not easy. The GPS tracks themselves are not sensibly cuttable, of course, you’d end up with confetti in the middle. What I want is to cut the concave hull of my shape, plus do something clever to depict some internal structure. Not sure how to do that. Even concave hull isn’t easy; ST_ConcaveHull isn’t available until PostGIS 2.0 which I’m not yet using. So what I did was use a combination of QGIS and Inkscape to make a filled shape of all my walks, a raster blob, then use Inkscape’s bitmap tracer to turn that into an outline path. Even then I got kind of a mess, had to go in and remove a lot of points. I’ve still got a disjoint lobe in my object which is going to screw up the cut, but I left it in there because I was curious what would happen and I don’t know how to easily fix it anyway.

Second the San Francisco Bravo airspace. This was pretty straightforward; load up the shapefile from FADDS in QGIS, print it to SVG, done! Well almost; that results in a bunch of lines being double-drawn, which causes the laser to cut twice. Ponoko doesn’t want you to do that and has instructions on how to manually break up shapes so duplicate lines don’t print. I did my best but I probably missed some spots.

OK, my SVG file is done, ready to cut! Now then, what material? Ponoko has a fun variety of options. Cardboard would be the natural cheap material for testing, but it’s kind of flimsy for some of the fine angles and they recommend not using the raster engraving option, which I’d already done as test images. I went with cardstock on the theory it’d be most forgiving to any materials / delicacy problems.

Some sample prices for my relatively simple object, 7.1″ square material sheet. Prices are “making”, which I take to be laser time, and then the material.

  • Cardstock: $7.13 + $2.36.
  • Thin cardboard: $7.93 + $0.23.
  • Cherry veneer MDF: $14.83 + $4.34.
  • Fluorescent orange acrylic: $8.27 + $3.72.
  • Bamboo: $8.27 + $2.82.

$10 for the item and another $10 for shipping and the order is in! They say it takes “typically 1-2 weeks”, but I see there’s a design review first which will presumably take some time on their end and maybe mine.

 

CrashPlan on Linux

It’s taken me six months since my last server failure, but I’m finally implementing an offsite backup for my home Linux server. I use rsnapshot for local backups which is great for recovering from mistakes. But it does no good if your server box dies in a fire, need offsite backups for that. I like CrashPlan on my Mac, so I thought I’d try it on Linux.

The first hurdle is installation. The default install location is /usr/local/crashplan. The supplied shell script is quite nice and they even gave thought to letting you run the backups as some user other than root! I think if you don’t install it as root the /etc/init scripts don’t get linked in. Worse, those scripts don’t seem to have any provision for non-root users.

The second hurdle is setting it up. CrashPlan is only configurable via a GUI tool that assumes it’s running on the computer that’s being backed up. Weak! Fortunately there’s a workaround; the GUI client really just talks over a socket to the backup daemon and you can fake it out with to talk to a remote host via an ssh tunnel. The Mac client stores the port number in an awkward place, but then I found that instead of editing the .app config file I could edit /Users/nelson/Library/Application Support/CrashPlan/ui.properties and add the line servicePort=4200. Still, shame the GUI client doesn’t allow this setting.

One extra Linux challenge is that the real time backups feature uses the inotify kernel module which by default only allows watching 8192 files. The docs cheerfully suggest just upping this number, but then I read this post that suggests it costs 200 bytes per file monitored (or maybe it’s only 40). Either way I don’t want to bump this up to 100,000+ or whatever it’d take (one per directory?) so I simply disabled real time backups in the Advanced settings. I’d actually prefer it just ran a nightly backup anyway, to manage bandwidth.

The backup daemon is reasonably well behaved. It’s a java process (!) that’s using less than 5% of one CPU. The bandwidth throttle actually works.

I’m annoyed CrashPlan is listening on port 4243 on the LAN port, not just localhost. You can’t actually use this for remote administration, at least setting serverHost instead of serverPort in the client didn’t work out for me. I wonder how secure the daemon really is; the security FAQ only addresses file encryption. Update: if you disable listening for remote backups, then it only listens on localhost:4243, much more secure.

Checking out msgpack

msgpack sounds like it could be useful: a binary format alternative to JSON that promises to be “like JSON but it’s faster and smaller”. Is it really? Not significantly; on a sample of 175 JSON files I had lying around the msgpack files were on average 75% the size of the JSON files. Better, but not significantly so. And if you’re a bit careful with JSON formatting and float precision, it’s not clear msgpack has anything to offer.

The big winner (ukiah.json, msgpack is 12% the original) is a GeoJSON file with a few thousand lat/lon coordinates in it, all pretty-printed with spaces. Some files actually get bigger with msgpack; a quick look suggests those are files with short floats in them like “32.17”, and it may be the Python encoder is giving those a full 8 bytes for an IEEE double.

For a file I actually care about, my WindHistory stations-md.json database, the 1 meg JSON files goes to 500k. That’s a big win for me in a deployed webapp, I think msgpack may do a particularly good job with the arrays of small numbers that file contains, e.g. [0,5,6,4,4,15,18,14,9,5,7,7,6]. I’d considered doing a custom format for that, dropping in msgpack would sure be easier.

Update: I did a quick extra comparison, passing the data through zlib.compress() after encoding, before comparing lengths. Compressed msgpack is worse than compressed json! For my sample, the msgpack/gzip data was on average 106% the size of the json/gzip data. For the WindHistory database the msgpack was still smaller, but only a little; 90%. gzip must be good at removing the text redundancy in json files full of numbers. OTOH I don’t understand why msgpack would ever be worse.

I took a quick look at the format spec: I think all msgpack is doing is storing numbers in binary instead of ASCII. That’s an improvement, particularly for codec speed, but it doesn’t seem to make all that big a difference in size. Here’s the msgpack author’s own opinion on comparison to other formats. The most useful link is the StackExchange answer.

What I’m really hoping for is an encoding that divines the structure of the stored data and builds compressed representations based on an ad hoc schema. It’s not crazy, folks were doing this with XML in Java webapps 10 years ago. But it’s not easy either. First step; a lookup dictionary for key names in object maps.

import json, sys, msgpack, os

pcts = []
for fn in sys.argv[1:]:
    try:
        jsonData = file(fn).read()
        data = json.loads(jsonData)
    except: continue

    msgData = msgpack.packb(data)
    pct = 100.0*len(msgData)/len(jsonData)
    print "%d%% %s json %d msgpack %d" % (pct, os.path.basename(fn), len(jsonData), len(msgData))
    pcts.append(pct)

print "%d%% average size" % (sum(pcts) / len(pcts))
12% ukiah.json json 2025795 msgpack 251349
24% faithful.json json 1103 msgpack 275
37% multiple-child-classes.json json 1645 msgpack 609
40% pets.json json 319 msgpack 128
41% sample_flatpages.json json 762 msgpack 318
42% m2m_through.json json 682 msgpack 292
42% mypeople.json json 142 msgpack 61
42% nk-inheritance.json json 344 msgpack 146
42% non_natural_1.json json 481 msgpack 206
43% big-fixture.json json 1749 msgpack 756
43% fixture6.json json 777 msgpack 341
44% forward_ref_lookup.json json 645 msgpack 286
44% initial_data.json json 5758 msgpack 2558
44% sequence.json json 231 msgpack 102
44% thingy.json json 147 msgpack 66
45% fixture8.json json 651 msgpack 295
46% initial_data.json json 6220 msgpack 2882
46% multidb.default.json json 546 msgpack 253
46% multidb.other.json json 543 msgpack 251
46% testdata.json json 1849 msgpack 860
47% fixture1.json json 744 msgpack 357
47% raw_query_books.json json 2602 msgpack 1240
48% absolute.json json 158 msgpack 76
49% db_fixture_3.nosuchdb.json json 193 msgpack 95
50% authtestdata.json json 1785 msgpack 895
50% empty.json json 2 msgpack 1
50% fixture2.json json 408 msgpack 206
50% multidb-common.json json 196 msgpack 99
50% stations-md.json json 10835 msgpack 5523
50% testdata.json json 1783 msgpack 894
50% testdata.json json 1783 msgpack 894
51% comment_tests.json json 968 msgpack 502
53% db_fixture_1.default.json json 208 msgpack 112
53% fixture1.json json 434 msgpack 231
53% fixture2.json json 437 msgpack 234
53% initial_data.json json 211 msgpack 112
54% flare.json json 11413 msgpack 6220
54% zeppelin.json json 318590 msgpack 174435
55% feeddata.json json 725 msgpack 403
55% initial_data.json json 226 msgpack 126
56% direct_message-destroy.json json 397 msgpack 225
56% direct_messages-new.json json 397 msgpack 225
58% skyrim.json json 22577 msgpack 13124
59% us-borders.json json 1421 msgpack 843
61% show-89512102.json json 656 msgpack 405
61% update.json json 656 msgpack 405
61% user_timeline-kesuke.json json 658 msgpack 406
62% manifest.json json 307 msgpack 193
64% CellLocation-geo.json json 936985 msgpack 608302
64% WifiLocation-geo.json json 5026275 msgpack 3249817
64% sample.json json 34 msgpack 22
66% model-inheritance.json json 161 msgpack 107
66% test-region.json json 104 msgpack 69
67% package.json json 732 msgpack 494
68% miserables.json json 11535 msgpack 7877
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% streets.json json 2479390 msgpack 1717654
69% test-country.json json 23138 msgpack 16046
71% mkassawara-aprs.json json 5644 msgpack 4036
72% cells.json json 2186447 msgpack 1583116
72% steps.json json 98475 msgpack 71556
73% mkassawara-first-solo-xc.json json 2368 msgpack 1730
73% walks.json json 269914 msgpack 199435
74% marimekko.json json 1139 msgpack 847
75% ohio.json json 244951 msgpack 184823
75% stations.json json 2185 msgpack 1648
75% test-location.json json 31890 msgpack 23957
76% average size
76% bullets.json json 543 msgpack 417
76% status-destroy.json json 473 msgpack 364
76% us-state-centroids.json json 7849 msgpack 6009
79% track.json json 2570 msgpack 2048
79% us-counties.json json 901283 msgpack 718329
80% direct_messages.json json 240 msgpack 192
80% public_timeline.json json 9488 msgpack 7670
81% us-states.json json 88430 msgpack 71888
81% user_timeline.json json 356 msgpack 291
82% initial_data.json json 4563 msgpack 3748
82% turkers.json json 1866 msgpack 1533
83% friends_timeline-kesuke.json json 9045 msgpack 7585
84% KMER-df30.json json 321 msgpack 272
85% friends.json json 17796 msgpack 15233
85% world-countries.json json 252515 msgpack 216432
86% KLVK-df30.json json 322 msgpack 278
86% KRHV-df30.json json 319 msgpack 276
86% followers.json json 29176 msgpack 25124
86% trip.json json 25665 msgpack 22184
87% flare-imports.json json 34321 msgpack 30201
87% friendship-create.json json 468 msgpack 408
87% friendship-destroy.json json 468 msgpack 408
87% replies.json json 3298 msgpack 2895
87% show-dewitt.json json 722 msgpack 630
88% KAPC-df30.json json 322 msgpack 286
88% featured.json json 10056 msgpack 8854
89% KCCR-df30.json json 324 msgpack 289
89% KMRY-df30.json json 327 msgpack 293
89% KPAO-df30.json json 317 msgpack 283
89% KSTS-df30.json json 324 msgpack 291
89% KWVI-df30.json json 330 msgpack 296
90% KOAK-df30.json json 344 msgpack 313
91% KMAE-df30.json json 326 msgpack 299
91% KNUQ-df30.json json 317 msgpack 290
91% KVCB-df30.json json 328 msgpack 301
92% KHWD-df30.json json 327 msgpack 303
92% KMHR-df30.json json 332 msgpack 306
92% KSFO-df30.json json 348 msgpack 321
92% KSJC-df30.json json 334 msgpack 308
92% KSMF-df30.json json 339 msgpack 312
92% KSNS-df30.json json 326 msgpack 300
92% KSQL-df30.json json 317 msgpack 293
93% KMCE-df30.json json 328 msgpack 307
93% KMHR.json json 7656 msgpack 7182
93% KMOD-df30.json json 327 msgpack 307
93% KPAO.json json 7372 msgpack 6891
93% KSAC-df30.json json 333 msgpack 313
93% KSAC.json json 7485 msgpack 7035
93% KSCK-df30.json json 336 msgpack 314
93% KSUU-df30.json json 341 msgpack 320
94% KCCR.json json 7465 msgpack 7034
94% KMOD.json json 7388 msgpack 6953
94% KRHV.json json 7106 msgpack 6714
94% KSFO.json json 7710 msgpack 7269
94% KSQL.json json 7615 msgpack 7199
94% KSUU.json json 7555 msgpack 7160
94% district.json json 53585 msgpack 50817
94% district.json json 53585 msgpack 50817
94% district.json json 53585 msgpack 50817
95% KAPC.json json 7541 msgpack 7220
95% KDVO.json json 7826 msgpack 7467
95% KHWD.json json 7646 msgpack 7329
95% KLVK.json json 7442 msgpack 7100
95% KMAE.json json 7582 msgpack 7231
95% KMCE.json json 7278 msgpack 6959
95% KMER.json json 7258 msgpack 6909
95% KOAK.json json 7662 msgpack 7332
95% KSCK.json json 7591 msgpack 7263
95% KSTS.json json 7548 msgpack 7210
95% KWVI.json json 7711 msgpack 7375
96% KMRY.json json 7760 msgpack 7454
96% KNUQ.json json 7701 msgpack 7433
96% KSMF.json json 7777 msgpack 7512
96% KSNS.json json 7700 msgpack 7426
96% KVCB.json json 7726 msgpack 7417
97% KSJC.json json 7758 msgpack 7567
99% test-usstates.json json 152305 msgpack 152245
99% test-worldborders.json json 911213 msgpack 911121
107% flowers.json json 14123 msgpack 15152
110% unemployment.json json 1383 msgpack 1532
120% world.json json 142051 msgpack 170748
121% unemployment.json json 39718 msgpack 48273
76% average size

Python: showing time in another timezone

Python’s date and time APIs are awful. Actually they’re awful in most languages, Java’s were sure terrible. But Python is worse because it has several ways to do things and none of them are really correct. The newish datetime module is better than the old time module and its bizarre “tuple that may or may not be timezone aware” type. But even datetime is stupid about time zones, only supporting UTC or the local computer’s time. You need the add-on pytz to bring in the Olson timezone database to start doing real work, and even then it’s complex.

I have some timestamps, seconds-since-Unix-epoch, which is intrinsically UTC. Unambiguous integers. Now I want to print them in Florida’s timezone, no matter what my computer’s time zone is. Here’s one way:

florida = pytz.timezone('US/Eastern')
floridaDatetime = datetime.datetime.fromtimestamp(ts, florida)
print floridaDatetime.strftime("%b %d %H:%M")

This seems to work, but the pytz docs admonish “Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones. It is safe for timezones without daylight savings trasitions though, such as UTC” The docs recommend this instead:

florida = pytz.timezone('US/Eastern')
utcDatetime = datetime.datetime.fromtimestamp(ts, pytz.utc)
floridaDatetime = utcDatetime.astimezone(florida)
print floridaDatetime.strftime("%b %d %H:%M")

I’m not positive, but I think my simpler code actually will work as long as I don’t try to do anything fancy with floridaDatetime like arithmetic. The problem is described in detail in the pytz docs: it’s some combination of datetime being limited and that certain timestamps are ambiguous because of DST. So really pytz is encouraging us to always always always only ever do math with UTC time and defer conversion to local timezone to the last possible moment before string output. Which is imminently sensible, if frustratingly verbose.

I think the right library would be a datetime type whose internal representation is always only ever seconds-since-epoch plus desired timezone. That way all the library code can do arithmetic without worrying about DST. I wonder if any other languages do it that way. Python’s got some unfortunate legacy hanging around and I don’t think Python3k tried to fix up the mess.

interactive fsck on Ubuntu

My headless server in Kansas didn’t reboot properly. The nice guys at the datacenter plugged in a console and found fsck waiting for them to press “Y”, which they did, and the system came back. Interactive fsck is pretty much always a terrible idea, particularly for a headless server, why was it waiting?

I can’t find good docs on this for Ubuntu. I’ve asked a question on StackExchange and started digging through code. I think the important setting is FSCKFIX /etc/default/rcS:

When the root and all other file systems are checked, fsck is invoked with the -a option which means “autorepair”. If there are major inconsistencies then the fsck process will bail out. The system will print a message asking the administrator to repair the file system manually and will present a root shell prompt (actually a sulogin prompt) on the console. Setting this option to yes causes the fsck commands to be run with the -y option instead of the -a option. This will tell fsck always to repair the file systems without asking for permission.

So Ubuntu already partially runs fsck in non-interactive mode; the -a flag (aka -p) “This option will cause e2fsck to automatically fix any filesystem problems that can be safely fixed without human intervention.” I guess something was wrong enough with the filesystem on reboot that -p was afraid to fix it. But in my case I don’t care; I have a backup, I need the server up under any circumstance, and I never knew how to answer fsck’s questions anyway.

I found this by reading through code. Ubuntu mounts filesystems via a program called mountall. Init invokes mountall and uses a shell script to set options. Here’s relevant bits of code:

/etc/init/mountall.conf:

[ "$FSCKFIX" = "yes" ] && fsck_fix="--fsck-fix"

mountall.c:

if (fsck_fix || mnt->fsck_fix) {
  NIH_MUST (nih_str_array_add (&amp;args, NULL, &amp;args_len, "-y"));
} else {
  NIH_MUST (nih_str_array_add (&amp;args, NULL, &amp;args_len, "-a"));
}

So there we have it, I think setting FSCKFIX=yes in /etc/default/rcS is my solution. And I’m glad to see even with that not set Ubuntu mostly runs fsck non-interactively.

Ubuntu 12.04 power savings

This is kind of neat; Ubuntu 12.04 is saving me 10-15 watts or about 25% of my server’s power consumption. I upgraded from Ubuntu 11.10 and my UPS is telling me my server uses 45W now instead of 58W, or thereabouts. The system is a few degrees cooler, too.

I suspect the important change is from the 3.0 Linux kernel to the 3.2 kernel, and the subsequent Power Saving Tweak where the Intel chipset is told to shut down the built in GPU. That’s a win for a lot of folks; headless servers (without weird code using the GPU) and desktop computers with “real” graphics cards. I’m surprised it’s so much an improvement though.

A second possibility is CPU affinity; there’s been some work on multicore systems trying to keep some cores shut down more often if the workload is light. Details on Less Watts tips. I enabled sched_smt_power_savings a few hours after upgrading Ubuntu, but I didn’t see any difference, so maybe not. The CPU frequency scaling graph suggests that maybe something’s changed.

The one alarming thing is that the IO Service Time went way up, from .00001s to .05s. Huh? I’m not doing much IO, so maybe this is a bogus measurement, and I can’t really understand what Munin is measuring anyway. This may be an artifact of the disks being put to sleep more often, or maybe the measurement changed scale, or who knows what. Simple disk benchmarks suggest nothing’s really wrong.

Update: turns out this was a change in the Munin scripts, a fix for an eight year old bug. The Ubuntu 11.10 version was reporting bogus numbers that were backwards and too small. Supposedly the new numbers are correct, and also report no data correctly now. Just reading the numbers off the graph, my system now says writes take about 20ms when before it was saying 0.1ms. Disk seeks are roughly 10ms, so I’m inclined to believe the new numbers are more correct. The bug comments also note that the various disk stats graphs contain similar information but are better.

www.ʬʬʬ.com

Someone on Metafilter mentioned they registered the IDN http://www.ʬʬʬ.com (aka http://www.xn--5paaa.com). I thought that was cool, so I posted it to my usual social media thing. And it worked, correctly rendering everywhere! Here’s the flow of where that worked

  • Pasted the name into the Pinboard Chrome extension
  • Had it show up on Pinboard
  • Had dlvr.it pick it up from an RSS feed and post it to Twitter
  • Saw the IDN in my Twitter client
  • Clicked on the link, redirecting through t.co and dlvr.it

In retrospect, I think why this works is IDNs aren’t really Unicode, they’re Punycode (that xn-5paaa thing). So most of the tools are treating that thing as ASCII but the browser happens to do the interpretation so it displays correctly. I confirmed that a bit by tweeting “this is a test http://www.ʬʬʬ.com”, which shows up on Twitter as “this is a test http://www.xn--5paaa.com” on both Twitter.com and the MacOS client. The link still works, but it looks wrong; Twitter should probably translate.

Fixing a slow Samba server on Ubuntu 12.04

I recently upgraded my Ubuntu from 11.10 to 12.04. Mostly worked fine, the usual little config mishaps. But then one really bad problem: my SMB server on the Ubuntu box was terribly slow with my Mac client. Like reading a file would get 100kbytes/second. This on a gigabit ethernet where I used to be able to do SMB at the disk speed of 30Mbytes/second.

I ruled out some basic stuff: local disk access was fine, and copying the file via nc was super fast so it wasn’t the network. I started at guessing things. The final fix was to remove this line I’d previously put in my smb.conf

socket options = TCP_NODELAY SO_RCVBUF=8192 SO_SNDBUF=8192

Not sure why those settings would be harmful, nor which specific setting is the problem. The smb.conf man page suggests TCP_NODELAY is the default so I’m guessing it’s the buffers. Anyway, SMB is fast again.

Kartograph

Kartograph is looking promising. It’s a new Javascript map library that is fully vector based, drawing maps in SVG. First time I’ve seen a complete break with the slippy map raster tiles that Google made so popular. The nice thing about a vector map is you can easily use your own projection. Of course you can do raster tiles in many projections too, but most of the existing raster libraries have Google Mercator baked pretty deeply into them. Also vector rendering is beautiful and somewhat scale invariant.

The code’s on GitHub. And if you dig into the demo pages you can find the source code hidden inside the <div> element that contains the map itself. It looks pretty straightforward, a nice API. I’m a bit alarmed to see methods like “chloropleth” and “dotgrid” right on the map object; that suggests the author has in mind a set of hardcoded visualization types. I hope he’s left room for other developers to easily add their own visualization types. Also none of the examples have any navigation, none of the usual pan/zoom controls we expect. That’s totally fine for many visualizations, but may distinguish the uses of this library compared to Leaflet and friends.

 

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.

Simplifying walk tracks

I have a bunch of GPX tracks generated by iSmoothRun, a GPS tracker for the iPhone that tries to correct for location error by using the accelerometer as a pedometer. The tracks it produces are pretty lumpy too, so I’m trying to use ST_Simplify afterwards to clean them up.

ST_Simplify takes as a second parameter the “tolerance”, how much to smooth. This parameter is not well documented but it seems to be measured in the units of the geometry you are simplifying. For my walking tracks 0.00005 seems to be about right. If that were degrees, that’d correspond to about 15 - 20′ in San Francisco.

Here’s a quicky chart of the average percentage difference between the original track length and the simplified track length, for different tolerances.

0.00001   0.1%
0.00003   0.7%
0.00005   1.8%
0.00007   2.8%
0.0001    4.4%
0.001    19.9%

0.00005 seems to be a reasonable compromise. It produces tracks with about 1/3 the number of points as the original. Below is a picture of the original track and the simplified drawn on top of it, to show the geometry change.

I wish I understood SRIDs more intuitively, I feel like I’m bashing about. Half my data is WGS84 and half is Google Mercator, and then below I’m using SRID 2163 to do the distance calculation. That’s a bit of cargo cult coding, I think it’s NAD83 which is close enough to WGS84 to get away with.

-- Create a simplified view of an ogr2ogr imported track
create or replace view simple_tracks as
select
ogc_fid,
ST_Simplify(wkb_geometry,0.0001) as wkb_geometry,
name
from tracks;

-- Display the difference between original and simplified
select
  miles-smiles as difference,
  round((miles-smiles)/miles*100) as pctlength,
  round(spoints*100/points) as pctpoints,
  * from
(select
tracks.name,
ST_Length(ST_Transform(simple_tracks.wkb_geometry, 2163)) /1609 as smiles,
ST_Length(ST_Transform(tracks.wkb_geometry, 2163)) /1609 as miles,
ST_NPoints(simple_tracks.wkb_geometry) as spoints,
ST_NPoints(tracks.wkb_geometry) as points
from simple_tracks inner join tracks
on simple_tracks.name = tracks.name order by name) as m;

-- Calculate just the average difference
select avg((miles-smiles)/miles*100) from
(select
  tracks.name,
  ST_Length(ST_Transform(simple_tracks.wkb_geometry, 2163)) /1609 as smiles,
  ST_Length(ST_Transform(tracks.wkb_geometry, 2163)) /1609 as miles
from simple_tracks inner join tracks
on simple_tracks.name = tracks.name order by name) as m
where miles > 1;

60 walks

I imported 60 different GPX tracks from RunKeeper into my database, using this hack. I’ve been dorking around with the data using TileMill as a sort of GIS app; it’s nicer than QGIS! But it’s silly for me to try to draw my own complete map from OSM data, as fun as that is, so I’ll probably switch to some GeoJSON overlay on top of a slippy map with nice terrain tiles next. Anyway, here’s a map of just the walks and then parks in SF.

I like the way the transparency + the GPS noise naturally shows streets I walk on more frequently.

SF Steps revisited

I improved my query for all the steps in San Francisco, by narrowing it down to steps that are really just in the city of SF itself and not whatever happens to be in the OSM Metro import I have in my database.

First I had to find where in the database was the actual boundary of San Francisco:

select name, * from planet_osm_polygon where boundary = 'administrative';

Visually inspecting that list turns up OSM_ID -111968, San Francisco. Below is a quick drawing of that polygon in OSM. It’s not quite correct; all the water is fine, but it leaves out the Farallons and includes a tiny bit of Alameda and Angel Island. Still, close enough.

Then it’s just a matter of doing the geographic intersection. This query makes me scratch my SQL head a little bit, I cribbed it from the PostGIS book, but it runs pretty fast. Much slower if you try this intersection on all the roads in the SF Metro.

select
planet_osm_line.name, round(ST_Length(planet_osm_line.way)) as meters, 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;

And here we go, 366 stairs.

meters name
280 (none)
245 Sand Ladder
222 (none)
198 Lyon Street
195 Lulu Alley
193 Oakhurst Lane
191 Vulcan Steps
169 Pemberton Place
158 Onique Lane
154 Filbert Steps
154 (none)
148 (none)
147 Harry Street
141 (none)
136 Blairwood Lane
129 (none)
129 Quintara Street
125 Ortega Way
124 Path Street
122 (none)
122 Mount Lane
118 Greenwich Street Stairs
117 Hawkins Lane
114 (none)
114 Terrace Walk
113 Flibert Steps
111 (none)
110 Peter Macchiarini Steps
110 Peter Macchiarini Steps
109 (none)
109 (none)
108 Aerial Way
107 Cascade Walk
106 (none)
104 Joy Street
103 (none)
102 (none)
102 Moraga St. Steps
102 8th Avenue
102 Linda Vista Steps Street
102 Vallejo Street
101 Coralino Lane
101 Mandalay Lane
99 Athens Street
99 Avoca Alley
97 (none)
96 (none)
96 Aerial Way
96 Pacheco Street
95 Glenhaven Lane
95 Farnsworth Lane
94 Oriole Way
93 (none)
93 (none)
92 Esmeralda Avenue
91 (none)
89 (none)
89 (none)
87 (none)
87 Saturn Street Stairs
85 The Agave Trail
83 (none)
83 Acme Alley
83 Waller Street
80 Onique Lane
80 (none)
80 Amatista Lane
80 Stairs
80 (none)
79 Ward Street
79 Vallejo Street Stairway
77 Sunglow Lane
77 Blairwood Lane
77 (none)
76 (none)
76 Fair Avenue
76 Monument Way
74 (none)
74 Macondray Lane
74 Esmeralda Avenue
74 (none)
73 (none)
73 Greenwich Street Stairs
73 (none)
73 Esmeralda Avenue
73 Hillview Court
72 Eugenia Avenue
72 Griffith Street
72 (none)
72 (none)
71 (none)
71 (none)
68 (none)
68 (none)
68 (none)
68 Iron Alley
67 Greenwich Street
67 Vista Lane
67 Terrace Walk
66 Naglee Avenue
66 27th Street
65 (none)
65 Beeman Lane
65 (none)
65 (none)
63 (none)
63 Sunbeam Lane
63 (none)
62 (none)
61 Liberty Street
61 (none)
61 Prospect Avenue
60 3rd Avenue
60 (none)
58 (none)
58 Acme Alley
58 (none)
58 (none)
54 Andover Street
53 (none)
53 Harrison Street
53 (none)
53 (none)
53 (none)
53 (none)
52 (none)
52 (none)
51 Saint Mary’s Avenue
51 Opalo Lane
51 Oneida Avenue
50 Reno Place
50 (none)
49 Chestnut Street Steps
49 Mono Street
49 (none)
49 Douglass Street
47 (none)
47 Greenwich Street Stairs
47 Clifford Terrace Stairway
47 (none)
46 (none)
46 (none)
45 Kenny Alley
45 20th Street
44 Fair Avenue
44 20th Street
44 Levant Street Stairway
43 (none)
42 (none)
42 (none)
42 Corbin Place
41 (none)
41 (none)
41 (none)
41 (none)
39 (none)
39 (none)
38 (none)
38 Duncan Street
38 (none)
38 (none)
37 (none)
37 (none)
37 Priest Street
37 (none)
37 Larkin Street
37 (none)
35 Houston Street
35 (none)
35 (none)
35 (none)
35 (none)
35 (none)
34 (none)
34 (none)
33 (none)
33 Aztec Street
33 (none)
33 (none)
32 (none)
32 (none)
32 (none)
31 (none)
31 (none)
31 (none)
31 Glendale Street
31 (none)
31 (none)
30 (none)
30 (none)
30 (none)
30 Bessie Street
29 (none)
29 (none)
29 (none)
29 (none)
28 (none)
28 (none)
28 Bronte Street
28 (none)
28 (none)
27 (none)
27 (none)
27 (none)
27 (none)
27 (none)
27 (none)
27 (none)
26 (none)
26 Forest Hill Path
25 (none)
25 (none)
25 20th Street
25 (none)
24 (none)
24 (none)
24 (none)
24 (none)
24 (none)
24 (none)
24 (none)
23 (none)
23 Gilroy Street
23 Steps to the soutbound Caltrain platform
23 (none)
23 Havens Street
22 (none)
22 (none)
22 Franconia Street
22 (none)
22 (none)
21 (none)
21 (none)
21 (none)
21 (none)
21 (none)
21 (none)
21 (none)
21 (none)
21 (none)
21 (none)
21 (none)
20 (none)
20 (none)
20 (none)
20 Kingston Street
20 (none)
20 (none)
20 (none)
20 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 (none)
19 Tuscany Alley
18 (none)
18 (none)
18 (none)
18 (none)
18 (none)
18 (none)
17 Codman Place
17 (none)
17 (none)
17 (none)
17 (none)
17 (none)
17 De Forest Way
17 Filbert Steps
17 (none)
16 Moraga Street
16 (none)
16 (none)
16 (none)
16 (none)
16 (none)
16 (none)
16 (none)
16 (none)
15 (none)
15 (none)
15 (none)
15 (none)
15 (none)
15 (none)
14 (none)
14 (none)
14 (none)
14 (none)
14 (none)
14 (none)
14 (none)
14 (none)
14 (none)
14 (none)
14 (none)
13 (none)
13 (none)
13 (none)
13 El Camino del Mar
13 (none)
13 (none)
13 (none)
12 (none)
12 (none)
12 (none)
12 (none)
12 Franconia Street
12 (none)
12 (none)
12 (none)
11 (none)
11 (none)
10 (none)
10 (none)
10 (none)
10 (none)
10 (none)
10 (none)
10 (none)
9 Broadway Street
9 (none)
9 (none)
9 (none)
9 (none)
9 (none)
9 (none)
8 (none)
8 (none)
8 (none)
8 (none)
8 (none)
8 (none)
8 (none)
8 (none)
7 Jack Micheline Place
7 (none)
7 (none)
6 (none)
6 (none)
6 (none)
6 (none)
6 (none)
5 (none)
5 (none)
4 (none)
4 (none)
4 (none)
4 (none)
4 (none)
3 (none)
3 (none)
3 (none)

Location tracking

There’s a bunch of location tracking apps now, all of which basically collect where you are all the time in a casual way. The key thing is that they only sample location occasionally, to save battery life.

I did a 15 minute drive in San Francisco today, then a 40 minute walk home. About 2.5 miles each way. I was running four of these tracking apps at once on my iPhone, to compare how much data they logged.

  • Google Latitude: 12 points
  • Geoloqi (Battery saver mode): 4 points
  • OpenPaths: 6 points
They all sampled roughly the same amount of data, although the extra resolution from Latitude makes a big difference in the final picture. None of them captured any points at all when I was driving. I’d hoped these apps would realize I was moving quickly and start sampling more frequently but, well, no.
I wonder if there’s a direct correlation between sampling rate and battery consumption. Google Latitude does use more battery than Geoloqi, but I’m not sure how much more. Haven’t really tried OpenPaths yet.
Here’s screenshots of the maps each tracker generated, along with a detailed track from iSmoothRun.

The steps of San Francisco

I was curious about what ways in OpenStreetMap were defined as Steps, so I did some basic queries and maps and reports. The query’s overly broad, I need to learn how to intersect that with the actual city of SF.

select
  name, round(ST_Length(way)) as meters, osm_id
from planet_osm_line
where highway = 'steps'
order by meters desc;
meters name
290
280
273
271 Dipsea Trail
260 Arbon Path
245 Sand Ladder
239
226 Wildcat Path
222
213 Chaumont Path
206
201 Fred Herbert Path
198 Lyon Street
195 Lulu Alley
193 Oakhurst Lane
193 Belap Path
191 Vulcan Steps
190
185 El Paseo Path
180 Locarno Path
171
169 Pemberton Place
166 Dipsea Stairs
158 Onique Lane
154 Filbert Steps
154
153 Opal Street
151 Prospect Steps
148
147 Harry Street
146 Poppy Path
141
138
136 Blairwood Lane
135 Sterling Path
134 Covert Path
134 Yosemite Steps
133 Shasta Path
130
129 Quintara Street
129
129 Glendale Path
129 Erba Path
128 El Monte Lane
126 Upper Alcatraz Place
126
125 Cleveland Cascade
125 Orchard Lane
125 Tamalpais Path
125 Ortega Way
124 Path Street
123 Post Street
123
122 Mount Lane
122
121 The Footway
120 Northgate Path
118 South Crossways
118 Greenwich Street Stairs
117 Hawkins Lane
117 Bootlegger’s Steps
116 Stevenson Path
116
115 Ridgeview Path
114 Poplar Path
114
114 Claremont Steps
114 Terrace Walk
114
113 Flibert Steps
113 Rotundo Path
112 Easter Way
111 Visalia Walk
111 Covert Path
111
110 Peter Macchiarini Steps
110 Peter Macchiarini Steps
110
109
109 Stolte Grove
109
109
108 Aerial Way
107 Cascade Walk
106
106
104
104 Bret Harte Path
104 Joy Street
103
102 Moraga St. Steps
102 Redwood Terrace
102 Vallejo Street
102 8th Avenue
102 Linda Vista Steps Street
102
101
101 Coralino Lane
101 Mandalay Lane
101 Stevenson Path
99 Altas Path
99 Avoca Alley
99 Athens Street
97
97
96
96
96 Aerial Way
96 Dipsea Steps
96 Path #9
96 Pacheco Street
95 Glenhaven Lane
95 Farnsworth Lane
94 Oriole Way
94
93
93
93
93
92 Esmeralda Avenue
91 Vincente Walk
91
91 Andeer Path
91 Whitaker Path
91
89
89
89
87 Brookside Lane
87
87
87 Saturn Street Stairs
86
86 Acacia Steps
85 Bancroft Steps
85 The Agave Trail
85 Martinez Path
84
84 Maryland Walk
83 Acme Alley
83 Waller Street
83
81
80
80 Yosemite Steps
80 Stairs
80 Wilson Walk
80
80 Amatista Lane
80 Onique Lane
79
79 Vallejo Street Stairway
79 Ward Street
79 North Path
78 Coastal Trail
77 Cedar Street Path
77 Anne Brower Path
77 Arollo/Arolla Path
77
77 Sunglow Lane
77 Blairwood Lane
76
76
76 Monument Way
76 Fair Avenue
75 Rock Walk
74 Macondray Lane
74
74
74 Esmeralda Avenue
73 Esmeralda Avenue
73
73 Greenwich Street Stairs
73 Hillview Court
73
72
72
72 Griffith Street
72
72 Eugenia Avenue
71
71
68 Iron Alley
68
68
68
68
68
67 Terrace Walk
67 Greenwich Street
67 Vista Lane
67
67 Hill Court Steps
67
66 27th Street
66 Naglee Avenue
65
65
65
65 Beeman Lane
65
64 Verona Path
64
63
63
63 Sunbeam Lane
62
62
61 Prospect Avenue
61
61 Liberty Street
60
60 Stoddard Path
60
60
60 3rd Avenue
59
58
58
58
58 Acme Alley
58
56
56
56
56
55 Bret Harte Lane
55
55 Le Roy Steps
55
54
54 Andover Street
54 Verona Path
53 Orchard Lane
53 Harrison Street
53
53
53
53
53 Boynton Walk
53
53
52 Path #6
52
52
51 Opalo Lane
51
51 Saint Mary’s Avenue
51 Oneida Avenue
50
50 Reno Place
50
50
50
49 Douglass Street
49
49
49 Mono Street
49 Chestnut Street Steps
49
48
48 Muir Path
48
47 Clifford Terrace Stairway
47 Greenwich Street Stairs
47 Billie Jean Walk
47
47
46
46 Arden Steps
46
46
46
45 Gondo Path
45
45 Kenny Alley
45 20th Street
45
44 Lagunitas Avenue
44 Rose Steps
44 20th Street
44 Orchard Lane
44 Levant Street Stairway
44 Fair Avenue
43
43
42
42 Excelsior Lane
42
42 Corbin Place
41
41
41
41
41
40
40 Plank Trail
40 Florida Walk
39
39
39
38
38
38 Duncan Street
38
38
38
37
37 Larkin Street
37 Priest Street
37
37
37
37
37
36 Coastal Trail
36
36
36
36 Path #9
35
35
35
35
35
35
35 Cowboy Rock Trail
35 Houston Street
35
35
35
34
34
34
34
33
33 La Vareda Steps
33
33
33
33
33 Latham Walk
33
33
33
33 Aztec Street
33
32 Fred Herbert Path
32
32
32
32
32
32
32
32
31
31 Glendale Street
31
31
31
31 Crescent Park Path
31 South Street
31
31
31
31 Indian Rock Path
30
30
30
30
30
30 Quail Lane
30 Bessie Street
30
30
30
30
29
29
29 Billie Jean Walk
29
29
29 The Steps
29
29
29 Tamalpais Path
28
28
28
28
28 Bronte Street
28
28
27
27
27 Glendale Path
27
27
27
27 Hawthorne Steps
27
27
27
27
27
27
26
26 Forest Hill Path
26
25
25
25 Fountain Walk
25
25
25
25 20th Street
25
24
24
24
24
24
24
24
24
24
24
24
24
24
23 Boynton Walk
23 Gilroy Street
23 Steps to the soutbound Caltrain platform
23
23
23
23 Havens Street
23
23
22
22 Palmer Avenue
22
22
22
22
22
22 Franconia Street
22
22
21
21
21
21
21
21
21
21
21
21
21
21
21
20
20
20
20
20
20
20
20
20
20
20 Kingston Street
20
20 Bootlegger’s Steps
19
19
19
19
19
19
19
19
19
19
19
19
19
19 Santa Barbara Path
19
19
19
19
19
19
19
19
19
19
19 Tuscany Alley
19
19
19
19
18
18 Path #6
18
18
18
18
18
18
18
18
18 Path #3
18
18 Glen Rose Alley
18
18
18
17
17
17 La Loma Steps
17 Filbert Steps
17
17
17
17
17 De Forest Way
17 Path #6
17
17 Glendale Path
17 Hawthorne Steps
17
17
17
17 Ardmore Path
17
17 Codman Place
16
16
16
16
16
16 Moraga Street
16
16
16
16
16
16 La Loma Steps
16
16
16
16
15
15
15
15
15
15
15
15
15
15
15
15
15
15
15 Path #4
15
15
14
14
14
14
14
14 Stratford Path
14
14
14
14
14
14 Rose Walk
14
14
14
14
14
13
13
13
13 Short Cut
13
13
13
13 West Lane
13 Indian Rock Path
13
13
13
13
13
13 El Camino del Mar
13
13
13
13
12
12
12
12
12
12
12
12
12
12
12
12
12
12
12 Franconia Street
12
12
11
11
11
11
11
10
10
10
10
10
10
10
10
10
10 Glendale Path
10 Glendale Path
10
10
10
10
10
10
10
10
10
9
9
9
9
9 Broadway Street
9
9
9
9
9
9 Arden Path
9
9
9
9
8
8 Mosswood Lane
8
8
8
8
8
8
8
8
8
8
8
8
8
7
7
7
7
7
7
7
7 Jack Micheline Place
7
7 Stolte Grove
6
6
6
6
6
6
6
5 West Lane
5
5
5
4
4
4
4
4
4
3
3
3
3

OSM “interesting” columns

To better understand the OSM schema, I did a bunch of queries to find out which columns in which tables actually contained meaningful data. Kind of like the query about highway types I did, but for every single column. Then I went through by hand and copied out the “interesting” columns, ones that seemed to have a lot of data.

Here’s a big list by table, then column, then  the distribution of the values in that column. SF Metro only. One thing that’s clear; even in SF the data’s not complete enough to be an unbiased sample. For instance you can’t tell from OSM how many Jewish synagogues there are vs. how many Christian churches, the data’s just not complete enough.

Table planet_osm_line has 62256 rows

aeroway
99% 62093 None
 0% 143 taxiway
 0% 16 runway
 0% 3 apron

bridge
96% 60376 None
 3% 1872 yes

foot
96% 60024 None
 3% 2060 yes
 0% 117 permissive

highway
46% 29165 residential
14% 8897 service
10% 6307 None
 8% 5252 footway
 3% 1870 motorway_link
 2% 1841 tertiary
 2% 1765 secondary
 1% 1150 motorway
 1% 1113 unclassified
 1% 1063 path

man_made
98% 61560 None
 0% 618 pier
 0% 62 pipeline
 0% 12 breakwater

oneway
85% 52927 None
14% 9163 yes
 0% 74 no

railway
97% 60397 None
 1% 787 rail
 0% 322 tram
 0% 314 subway
 0% 166 spur
 0% 79 platform
 0% 68 disused
 0% 58 abandoned
 0% 42 light_rail
 0% 19 monorail

route
98% 61516 None
 0% 420 bicycle
 0% 122 road
 0% 73 subway
 0% 39 tram
 0% 29 scenic
 0% 23 bus
 0% 18 ferry
 0% 8 hiking
 0% 4 railway

service
91% 56958 None
 5% 3588 parking_aisle
 1% 956 driveway
 0% 321 spur
 0% 191 alley
 0% 121 siding

tunnel
99% 62024 None
 0% 227 yes

waterway
97% 60497 None
 2% 1317 stream
 0% 345 canal
 0% 74 drain
 0% 12 river
 0% 7 dam
Table planet_osm_polygon has 39872 rows

aeroway
99% 39841 None
 0% 17 apron
 0% 9 terminal
 0% 3 aerodrome
 0% 1 serodrome
 0% 1 boundary

amenity
92% 36797 None
 5% 2098 parking
 1% 416 school
 0% 81 restaurant
 0% 71 place_of_worship
 0% 51 fast_food
 0% 30 library
 0% 27 hospital
 0% 25 bank
 0% 19 toilets

building
60% 24237 yes
19% 7585 None
12% 5165 residential
 5% 2196 house
 0% 228 school
 0% 106 tank
 0% 55 apartments
 0% 54 retail
 0% 35 garages
 0% 34 terrace

leisure
94% 37581 None
 2% 875 pitch
 2% 847 park
 0% 177 playground
 0% 113 common
 0% 71 swimming_pool
 0% 47 golf_course
 0% 47 garden
 0% 31 sports_centre
 0% 24 track
Table planet_osm_point has 30916 rows

aeroway
99% 30763 None
 0% 107 gate
 0% 36 helipad
 0% 8 aerodrome
 0% 1 seaplane_base
 0% 1 checkin

amenity
73% 22602 None
 3% 1225 restaurant
 3% 997 place_of_worship
 3% 945 school
 2% 687 fire_hydrant
 1% 500 post_box
 1% 421 cafe
 0% 266 fast_food
 0% 263 bench
 0% 256 parking

highway
68% 21209 None
13% 4047 turning_circle
 5% 1850 traffic_signals
 4% 1534 crossing
 3% 979 bus_stop
 2% 903 stop
 0% 189 motorway_junction
 0% 184 mini_roundabout

leisure
97% 30131 None
 1% 524 park
 0% 151 playground
 0% 27 sports_centre
 0% 13 garden
 0% 10 slipway
 0% 9 designated smoking area
 0% 8 common
 0% 8 swimming_pool
 0% 8 picnic_table

man_made
99% 30620 None
 0% 100 water_tower
 0% 85 tower
 0% 30 crane
 0% 22 pier
 0% 12 monitoring_station
 0% 10 water_tank
 0% 6 mine
 0% 5 survey_point
 0% 4 lighthouse

natural
99% 30718 None
 0% 86 peak
 0% 44 bay
 0% 28 beach
 0% 18 tree
 0% 8 wood
 0% 7 spring
 0% 4 wetland
 0% 2 cave_entrance
 0% 1 cliff

power
93% 28782 None
 6% 2038 tower
 0% 90 pole
 0% 3 sub_station
 0% 2 station
 0% 1 generator

railway
97% 30282 None
 0% 260 level_crossing
 0% 168 tram_stop
 0% 63 subway_entrance
 0% 60 station
 0% 54 switch
 0% 21 crossing
 0% 4 turntable
 0% 3 buffer_stop
 0% 1 stop

religion
96% 29948 None
 3% 937 christian
 0% 14 jewish
 0% 12 buddhist
 0% 3 muslim
 0% 1 unitarian
 0% 1 scientologist

OSM unclassified lines, etc

I had a little todo item today, “Edit OpenStreetMap”. Thought it’d be fun to try out the editor. After 10 minutes I declare failure with Potlatch; the Flash app on the main server is so terribly slow as to be unusable. I need to read the Beginner’s Guide and other editing options.

After a bit of patience, Potlatch loaded usefully. I ended up editing the map to put a name on the tiny little Duncan-Castro park. I hope I did this right, the UI for adding a name to a park is not clear. I ended up using the Advanced view to add a name=Duncan-Castro field to the list for the way.

My big plan was to edit one of the 6000+ entries in the SF Metro extract that have no “highway” tagged on them. Turns out that’s not necessary; they tend to be other features, like creeks or county boundaries or stuff. D’oh.

I did find one entry for an uncategorized “Center Street” in SF, osm_id 8489931. But there’s so many other overlapping “Center Streets” in the database I think the fact this one is untagged is not a problem.

select
  name,
  ST_Length(ST_Transform(way, 2163))/1609 as miles
from planet_osm_line
where
  highway is null
order by miles desc;

"Golden Gate National Recreation Area";50.114480677903
"";50.1127120036684
"San Francisco";50.1127120036684
"San Mateo County";49.8960294825062
"";49.6164354346274
"Alameda County";49.5445744035326
"";49.3526266530211
"San Francisco County";49.3158064558191
"";49.2591797769354
"";49.2302041734416
"";49.2049183432214
"";49.1809376585467
"";49.0948344172935

Playing with OSM data, in TileMill

I revisted my earlier OSM experiment only using TileMill instead of QuantumGIS to make the map. TileMill has much nicer output, particularly if you want to ship a set of slippy map tiles or frame out specific high quality images / prints. It’s also more of a textual programming kind of paradigm, which I like better. OTOH TileMill also has very specific limits on what it’s capable of doing; it’s not a generic GIS toolset.

It was pretty easy; the hardest part was remembering the weird way to filter a table with select in TileMill; their PostGIS support is a bit idiosyncratic. Also it guessed wrong on the SRS for my tracks; they’re in WGS84 but it was trying to draw them as if they were in Google Mercator, way out of scale. That seems like a bug.

Anyway, I remade my map of my walks around SF, here’s an image and some code.

        "table": "(select * from planet_osm_polygon\n where leisure = 'park'\n  and geometrytype(\"way\") in ('POLYGON', 'MULTIPOLYGON')\n) as parks",
        "table": "(select * from planet_osm_line\n where \"railway\" is null\n) as road",

@road: #444444;
@border: #222222;
@park: rgb(196, 243, 170);
@water: #b8dee6;
@bg: #ffffff;
@track: rgb(237,101,22);

Map { background-color: @water; }

#sanfrancisco {
  polygon-opacity:1;
  polygon-fill:@bg;
  line-width: 2;
  line-color: @border;
}

#tracks {
  line-color: @track;
  line-width: 3.0;
}
#road {
  line-color: @road;
  [highway='motorway'] { line-width: 3.0; }
  [highway='motorway_link'] { line-width: 2.0; }
  [highway='footway'] { line-width: 0.7; line-color: lighten(@road, 20%); }
}
#parks {
  line-color: @border;
  line-width: 1.0;
  polygon-opacity: 1;
  polygon-fill: @park;
}

OpenStreetMap schema griping

OpenStreetMap is all kinds of awesome, but boy the data schema is a mess. planet_osm_roads doesn’t really contain all the roads, you want planet_osm_line. (Yes, one name is singular, one is plural). planet_osm_line sure contains a lot of lines, what are they all? The “highway” column tells you. here’s the most popular types of “highway” in the San Francisco metro extract.

select
  count(*) as cnt, highway
from planet_osm_line
group by highway
order by cnt desc;

  cnt  |        highway        
-------+-----------------------
 29165 | residential
  8897 | service
  6307 | 
  5252 | footway
  1870 | motorway_link
  1841 | tertiary
  1765 | secondary
  1150 | motorway
  1113 | unclassified
  1063 | path
   959 | track
   890 | primary
   712 | steps
   594 | cycleway
   191 | trunk
   150 | primary_link
   116 | pedestrian
    65 | trunk_link
    44 | construction
    39 | road
    35 | secondary_link
    24 | tertiary_link
     3 | footway_unconstructed
     2 | raceway
     2 | proposed
     2 | bridleway
     1 | service; residential
     1 | platform
     1 | crossing
     1 | living_street
     1 | abandoned
(31 rows)

It’s not terrible; things that are correctly classified really are. But “all roads” requires identifying several classes, there’s some ambiguity, and some stuff clearly doesn’t belong there. Still the data exists and is free, so I shouldn’t complain too much!

(Migurski’s High Road is a set of SQL views that present a cleaner schema of roads. But just roads, nothing else.)

Playing with OSM data

I’m playing with OpenStreetMap data in PostGIS, drawing maps in QGIS. No serious cartography, mind you, just trying to get a feel for the data. I’m starting with Mike Migurski’s metro extracts, the .osm.bz2 file for San Francisco

Import that into PostGIS, which gives this schema which describes these map features.

osm2pgsql -d walks --style /usr/share/osm2pgsql/default.style san-francisco.osm.bz2

For the SF metro, there’s 8000 roads, 40,000 polygons, 31,000 points, and 62,000 lines. You can import all these tables directly from pgsql into QGIS and render them for a basic view. The lines contain the street grid; roads contains just the larger highways, etc.

QGIS makes it easy to explore the tables. When you add a new PostGIS layer and choose a table, you can then choose specific fields and sample their values. Exploring around you can find that “leisure=park” is an interesting subset of polygons, for instance.

Roads are terribly complicated, so to simplify I tried using Migurski’s High Road. It creates custom views with names like “planet_osm_line_z14” where just roads relevant at that zoom level are present. Also some fancy stuff to make drawing casings vs. road surfaces easier. z15plus is the big set of all roads (170,000); _big is 24000 roads and _small is the other 144,000 lines (footpaths and such). Unfortunately QGIS can’t use the High Road views; details in this issue I filed.

I was able to use the High Road code as a guide for categorizing road by size, though. The “highway” field is the key one. It’s a messy schema, there’s about 7 synonyms for “street”.

Here’s a map of the walks I’ve taken in my neighborhood, with streets and parks.

 

Scraping GPX files out of RunKeeper into Postgres and QGIS

I’ve been using RunKeeper to track my walking. I wanted to work with the 40+ GPS tracks they’ve logged for me and didn’t want to download them one at a time. Some quick notes on how to scrape them all out.

  1. Log into the website in your browser and go to your Activities page. It has a URL like http://runkeeper.com/user/USERNAME/activity/70000177
  2. Save that big HTML page to a file named activities.html
  3. Capture the IDs of all your activities from that page with a regexp like this:
    printMatches  ‘link=”/user/USERNAME/activity/([0-9]+)’< activities.html > ids
  4. You can now download a GPX for that ID with a URL like http://runkeeper.com/download/activity?activityId=70000177&downloadType=gpx. However, the download requires a URL, at least if your activities are private.
  5. Look in your browser for your JSESSIONID cookie. That’ll stand in for a login.
  6. Use wget with that cookie. Here’s my little shell script to get them all
cat ids | while read id; do
  wget --no-cookies \
       --header 'Cookie: JSESSIONID=C~2BF2D2156284732CE8D8BDA900000000' \
       -O $id.gpx \
       "http://runkeeper.com/download/activity?activityId="$id"&downloadType=gpx";
done

Set up a PostGIS database with all the data

  1. createdb walks
  2. psql -d walks -f postgis.sql
  3. psql -d walks -f spatial_ref_sys.sql
  4. psql -d walks -f postgis_comments.sql
  5. for f in *gpx; do echo $f; ogr2ogr -append -f “PostgreSQL” PG:dbname=walks $f; done

ogr2ogr will create a fancy schema for you that contains every field ever seen in a GPX file. For RunKeeper data, the salient things are:

  • tracks.wkb_geometry: one row per track, multiline string
  • track_points: one row per point with a point, elevation, timestamp, etc.

QGIS did a fine job rendering the tracks table for me. I also pulled in a raster OSM map for a base layer from http://wms.latlon.org/.

Here’s a quicky query to get the length of a track in miles. Need to understand the ST_Transform better, also join to something else to get proper data about each imported track.

select name, ST_Length(ST_Transform(wkb_geometry, 2163)) /1609 as miles from tracks order by name;

A quicky view to simplify the tracks a bit, plus a query that compares the length of the original and simplified views.

create or replace view simple as
select
 ogc_fid,
 ST_Simplify(wkb_geometry,0.00005) as track,
 name
from tracks;

select
  tracks.name,
  ST_Length(ST_Transform(simple.track, 2163)) /1609 as miles,
  ST_Length(ST_Transform(tracks.wkb_geometry, 2163)) /1609 as miles
from simple inner join tracks
on simple.name = tracks.name order by name;

Multimarkdown reference

I’ve finally got an editing tool that does enough with Markdown to be useful: Notational Velocity. No WYSIWYG, but the live preview is pretty great. Shockingly there’s no really concise quick reference to all of Multimarkdown; it’s full of ugly complex stuff. The Human Markdown Reference is pretty good, but I made my own.

# Header 1
## Header 2
### Header 3

Text can be _italics_ or **bold** or `fixed width`.

> This is a blockquote.

*  lists are
*  implicitly formed

We can make [basic links](http://www.somebits.com). You can also do this [Stupid link style][1].

[1]: http://www.google.com/

    code samples come
    by indenting four spaces
    
| Features | Advanced? |
- | -
Tables | Yes
Paragraphs | No

----

Multi-markdown link: <http://fletcherpenney.net/multimarkdown>

Header 1

Header 2

Header 3

Text can be italics or bold or fixed width.

This is a blockquote.

  • lists are
  • implicitly formed

We can make basic links. You can also do this Stupid link style.

code samples come
by indenting four spaces
Features Advanced?
Tables Yes
Paragraphs No

Multi-markdown link: http://fletcherpenney.net/multimarkdown

GeekTools to show iTunes current song

I wanted to display the current song playing on my desktop using GeekTools. I found some info on accomplishing this with AppleScript here. Pretty straightforward, but their script is clever in that I think it only runs if iTunes is running. I modified the script a bit, here’s what I have:

tell application "System Events"
	set powerCheck to ((application processes whose (name is equal to "iTunes")) count)
	if powerCheck = 0 then
		return ""
	end if
end tell
tell application "iTunes"
	try
		set playerstate to (get player state)
	end try
	if playerstate = stopped then
		return "Stopped"
	end if
	set trackID to the current track
	set trackName to the name of trackID
	set artistName to the artist of trackID
	set albumName to the album of trackID
	set totalData to artistName & "
" & albumName & "
" & trackName
	return totalData
end tell

Coffee

All the Internet sources I read say coffee is best brewed at 195F – 205F. This fancy new Keurig cup brewer I got maxes out at 192F, the “optimal temperature” according to them. Most home drip makers struggle to get to 190F.

Adding album art to Thinner’s MP3

The Thinner netlabel included JPG images for all their albums but didn’t embed them in the MP3 files. Consequently iTunes can’t find them. Dealing with id3 is a bit of a black art, the tools and formats are varied and poorly documented. But I think this works and is safe:

eyeD3 --to-v2.3 --add-image thn018.jpg:FRONT_COVER *.mp3

That adds thn018jpg as a front cover to all MP3s in the current directory. The converstion to 2.3 is necessary; eyeD3 can read but not write the 2.2 tags that are in the early Thinner releases. Note that this will add a second image if one already exists. Only safe to run once :-P

Getting clever:

#!/bin/bash
for d in thn*; do
 JPG=$d/$d.jpg
 if [ ! -f "$JPG" ]; then
 echo "$JPG not found, skipping directory"
 continue
 fi

eyeD3 --to-v2.3 --add-image $JPG:FRONT_COVER $d/*.mp3 > /dev/null
done

Sad fact: iTunes won’t display GIFs, only JPGs.

MacOS top: “stuck” means “uninterruptible”

MacOS’ version of “top” reports a weird process state; “stuck”. According to top many of my processes are “stuck” including Postgres while it’s completing a table scan, and Growl, and many Google Chrome subprocesses. But checking the top sources indicates “Stuck” really means TH_STATE_UNINTERRUPTIBLE, which I believe is what ps reports as process state “U”. I’m guessing this is what Linux calls “D” for “Device Wait”. In which case, in most cases the process is fine, it’s waiting for some I/O to complete.

While I’m here, is there any good reason MacOS top defaults to sorting by process ID? I have to type “ocpu” every time to get it to sort by cpu.

 

Trying to recover a Postgres database

When my old server died I had some data in Postgres. I don’t think it was anything important but I can’t really be sure, I’d like to recover it. All I have are the binary files Postgres stores its data in. Turns out recovering from those sucks. Lesson learned: if you care about recovering your data, back it up into a SQL dump.

Postgres makes no effort to make its binary files compatible between versions. A 9.0 database can’t be used in a 9.1 install; when you upgrade, you have to run a funky recovery tool which dumps the 9.0 db and imports it to 9.1. A 9.0 database on a 32 bit machine can’t be imported into 9.0 built for a 64 bit machine, either. I’ve also seen problems in the past trying to work with data from a PostGIS database in a non-PostGIS install. I’m sure this format flexibility makes it easier to build a fast database engine, but it sure makes data recovery difficult.

I tried building 9.0 sources on my amd64 box and running it. That was easy enough, although setting up users and permissions is a bit finicky when installing by hand. But the DB was generated on an i386 box (32 bit) so it won’t load. At least it failed quickly, “FATAL:  incorrect checksum in control file”. Then I started looking in to cross-compiling and realized the last thing I want is to set up a whole separate build toolchain. (A quick try with the linux32 command didn’t work.)

So screw it, what was I really storing in Postgres anyway? Not much, I did a quick test to see:

find . -type f -name \*py | xargs egrep -i ‘psycopg2|postgres’

Only one Python program I wrote even imports the Postgres driver. And I can recover that data from original sources. I think I have some geodata I imported with shp2pgsql, too, but I can redo all that. So I give up on recovering data.

Cross-compiling

Maybe I gave up too fast. Building a 32 bit version of Postgres on Ubuntu was as easy as

./configure CC=’gcc -m32′ --prefix=/tmp/pgsql90i386  --without-readline --without-libz

(there’s probably 32 bit versions of readline and libz, but I don’t really need them). Building a server this way, my amd64 machine can load the database binaries generated on the i386 machine. I had no idea the 64 bit Linux distributions could build 32 bit code so easily.

And it works! “psql -l” to find what databases were there, then “pg_dump database” to get the data out, then “psql” to get the data back into my 9.1 database. Yay!

Backups

Lesson learned, I’m now doing some simple nightly SQL backups of my databases. There are fancy ways to do this, I’m going very simple:

DEST=/mnt/sdb1/BACKUPS/postgres

set -eu
renice 10 $$ > /dev/null

pg_dumpall --lock-wait-timeout=$[5*60*1000] | gzip -9 >| $DEST/dumpall-sql.gz

 

secure remote backups with rsnapshot

I’m trying to back up my machine in a datacenter to my home server, using rsnapshot. The home machine is behind a firewall and pretty secure but I don’t want to be stupid about it. The remote machine should be secure, but is not firewalled. (OTOH both run ssh and http, so the attack surface is about the same). I found two useful guides for doing remote backups securely: one, two.

My final config is a pastiche of the two. Here’s the concept behind what I did. Backups run as root on the backup server and as a special-purpose user on the client being backed up (who can sudo to root to run rsync).

  • On the backup server, tell rsnapshot to backup a remote host via rsync.
  • On the backup client, create a new user who has no special privileges
  • Set up ssh keys (with no passphrase) so that root on the backup server can login as the backup user on the client. Restrict that ssh key to only be allowed to run an rsync frontend.
  • On the client, give the backup user the right to sudo to root but only to run /usr/bin/rsync.

I feel pretty good about the security; the user would have to steal my private key from the backup server to access the client, and even then they’re only restricted to run rsync. However that rsync is run as root and I’m sure could pretty easily escalate by, say, overwriting /etc/sudoers.

It’d be more secure to run backups on the remote client as some user other than root. But I want to back up files only root can read, so I’m kind of stuck.

 

Sonos id3v2 tags

Over on the Sonos forums I asked about which ID3v2 tags the Sonos uses. I got a great reply that seems to be correct, reproducing it here. It’s from Rick Parsons aka “renowden”.

TIT2 [Title/songname/content description] - commonly called Track

On the Sonos this is called “Track” and is available in an index and on the controller screen when the track is playing.

TPE2 [Band/orchestra/accompaniment] - commonly called Album Artist

On the Sonos this is called “Artist” as an index but does not appear on the display at all when a track is playing.

TPE1 [Lead performers(s)/soloist(s)] - commonly called Artist.

On the Sonos this is called “Contributing Artist” as an index. It shown on the display as “Artist” when a track is playing. In theory multiple artists can be put in this field (separated by a “/” but some tag editors show it as a “;”). In practice the Sonos sometimes shows only the last one on the list. I haven’t been able to determine why.

TALB [Album/movie/show title] - commonly called Album

On the Sonos this is used as an index. It also shows on the display when a track is playing.

TRCK [Track number/position in set]

This is not displayed anywhere but is used to determine the track order in albums.

TCOM [Composer(s)]

This is used as an index but does not show on the display during playback.

TCON [Content type] - commonly called Genre.

This is used as an index but does not show on the display during playback.

COMM [Comments] {iTunNORM}

This is written by iTunes and is discussed at length elsewhere. In summary it can, in the right conditions, be used to level the volume of playback.

There is another tag written by Windows media Player which performs a similar function to iTunNORM but I haven’t discovered what it is.

Canonical music genres

Still wrangling the metadata on my music library. ReadyToPlay did a good job on the rip and categorized all music into a relatively small set of Genres. I’m taking this as canonical for now.

Avant-Garde • Ballet • Blues • Chamber Music • Choral • Christmas • Comedy\Spoken • Concerto • Country • Electronica • Folk • Jazz • Keyboard • Latin • New Age • Opera • Orchestral • R&B • Rap • Reggae • Rock • Soundtrack • Spoken Word • Symphonic • Vocal Music • World

Well, not entirely canonical; I’ll probably unify a couple of these. Also the classical feels wrong to me: I couldn’t tell you Orchestral from Symphonic. I’d prefer to break it down by Musical era: Early, Baroque, Classical, Romantic, Modern. Of course those are ambiguous too.

One thing that’s really annoying in my metadata; music is indexed by the composer’s first name. So Tchaikovsky is filed under “P”, for “Pyotr Il’yich Tchaikovsky”. It’s a bit of a trivia game.

 

Metadata for .m4a apple lossless (ALAC) files

My new music library is all nicely ripped Apple Lossless files in .m4a containers. These contain metadata, but it’s not id3v2 and the universe of mp3 tools mostly don’t work. ffmpeg’s ffprobe sort of works but doesn’t show all tags.

What does work for displaying m4a metadta is mp4v2, installable via Homebrew. Docs here. It seems pretty stable but still gets some updates.

(imac) = mp4file --list test.m4a
BRAND  COMPAT              SIZING  FILE
----------------------------------------------------------------------
M4A    M4A,isom,mp42       32-bit  test.m4a

(imac) = mp4info test.m4a
mp4info version 1.9.1
test.m4a:
Track	Type	Info
1	audio	alac, 260.806 secs, 562 kbps, 44100 Hz
 Name: Pastourelle (E passo de dossai: Ah! viens pres de moi), folksong for voice & orchestra (Chants d'Auvergne, Series 2, No. 1)
 Artist: Dawn Upshaw
 Composer: Joseph Canteloube
 Release Date: 1994
 Album: Canteloube: Songs of the Auvergne
 Track: 1 of 15
 Disk: 1 of 1
 Genre: Vocal Music
 BPM: 0
 Part of Compilation: no
 Cover Art pieces: 1
 Album Artist: Kent Nagano
 Media Type: Movie
 TV Episode: 0
 TV Season: 0

(imac) = mp4track --list test.m4a
track[0] id=1
  type           = audio
  enabled        = true
  inMovie        = true
  inPreview      = true
  layer          = 0
  alternateGroup = 0
  volume         = 1.0000
  width          = 0.00000000
  height         = 0.00000000
  language       = UNDEFINED(0)
  handlerName    =
  userDataName   = <absent>

(imac) = mp4art --list test.m4a
IDX     BYTES  CRC32     TYPE       FILE
----------------------------------------------------------------------
  0     11255  299646cd  jpeg       test.m4a

(imac) = mp4tags
mp4tags: You must specify at least one MP4 file.
usage mp4tags OPTION... FILE...
Adds or modifies iTunes-compatible tags on MP4 files.

      -help            Display this help text and exit
      -version         Display version information and exit
  -A, -album       STR  Set the album title
  -a, -artist      STR  Set the artist information
  -b, -tempo       NUM  Set the tempo (beats per minute)
  -c, -comment     STR  Set a general comment
  -C, -copyright   STR  Set the copyright information
  -d, -disk        NUM  Set the disk number
  -D, -disks       NUM  Set the number of disks
  -e, -encodedby   STR  Set the name of the person or company who encoded the file
  -E, -tool        STR  Set the software used for encoding
  -g, -genre       STR  Set the genre name
  -G, -grouping    STR  Set the grouping name
  -H, -hdvideo     NUM  Set the HD flag (1\0)
  -i, -type        STR  Set the Media Type(tvshow, movie, music, ...)
  -I, -cnid        NUM  Set the cnID
  -l, -longdesc    NUM  Set the short description
  -L, -lyrics      NUM  Set the lyrics
  -m, -description STR  Set the short description
  -M, -episode     NUM  Set the episode number
  -n, -season      NUM  Set the season number
  -N, -network     STR  Set the TV network
  -o, -episodeid   STR  Set the TV episode ID
  -P, -picture     PTH  Set the picture as a .png
  -s, -song        STR  Set the song title
  -S  -show        STR  Set the TV show
  -t, -track       NUM  Set the track number
  -T, -tracks      NUM  Set the number of tracks
  -w, -writer      STR  Set the composer information
  -y, -year        NUM  Set the release date
  -R, -albumartist STR  Set the album artist
  -r, -remove      STR  Remove tags by code (e.g. "-r cs"
                        removes the comment and song tags)

Using inline data: URLs for images

Looking at traffic stats and Google’s mod_pagespeed I thought of a way to optimize my blog a bit: replace some of the small images with inline data: URLs. According to Wikipedia this works in all modern web browsers. IE7 is out of luck, but it (kind of) works in IE8.

For example, this Creative Commons logo is a 1082 byte GIF. Small, but there’s a lot of overhead in doing an HTTP request just for that image used in one place on my page. Fetching with wget takes 11 packets and 3 or 4 round trips. (A little better in a real browser with HTTP keepalives).

As a base64 data: URL it’s only 1467 bytes. That adds 1-2 TCP packets to the request and 0-1 round trips. The downside of inlining is that the image is now served with every single HTML page. No caching and bots will have to pay for it too. In the end I think it’s more work for my server, less work for the client, which is a good tradeoff for small images. (It may be less work for the server in general; fewer client requests per page.)

I arbitrarily decided 3k was the cutoff for converting to data URLs. That results in 5 images:

I converted the images via this online encoder. I am too lazy to measure the actual impact the change had, too much trouble. The HTML size of my blog went up 10k (46k vs 36k), but I’m loading 5 fewer HTTP requests (16 vs 20) and not loading about 7k worth of image binaries. I’m optimistic.

Energy usage notes

My electricity bill is just terrible now, $500 / month. Since we moved in we’re using 800-1200 kWh / month, or about 1400W average usage all day every day. We’re both home all day and use computers, so I expect our power usage to be high, but that’s absurd. Where’s it going?

Now that we have a Smart Meter, PG&E has an awesome “My Energy” site where you can see hourly energy usage for your house, per day. Here’s a typical day, Tuesday January 24, 2012. We tend to be awake from 7am to 10pm. (I also have a private graph for the whole month.)

Looking at this, it’s clear turning the lights on in the morning and at night has a big impact. Our house has terrible lighting design, a lot of light wasted in ceiling cans. Also still all incandescent bulbs, although on fancy dimmers that should lower power usage.

What really surprises me is the constant usage of 700W all the time, even when we’re asleep. We turn the lights out at night! And sometimes it’s worse, up to 1000W. Fixing that nighttime usage seems like a good place to start.

Here’s a quick audit of things I know take constant power.

  • 150W Wine cooler (450W when active)
  • 50W Refrigerator (average)
  • 120W My computer (when in use)
  • 200W Ken’s computer (constant)
  • 50W Linux server (constant)
  • 80W A/V rack (when idle)

That’s 650W right there, all the time. We can easily turn off my computer and Ken’s computer, that’d cut about 300W out of the wasteage. My computer already goes down to 30W when idle but I can make that 1W. Ken’s computer is awful; it never goes to low power mode and the monitors constantly wake up in the middle of the night. I don’t know why, it’s a Windows 7 box.

I just unplugged the wine cooler. It’s really not necessary in winter. It’s insane that it runs one third of the time even when it’s cool outside; the manual says something about maintaining humidity. Paying $40 / month to keep my wine at 54F instead of 65F seems stupid. It may be more power than that, btw, the Kill-a-Watt registers 450W but 750VA. The website says it draws 6 amps when running, which is more like 660 kWh/hour, yes?

It’d be nice to shut down the A/V rack. But the Tivo is actively doing something useful, and that’s half the power. The other half is keeping a bunch of Sonos units running at 5W each. Probably not worth the bother to buy a timer or something.

Other ideas

It’d be awfully nice to get the usage data in real time off my meter and not have to wait 2 days for it to show up on the website. The buzzword for this is “Home Area Network” and PG&E, of course, is slow to deploy. No doubt in part because they have to worry about the insane people with imaginary diseases. Anyway, here’s some info on a HAN trial.

It’d be nice to install a solar panel on my roof. SF Solar Map estimates I have 1300 sq ft of space for panels which is good for 5kW. At 4.5 hours of sunlight / day that’s 6324 kWH / year, or about half my electricity usage for the year. A 5kW system costs $32,000, but after incentives the cost to me is $21,000. It’d save me about $2600 / year so I’d break even in roughly 8 years. A 2kW system would cost $7400 and break even in about 7 years. (Cost estimate assume $6.50 / W-dc, which may be optimistic.)

Surround sound formats

Theory

All this TV setup makes me curious; am I getting proper surround sound? I have 5.1 speakers connected to a Denon AVR-2309CI and everything HDMI, is it actually working?

The Denon receiver can decode the following formats via HDMI. I barely know what most of these are, but here’s a useful reference, also wikipedia.

  • 2 channel linear PCM (16, 20, or 24  bit samples, 32-192 kHz), also multi-channel.
  • Dolby Digital (5.1), DD Plus (7.1), Dolby TrueHD (7.1 high quality). Also known as AC3.
  • DTS (5.1) and DTS-HD (7.1)

When playing back a 2 channel audio source, my Denon supports a bunch of playback modes to fake out surround sound (“matrixed”). I believe the sound has to have been mixed this way for this to actually work.

  • Dolby Pro Logic II (fake 5ch) and IIx (fake 7.1)
  • DTS Neo:6 (fake 6.1) and “Neural” (XM HD Surround)

Looking at the random video files I have on my hard drive, most have audio in MP3 2.0 or AAC 2.0. One is DTS 5.1 and a couple are Dolby Digital 5.1. I don’t think there’s any way to tell if any of those 2.0 files are matrix encoded fake surround, probably not.

Playback

That’s all the theory, what happens in practice?

The good news is my new AppleTV seems to correctly play back 5.1 sources, via both Netflix and PLEX. In particular the receiver seems to autodetect DTS or Dolby Digital and if I stand next to a rear speaker it does sound differentiated. Yay! It may help I told PLEX my receiver can decode AC3 (aka Dolby Digital).

The confusing news is for all these stereo sources I don’t really know what receiver setting is best to use. I have no idea how common this matrixed audio stuff is or whether it’s worth the effort to decode it. I’ve got a button on my remote labelled “Movie Sound” that cycles the various matrix modes but can’t really hear much difference in a quick test.

Testing

After a bit of looking I found a test suite, the charmingly named “AC3 Dolby digital 5 1ch Sound Test”. It’s available around the net in various places, like filestube. (Or watch it in 2.0 on Youtube.)

This file plays back fine via PLEX on my Apple TV. I also played with using Handbrake to encode it in various ways. Sounds great in true Dolby Digital 5.1. Also sounded surprisingly good in matrixed Dolby PLII; the rear channel separation worked well, although the subwoofer was silent. HandBrake also supports a “6-channel discrete” mode which didn’t really work right on my A/V system.

TV remote success

My A/V rack is controlled by a UniversalRemote MX 900 with a Univeral MRF-350 RF Base Station. It’s not going to win any UI awards but when we were shopping for this stuff three years ago this came in as the most capable and flexible system. So sad the A/V guy I hired to set it up, money well spent: he did an excellent job. My whole system is controlled from a single remote that’s not awful to use.

And as of today, now the new Apple TV is, too. I reprogrammed the remote myself. It turned out to be relatively easy..

  1. Get a copy of the programming software MX_900Setup.zip (23,290,684 bytes); the official source requires a password they only give to resellers.
  2. Run it on a windows box and plug the remote in via Mini-USB
  3. Select “Communication / Upload” to get a copy of the current remote configuration from the remote itself.
  4. Save that file away for safekeeping.
  5. Edit. The manual is essential because the paradigm is weird. Most things are driven by the Program menu. Macros are recorded by clicking simulated remote buttons on the emulator. Codes can be imported via a database, and there’s a learning mode I fortunately didn’t have to use.
  6. Download back to remote. Done!

The hardest part turned out to be digging through boxes to find a spare IR emitter on a cable. The IR Blaster in the front of my base station didn’t seem to be enabled, probably to help prevent crosstalk. It’s 2012 and we still use infrared and little cables to control A/V devices, it’s terrible.

 

Linux options for faster disk access

All these new computers have me interested in improving throughput. I’ve suddenly got gigabit ethernet, a huge amount of RAM, fast CPUs with many cores.. What’s missing is fast I/O. The hard drive’s 30 megabyte/second throughput is often a limiting factor for me. What are my options?

  • Put my data on an SSD. Appealing, but I don’t trust consumer SSDs not to fail. Also I hate having multiple disks with different capacity; I can never decide what to put on the SSD, what to put on platters. IE: right now I’m doing a lot of work with 300 gigs of music files and would like that to be fast, but it’d be stupid and expensive to leave those on an SSD forever (at 2012 prices).
  • Use an SSD as a writeback cache for hard drive. Very appealing option, and there’s three options. My Z68 motherboard includes support for Intel Smart Response Technology but sadly there’s no Linux support. There are two Linux projects that do something similar: Flashcache and Bcache. But both seem pretty bleeding edge and require lots of manual setup. The Bcache release notes a few months ago included a comment about “slow silent data corruption” that put me right off.
  • Hardware RAID. This Z68 motherboard has Intel RAID right on the motherboard, perfect! Only it turns out this kind of RAID is what’s known as fakeRAID; the operating system does most of the work. Linux can support fake RAID but if you’re going that route most people suggest just using Linux software RAID. (The advantage of motherboard RAID is the BIOS can help boot your OS).
  • Software RAID. It’s been awhile since I checked in on the state of Linux RAID and sadly, it’s in disarray. Docs on the net are all randomly out of date, talking about 2.6 kernels or 3 year old versions of Ubuntu. I think the systems are pretty stable, being based on md, just poorly documentd. These 9.10 docs are the best I’ve found. The Ubuntu installer will create a RAID array for you or you can go low level with mdadm. Apparently GRUB 2 understands Linux software RAID so you can boot right off the RAID disk.

Of course there are many flavors of RAID. I’m mostly interested in speed, not reliability, so RAID 0 seems like the obvious choice except everyone says that’s nuts because you double your chance of a disk failure destroying everything. Fun!

bash 4.2 $variable expansion bug

bash-4.2 (default on Ubuntu) has a super annoying bug.

d=/usr/bin
ls $d/ssh-keyg[user presses tab]
ls \$d/ssh-key

In a nutshell, bash “helpfully” adds a backslash to escape the dollar sign because the user must have meant the literal character $. Previous to bash-4.2 it would have expanded the variable, so we would have seen “ls /usr/bin/ssh-keygen” instead. Which is way more useful

A quick search online finds the usual set of incorrect explanations and cargo-cult changes to bash-completion. (A popular fix is to use complete to make it so that the “cd” command works, leaving expansion broken for every other command.)

The actual truth is that this expansion is intended behavior in 4.2. Chet Ramey himself said so. He also recognizes this is awkward and has written a patch to add a new shopt called “direxpand” that will restore the desired, pre-4.2 behavior. Sadly that patch hasn’t made its way into Ubuntu’s Oneiric distribution yet.

One workaround for now is to press ESC C-e before hitting tab; that forces the command line to expand everything first.

Unlocking AppleTV notes

I’m trying to unlock a new AppleTV 2 so I can use XBMC or Plex to play videos from my home network on my PC. It’s been seven years since I first ran XBMC on a hacked Xbox and it’s still way too hard to get low power hardware to play your own TV.

AwkwardTV seems like a useful reference.

Some notes on the jailbreak process:

  • Apple firmware is signed via some online process. You need a “shsh” signature to bless firmware to run, even on already jailbroken systems. In general Apple only signs the most recent firmware, so it’s very hard to downgrade firmware.
  • There’s a program called TinyUmbrella that will generate shsh for firmware you have already. However, it’s mostly not useful except generating a shsh for a current version. My AppleTV out of the box had 4.3 but I was “too late” to get a shsh for it, despite it running. TinyUmbrella is evil software that modifies /etc/hosts and does god knows what else as root. There’s a competitor called iFaith, which may get shsh even for old firmwares, but it’s Windows only.
  • Seas0npass is the preferred jailbreaking software. Their guide is quite good. Don’t be fooled that it’s dated a year ago; they keep updating the jailbreak software.
  • Jailbreaking really boils down to putting the AppleTV in DFU mode and reflashing the firmware with some funky thing. All the weirdness around Seas0npass is creating that firmware and then scripting iTunes to install it.
  • If something goes wrong this Seas0npass troubleshooting guide is great. In particular I had the problem of iTunes saying “This device isn’t eligible for the requested build”. Turns out TinyUmbrella had evilly rewritten my /etc/hosts and was breaking the iTunes update process; telling TinyUmbrella not to do that fixed it.
  • It took about seven tries, but I now have an Apple TV 2 running 4.4.4 (3330), but jailbroken. Ie: I can run my own software and the hardware I purchased.

Now what? Well simple thing is log in as root with the default password “alpine”. Hey, look, it’s like a Unix box! It’s even got apt-get, plus a bunch of apt sources of dodgy software.

First thing up is to install Plex, a media player that works by streaming video from a transcoding server. There are many sets of conflicting instructions on how to install Plex. This forum thread seems up to date as of January 2012. Conceptually...

  • Install Python via apt
  • Download this scary installer(a zip file)
  • Change your root password back to the default “alpine”
  • Run the scary installer
  • It reboots the Apple TV, and now you have Plex!
  • Run Plex, go to Settings / Security and disable tracking.
Plex Media Server is awfully finicky about finding files. It desperately wants to match video filenames to a poorly documented naming system; if files don’t match, they just don’t show up. And it tries to cache the scan so simply renaming files doesn’t really force a rescan. There’s no “scan everything” option in the web UI (there is in the native client). Oh, and the Web UI is terribly buggy and you have to reload it every time you change the folder list.

Next thing would be to install XBMC, but I’m already feeling bruised from dealing with all this poorly packaged hackerware. Full props to the folks making media software on unauthorized devices, but man is usability a challenge.

BTW, two crappy things about the Apple TV:

  • There’s no HDMI cable in the box
  • The remote is IR only

New kernel fail

I decided to build a custom Linux kernel on my Ubuntu 10.10 Oneiric box. 3.0.0 feels awfully old, and I’ve been having trouble with a couple of things (well documented here). I was hoping a modern 3.2 kernel from Ubuntu precise would fix both my ethernet driver problem and, by building specifically for a modern Intel CPU, enable sched_mc_power_savings. No such luck.

Building a Linux kernel has gotten remarkably complex. I mostly quit trying myself back in 2.2 or so; once loadable kernel modules got reliable there was little reason for a top end developer like me to muck with the kernel. These Ubuntu-specific instructions got me there, although it’s a long winded and complex thing involving a lot of configuration management.

Then I got it built and installed and rebooted and miracle! It worked. Only with the same old bugs. 10+ seconds to initialize the ethernet, and that power savings sysctl still missing. I gave up and removed my custom kernel. I’ll wait for the Ubuntu release to upgrade.

 

Cyberpower pwrstatd notes

I bought a Cyberpower UPS for my Linux server. I mostly like it, but the Linux software they include for it (pwrstat and pwrstatd) is comically bad. Network UPS Tools supports this UPS hardware too, if I weren’t so invested in this software already I’d try it instead.

Here are some bugs:

  1. There’s no source code available, just two little ELF binaries pwrstat and pwrstatd
  2. pwrstatd has to run as root, not a big surprise since it can shutdown the machine, but see bug #1. Also pwrstat (the userspace program) has to run as root, even to get the UPS status! It seems to mmap() itself into pwrstatd :-(
  3. The default configuration is to shut down your machine after 60 seconds of power failure, then shut the whole UPS off after 10 minutes. That’s awfully aggressive.
  4. Once a Linux box is shutdown, the ACPI system means it won’t reboot itself again when power is restored. Wake-on-LAN is the right way to fix this, I don’t know a quick and dirty way.
  5. The various utility shell scripts /etc/pwrstatd-*.sh are very poorly written. The mail program assumes /bin/mail has a -r flag (mine doesn’t). One script has a test for ENABLE_EMAIL being “YES”, the other tests for it being “yes”. None of the test arguments are quoted so missing variables throw shell syntax errors.
  6. Did I mention all the real work is done in pwrstatd, which runs as root, and for which there is no source code provided?

The cool thing about the UPS is the status report it gives over the USB includes a bunch of data, including how many watts the UPS is driving right now. I wrote a little Munin script and now I have a fancy graph of my server’s power consumption.

That graph above includes me unplugging the UPS and letting it run to zero. Original estimate was 82 minutes of runtime, actually got about 70. Oddly the power drain went up 10W after unplugged; the inefficiency of the AC generation?

This UPS seems to consume 10W of its own even when fully charged, and about 20W when charging. Not happy about that 10W. Also the “battery capacity” value is totally bogus during charging; it only updates when I force the UPS to run off battery or run a self-test.

Here’s my Munin plugin (first ever!)

#!/usr/bin/env python

"""
pwrstat - Plugin to monitor Cyberpower UPS via pwrstat

by Nelson Minar <nelson@monkey.org>, placed into the public domain

Unfortunately this plugin must run as root, because pwrstat requires
root to even read data from the UPS.
"""

import sys, subprocess

# config
if len(sys.argv) > 1:
 if sys.argv[1] == "config":
 print """
graph_title Cyberpower UPS Status
graph_category UPS
graph_vlabel value

inV.label Utility Voltage
inV.min 0
inV.max 200
inV.warning 100:130

outV.label Output Voltage
outV.min 0
outV.max 200
outV.warning 100:130

battery.label Battery Capacity (Percent)
battery.min 0
battery.max 100
battery.warning 35:105

runtime.label Remaining Runtime (Minutes)
runtime.min 0
runtime.max 200
runtime.warning 10:200

loadWatts.label Load (Watts)
loadWatts.min 0
loadWatts.max 1000
loadWatts.warning 30:150

loadPct.label Load (Percent)
loadPct.min 0
loadPct.max 100
loadPct.warning 0:75
"""
 sys.exit(0)
 else:
 sys.stderr.write("Unknown argument %s\n" % sys.argv[1])
 sys.exit(0)

# fetch

output = subprocess.check_output(("/usr/sbin/pwrstat", "-status"), shell=False)
output = output.split('\n')
data = {}
for datum in output[10:-2]:
 name = datum[:29].strip('.').strip()
 value = datum[31:].strip()
 data[name] = value

print "inV.value", data["Utility Voltage"].split()[0]
print "outV.value", data["Output Voltage"].split()[0]
print "battery.value", data["Battery Capacity"].split()[0]
print "runtime.value", data["Remaining Runtime"].split()[0]
print "loadWatts.value", data["Load"].split()[0]
print "loadPct.value", data["Load"].split()[1].split('(')[1]

sys.exit(0)

# This is the pwrstat format that we parse. Note, it contains tabs.
# Comes from pwrstat version 1.2
exampleOutput="""
The UPS information shows as following:

Properties:
 Model Name................... UPS CP1000AVRLCD
 Firmware Number.............. BFC7101.4K1
 Rating Voltage............... 120 V
 Rating Power................. 600 Watt

Current UPS status:
 State........................ Normal
 Power Supply by.............. Utility Power
 Utility Voltage.............. 125 V
 Output Voltage............... 124 V
 Battery Capacity............. 100 %
 Remaining Runtime............ 77 min.
 Load......................... 54 Watt(9 %)
 Line Interaction............. None
 Test Result.................. Passed at 2012/01/25 01:39:47
 Last Power Event............. None
"""

New server power consumption

Power consumption of various computers, as measured with the handy Kill-o-Watt
  • 2012 Linux server. 50W - 120W
  • 2011 iMac. 50W - 210W
  • 2010 Windows PC. 120W (always!)
  • 2003 Linux server. 50W

I like how the iMac numbers line up. The iMac has a GPU and a large LCD, so it maxes out higher, but when idle it’s about the same as the Linux server. It’s a very similar motherboard and the same CPU, so that all makes sense.

I don’t quite understand why the idle Linux box is using 50W and not, say, 10W. I don’t think the Intel CPUs will completely shut down a core when idle, that’s part of it.

Update: some useful notes from Intel and on SuperUser. Taking cpus offline via /sys/devices/system/cpu/cpu3/online didn’t save me any power. Either idle CPUs take very little power (unlikely) or the comment on SuperUser is right that this doesn’t halt the processor. The /sys/devices/system/cpu/sched_smt_power_savings also didn’t save me any power. I think sched_mc_power_savings would be useful, but it’s missing on my system. Apparently I need to rebuild the kernel with my processor family to enable it.

Update2: according to this article at low power an i7-2600 uses about 5W. Their measured idle system power (whole computer) is about 70W, so my 50W is in line. Where does it all go?!

At $0.33276/Kwh, every extra watt costs me $0.25 a month.

Python script to find Amazon store MP3 files

I’m working on rationalizing my MP3 collection.  Here’s a Python script to print out the names of all songs that seem to have been bought from Amazon MP3. It uses the presence of “Amazon” in the ID3v2 comment tag. It’s not entirely reliable; songs I bought in 2007, 2008 are missing that tag.

#!/usr/bin/python

"""Print out names of MP3 files that are from Amazon.
Works by looking for the Amazon ID3v2 comment tag with a song ID.
This method is not complete: some early Amazon sales don't have this."""

import sys, os
from mutagen.id3 import ID3

def isAmazon(fn):
  "Return the Amazon comment if it's an Amazon MP3, else None"
  id3=ID3(fn)
  for c in id3.getall('COMM'):
    if "Amazon" in str(c):
      return str(c)
  return None

for dirpath, dirnames, files in os.walk('.'):
  for name in files:
    if name.endswith(".mp3"):
      fn = os.path.join(dirpath, name)
      try:
        if isAmazon(fn):
          print fn
      except:
        pass # ignore errors

sys.exit(0)

Realtek ethernet drivers: r8169 vs r8168

Update Jan 2013: this driver issue was fixed in Ubuntu 12.04 / kernel 3.2.0-14 or so.

Ubuntu doesn’t work out of the box with my ethernet adapter. The ethernet interface is very slow to come up after boot, taking 10-120 seconds. The problem is the Realtek 8111 or 8168, a very common motherboard ethernet adapter. The motherboard docs say it’s a Realtek 81111E. The Linux drivers are broken. Apparently this is a common problem across many Linux variants and people report other problems, too, packet loss and dropped packets. It’s a four year old bug in Ubuntu! How to fix it? (Other than buying a new NIC; Realtek NICs are not well loved.)

I did a lot of research. One proposed fix is to get a different device driver, from Realtek, not the Linux kernel sources. (More notes). Another suggestion is to enable Wake-on-LAN (via Windows), but I don’t really believe that will work. A third option is to upgrade kernels, there’s some possibility that the mainline Linux driver is better. (Most recent Ubuntu bug is 864196).

I decided to try Realtek’s driver. r8168-8.027.00. md5sum:
98155ce1ad5c248eeb7a93c9954d8344  /tmp/r8168-8.027.00.tar.bz2

Sadly, it doesn’t fix my problem. The NIC still takes 10-200 seconds to come up after boot. I also tried enabling wake-on-lan (via Linux, ethtool) and that didn’t fix it either. No surprise but I thought I’d give it a shot. I’m left with the conclusion there is no fix for this bug right now, despite the superstitions about Wake-on-LAN, or r8168 drivers, or whatever.

BTW, the autorun.sh script that comes with the r8168 driver from Realtek is pure evil. First, it unloads your ethernet driver. Completely killing your machine if you’re logged in via ssh and don’t have physical access! Then it goes and rewrites a bunch of stuff in /lib/modules and rebuilds your initram disk. It seems to get this right, but it’s awfully intrusive. I finally removed r8168.ko by hand and did an “apt-get install --reinstall  linux-image-3.0.0-15-server” to set things back.

I’m going to try living with this bug; I never reboot the box anyway. The first time I experience massive packet loss, or the ethernet doesn’t come up after boot, I’m getting a real NIC and putting it in a PCI slot. And never again buying a motherboard with a Realtek NIC for Linux use.

Details from lspci -v from stock Ubuntu, before I tried adding the r8168 driver:

03:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 06)
 Subsystem: ASUSTeK Computer Inc. P8P67 and other motherboards
 Flags: bus master, fast devsel, latency 0, IRQ 45
 I/O ports at e000 [size=256]
 Memory at d0004000 (64-bit, prefetchable) [size=4K]
 Memory at d0000000 (64-bit, prefetchable) [size=16K]
 Capabilities: <access denied>
 Kernel driver in use: r8169
 Kernel modules: r8169

Configuring lm-sensors for Asus P8Z68-M-Pro

The temperature, fan, and voltage sensors in my fancy new Asus P8Z68-M-Pro motherboard weren’t recognized right out of the box. I fixed it by installing a custom kernel module and then telling the sensors(8) program to ignore some bogus readings.

The motherboard has two sets of sensors. coretemp-isa-0000, from the Intel chip, and nct-6776-isa-0290, from the motherboard. That second chip requires a custom kernel modules which I got from Guenter Roeck: w83627ehf. Easy to build and install, and afterwards sensors(8) shows lots of data.

Some of the data is bogus (see  this github issue), so I fixed it by dropping the following file in /etc/sensors.d:

# Configs by nelson to hide bogus values on my ASUS P8Z68-M PRO motherboard,
# which uses an nct6776-isa-0290 chip.

chip "nct6776-*"
 # These are not configured in sensors3.conf
 ignore in1
 ignore in4
 ignore in5

# Fans I don't have plugged in
 ignore fan1
 ignore fan3
 ignore fan4
 ignore fan5

# ignore CPUTIN and AUXTIN; bogus values
 ignore temp2
 ignore temp3

Those in and temp sensors are returning meaningful data, but they’re not configured correctly in the default /etc/sensors3.conf and I’m too lazy to track down exactly what they might mean. One of those fan sensors probably is for the chassis fan, but mine isn’t plugged in to my motherboard.

Disk and data transfer rates

All these disks and stuff have me confused about what fast transfer rates are. Here’s some numbers, mostly practical rates, not theoretical. All numbers are Megabits / second. See also the Wikipedia List of device bit rates.

  • 168,000: RAM for an i7-2600 (theoretical) (ref)
  • 10,000: HDMI v1.3
  • 6400: PCI (64 bit, 100MHz)
  • 5000: USB 3.0 (theoretical)
  • 4800: 6.0Gbit SATA
  • 2400: 3.0Gbit SATA
  • 800-4000: SSD drives (ref)
  • 1000: 7200 rpm hard drive disk-to-buffer (ref)
  • 1000: gigabit ethernet
  • 800: IDE, UDMA 5 aka Ultra ATA/100 (ref)
  • 250-480: USB 2.0 hard drive (ref)
  • 100: 100M ethernet
  • 30: fast US home Internet
  • 20: 802.11g wifi (ref)
  • 12: USB 1.0
  • 6: my crappy home DSL
  • 1: AT&T 3G downloads (ref)
  • 0.05: old acoustic modems
Bottom line: USB 2.0 is a little slower than a desktop hard drive. And SATA is significantly faster than a hard drive. I wish I could narrow the SSDs down, I think performance on those things varies quite a bit. My friend Lars just built a RAID 5 array of SSDs that’s showing about 10,000 Mbit/sec.
Some practical tests on my brand new Sandy Bridge server with 7200 RPM disks plugged into SATA/6 and formatted ext4fs. All numbers are Megabits/second
  • 1000: hdparm -t, testing disk read throughput from the platter
  • 110,000: hdparm -T, testing read from RAM cache (ie: never touching SATA or disk)
  • 1088: writing 16 gigs of zeroes
    dd if=/dev/zero of=zeros bs=1M count=16384
  • 440: copying 16 gigs of zeroes on a single drive
    dd if=zeros of=zeros3 bs=1M
  • 872: copying 16 gigs of zeroes from one drive to another. Parallelism!
    dd if=zeros2 of=/tmp/zeros bs=1M
  • 570: rsyncing 300 gigs of files from a FAT32 drive over USB-3 to an SATA/6 drive.
  • 20,000: writing 1 gig of zeroes. ext4fs must fully cache this before commit
    dd if=/dev/zero of=zeros5 bs=1M count=1024
  • 88: creating a file of random bits from /dev/urandom. I had no idea that driver was that slow.
These tests are all for big files. Linux gets a lot slower when dealing with lots of little files. Running rsync from a USB 2 disk copying to an SATA disk I’d see a factor of 10 difference in disk throughput between giant files and lots of tiny files.

The new Linux server

Here’s the parts I’m getting for my new server. Many thanks to Adam for sharing his system build of a few months ago. This system’s remarkably similar to a new iMac, albeit without the SSD. By all accounts this Sandy Bridge stuff is terrific.

1 of: Antec 380 Watt Power Supply Mid Tower Case NSK4482B (Black) $89.99
2 of: Western Digital 1 TB Caviar Blue SATA III 7200 RPM 32 MB Cache Bulk/OEM Desktop Hard Drive - WD10EALX $129.08
1 of: Intel Core i7-2600 Processor 3.4GHz 8 MB Cache Socket LGA1155 $295.00
1 of: ASUS SATA 6 Gb/s DisplayPort Intel Z68 Micro ATX DDR3 2200 Intel LGA 1155 Motherboards P8Z68-M Pro $119.99
1 of: Corsair 16 GB (4x4GB) Vengeance Blue Low Profile 1600mhz PC3-12800 240-pin Dual Channel DDR3 Memory Kit 16 Dual Channel Kit - CML16GX3M4A1600C9B $89.99

Junky case and very simple disk system. I won’t even run RAID, don’t trust it. No SSDs either, don’t trust those consumer parts. Just simple spinning platters. Some of the details matter. The i7-2600K is more popular because it’s overclockable. But I never overclock, and it turns out the i7-2600 has some virtualization capabilities that the i7-2600K doesn’t. It’s clear the Z68 chipset is the best motherboard, and I went with ASUS just because I always have. But they make like 6 Z68 motherboards and I can’t really tell one from the next. (After building this I learned the Realtek ethernet chip in the P8Z68 M Pro doesn’t work well in Linux. The P8Z68-V boards have Intel ethernet chips, may be a better choice.)

I told myself years ago I’d never build another computer from parts. Yet here I am. The local screwdriver shops are charging too high a premium, and then it’s a struggle to get them to understand you really want no graphics card, no OS, really just the simple server. “Oh, a server? How about this $4000 2U rackmount?”

At least I already know all about Ubuntu server.

IDE, the obsolete standard

My home Linux server died. We had an ugly power outage and when the power came back up and when I turned on the computer, out came the magic smoke. I hope that just the power supply fried, or maybe the motherboard, because I don’t have a backup of the data on the hard drives. 15 years of data, programming, photos, financial records, email, writing. It’s very unlikely that the data is gone; worst case, I send the platters to a data recovery service. But it sucks.

I’ve ordered the parts to build a fancy new computer. It’ll be an awesome fast upgrade based around Sandy Bridge parts. My plan was to install Ubuntu on the fancy new SATA drives, get things sort of working, then plug in the old IDE/PATA drives to copy the data over.

The motherboard doesn’t even have IDE ports.

When did that happen? When did IDE become so obsolete they don’t even put ports for it on a motherboard? I mean, the motherboard still has PS/2 keyboard, old school serial, parallel. No IDE. Ugh. I’ve ordered a USB adapter to get data off the old drive. Amazon is full of these jobbies for $7, complete with 10+ one star reviews saying “the power supply is junk and fried my drive”. Awesome. The one I picked has the most reviews and almost all are positive.

I’m not so stupid as to not have any sort of backups of the data. I have a complete rsnapshot mirror. On a second drive, in the dead machine, the one that might have sent a surge of death through every plugged in component. Yeah, didn’t think through all failure modes. I am committed to doing real offsite backup of all my computers now. I have CrashPlan on the Mac already; something for Linux will be coming.

While I’m waiting for the adapter I tried playing with an old USB drive enclosure I had lying around, thinking I could put the drives in and plug them into my Mac to reassure myself the data is still there. Turns out mounting ext3fs on MacOS is a clusterfuck. fuse-ext2 is the recommended way but MacFuse doesn’t work on Lion and is abandoned and all the Fuse folks have scattered every which way. This blog post claims that OSXFuse + Fuse-ext2 will work on Lion, but I don’t have enough confidence in all this jury rigging to bother trying it. I’m much more comfortable recovering data in a Linux system.

Organizing all my git

I use git enough now that my repositories are getting a bit messy. I decided to centralize them all in one place so I can access them over the network. (You know, the distributed part of DVCS). There’s lots of options, I settled on just using a bunch of bare repositories on a host I can ssh to.

Alternatives I considered.. Dropbox is a good alternative for the central git repository but I’ve got my own server so I’m using that. The git:// protocol seems like unnecessary complication. As for hosting and web frontends.. GitHub is too expensive for my 10+ private repos,, charging per repo. Sites like repositoryhosting, gitorious, codeplane, and bitbucket have cheap or free options, but I don’t really need a centralized host since I’m mostly working alone. I could also have gotten fancy and installed something like gitolite to have a webapp front end, but that’s overkill for me now. Maybe I’ll set up gitweb at some point.

Here’s how I migrated my exisiting ad-hoc repos to one canonical gitrepos directory on a server. I found a lot of conflicting and incomplete info on how to do this, for instance these notes, this blog post, and this stackoverflow post. Correctly getting all branches into the new canonical repo and then patching up the config of the old ad-hoc repo is not straightforward. I’m not confident this is really correct, either, but it seems to work for simple things.

Find all the .git repos. Still have to hand-edit this list.
$ find ~ -type d -name .git | egrep -v '/d3|polymaps/'

Create a new bare repo in my new ~/gitrepos directory, based on code from ~/src/dotfiles.
$ cd ~/gitrepos
$ git clone --bare ~/src/dotfiles dotfiles
$ # is this a good idea? necessary?
$ # cd dotfiles; git remote rm origin

Change my old ad-hoc repo to consider this bare repo as its origin.
$ git remote add origin ~/gitrepos/dotfiles
$ git push
$ git branch --set-upstream master origin/master

That bit about pushing and then setting the upstream is 100% black magic for me, I have no idea what it does. It seems to be necessary to create the magic so that later “git status” will tell you if your local branch is ahead of the canonical copy in ~/gitrepos.  The push is necessary for some git config reason, even though there’s nothing to push. I find it confusing how git uses branches to track remote repos.

Also useful: “git remote -v” for seeing what remotes are configured, and “git branch -avv” for seeing more about git’s local view of various branches and remotes.

None of those examples above use a really remote repository, it’s all just Unix file paths. You can so name repositories like “nelson@example.com:~/gitrepos/dotfiles” and it will ssh to example.com and everything just works.

About this blog

A few folks have subscribed to this blog recently. Welcome! I am not writing for you. I am truly, only, writing work notes for myself. Stuff I learn and don’t want to forget. You’re welcome to read along, comment, share, whatever. But this post is probably the last time I’ll ever think about what you think, dear reader.

My real blog was also intended to be written for myself but somewhere along the way became a publication medium. When I write there I care to be clear, grammatical, concise, interesting. Here, not so much.

 

A place where bzip2 is useful

I almost always regret using uber-compressor bzip2. It generally compresses to, oh, 90% of the size of gzip but takes 10x as long to compress and 2x as long to decompress. Not worth it, bad space/time tradeoff.

The exception is Apache access log files. Something about the terribly repetitive text of these things is really good for bzip2. Here’s a quick test on a 26 meg access.log (using bzip2 1.0.5 and gzip 1.4 on Debian i686)

gzip: 10.8%, 860ms to compress, 160ms to decompress

bzip2: 5.7%, 12700ms to compress, 1600ms to decompress

The bzip2 is literally half the size of the gzip. That’s a lot. Too bad it took 15x as much time to generate it and 10x as much time to decompress it again. A quick Google suggests most people find bzip2 about 3x-5x slower, not sure why it’s so bad for me. Maybe because my sample is also unusually good at compressing!

Some other fast compression options: pigz, pbzip2, threadzip for parallel compressors, or snappy for Google’s very-fast-but-not-as-tight compressor.

Here’s the sample data I tested:

207.46.13.138 - - [04/Jul/2010:06:32:55 +0000] "GET /robots.txt HTTP/1.1" 301 329 "-" "msnbot/2.0b (+http://search.msn.com/msnbot.htm)"
207.46.13.138 - - [04/Jul/2010:06:32:55 +0000] "GET /robots.txt HTTP/1.1" 200 107 "-" "msnbot/2.0b (+http://search.msn.com/msnbot.htm)"
61.135.216.105 - - [04/Jul/2010:06:32:55 +0000] "GET /weblog/index.atom HTTP/1.1" 304 - "-" "Mozilla/5.0 (compatible;YoudaoFeedFetcher/1.0;http://www.youdao.com/help/reader/faq/topic006/;2 subscribers;)"

Ubuntu server cron jobs

Here’s all the cron jobs on my relatively vanilla Ubuntu Server setup. I’ve added Apache and a few other minor things to the default install.

Daily:

  • htcacheclean, for Apache’s mod_cache disk cache
  • apport, cleans up old reports in /var/crash
  • apt, cache management
  • aptitude, making logs of what’s installed
  • dpkg, also making logs of what’s installed
  • popularity-contest, telling Ubuntu what people installed
  • bsdmainutils, managing user’s ~/calendar files
  • logrotate
  • man-db, managing the man page database
  • mlocate, an efficient implementation of good ol’ locate for fast finds
  • ntp, managing ntpstats (which aren’t enabled by default)
  • passwd, making backups of /etc/passwd and friends. (wtf?)
  • standard, the “standard daily maintenance script”. backs up /etc/passwd (again?) and looks for lost+found files. Dumb script, and redundant
Weekly:
Logrotate is configured to back up weekly and keep 4 weeks worth of logs and, surprisingly, not compress old logs. Apache overrides this to keep 52 weeks of logs and to compress them. I’m pleased to see the Ubuntu logrotate has a dateext and dateformat option to name logfiles like “access.log-20120108” rather than “access.log.3” and then renaming that to “access.log.4” the next week. That should be the default behavior but apparently that option isn’t available in older versions of logrotate.

Ubuntu and FQDNs

Setting the fully qualified domain name on an Ubuntu host is way too hard. The Internet is full of confusing advice. Most people first seem to notice the FQDN isn’t right when setting up Apache, but it’s a broader problem than that. (You can fix Apache just by giving an explicit ServerName directive.) “hostname -f” should return the right thing.

My solution:

  • /etc/hostname contains just the system name, “wi”
  • /etc/hosts contains an entry like this:
    208.110.64.210  wi.nelson.monkey.org wi
  • /etc/resolv.conf contains an entry like this:
    domain nelson.monkey.org

And now “hostname” returns “wi”, “hostname -f” returns “wi.nelson.monkey.org”. Note I don’t have a reverse DNS entry for that IP address. (I do have forward DNS so wi.nelson.monkey.org resolves, but I don’t think it’s used.)

Part of the confusion is a lot of people (and Ubuntu by default) want you to do something like

127.0.1.1 wi.nelson.monkey.org wi

This kind of works, despite the odd loopback address number. But it’s not really correct: your FQDN should resolve to a routeable IP address, not a loopback.

 

 

Ubuntu server notes from an old Debian user

I’m setting up a new Linux server and using Ubuntu for it for the first time. I’ve been a Debian guy for a long time now (and before then, Red Hat), so Ubuntu is both new and old. I switched to it because it’s got a faster upgrade cycle than Debian, but I like all the extra tools they’ve added, too.

Here’s some of the new things in Ubuntu I’ve learned about. The Ubuntu server docs are an excellent place to start.

  • upstart, a replacement for SysV init scripts that runs things in parallel. The configuration files live in /etc/init. There’s still old SysV stuff in /etc/rc2.d and /etc/init.d being run. The new service command is nice, ie “service --status-all”. There’s plans for upstart to replace cron and at, too. Docs: UbuntuBootupHowto, original rationale, upstart tutorial, and cookbook. (Ubuntu does not use systemd, another modern init replacement).
  • plymouth, the graphic splash boot screen. For some reason this is complicated and intertwined with upstart.
  • ureadahead (aka Über-readahead), a clever system to improve boot times by reading all necessary user files off of disk in one big transfer at the beginning of boot. The boot image is kept in /var/lib/ureadahead and there’s clever stuff to invalidate and re-write the files when new things are installed. It seems to save a few seconds on boot for me, not positive. More info here.
  • ext4fs is the default filesystem. It has various incremental improvements to ext3fs, many of them aimed at efficiently handling big files and disks.
  • AppArmor, a security mechanism. It lets the kernel restrict what access various programs have. For instance, ntpd is only allowed to write to certain log files so if there’s ever an exploit against ntpd it won’t go writing random files as root. It seems like a fairly limited security mechanism given how big the attack surface of Linux is, but also harmless and potentially useful.
  • ufw, Uncomplicated Firewall, is a friendlier interface for firewall rules than iptables.
  • Automatic software updates. The setup process is embarrassingly manual, but you can have Ubuntu install security updates (or all updates) automatically.
  • pam_motd, the absurd thing that makes /etc/motd show current system stats. It seems to update on login. If it ever breaks I will be very angry if I can’t log into my system.
  • JeOS is a stripped down Ubuntu server for running as a guest in a virtualization environment. I have no need for this now, but it’s a good idea.
  • Bacula, a fancy backup system. I will probably stick with rsnapshot and rsync.
  • Launchpad, a website where many Ubuntu projects are hosted. Bug tracking, etc.

One thing they haven’t improved is libresolv; it still queries nameservices serially, one at a time. Worse, the first entry in /etc/resolv.conf for me named 192.168.1.100 as the nameserver, a bogus entry from the initial setup in a different DHCP environment. So every DNS query was waiting 5 seconds for that to time out. I fixed it by putting Google’s 8.8.8.8 as the first nameserver.

My next project is to automate all my deployment of my own stuff to the server using Puppet or maybe Chef Solo. I’m trying to avoid the thing where my servers become an irreproducible rat’s nest of random crap I’ve collected over time. OTOH, I can tell already it’s going to be a lot of work for one little personal projects server.

 

METAR parsing libraries

METAR, the weather observation format, is a great little text format

KOAK 032353Z 00000KT 5SM BR SCT200 11/08 A3029 RMK AO2 SLP256 VIS SE 1 1/2

It’s also not a very standardized format, making parsing a bit of an art. Here’s a few different METAR parsing libraries I’ve found:

  1. Tom Pollard’s python-metar, (sourceforge, github). This is what I used to prepare windhistory.com and it’s pretty good.
  2. Joe Yates’ metar-parser for Ruby. Has some test coverage. Also references other Ruby implementations.
  3. METAR decoding software from NWS. The closest thing to official code, written by Eric McCarthy, now on SourceForge. It’s 12,000+ lines of C code (!), albeit with a lot of comments, unit tests, etc. Has some interesting code for interpreting the meaning of METARs, like whether it codes for a tornado or the like.

There’s lots of other parsers for various languages: PHP, .NET, etc.

 

Full-height HTML divs

I keep forgetting the right way to make a DIV take up the full height of the web browser. For, say, a full screen map. Chrome and Safari default to filling the whole container but Firefox prefers to calculate a minimum height div. Long story short, here’s what to do:

html, body, div#map { height: 100% }

I’m not entirely sure this is correct but it seems to work and is in line with advice on this StackOverflow discussion. It’s not enough to set the div’s height, you have to set the containers too. There’s also something about using min-height instead but it seems unnecessary. What I don’t know is how to set the height of a div to be 100% minus 100px or the like; something that leaves room for a header or footer.