Tags

cellphones 3g carrboro closure code content csv gastronomonomy molecular jquery mobile music cowon !ipod olpc laptop OSGi records REST sling spreadsheet vendorprisey xml

Recent Comments

wellbutrin cr alprazolam without prescription vicodin es 7.5 ativan canada ativan prescribing azithromycin 3 day norco online vicodin 15 mg azithromycin capsule azithromycin purchase vicodin 3598 acyclovir pill acyclovir generic name 10mg vicodin ativan without prescription buy alprazolam alprazolam 027 acyclovir 800 propecia hair loss treatment amoxil 12h vicodin cod vicodin es purchase vicodin vicodin yellow glucophage price vicodin street vicodin 35 96 metformin 1000 mg order propecia vicodin capsule acyclovir in india alprazolam from mexico purchase propecia vicodin no script vicodin 5 mg imitrex 60 mg vicodin substitutes india vicodin propecia tablets vicodin manufacturer purchase ativan alprazolam 25 mg generic ativan glucophage tablet cipro prices imitrex $25 wellbutrin 150 mg propecia australia metformin mg vicodin without a prescription azithromycin 5 day dose pack accupril 20 vicoden vicodin street prices amoxil over the counter canada vicodin amoxil 500 imitrex 25 mg acyclovir 450 metformin medication vicodin street name vicodin pdr metformin 5 500 advil and vicodin vicodin snorting acyclovir india alprazolam cost azithromycin 2 g acyclovir 2 azithromycin 1 g vicodin no rx propecia no prescription vicodin 660 azithromycin tablets 500mg vicodin prescription vicodin 10 660 codeine vs vicodin azithromycin uk cheapest accupril online m357 vicodin glucophage 2 azithromycin 600mg vicodin 7.5 500 ativan no rx drugs acyclovir vicodin online pharmacy acyclovir n943 vicodin no membership acyclovir 500 alprazolam online azithromycin for sale accupril 10 ativan pharmacy propecia mexico imitrex 100 mg amoxil 1 imitrex mg alprazolam tablets metformin 2000 vicodin online amoxil prescribing acyclovir 20 mg cheap metformin propicia acyclovir no prescription glucophage 750 mg vicodin mg glucophage xr 500mg vicodin and tylenol accupril medication 750 vicodin vicidin order accupril ativan generic name vicodin 5114 vicodin pill vicodin per pill wellbutrin 100 mg glucophage mg vicodin 567 amoxil 3 accupril 10 mg medicine vicodin ativan ld50 imitrex 100 online imitrex ativan online prescription propecia hair loss medication vicodin canada 3596 vicodin wellbutrin diet pills propecia india alprazolam 3mg propecia online prescription ativan medicine vicodin costs cheap accupril vicodin cr generic of glucophage vicodin 5 500 mg glucophage 100 vicodin prices amoxil capsules vicodin 10 m365 vicodin vicodin how much alprazolam discount cost of metformin vicodin 3601 vicodin 2355 imitrex picture buy amoxil online generic wellbutrin alprazolam uk metformin hcl 1000 prescription metformin attivan propecia generic alprazolam 1 mg accupril 20 mg acyclovir price vicodin treatment pharmacy vicodin imitrex medicine propecia pharmacy overnight vicodin accupril online metformin 100 mg discount imitrex wellbutrin 50 mg glucophage 1 vicodin purchase alprozalam alprazolam 2 mg alprazolam ld50 vicodin ip 111 vicodin es 7.5-750 vicodin generic pills amoxil wellbutrin no prescription vicodin m362 vicodin vs norco metformin 250 glucophage 500mg brand name for acyclovir accupril cost imitrex pill yellow alprazolam vicodin m365 ativan 10 mg propecia canada propeica azithromycin generic vicodin watson 349 wellbutrin purchase buy vicodin imitrex 5 metformin cost vicodin from mexico glucophage 875 alprazolam 20 mg metformin pills ativan 5mg azithromycin prescription vicodin 349 acyclovir 5 times buy acyclovir online wellbutrin price imitrex cost vicodin description cipro 500 glucophage tablets azithromycin 200mg buy vicodin online metformin 1 gram acyclovir sale vikodin glucophage 1000 order vicodin no prescription imitrex for sale alprazolam for sale ativan 25 mg vicodin online order propecia best price ativan online no prescription vicodin ld50 pictures of metformin vicodin overnight azithromycin 100mg acyclovir 100 mg vicodin es tablet vicodin pill picture alprazolam no prescription metformin 1 g 3601 vicodin generic for glucophage m366 vicodin amoxil 500g vicodin for sale glucophage 850 mg side effect cheap propecia alprazolam next day vicodin how it works alprazolam 15 mg acyclovir costs glucophage 750 glucophage 10 amoxil without prescription accupril 20mg glucophage 100 mg vicodin mail order discount acyclovir cheap vicodin accupril tablet azithromycin 5 day dose vicodin flexeril vicodin watson 385 metformin price vicodin 3592 7.5 vicodin vicodin online prescription amoxil capsules buy vicodin 800 generic for accupril accupril prices generic cipro propecia pricing vicodin 10 325 vicodin m366 vicodin 3600 acyclovir prices imitrex 4 mg ativan 1 mg ativan 0.5 mg accupril canada acyclovir pictures imitrex 15 generic vicodin es vicodin m367 vicodin 5-500 propecia medication metformin pill buy vicodin cod vicodin 1000 cipro 500 mg metformin 15 500 glucophage 2500 mg purchase accupril alpraazolam propecia 0.5 mg metformin pictures vicodin overseas cipro 200 mg wellbutrin sr acyclovir 500 mg vicodin tabs wellbutrin online azithromycin 2g accupril 10mg alprazolam cheap overnight amoxil 2

Flickr

Best Snack EverPagoda @ Duke GardensBacklit RoseAutumnal Dog Walk

On Bankers

Here’s some unsolicited advice for performing long-distance one-off transactions with financial institutions: if your transaction is at all unusual and requires that documentation of some sort or another be passed around and notarized and suchlike — get the procedure documented.  That person  you’re talking to on the phone, unless you’re really lucky, doesn’t know that the dark, cold hands of Institutional Policy are poised to strangle any vestiges of trust you have in corporate behavior if you follow the seemingly simple procedure.  The bureaucracy always wants a Very Serious Document prepared, and it’s quite easy to blow you off, because what are you but some disembodied, highly compressed voice coming out over a Very Small Speaker?

Of course, if banks weren’t somewhat risk averse, we wouldn’t put our money into them.  Know, however, that the risk aversion is about you (the customer) not so much or not at all, and almost entirely about the Organization.  And the rules and regulations governing this stuff are Very Complex indeed, and typically aren’t the sorts of things that are known by the type of employee who has to (eurk!) take phone calls from the public. If they knew that, they’d be too busy in meetings deciding what the next set of rules are to take the time to deal with your piddly little problems.

The beauty of this whole setup is that it takes no active or deliberate malice on any individual’s part, and you, dear friend, will have to seek and pay for the advice of a lawyer.  Ain’t modern life grand?  Philly Joe Remarkable is not the only one looking on in disbelief.

On Nostalgia

There’s a whiff of wistfulness out there on the ‘tubes for the passing of Sun Microsystems, and I’ve got to admit I’ve participated a bit in that; the absorption by Oracle of Sun’s assets certainly marks some kind of transition in the industry that helps me pay my bills, call it ‘maturity’ or ‘loss of innocence’, or “oh no, we’re all doomed!”

On the other hand, I was clearing out some gunk in my attic this evening, and I came across a pretty hefty printout that details how to write a very simple custom component for Java Server Faces 1.0; it clocks in at around 15 pages or so. And then, you know, maybe I’m not so surprised at what happened to Sun.

And then it hits me that what’s swallowing Sun is Oracle. And then I’m surprised again.

File under “Vendorprisey”

The Third G Drops

I’ve been thinking of it as effectively a rumour up until now, but today, my Android phone started getting a 3G signal in Chapel Hill and Carrboro (that’s T-Mobile, in case you didn’t know). So, now I go from having been a double early-adopter sucker (64Kbits/s and the first generation phone) to a reasonably fast-browsin’ (750-880Kbits/s) early-adopter sucker.

It’s progress, I guess. I understand that it’s possible to write applications for these things. If only I knew how to use a computer.

In Which I Become a Food Blogger

Some time ago, a friend pointed me to this magical stuff that turns fats into powders. T’other day, I finally got my hands on some of this tapioca maltodextrin, as it’s called; it’s a starch, and there’s really not much more to turning a really fatty thing into a powder than mixing the two things together.

The starch is close enough to flavourless, but any statements you may have encountered to the effect that you put the powdered (olive oil/peanut butter/hazelnut-and-chocolate-spread) into your mouth and voilà! it’s the original stuff again! are not really operative. There’s a noticeable effect on the texture, and you’ve got a bunch of starch that wasn’t there before.

Still, it’s amazing to work with and it’s truly a surprise for your taste buds.

Generating CSV from XML

I was helping a friend out recently who wanted to import some XML data he got into a more useful format [ ed. WHAT? err, useful to him, 'kay?].  It seems like there are a few services out there that will give you data in some kind of home-grown XML format in a record-oriented structure, e.g.

<contacts>
    <contact>
        <id>...</id>
        <name>....</name>
        <email>...</email
    </contact>
    ... <!-- more contact elements -->
</contacts>

When you have data like this, what you’ve got is essentially a degenerate spreadsheet, easily represented as CSV.  But if the service doesn’t provide CSV export, you can get it fairly easily via XSLT.  The idea is, you want to output one row (the header) with the names of the elements in each record, and then output each row thereafter.  What matters, as far as the input, is that it has the structure mentioned above: the document consists of a root element with a number of child elements, each one of which represents a record in the data. Note that the following restriction applies: each record element must contain the same number of child elements in the same order. In order to make it a little more robust, I added some logic to quote non-numeric values, which should provide a reasonable amount of protection from values that contain commas.   For extra fun (and this was my friend’s idea, and I was too lazy to follow through the steps) you could register this XSLT as a filter in OpenOffice.org so you can (nearly) automatically import these files into oocalc. It’s not entirely elegant (the logic for outputting the header row is duplicated with the logic for outputting a normal row), but it gets the job done. So here it is, I place it in the public domain.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text"
    encoding="iso-8859-1"/>

    <xsl:template match="/">
        <xsl:variable name="records" select="*/*"/>
        <xsl:call-template name="header-row">
            <xsl:with-param name="header" select="$records[1]"/>
        </xsl:call-template>
        <xsl:for-each select="*/*">
            <xsl:call-template name="output-row"/>
        </xsl:for-each>
    </xsl:template>

    <xsl:template name="output-row">
        <xsl:for-each select="child::*">
            <xsl:variable name="numeric" select="not(string(number(.)) = 'NaN')"/>
            <xsl:choose>
                <xsl:when test="$numeric">
                    <xsl:value-of select="normalize-space(.)"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:text>"</xsl:text>
                    <xsl:value-of select="normalize-space(.)"/>
                    <xsl:text>"</xsl:text>
                </xsl:otherwise>
            </xsl:choose>

        <xsl:choose>
            <xsl:when test="position() = last()">
                <xsl:text>&#13;&#10;</xsl:text>
            </xsl:when>
            <xsl:otherwise>
            <xsl:text>,</xsl:text>
            </xsl:otherwise>
        </xsl:choose>
        </xsl:for-each>
    </xsl:template>

    <xsl:template name="header-row">
        <xsl:param name="header"/>
        <xsl:for-each select="$header/*">
            <xsl:call-template name="quotevalue"/>
        </xsl:for-each>
    </xsl:template>

    <xsl:template name="quotevalue">
        <xsl:text>"</xsl:text>
        <xsl:value-of select="normalize-space(name(.))"/>
        <xsl:text>"</xsl:text>
        <xsl:choose>
            <xsl:when test="position() != last()">
                <xsl:text>,</xsl:text>
            </xsl:when>
            <xsl:otherwise>
                <xsl:text>&#13;&#10;</xsl:text>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

A Few Minutes With Apache Sling

Apache Sling is almost painfully hip, in a way only a dedicated nerd could appreciate (or, ok, believe) — it provides a RESTful frontend to a Java Content Repository, and the whole thing is based on OSGi. Roughly, it gives you a content repository with customizable processing and presentation for different types of content, and the only ‘driver’ you need is a library that truly understands HTTP.

As part of evaluating it for the day job, I put together an s5 presentation with that other reST, and the result is Apache Sling Overview. I also dug into the codebase to figure out a bit more about Sling’s default POST processing servlet. I do hope I didn’t say too many materially false things.

Straight Outta Victoria

UVic’s Electronic Textual Cultures Lab encodes a song by some music guy in the Text Encoding Initiative XML format. There is, of course, a video.

What I want to know is, does this mean XML is cool or hopelessly pass&eacute;?  Discuss.

Goings On About Town

So, there’s this small office in downtown Chapel Hill that used to have a paper “Google” banner in the window.  Today, on a trip past the Cosmic Cantina, I noticed that the window now has a more permanent logo for Android. I’ll admit that the basic idea behind Android – a generally open cellphone platform mostly developed by the ‘net’s largest advertising distribution network — is really appealing, given how disappointing the current situation in the US is (e.g. I can take a picture on my current phone, but I can’t transfer it off the phone without emailing it, which means I’d have to pay a fee; and, equally important is the fact that the applications installed on the phone … well, they suck).  If it takes off, it could open up a range of possibilities for “mobile computing,” and I seriously hope it pulls the rest of the industry along with it.  We have these pocket communicators and the dominant business model for them is oriented around ringtones, fer gosh sakes.  Hm, on second thought, I don’t see how a modular, extensible platform’s going to change that, but maybe it will let me ignore it somewhat, which is good enough.

But why’s there an “Android” office in downtown Chapel Hill?  One related development suggests itself …

Fun With Copyright Renewal Records

Based on an enormous amount of work by contributors to Project Gutenberg and the Distributed Proofreaders, combined with healthy sourcing of the US copyright office’s records, Google has compiled a a list of works originally copyrighted between 1923 and 1963 which have been renewed at some point, the upshot being that if a given work published in that time span is not on the list, it’s likely in the public domain.

One problem with the list that the database is a 370+ megabyte XML file, which is hard to load up in an XML-aware editor and even caused eXist to choke.  So I broke it up into chunks with a shortish Groovy script, for neat ingestion into an XML database.  The heart of the script is a SAX handler that basically churns each record in the XML file into a Groovy object, and a closure (there’s that word again!) that handles each record as it is constructed.  As written, the script simply breaks the big file into a bunch of files, one for each year (you will of course have to edit the paths).  By supplying a different closure, you could do all sorts of different things with the records, e.g. stuff them into a relational database.

In the spirit of the thing, the script is in the public domain — but I make no representations as to the quality, idiomaticity or overall efficiency of the script; despite being SAX-based, it still manages to chew up quite a bit of memory, so watch out.  Note that you will need Apache Commons Lang (say, version 2.4) on the classpath (e.g. in $HOME/.groovy/lib) for this script to work. Developed with Groovy 1.5.6.

I’ve tried to stop wordpress from ‘prettyfying’ the output, which appears to mangle quotes. I hope to have that fixed soon …

import org.xml.sax.helpers.DefaultHandler
import org.xml.sax.Attributes
import org.xml.sax.helpers.XMLReaderFactory
import org.xml.sax.InputSource

import org.apache.commons.lang.StringEscapeUtils
import org.xml.sax.Locator

/**
 * Represents an individual <Record> element
 * in the document.
 **/
class Record {
    def file

    def lines

    def recno

    def title

   def copyrightYear

    def copyrights = []

    def renewalYear

    def renewals = [] 

    // where it was published
    def published

    // rare!
    def note

    // source of the copyright info
    def source
    def snippet
    def md5sum

    // contributors, holders, and pseudonyms
    def people = []

    /**
     * Get the XML representing this element.  Note
     * that proper functioning here depends on how the
     * handler builds the elements.
     * @return a string containing this record's XML.
     */
    def xml() {
        def buf = new StringBuffer()
        buf << """
<Record>
    <Title>${title}</Title>
    <File>${file}</File>
    <Lines>${lines}</Lines>
    <MD5Sum>${md5sum}</MD5Sum>
"""
        if (snippet) {
            buf << "\t<Snippet>${snippet}</Snippet>\n"
        }
        if (note) {
            buf <<"\t<Note>${note}</Note>\n"
        }
        buf <<
"""
    <Source>${source}</Source>
    <CopyrightYear>${copyrightYear}</CopyrightYear>
    <RenewalYear>${renewalYear}</RenewalYear>
"""
        copyrights.each() {
            buf << it.xml()
        }
        renewals.each() {
            buf << it.xml()
        }
        people.each() {
                buf << it.xml()
        }
        buf << "</Record>\n"
        return buf.toString()
    }
}

/**
 * An inelegant class representing the elements that denote
 * people (copyright holders, contributors, aliases, etc.)
 **/
class Person {

    static ELEMENTS = ["Holder" :   [ "Name", "Type" ],
                        "Contrib" : [ "Name", "Role" ],
                        "Pseudonym" : [ "Pseudo", "Real" ],
                        "Neenym" : [ "Nee", "Now" ],
                        "Aka" : [ "Alias", "Real" ] ]

    static ROLES = ELEMENTS.keySet()

    def role

    def name

    def honorific

    def type

    def xml() {
        def firstElement = ELEMENTS[role][0]
        def secondElement = ELEMENTS[role][1]
        def buf = new StringBuffer()

        buf << """
<${role}>
    <${firstElement}>${name}</${firstElement}>
    <${secondElement}>$type</${secondElement}>"""
    if ( honorific ) {
        buf << "\t<Hon>${honorific}</Hon>\n"
        }
    buf << "</${role}>\n"
    return buf.toString()
    }
}

/**
 * Represents copyright and renewal date elements.
 */
class RecordDate {

	static ELEMENTS = ["Copyright", "Renewal"]

    def role
    def date
    def id
    def xml() {
        return """<${role}>
    <Date>${date}</Date>
    <Id>${id}</Id>
</${role}>"""
    }
}

/**
 * SAX handler that turns each <code>Record</code> element
 * into a <code>Record</code> domain object.
 **/
class RecordHandler extends DefaultHandler {

    /**
     * Stack of strings that represents the current
     * element context.
     **/
    Stack context = new Stack()

    /**
     * the current record being built.
     **/
    Record currentRec

    /**
     * the current Person element being built.
     **/
    Person currentPerson

    /**
     * The current date information being collected.
     **/
    RecordDate currentRecDate

    /**
     * A closure which will be called as each record is
     * read in.
     **/
    def recordListener

    /**
     * a buffer to collect the current text, since SAX might
     * not report all contiguous chunks of text at once.
     **/
    StringBuilder currentText = new StringBuilder()

    def locator

    @Override
    public void setDocumentLocator(Locator locator)
    {    println "Got a locator: ${locator}"
        this.locator = locator
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes atts)
    {
        context << localName
        switch( localName ) {
            case "Record":
                currentRec = new Record()
                break
            case Person.ROLES:
                currentPerson = new Person()
                currentPerson.role = localName
                break
            case RecordDate.ELEMENTS:
                currentRecDate = new RecordDate()
                currentRecDate.role = localName
                break
        }
    }

    @Override
    public void characters(char [] ch, int start, int len)
    {
        currentText.append(ch,start,len)
    }

    @Override
    public void endElement(String uri, String localName, String qName)
    {
        String txt = StringEscapeUtils.escapeXml(currentText.toString().trim())
        switch(localName) {
            case Person.ROLES:
                currentRec.people << currentPerson
                break
            case ["Type", "Role", "Real", "Now"]:
                currentPerson.type = txt
                break
            case ["Name", "Pseudo", "Nee", "Alias"]:
                currentPerson.name = txt
                break
            case "Hon":
                currentPerson.honorific = txt
               break;
            case "CopyrightYear":
                currentRec.copyrightYear = Integer.parseInt(txt)
                break
            case "Date":
                currentRecDate.date = txt
                break
            case "Id":
                currentRecDate.id = txt
                break
            case "Copyright":
                currentRec.copyrights <<currentRecDate
                break
            case "RenewalYear":
                currentRec.renewalYear = Integer.parseInt(txt)
                break
            case "Renewal":
                currentRec.renewals << currentRecDate
                break
            case "Recno":
                currentRec.recno = txt
                break
            case "Source":
                currentRec.source = txt
                break
            case "Lines":
                currentRec.lines = txt
                break
            case "MD5Sum":
                currentRec.md5sum = txt
                break
            case "File":
                currentRec.file = txt
                break
            case "Snippet":
                currentRec.snippet = txt
                break
            case "Title":
                currentRec.title = txt
                break
            case "Published":
                currentRec.published = txt
                break
            case "Record":
                recordListener(currentRec)
                break
            case "Note":
                currentRec.note = txt
                break
            case "CopyrightRenewalRecords":
                break
            default:
                println "Unrecognized element '${localName}' at line ${locator.lineNumber}"
                System.exit(1)
            }
        currentText.length = 0
    }

}

def file = new File("input-dir/google-renewals-20080624/google-renewals-20080624.xml")

/**
 * A listener that will output each record into a different stream depending
 * on the CopyrightYear of the record.
 **/
def listenerBase = { Map streams, Record it ->
    if ( !streams.containsKey(it.copyrightYear) ) {
        def f = new File("/output/dir/copyright-${it.copyrightYear}.xml")
        println "creating ${f.absolutePath}"
        def stream = f.newWriter()
        streams[it.copyrightYear] = stream
        stream.append("<CopyrightRenewalRecords>")
    }
    Writer s = (Writer)streams[it.copyrightYear]
    s.append(it.xml())
    s.flush()
}

def reader = XMLReaderFactory.createXMLReader()
def handler = new RecordHandler()
def outputStreams = [:]
handler.recordListener = listenerBase.curry(outputStreams)
reader.setContentHandler( handler )

try {
    reader.parse( new InputSource( file.newInputStream() ) )
} catch (Exception x) {
    x.printStackTrace()
    println "Error at line ${handler.locator.lineNumber}"
}

outputStreams.each() {
    k, BufferedOutputStream v ->
        println "Closing ${k}"
        v.append("</CopyrightRenewalRecords>")
        v.flush()
        v.close()
}

Adding Shift-select with jQuery

I’ve been using jQuery a bit here and there to add some (I hope) usability enhancements and for light AJAJ work. Today I encountered a situation where I thought adding the “shift-select” feature on a longish list of checkboxes would be a good thing. This sort of feature pops up in webmail interfaces, where you tick off one box, scroll down through 750 spam messages, and then, while holding down shift on the 751st piece of spam in a row, click its checkbox to select all of the rows in between. It turns out that adding this with jQuery is pretty elegant, so here’s the code. I don’t for a moment think this is the best implementation of this idea, but I was struck by how concise the result was, while supporting — via a straightforward use of a closure, multiple instances on the same page. For giggles, I added a feature that allows you to de-select a range, although I’m not convinced it works in an intuitive way.

To use this, you’ll need jQuery (tested against 1.2.3) in your page, and a CSS selector that matches the checkboxes you want to enable shift-select on. Then call $(selector).shiftSelect(); and you’re done.

 jQuery.fn.shiftSelect = function() {
    var checkboxes = this;
    var lastSelected;
    jQuery(this).click( function(event) {

        if ( !lastSelected ) {
            lastSelected = this;
            return;
        }

        if ( event.shiftKey ) {
            var selIndex = checkboxes.index(this);
            var lastIndex = checkboxes.index(lastSelected);
            /*
             * if you find the "select/unselect" behavior unseemly,
             * remove this assignment and replace 'checkValue'
             * with 'true' below.
             */
            var checkValue = lastSelected.checked;
            if ( selIndex == lastIndex ) {
                return true;
            }

            var end = Math.max(selIndex,lastIndex);
            var start = Math.min(selIndex,lastIndex);
            for(i=start;i<=end;i++) {
                checkboxes[i].checked = checkValue;
            }
        }
        lastSelected = this;
    });
}