Some Bits: Nelson's log

23 posts in 2010

I hate C++

It’s been a long time since I’ve written C++ code. Or C code, for that matter. Like before STL, before g++ really did templates right, before namespaces. I sort of miss the drama of C hacking, but I sure don’t miss all the stupid stuff about C.

A friend of mine wrote a brand new Minecraft map renderer, in C++. It’s really fast. But compiling it was such a mess. g++ 4.4 apparently moved some include files around, so I had to manually include stdint.h in a few places. Why? So you can get an honest-to-goodness 32 bit wide int reliably, since of course C still assumes int is some random width that happens to be the default in that version of the compiler on that kernel. Even with stdint.h included the compiler still couldn’t pick up a macro from inside it. I never could figure out why, I finally just copypastaed the macro into the code. Awesome.

Then there’s linking. What a bizarre thing to have to do with code. The nice thing about linking is you can also link -static, and get a binary that really will run pretty much on any compatible system. Java can do the equivalent reasonably well, but Python is a total nightmare for distributing portable code.

At least I haven’t seen any segmentation faults in the running code yet. Nor buffer overruns. Nor typecast problems. Ah, C, your edges are so sharp!

Tile hosting?

Let’s say I make some great SRTM altitude tiles, where can I host them that I don’t go broke? Map tiles are funny, they’re just static files so you don’t need a big server, just cheap bandwidth. I did a quick look around at some options:

  • Amazon S3 / CDN: $150/mo = 1TB, no server
  • Google AppEngine: $120/mo = 1TB. Limitations may make it impossible.
  • oneandone.net: $150/mo = 3TB with a server. SkyVector is here.
  • godaddy: $135/mo = 1.5TB with a server. Used by PDFPlates? NACOmatic was serving 20TB / month for awhile, not sure how that worked out
  • Voxel: $100/mo = 1TB. FlightAware is here.
  • one guy I know uses GoDaddy, hostgator, justhost, and linode to push about 2TB / month. HostGator supposedly cut him off without notification at some point.
  • I heard ReadyHosting shut down a 20 TB / month project
  • random “unmetered” hosting: the challenge is to find the one that’s actually unmetered and doesn’t have hidden throttles or termination policies.

I don’t know much about hosting. Static map tiles are a weird kind of thing to host.

Update: chunkhost offers $66/mo = 3.2TB with a decent Xen slice.

Slippy map tile image format

Now that I have sample tiles from my SRTM data, what format do I want to store them in?

An 8 bit paletted image is sufficient. I really only need 2 colours: transparent (below 8000′) and white (above 8000′). All the other colouring is just so it looks nice. (May save space using 64 or 128 colours). Even GIF would work, but I think PNG-8 (color type 3) is a better choice. Interestingly, even palettized PNGs support a full alpha channel for all 256 colours, see the tRNS chunk.

Do all the tiles need to have the same palette? They can, since it’s the same colormap for all the images. Not sure how to convince GDAL / other tools to reuse the palette, though, particularly with the transparency data. I’m guessing I’m going to need a post-processing step after GDAL generates the final slippy map tiles. Maybe that final PNG baking step is the time to enforce a single palette. The other processing I want to do is optimize via one of pngslim pngnq pngcrush optipng advpng. A quick test shows optipng saves 50%, I think by translating 24+8 bit images to 8 bit paletted images. I swear I saw a map hacker’s notes on comparing these tools once.

One related idea I’ve had for awhile: it’d be awesome to make a set of SRTM tiles that were a simple greyscale, 0-255, and then remap them to full colour + transparency in Javascript, in the client. That way the user could quickly choose what altitudes to highlight. I think it’s barely possible using the canvas API, not sure if it’s a good idea.

gdaldem for SRTM translation

Working on a static render of my SRTM tiles. Decided to use gdaldem to do the color mapping, it does all I need.

First I needed gdal 1.7 to use gdaldem, but Debian still packages older versions. There’s a lot of instructions for compiling. Long story short, ./configure; make works fine. It’s 1 million lines of code, so I had a nice cup of coffee.

Here’s how to use gdaldem to turn an SRTM .hgt file into a PNG: gdaldem color-relief -alpha -of png N39W120.hgt nelson.cmap gdaldem.png. There’s a variety of color map options, I hand-coded my own:

30000   180     0       0       255
4572    180     0       0       255
3049    130     80      80      255
3048    80      80      80      255
2438    0       0       0       255
2437    0       0       0       0
0       0       0       0       0
nv      0       255     0       255

That maps everything from 0-2437 meters (8000′) to transparent, then a grey ramp up to 10000′, then a red ramp up to 15000′, then solid red. Missing values (NV) are coloured green; need to deal with them later. The result looks like this

Now a bit of shell scripting to run the whole set:

for f in *.hgt; do
  ../experiment/gdaldem color-relief -alpha -of png $f ../png/nelson.cmap ../png/${f%.hgt}.png;
done

It’s awfully fast, I’m impressed with GDAL speed. The output PNG isn’t so bad, either, the empty tiles end up being 2k or so each.

Next up: gdal2tiles.py to turn these into tiles I can serve for a slippy map. I might need to gdalbuildvrt first to combine all the files into one big virtual map.

gdal tutorial notes

I took a quick trip through this gdal tutorial on raster data, albeit with SRTM data instead of the example data. Things I learned:

  • gdalinfo has useful flags for finding min/max values, stats, etc.
  • gdal_translate is how you render a dataset to an image
    gdal_translate -ot byte -scale 1152 3184  -of PNG  N39W120.hgt test.png
    Input range doesn’t seem to autoscale, despite what the docs say. Haven’t figured out how to apply a custom colormap yet. (The FAQ is discouraging, but gdaldem color-relief might do what I need.) The PNG output from GDAL doesn’t seem to have any geodata stored in PNG chunks.
  • gdalwarp is how you reproject data
  • gdal_merge is how you mosaic images. You can use gdalwarp to do it, too, but it’s overkill.
    gdalwarp N39W120.hgt N39W121.hgt N38W120.hgt N38W121.hgt big.tiff
    gdal_translate -outsize 50% 50% -scale 1000 3000 -of PNG big.tiff test.png
  • gdal_rasterize lets you render vector data (via OGR) into raster data
  • gdaladdo creates downsampled overviews for data, for faster access. In my previous experiments the overviews didn’t make mapserver any faster on my SRTM data.
  • gdal has virtual formats which are a text file that describes multiple raster files as a single dataset. mapserver uses something different to accomplish this, a shapefile.

Chrome developer tools

I do all my Javascript development in Chrome. But I never really sat down to learn about the Chrome developer tools other than learning how to open the console. Here’s some bits I learned reviewing the docs.

  • Ctrl-shift-C lets you inspect DOM elements with mouseover. This is the same as clicking the little magnifying glass in the tools.
  • In Elements, the panels on the right show the live state of the DOM, CSS, etc. Most bits are editable as well as inspectable.
  • In Scripts, you can set breakpoints by clicking on the line numbers.
  • The docs describe a cool-sounding network page that I don’t have in my Chrome/stable. May be only available in developer for now?
  • There’s ridiculously powerful performance tools built in. Learning it all would take hours, but quickly: go to Timeline, click the round record button, reload your page, then click record again to turn off recording. There’s a profiler too, for statistical profiles. Both seem to work better in Incognito mode so you don’t have any extensions.
  • The console scripting prompt has some limited support for jQuery-like DOM identification of elements.

Flying today: GPS track accuracy

No hacking today, went flying instead. Ended up being a passenger the whole 3 hour flight, crappy IFR weather. But as always I captured the flight on my little AMOD GPS tracker and mapped the track through my custom GPS track mapper project. The result is quite surprising; not only is data missing, but the track is wrong! In particular when we left Modesto we did not fly south, we flew more or less west, and the GPS recorded the wrong position. What happened?

My GPS tracker logs NMEA sentences once a second and records all sorts of neat data. Unfortunately I’m not graphing it yet, so I turned instead to GPS visualizer to visualize some auxilliary data: specifically the # of satellites we had for the fix as well as the horizontal dilution of precision, a measure of fix accuracy.

As you can see in the graph, the HDOP spiked really high for about 10 minutes around 23:20, or exactly when my position data was bad and then disappeared. I’d naively assumed the GPS tracker wouldn’t even record data if it didn’t have a good fix. Apparently it does. The Wikipedia article suggests I should be ignoring fixes with HDOP > 10 or so. My tracker also records vertical DOP; in general GPS isn’t as good at vertical position as horizontal, so that data may be even worse.

One other graph: # of satellites as a function of HDOP. My GPS apparently needs to see 5 satellites to give an accurate position. No idea if that’s true for all GPS chipsets (I think 4 is minimal), but this tracker uses the decent SiFR III chipset so I imagine it’s doing about as good as it can.

I’ve got a long list of things to do with my GPS track mapping program. I hope to make it a web site for others to use some day.

Binding CapsLock in Windows

I wanted to re-use my useless CapsLock key to search Google. I started by modifying WinUrl, an old program I’d used forever. Seemed easy enough, just RegisterHotKey(..., VK_CAPITAL). It even seemed to somehow suppress the capital locking function, all done! Except not, some confusing thing happened where caps would be on in some windows, off in others.

I went down a rabbit hole trying to disable caps locking. It’s buried deep in the drivers somewhere in Windows. The recommended work around is to use SendInput() to fake a new CapsLock keystroke to toggle it back, or maybe SetKeyboardState() to obliterate the CapsLock bit. But about the time I was putting 2 second delays in my code to prevent recursion from triggering my own functions, I gave up on that approach.

I ended up using AutoHotKey instead with this script. I don’t like AutoHotKey, it’s way overengineered. Custom scripting language, custom compiler to native code?! But it’s also very capable. And it knows how to override CapsLock.

Starting on gdal for SRTM data

Awhile back I made a slippy map of parts of the US over 8000′. I did it using SRTM elevation data turned into images with mapserver, a dynamic program. Easy to get going but awfully slow to serve. I’d like to make the same map but statically. Inspired by Matt’s success with gdal2tiles.py I thought I’d try again.

My source data is the .hgt files for North America. They’re bundled together into a single index.shp file using gdaltindex, as described in the mapserver docs. A quick and dirty render is accomplished with

gdal2tiles.py N37W119.hgt ~/public_html/tmp/gdal2tiles

That does all the expected tiling and rendering at multiple scales, but doesn’t have a meaningful colourmap. But in my work with Mapserver I created a meaningful colormap:

  LAYER
    NAME         srtm
    TILEINDEX    "index.shp"
    TYPE         RASTER
    STATUS       DEFAULT
    PROCESSING   "SCALE=2438,4572"    # 914m = 3000', 2438m = 8000', 4572m = 15000'
    PROCESSING   "BANDS=1,1,1,1"
    PROCESSING   "LUT_1=0:0,1:0,73:80, 74:130, 255:180"
    PROCESSING   "LUT_2=0:0,1:0,73:80, 74:0, 255:0"
    PROCESSING   "LUT_3=0:0,1:0,73:80, 74:0, 255:0"
    PROCESSING   "LUT_4=0:0,1:255,255:255"

What that says, in mapserver-eze, is:

  1. For each input point from SRTM, map the range 2438:4572 to 0:255.
    This maps everything < 8000′ to 0, everything over 15000′ to 255, and a linear range between.
  2. Map the input band “1” (the altitude) to the output channels RGBA. Ie, a full 32 bit image with 8 bits of alpha.
  3. LUT_4 maps everything that is 0 (< 8000′) to transparent, everything > 0 to fully visible (alpha = 255)
  4. LUT_1-3 apply a colourmap. 1 (8000′) is mapped to 0,0,0 (black), 73 (10000′?) maps to 80,80,80 (grey), and 255 (15000′) maps to red. This gives a color ramp: black to grey to red.

Now I need to figure out how to generate the same colourmap using solely GDAL. And then convince gdal2tiles to do that colourmapping, probably by first turning my HGT files into GeoTIFF and then tiling the GeoTIFF.

 

SRIDs, GeoDjango, PostGIS, and me

Now that I have GeoDjango up and running I was able to import a bunch of airport data using Adam’s code. Back to PostGIS to play!

select facility_name,
  floor(ST_Distance_Sphere(point,
    ST_GeomFromText('POINT(-122.4522 37.7555)')))
    as distance
  from airports_airport
  where control_tower = true
  order by distance
  limit 10;

ERROR:  geometry_distance_spheroid: Operation on two GEOMETRIES with different SRIDs

Frowny. Face. What’s that mean?

Long story short, an SRID identifies which Spatial Reference System the coordinates are with reference to. It’s a bit like units: it’s not enough to say something “weighs 100”, you have to specifiy if you mean 100 lbs, or 100 kgs, or whatever. For more theoretical background, see Geodesy. There’s a giant database of SRIDs at http://spatialreference.org/. (Related keyword: EPSG). Greatest hits:

  • 4326: WGS 84, the reference most GPSes use. I think many people assume this is the SRID by default.
  • 4269: NAD83, a popular North American standard
  • 54004: World Mercator
  • 900913: Google Maps’ modified Mercator. (It spells “google” in l33t).

So the problem is I’m trying to do arithmetic with points in two different SRIDs.

select ST_SRID(point) from airports_airport limit 1;
4326

select ST_SRID(ST_GeomFromText('POINT(-122.4522 37.7555)'));
-1

select ST_SRID(ST_GeomFromEWKT('SRID=4326; POINT(-122.4522 37.7555)'));
4326

GeoDjango defaults to SRID 4326; you can use others, details here. PostGIS ST_GeomFromText defaults to an SRID of -1, which I guess means unknown. But if you’re explicit then it works fine. You can also use PostGIS to transform from one SRID to another, I believe underneath it uses PROJ.4

SELECT ST_AsEWKT(
  ST_Transform(
    ST_GeomFromText('POINT(743238 2967416)', 2249),
  4326
));
SRID=4326;POINT(-71.1776848522251 42.3902896512902)

Personally I find this all frustrating; can’t we just use WGS 84 everywhere and be done with it? Sure, you still need to project when rendering a flat map, but consider that a separate thing entirely.

Fun fact: the reference points for WGS 84 move. And are remeasured roughly yearly. Apparently Greenwich is not at 0 longitude in WGS 84.

Django 1.2 and GeoDjango on Windows

I’ve been trying to develop code on my Windows box. It’s the machine I sit in front of, it’s fast, and I like WingIDE. I have a Linux box for “real work”, but think there’s some discipline in moving back and forth between the two systems.

For GeoDjango hacking I decided to run the PostGIS database on my Linux box and the Django webapp on my Windows box. I’d hoped this would avoid having to install a bunch of funky binaries on Windows. No such luck. The GeoDjango docs are a bit out of date and the official GeoDjango Windows installer binary is for an old version.  Here’s what I’ve learned doing it myself.

The first step is getting regular Django working. Here’s what I did:

  • Installed PostGIS + dependencies on Debian (testing) via
    aptitude install postgresql-8.4-postgis
  • Installed stock Python2.5 on Windows from Python.org
  • Installed Django 1.2 on Windows. I forget how I did this, I think using easy_install, which in turn requires installation as well. It wasn’t hard, just followed the tutorial. Django 1.2 includes GeoDjango Python libraries.
  • Installed psychopg2, the database driver, on Windows. There’s binaries at http://stickpeople.com/projects/python/win-psycopg/

GeoDjango is harder. It relies on a lot of C libraries, some of which don’t support Windows well. The main hurdle is a working GEOS DLL. The GEOS page itself doesn’t have binaries. I found binaries from three places: OSGeo4W,  the GeoDjango Windows Installer, and PostGIS. Here’s a quickie test program I wrote to try them out:

geosPath = r'.\libgeos_c-1.dll'

from django.conf import settings
settings.configure(GEOS_LIBRARY_PATH=geosPath)
from django.contrib.gis.geos import tests
tests.run()

Unfortunately, both the OSGeo4W and GeoDjango versions of the DLL don’t pass the tests. Version skew? Bug? The underlying error seems to be in memory management, something like

ERROR: test02_wktwriter (django.contrib.gis.geos.tests.test_io.GEOSIOTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "c:\Python25\lib\site-packages\django\contrib\gis\geos\tests\test_io.py", line 30, in test02_wktwriter
    self.assertEqual(ref_wkt, wkt_w.write(ref))
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\io.py", line 147, in write
    return wkt_writer_write(self.ptr, geom.ptr)
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\threadsafe.py", line 55, in __call__
    return self.cfunc(*args)
  File "c:\Python25\Lib\site-packages\django\contrib\gis\geos\prototypes\errcheck.py", line 87, in check_string
    free(result)
WindowsError: exception: access violation reading 0x02F12494

The library that did work for me was the version that came with PostGIS. I didn’t even install PostGIS, just grabbed the DLLs out of their zipfile. Unfortunately GEOS is spread into two files: libgeos_c-1.dll and libgeos-3-2-2.dll. The latter needs to be in a directory where Windows can find it as a normal DLL, I put it in the working directory of my own code.

GEOS was enough for me to get the tests working and my simple GeoDjango program working correctly. There’s more work to be done: I believe you want both GDAL and PROJ.4 available to GeoDjango on the Windows side. Or does PostGIS do the work on the database server? I haven’t tested that yet.

In addition to basic GeoDjango on Windows setup, here’s notes specific to my code:

  • Followed instructions on getting WingIDE to work with Django
  • Sweated a lot over environment considerations, specifically Python path. I hate setting up new development environments, and Django with its mix of servers and applications and developer code and third party libraries is complicated.
  • I’m trying to run a script directly, not via manage.py. To make that work you need to set the DJANGO_SETTINGS_MODULE system environment variable to point to the Python path of your settings.py
  • settings.py needs to specify a special database engine:
    ‘ENGINE’: ‘django.contrib.gis.db.backends.postgis’

There’s some more useful notes about Windows and GeoDjango in this blog post by Reinout van Rees.

Javascript code review

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

Here’s some complicated things I learned from him:

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

Also some simple things:

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

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

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

HTML 5 local storage, quickly

Inspired by my playing with Chrome Web Apps, I sat down and read up on two of the ways HTML 5 allows Javascript to use local storage.

Offline Web Applications let you build webapps that work even when the user has no network connection. The key thing is you create a “cache manifest” file which contains a list of the files that should be cached locally. If the user is offline (or if the site is down?) then the browser will use the cached version. There’s complicated extra stuff for fallbacks and wildcards that allow for webapps to opportunistically cache just the stuff the user saw for some other reason. And there’s DOM events to let the webapp know what’s going on with caching and network status.

Local Storage is a variety of technologies for a webapp to read and write data on the local hard drive. The main new one is the localStorage object, a persistent Array. Basically a key:value store with String being the only datatype. Apps get 5 megabytes of local store. There’s also some work being done on SQL and object databases, but nothing finished yet. Miraculously, local storage seems to work in every browser, even IE 8 and above.

Google Chrome apps

Over on my main blog I just posted What’s a Chrome Web App? Long story short, it’s basically either a bookmark or a Chrome extension.

As part of my research I turned my aviation weather experiment into a Chrome Application. It took about 15 minutes, and most of that was resizing the icon. Here’s the mainfest.json file that makes it go:

{ "name": "AvWx",
  "description": "Experimental aviation weather page",
  "version": "1",
  "app": { "launch": {
      "web_url": "http://www.somebits.com/avwx/static.html",
      "container": "panel",
      "width": 720,
      "height": 640
  } },
  "icons": { "128": "avwx-128.png" } }

The most interesting part of that is the “container: panel”. That tells Chrome to launch it without any navigation UI, so it looks like a standalone application. I could also be asking for extended privileges, like accessing geolocation or delivering notifications.

Chumby, the difficult alarm clock

I bought a Chumby. An “Insignia”, to be specific, from Best Buy for sale $50. Totally on a whim, but I bought two with the idea the other is a gift. What’s a Chumby? It’s an Internet-enabled alarm clock. Really it’s a tiny little hacker-friendly embedded system (Linux?) with WiFi, a 320x240 touchscreen, and a small form factor. It’s a toy.

Pretty bad user experience out of the box. Here’s the horror so far on first use. My goal was to see what time it is.

  • Plug it in, first thing you do is calibrate the touchscreen. Despite my dragging the little circle into the ring (visually), it doesn’t seem to register until the third try.
  • Second thing you do is set it up on your WiFi. It doesn’t see any networks. I type my SSID manually. It’s still lost. I type my WEP key in manually on the terrible touchscreen, unsure if it is even the kind of key it’s looking for. Press connect, 60 seconds later a timeout and no joy. Set up a second wifi network with no password. Chumby can’t find it either, even manually. Go online, read support, try rebooting the device. It finds the network! It’s online! Including a charmingly nerdy screen full of info about MAC addresses, Tx packet counts, etc. Lol.
  • Eager to move along my one page quick start manual, I find I’m not being asked to set the time. Which makes sense; it’s online afterall, but then why does the manual say it should?
  • Asked to register my device online. Have to create yet another @#*$#$ website account, with another username that’s unique, with another password, with another email verification step, with another “click here to not get spam” choice. I’m tired of Internet accounts. Fortunately, the device pairing goes smoothly, including a nice little AJAX notification in the browser.
  • Start the device. Maybe I can see a clock now? No, I get some headline scroll of TUAW feeds, including the word “RSS” prominently featured in the Chumby UI.
  • Stuck, not sure how to get to the clock, I randomly hit buttons. Suddenly presented with the option to upgrade the Chumby. OK, sure, and now for 5 minutes I’m being admonished “Do not disconnect the power at any time.”
  • Chumby finally reboots. I’m treated to a scrolling slideshow of apps I don’t want. What time is it?!
  • Find the button on top of the device (not the touchscreen), which lets me choose apps. Scroll through “featured apps” to 10 of 16, which is a clock. Find it’s 15 minutes after I started, then the app disappears.
  • Sometime later my Chumby starts scrolling apps again, including one to a page with ads selling me more crap from the manufacturer. Charming.

I think I’ll be setting up the other Chumby at home before presenting it as a gift. I like to troll my Apple-loving friends with how pretentious, closed, and expensive Apple devices are. But I’ll give Apple this, they have an excellent first-time user experience. OTOH their equivalent device, the iPod Touch, is 5x as expensive.

Snark aside, it’s not a bad device for $50. The main UI is “scroll through a bunch of Flash apps”. That doesn’t work for me, so I’ve set it to run a single app, the Flickr + clock app. It’s also able to play Internet radio streams in the background. That’s pretty slick.

Quick and dirty referer tracking

About once a month someone links to my blog and I get all excited to see how many clicks they drove. Despite 10+ years of Javascript tracking systems like Google Analytics, I still don’t have a proper tool to just quickly show me “what’s driving traffic today?”. I usually cobble together some hideous thing that starts awk { print $7, $11 } | grep -v ... and then get annoyed. So today I wrote a proper Python script:

#!/usr/bin/python

import itertools, re

skipRE = re.compile(r'(js|png|gif|jpg|css|rss091|atom|ico)$')
def skip(url, referer):
    return skipRE.search(url) is not None or \
        referer == '-' or \
        referer.startswith('http://www.somebits.com')

for l in itertools.chain(file("/var/log/apache2/access.log.1"), file("/var/log/apache2/access.log")):
    d = l.split()
    url = d[6]
    referer = d[10].strip('"')
    if not skip(url, referer):
        print url, referer

The output is then piped through a Python script I wrote years ago which counts up the most common lines.

One remaining mystery; the large majority of my pageviews have a referer of -, or empty. I know folks aren’t pasting URLs in by hand, where does this come from? Do redirectors somehow clear Referer?

Minecraft today

No hacking; that time got spent playing Minecraft instead. It’s an amazing indie game and while I’m mostly done with it, today my friends had a one-day PvP event on the server that was sort of interesting. It doesn’t make for a very good PvP game, honestly.

Testing Windows Live Writer

In a bit of a yak shaving exercise, I’m looking for a really simple blog post writer that’s more convenient than using wordpress.com’s web editor. Windows Live Writer works with wordpress.com, how good is its HTML?

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

There’s no support for <pre> tags, but I found a plugin that does it. (Update: not suitable for wordpress.com, since it requires Javascript. Use wordpress.com’s builtin

tag instead) The ribbon UI is pretty bad and there’s a lot of junk between me and my thoughts. But it’s not terrible. Here’s a picture:

5181557705_83c429094f_m

AvWx: dynamic HTML aviation forecasts

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

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

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

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

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

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

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

 

Learning some GIS

Today’s hacking project is getting up to speed with modern GIS. Specifically, PostGIS (Postgres with spatial features) as a database, QGis as a graphical frontend for viewing graphics data, and GeoDjango for building webapps.

QGis is awesome: you can quickly add layers, including layers that come from PostGIS. Loaded layers are on the tray to the left, you can right click them to set display options, enable a query to filter what’s displayed, etc. There’s also an edit mode for editing geometry.

PostGIS is encouraging. Some notes:

After finishing all the setup I loaded the cities and counties file referenced in that first tutorial (at USGS) It was easy to load them up into QGis for display. “Show me county outlines, and the names and locations of all cities with more than 100,000 residents”.

Playing in PostGIS, here’s some interesting queries:

select county, ST_Area(wkb_geometry) as area from us_counties
where state = 'CA'  order by area desc limit 5;
Biggest county. Units of Area are.. degrees?
                       county                       |       area
----------------------------------------------------+------------------
 San Bernardino County                              | 5.13534296766738
 Inyo County                                        | 2.66716021408502
 Kern County                                        | 2.09407653001836
 Riverside County                                   | 1.84319135357509
 Siskiyou County                                    | 1.77534424474288

select county, ST_AsText(ST_Simplify(wkb_geometry, 0.1))
  from us_counties where state = 'CA'  limit 1;
(returns a simplified polygon of the county outline)

\d us_counties
shows all the columns. The interesting one is
  wkb_geometry | geometry
Geometry is a polymorphic type, in the case of this shapefile it's a Polygon. The "WKB"
name is just a descriptive, but implies the import source was in "well known binary" format. 

select name, ST_X(wkb_geometry), ST_Y(wkb_geometry)
  from us_cities where name like 'San %' and state = 'CA';
 San Anselmo                                      | -122.561653137207 | 37.9746437072754
 San Rafael                                       | -122.531089782715 | 37.9735336303711
 San Quentin                                      | -122.487464904785 | 37.9412689208984

select name, state,
  floor(ST_Distance_Sphere(wkb_geometry, ST_GeomFromText('POINT(-122.4522 37.7555)'))) as distance_from_SF
  from us_cities where state='CA' order by distance_from_sf   limit 5;

                       name                       | state | distance_from_sf
--------------------------------------------------+-------+------------------
 San Francisco                                    | CA    |             3602
 Daly City                                        | CA    |             5596
 Broadmoor                                        | CA    |             8207
 Colma                                            | CA    |             8767
 Brisbane                                         | CA    |             9495


select county from us_counties where
  ST_Contains(wkb_geometry, ST_GeomFromText('POINT(-122.4522 37.7555)'));

shows which county contains an arbitrary lat/lon
select county, ST_Area(wkb_geometry) as area from us_counties where state = 'CA'  order by area desc limit 5;
county                       |       area
----------------------------------------------------+------------------
San Bernardino County                              | 5.13534296766738
Inyo County                                        | 2.66716021408502
Kern County                                        | 2.09407653001836
Riverside County                                   | 1.84319135357509
Siskiyou County                                    | 1.77534424474288
select county, ST_Area(wkb_geometry) as area from us_counties where state = 'CA'  order by area desc limit 5;
county                       |       area
----------------------------------------------------+------------------
San Bernardino County                              | 5.13534296766738
Inyo County                                        | 2.66716021408502
Kern County                                        | 2.09407653001836
Riverside County                                   | 1.84319135357509
Siskiyou County                                    | 1.77534424474288

Nelson’s Log

This is a personal journal of some hacking work I’m doing. While public, the only audience I’m writing for is myself.