Archive for the ‘Technology’ Category

Building a custom case for a handmade TV-B-Gone

Saturday, April 27th, 2013

I had a chance to visit MakerBar the other night, and tried building my own TV-B-Gone, using MakerBar’s own upgraded design.

It was the first time I’d soldered anything for a real project, and until I’d completed and tested it, I wasn’t sure if it would actually work.

But it did, and a big part of the reason why is that Zack Freedman, the designer of MakerBar’s upgraded circuit, not only took the time to write a detailed set of instructions but also waited patiently with us as we went through the process, and provided help as we needed.

My own functional TV-B-Gone, which I built myself

My own functional TV-B-Gone, which I built myself

Since the double-sided tape which was meant to mount the board on top of the battery case didn’t quite work, and I also didn’t like how the board was exposed, I went looking for a case I could use.

Hello, green tea mints

Hello, green tea mints

A empty box of mints was the perfect size, and it was easy to take apart. I needed some filler material, so I used the styrofoam container from one of my computers.

Almost a perfect fit

Almost a perfect fit

I wanted to be able to continue to use the styrofoam for my computer, though, so to preserve the structural integrity of the container, I planned two cuts, roughly a third of the width of the middle element.

Planning to cut out the bottom right and upper left rectangles

Planning to cut out the bottom right and upper left rectangles

One cut-out done

One cut-out done

Just as I was about to cut out the second piece, I remembered the concept of "single-piece flow" from The Lean Startup, and I stopped to check my first cut-out in the mint box.

One is enough!

One is enough!

It turned out that was all I needed, so not only did I not waste time cutting the second piece, but also I was able to keep the styrofoam more intact than if I’d cut the second piece.

The circuit board on top, battery case below

The circuit board on top, battery case below

A sectional view

A sectional view

I still needed something to stick the board to the styrofoam, and so I tried some mounting squares I had left over from another project.

Next, came the hardest part: cutting holes in the lid to accomodate the LEDs and circuit components.

I planned on cutting off this rectangle entirely, but making the two slits was hard enough, so I stopped there

I planned on cutting off this rectangle entirely, but making the two slits was hard enough, so I stopped there

Cut-outs for the top of the lid

Cut-outs for the top of the lid

Close enough

Close enough

Cutting the top of the lid, which was mostly clear plastic instead of metal, was much easier, and eventually I was able to fit the whole thing together.

Closing the lid, with a little gentle persuasion from a pair of pliers

Closing the lid, with a little gentle persuasion from a pair of pliers

I finished it by applying electrical tape around the edge, to make sure the lid would stay closed.

The completed case mod, nice and snug

The completed case mod, nice and snug

It came out quite nicely, and having the battery case underneath, gives the whole thing a nice sense of heft and control.

A live action shot

A live action shot

Ubuntu Server + Fluxbox on Mac OSX using VirtualBox

Sunday, March 31st, 2013

I like Mac OSX as a general computing environment, but I prefer Debian (and more recently Ubuntu) for development.

Instead of running my Mac in dual-boot mode, I tried using VirtualBox to run Ubuntu Desktop.

Unfortunately, the virtual image was unusable: even at two gigabytes of memory (the most allowed by the vm) it was painfully slow, and using the dash was basically impossible.

But since my development environment consists mostly of ROXTerm and emacs, I wanted to see how Ubuntu Server plus a lightweight window manager such as Fluxbox would work instead.

Fluxbox running like a champ on Ubuntu Server in VirtualBox

Fluxbox running like a champ on Ubuntu Server in VirtualBox

It’s been terrific so far, and the setup was simple:

  1. After downloading the Ubuntu Server iso file, I created a new virtual image and used the iso as the base media
  2. Once installed, I followed the instructions for setting up Fluxbox without a login manager:
    sudo apt-get install xorg fluxbox fluxconf
  3. Then, I started Fluxbox for the first time:
    startx
  4. For the Guest Additions installation, I installed these packages first:
    apt-get install dkms build-essential linux-headers-generic

    And then requested the guest additions from the VirtualBox menu: Devices -> Install Guest Additions which “loads” the guest additions virtual disk. Under gnome or kde the disk gets mounted automatically, but in Fluxbox I had to mount it myself before running the install script:

    sudo mount /dev/dvd /media/cdrom
    cd /media/cdrom
    sudo sh ./VBoxLinuxAdditions.run

Using webcams in ubuntu: fixing the audio

Monday, March 25th, 2013

I recently tried using my laptop’s webcam to record video for the first time, but ran into a problem with the audio.

The ubuntu community help page says:

With recent versions of Ubuntu (>= 12.10) you should use avconv instead of ffmpeg command:

avconv -f oss -i /dev/dsp -f video4linux2 -s 320x240 -i /dev/video0 out.mpg

Unfortunately, that gave me this error:

[oss @ 0xd5dbc0] /dev/dsp: No such file or directory
/dev/dsp: Input/output error

It turns out that the /dev/dsp device is part of the obsolete OSS sound API, which has since been replaced by the ALSA API.

In fact, the OSS API was removed from the ubuntu kernel in 2010, so it’s surprising to see such outdated advice on the ubuntu help page.

Buried deep in the avconv manpage are notes about how to use alsa.

First, I had to find the recognized cards and devices, which I got by using these two commands respectively:

$ cat /proc/asound/cards
$ cat /proc/asound/devices

In my case the “CARD,DEV,SUBDEV” values which follow the “hw:” prefix were “0,0,0″ and so the avconv command which did work was:

avconv -f alsa -i hw:0,0,0 -f video4linux2 -s 320x240 -i /dev/video0 out.mpg

State machines in Go (#golang)

Sunday, February 10th, 2013

I’ve been rewriting critical server components that were originally written in Python to use Go instead. Unlike Python, which is interpreted and uses a global lock because the interpreter is not thread-safe, Go has built-in support for concurrency, and is statically compiled.

One of the first things I tackled was implementing a state machine. The Python version was based on this article by David Mertz.

Mertz uses an object oriented approach, defining a class with both data and methods. His code, syntax aside, will be familiar to anyone who has worked with objects in C++, C#, and Java.

Go, however, does not provide a mechanism for coupling methods to specific data structures. Instead, Go allows you to associate methods with data structures, so that any method can be applied to any struct.

It’s a model which is closer to what Alan Kay meant when he defined the term object oriented in the first place.

With that in mind, here’s how I originally wrote the state machine class as a Go struct:

type Machine struct {
    Handlers   map[string]func(interface{}) (string, interface{})
    StartState string
    EndStates  map[string]bool
}

Just as in Mertz’s definition, Handlers is a map whose keys are name strings, and whose values are functions which accept a “cargo” value, and return a next state name string, along with the updated cargo value.

Go treats functions as first-class objects, so storing and passing them from state to state works exactly as it does in Python.

The only change I made was in the end state list: whereas Mertz used a list of strings, I used a map, since there’s no fast equivalent of detecting presence in a list (in Go, the only way to do it would be to iterate through the entire list of strings until or unless a match is found).

Since the handler function signature is a little unwieldy, I created a user-defined function type for it:

type Handler func(interface{}) (string, interface{})

type Machine struct {
    Handlers   map[string]Handler
    StartState string
    EndStates  map[string]bool
}

All that leaves is the definition of the methods associated with the Machine struct.

The first two provide a way to define which handler function is associated with which name string, and which name strings constitute end states:

func (machine *Machine) AddState(handlerName string, handlerFn Handler) {
    machine.Handlers[handlerName] = handlerFn
}

func (machine *Machine) AddEndState(endState string) {
    machine.EndStates[endState] = true
}

It’s worth noting that since EndStates is a map (or a list, in Mertz’s original), it’s possible to have more than one state terminate processing.

The final method is the one which executes the state machine, by applying the appropriate handler function to the cargo value, stopping when an end state has been reached.

Since the set of functions are stored as first-class objects in a map, looking them up based on their names and invoking them is trivial:

func (machine *Machine) Execute(cargo interface{}) {
    if handler, present := machine.Handlers[machine.StartState]; present {
        for {
            nextState, nextCargo := handler(cargo)
            _, finished := machine.EndStates[nextState]
            if finished {
                break
            } else {
                handler, present = machine.Handlers[nextState]
                cargo = nextCargo
            }
        }
    }
}

The only possible fly in the ointment is Go’s strong typing, since the type of the cargo value in the handler function signature needs to be specified.

By using the generic interface{} as the type, however, all the handler functions need to do is invoke a type assertion on the incoming cargo value, and they can handle any data (the test example uses a float for the cargo, but it can be any data type, even user-defined structs).

The complete state machine is available as a Go package.

Simple Social Media “Share” Buttons

Tuesday, December 18th, 2012

I’ve recently included social media “share” buttons both here on this site, and at macaronics.com (whether or not they serve any useful purpose is another question entirely).

A problem with implementing them, though, is that each site wants you to include a boatload of javascript along with the button images, and you also have to set the button within an iframe or other weird DOM construct foreign to your page layout.

Getting each of the buttons to line up in a simple row is so tricky, in fact, that a bunch of third party services have cropped up to do the work for you.

But if you don’t care about having the current number of “likes” or “shares” displayed, there is a simpler way.

My technique is based on this approach by Steve Wortham and reddit’s method for using javascript within the link to identify the window.location and use that to build the share link dynamically.

For the button images, I used Fatcow’s Free Icons for Facebook, Twitter, LinkedIn, and Google Plus.

Reddit and Pinterest both provide button icons (though for Pinterest I had to download the png logo file and scale it down to the same size as the others).

Except for reddit, none of the sites offered hosting (without involving all the extraneous javascript includes I didn’t want in the first place), so I used Imgur.

You can see the results here:

A practical guide to selling ebooks online

Sunday, December 2nd, 2012

"What’s Next?"

Since this is a question I get a lot from users at eBookBurn.com and the stock FAQ answer usually leads to even more questions, I thought I’d summarize the details here.

This guide assumes you do not have a literary agent or publisher and are embarking on a self publishing journey.

It also describes the steps I went through in posting my own ebook, "Hurricane Sandy: The Diet" for sale (and of course, I would be remiss not to mention that it’s also available on iTunes and Barnes & Noble as well).

What you’ll need

Amazon

Amazon Kindle Direct Publishing (KDP) is by far the largest marketplace and exercises the least editorial interference.

That’s both good and bad.

On the plus side you can write about almost anything, and it has the potential to reach hundreds of thousands or more readers (Amazon has never disclosed how many Kindles it has sold).

On the other hand, there is a ton of literary flotsam and jetsam that normally would never have seen the light of day otherwise, and your book will be competing for attention in that mix.


The KDP “Add Book” form is simple, and getting a book listed for sale is fairly quick, usually within a day or so.

While at Amazon, go ahead and create an affiliate account so that you can take an additional share of the sale if a buyer gets it by following a link from your web site, blog, twitter feed, etc.

If you’re unfamiliar with how affiliate programs work, read the help on Amazon’s site or this more general article at Wikipedia.

Apple

Apple’s iBookstore, which is part of iTunes, makes your book available to iPad and iPhone users, as well as people using Mac desktop or laptop computers.

Apple has some prerequisites of its own:

  • Get an Apple ID if you don’t already have one
  • Download iTunes Producer (as of this writing, the latest version is here)

Unlike the other sites which let you upload your epub file from any web browser, you must use iTunes Producer to deliver your book to the iBookstore, and since there are no versions for Windows or Linux, you must have access to a Mac OSX computer.

Apple is notoriously slow and capricious in its review process, and has been known to reject books for no good reason.2


One the plus side, the content in the iBookstore tends to be of better quality, and you can charge more for it.

Barnes & Noble

PubIt is Barnes & Nobles’ answer to Amazon’s KDP.

It seems the smallest of the three marketplaces, though it’s difficult to be sure: like Amazon, B&N has declined to say how many Nooks have been sold.

Functionally it is similar to KDP, and they too have an affiliate program (though it’s invite only, and it’s not clear if it’s worth the trouble at this point).

They are a little more complicated, though, in that immediately after creating an account they may send an email asking you to call them and verify information you provided through the web form with one of their employees.

That verification takes a few days, but once you are cleared, adding and editing books through its web form is easy, and changes take effect within one or two days.

Other ebook marketplaces

There are several of them out there, but none merit any attention.


The typical iPad, Kindle or Nook user is not going to look outside the built-in store for content, and the few technically-savvy ebook nerds who do are going to want content for free.


1 I’ve never understood the value of an ISBN: it provides no intellectual property or legal protection, and with other, free or non-profit initiatives to classify books such as the Library of Congress and Open Library, there’s no good reason to spend money to get one. Fortunately, none of the three marketplaces require it (perhaps they tacitly agree with my sentiment, but are not in a position to say so out loud).

2 Apple’s over-zealous editorializing has opened them up to sarcastic protests, and occasionally they get stung.

How to extract just the text from html page articles

Saturday, October 27th, 2012

One of the reasons I keep going back to Python is because of the lxml library.

Not only is it terrific in terms of handling xml, it can do wonders with html of all flavors, even badly-formed and specification-invalid html data.

A common task I have these days is to grab the text from an html page or article (e.g., in curating content for Macaronics).

As this gist shows, lxml makes this dead simple, using xpath and the “descendant-or-self::” axis selector.

The only real work is understanding the page structure and creating the correct xpath expression for each site (the readability algorithm is essentially a collection of these rules), and monitoring their changes over time so that the xpath expression can be updated accordingly.

Another bonus is that it works with foreign language sites, too, provided the parser is passed the same encoding as defined in the target page’s Content-Type meta tag.

Here’s an example of grabbing the text from a web article by Facta, a Japanese business magazine, and saving it as a text file, so I can add it to the list of articles in Macaronics:

>>> import urllib, text_grabber
>>> data=urllib.urlopen('http://facta.co.jp/article/201211043-print.html').read()
>>> t=text_grabber.facta_print(data)
>>> import codecs
>>> f=codecs.open('facta-201211043-print.txt', 'w', 'utf-8'); f.write(t); f.close()

Go (#golang) and MongoDB using mgo

Sunday, October 14th, 2012

After working in node.js last year, I’ve switched to learning Go instead, and I wanted to reprise my "Node.js and MongoDB: A Simple Example" post in Go.

Of all the Go drivers available for mongoDB, mgo is the most advanced and well-maintained.

The example on the mgo main page is easy to understand:

  1. Create a struct which matches the BSON documents in the database collection you want to access
  2. Obtain a session using the Dial function, which creates a connection object
  3. Use the connection object to access a particular collection in your database:
    • Searches load documents from the database into the struct
    • Inserts and updates take data defined in a struct and create/update documents in the database

So for a collection named “Person”, where a typical document looks like this:

{
        "_id" : ObjectId("502fbbd6fec1300be858767e"),
        "lastName" : "Seba",
        "firstName" : "Jun",
        "inserted" : ISODate("2012-08-18T15:59:18.646Z")
}

The corresponding Go struct would be:

type Person struct {
    Id         bson.ObjectId   "_id,omitempty"
    FirstName  string          "firstName"
    MiddleName string          "middleName,omitempty"
    LastName   string          "lastName"
    Inserted   time.Time       "inserted"
}

It turns out the third field in each line, the string literal tag which is normally optional in a Go struct, is required here, because mgo won’t find those fields in the database otherwise.

It’s also possible to convert database results directly into json, which is useful for creating API services that output json.

In that case, it’s necessary to define both a bson tag and a json one, surrounded by backticks:

type Person struct {
    Id         bson.ObjectId   `bson:"_id,omitempty" json:"-"`
    FirstName  string          `bson:"firstName" json:"firstName"`
    MiddleName string          `bson:"middleName,omitempty" json:"middleName,omitempty"`
    LastName   string          `bson:"lastName" json:"lastName"`
    Inserted   time.Time       `bson:"inserted" json:"-"`
}

The json tag follows the conventions of the built-in Go json package: “-” means ignore, “omitempty” will exclude the field if its value is empty, etc.

So far so good.

But accessing different collections in a database means that for each one: it has its own struct defined, it has its own connection with the collection name specified, and an access function (Find, Insert, Remove, etc.) which marshals/unmarshals those results.

And the last step in particular can lead to a lot of code repetition.

Inspired by Alexander Luya’s post on mgo-users, I’ve created a framework that allows for multiple access functions with a minimum of repetiton.

First, this function, which creates or clones the call to Dial() as needed (this is very similar to what Alex posted):

var (
    mgoSession     *mgo.Session
    databaseName = "myDB"
)

func getSession () *mgo.Session {
    if mgoSession == nil {
        var err error
        mgoSession, err = mgo.Dial("localhost")
        if err != nil {
             panic(err) // no, not really
        }
    }
    return mgoSession.Clone()
}

Next, a higher-order function which takes a collection name and an access function prepared to act on that collection:

func withCollection(collection string, s func(*mgo.Collection) error) error {
    session := getSession()
    defer session.Close()
    c := session.DB(databaseName).C(collection)
    return s(c)
}

The withCollection() function takes the name of the collection, along with a function that expects the connection object to that collection, and can execute access functions on it.

Here’s how the “Person” collection can be searched, using the withCollection() function:

func SearchPerson (q interface{}, skip int, limit int) (searchResults []Person, searchErr string) {
    searchErr     = ""
    searchResults = []Person{}
    query := func(c *mgo.Collection) error {
        fn := c.Find(q).Skip(skip).Limit(limit).All(&searchResults)
        if limit < 0 {
            fn = c.Find(q).Skip(skip).All(&searchResults)
        }
        return fn
    }
    search := func() error {
        return withCollection("person", query)
    }
    err := search()
    if err != nil {
        searchErr = "Database Error"
    }
    return
}

The skip and limit parameters are optional in that if skip is set to zero, it is effectively asking for all the results, and, similarly, if limit is set to an integer less than zero, it is ignored in the query that gets invoked inside the withCollection() function.

So with that framework in place, making a variety of different queries on the "Person" collection reduces to writing simple (often one-line) BSON queries, as in the following examples.

(1) Get all people whose last name beings with a particular string:

func GetPersonByLastName (lastName string, skip int, limit int) (searchResults []Person, searchErr string) {
    searchResults, searchErr = SearchPerson(bson.M{"lastName": bson.RegEx{"^"+lastName, "i"}}, skip, limit)
    return
}

(2) Get all people whose last name is exactly the given string:

func GetPersonByExactLastName (lastName string, skip int, limit int) (searchResults []Person, searchErr string) {
    searchResults, searchErr = SearchPerson(bson.M{"lastName": lastName}, skip, limit)
    return
}

(3) Find people whose first and last names being with the particular strings:

func GetPersonByFullName (lastName string, firstName string, skip int, limit int) (searchResults []Person, searchErr string) {
    searchResults, searchErr = SearchPerson(bson.M{
        "lastName": bson.RegEx{"^"+lastName, "i"},
        "firstName": bson.RegEx{"^"+firstName, "i"}}, skip, limit)
    return
}

(4) Find people whose first and last names match with first and last names exactly:

func GetPersonByExactFullName (lastName string, firstName string, skip int, limit int) (searchResults []Person, searchErr string) {
    searchResults, searchErr = SearchPerson(bson.M{"lastName": lastName, "firstName": firstName}, skip, limit)
    return
}

et. cetera.

As far as code repetition goes, however, this framework is not that efficient in that each collection requires its own Search[Collection]() function, where the only difference among the different functions is the type of the searchResults variable.

It would be tempting to write something like this:

func Search (collectionName string, q interface{}, skip int, limit int) (searchResults []interface{}, searchErr string) {
    searchErr = ""
    query := func(c *mgo.Collection) error {
        fn := c.Find(q).Skip(skip).Limit(limit).All(&searchResults)
        if limit < 0 {
            fn = c.Find(q).Skip(skip).All(&searchResults)
        }
        return fn
    }
    search := func() error {
        return withCollection(collectionName, query)
    }
    err := search()
    if err != nil {
        searchErr = "Database Error"
    }
    return
}

Except this is where Go's strong typing gets in the way: "there's no magic that would turn an interface{} into a Person", and so each Search[Collection]() function has to be written separately.

The right way to use setInterval() and setTimeout() in Javascript

Saturday, July 14th, 2012

Most of the tutorials and examples for using setInterval() and setTimeout() describe the first parameter (which represents the function to execute) as a string, like this,

setTimeout("count()",1000);

Even the normally reliable O’Reilly men do it this way, too. Stephen Chapman is one of the few who gets it right.

While this technique works, it has two problems.

First, if the function you want to pass has parameters of its own, escaping and formatting them into a string properly is a mess, even in a simple example like this one,

setTimeout('window.alert(\'Hello!\')', 2000);

and it can get even more complicated.

Second, this technique uses eval() to execute the function, which is evil, and to be avoided.1

Using a javascript closure is a better approach:

setTimeout(function () {
    // do some stuff here
  }, 1000);

This makes sending parameters to the underlying function easy,

setTimeout(function (a, b, c) {
    // do some stuff here
  }, 1000);

and it avoids using eval() entirely.

[1] While not exactly related, there’s more in this vein at the hilarious (the (axis-of (eval))) blog, which I found on news.lispnyc.org recently.

Goodbye Java

Sunday, July 1st, 2012

It has been several years since I touched any Java code, and since it’s unlikely that I’ll work in the new Cobol again, I donated all my ancient reference volumes to the local used bookstore today.