Monday, November 12, 2012

Android accelerometer sampling rates

An app I'm working on relies on quick spikes in accelerometer activity, like fractions of a second, so I have to have a pretty fast accelerometer. Android lets you specify accelerometer sampling rate, kind of: you can choose SENSOR_DELAY_NORMAL, SENSOR_DELAY_UI, SENSOR_DELAY_GAME, or SENSOR_DELAY_FASTEST. Then the phone will try to give you samples at a rate that works for your app.

On NORMAL, my Nexus S gives me about 7Hz. Not at all fast enough. On UI, GAME, or FASTEST, I get about 49Hz, which is almost fast enough. So I gave some friends a little test app which determined their phone's FASTEST sample rate and here's what I found (readings in Hz):

Motorola Droid X: 5.19
Motorola Droid X2: 6.23
ZTE Blade: 9.11
HTC Nexus One: 24.86
HTC Evo 4G: 37.54
HTC Wildfire: 38.40*
HTC Desire: 47.27*
LG Nexus S: 49.44
Samsung Galaxy S3: 93.98
Motorola Atrix: 94.32
Sony Ericsson x10 Mini: 94.77**
Samsung Galaxy S2: 96.03, 97.5
Samsung Galaxy Nexus: 99.8
Samsung Note II: 100.0
Samsung Galaxy S3: 100
Samsung Galaxy Teos: 109.42*
LG Nexus 4: 198

(* from this stack overflow post)
(** from this slideshow, slide 13)

Want to add a reading? Here's how:
1. Enable installation of apps from unknown sources (Settings -> Security -> Unknown Sources)
2. Download this app
3. Tap "start", wait 5 seconds, and post (in a comment) which phone you have and what reading you get.
Edit: thanks all for adding to this! If you're looking for some other phones, check out the comments below.

Sunday, May 20, 2012

vim: using the system clipboard

It annoyed me that I couldn't yank (copy) something in vim using y and then paste it in something else with ctrl-v, or vice versa. I found that the following line (linux, x11, vim 7.3), makes it just work:

:set clipboard=unnamedplus

What's going on here?
vim has "registers." Each register is like its own clipboard. You can choose your register with ". So for example:
"ayy
means "using the a register ("a), copy/yank the current line (yy)". But most of the registers only live within vim. Vim has two special registers though: * and +. On Windows and Mac, they are both the system clipboard. On X11 they are different and only the + is the system clipboard. So in vim on either system, you should be able to type:
"+yy
to copy the current line into the system clipboard, and then ctrl-v in a windowed application to paste it. Then the "set clipboard=unnamedplus" line just makes the + register the default one.

More info from vim tips here and here.

Side note: I think that by saying "system clipboard" I am being a little vague because there are actually three system clipboards in X11, but the ctrl-c ctrl-v one is the one I always want. I think this is called, amusingly, the CLIPBOARD clipboard. More here.

Another side note: on my older Macbook (OS X 10.6.8 Snow Leopard), I couldn't easily get Vim 7.3.74+ (where clipboard=unnamedplus is introduced). The MacVim version available is 7.3.53. However, as mentioned above, * and + are both the system clipboard on a Mac, so set clipboard=unnamed works. (be careful if using tmux.) You can check if unnamedplus is available, so my .vimrc now looks like:
if has('unnamedplus')

  set clipboard=unnamedplus
else
  set clipboard=unnamed
endif

Thursday, March 22, 2012

Nook Rooting and Mounting Drives in Unix

I got a Nook Simple Touch, because you can put Android on it and then use the Nook app, the Kindle app, or whatever pdf reader you want to read all of the ebooks, not just Amazon's or B&N's. To put Android on it, I used this guide. (this is for Nooks with firmware 1.1; here's the one for 1.0 or 1.0.1. Find your firmware version in Settings->Device Info->About Your Nook)

The process works as follows: download a disk image, put it onto a microSD card, put that card in the Nook, boot up the nook, and then do a bunch of things on the software to sign in to the Android Market and download apps. The tricky part for me was putting the image onto the SD card.

The command to put the image on the SDcard (where touchnooter-2-1-31.img is the name of the disk image file) is:
sudo dd if=touchnooter-2-1-31.img of=/dev/
The tricky part is that you have to replace "/dev/" with the name of your SD card. (this site clarifies: "where is your sdcard (for example /dev/sdc or /dev/mmcblk0, not the mount point of the sdcard or an existing partition like sdc1 or mmcblk0p1)." What does this mean?

If a volume (aka a partition of a drive) is "mounted", then it's got an alias in the big unix filesystem tree and you can access files on it. Usually, when you plug in an SD card or USB drive, the system mounts it automatically. You can just run the command "mount" to see what's already mounted; most of it didn't mean anything to me when I ran it, but at least I saw this:

/dev/sda1 on / type ext4 (rw,errors=remount-ro,commit=0)
which is my main hard drive's main partition, so that's interesting. You can also (in Ubuntu) use the "Disk Utility" to see what's mounted.

In Disk Utility, click on your card reader on the left, and you'll see in the top right "Drive" and in the bottom right "Volumes". Look for "Device:", which will tell you the name of the drive in the filesystem. For example, right now I've got a card in there that has one partition and a bunch of free space; the Drive is /dev/sdd and the Volumes are /dev/sdd1 (the existing partition) and /dev/sdd (the free space).

When you're running that sudo dd command above, you want to write to the drive, not a partition of that drive. I kept trying to dd the image to /dev/sdb1 (which was a partition of my SD card) instead of /dev/sdb (which represented the card itself). Once I wrote the file to /dev/sdb, it worked.

Note that playing around with dd is dangerous: if you accidentally write files to the wrong drive (like /dev/sda in my case), you can erase your hard drive. So make sure (via Disk Utility) that you're writing to the SD card.

Outstanding questions in my mind:
- what's the command-line tool that will tell me the same things that Disk Utility tells me?
- what is "/dev/sdb" and how does it get there? I guess it's just an identifier that refers to my SD card when I put it in, but why /dev/sdb? And what is it, is it a file descriptor or what? I think /etc/fstab and /etc/mtab are involved, but I'm not sure how; and who puts those two files there?
- is "unmounting" exactly the same as "ejecting" your SD card/USB drive?
- what does dd do that just moving the disk image file to the SD card doesn't do? According to wikipedia, dd is just a lower-level way to move raw data. So it can... cause some file to be run when you boot or something?

Wednesday, August 17, 2011

Double-UTF

I've stored a bit of a snapshot of all the music I've liked by picking one song per album and putting them into a seasonal playlist on itunes. So I've got "2006 Spring", for example, which has about a dozen songs I liked to listen to in spring 2006.

But I've just stored these in itunes. Not only does that mean they're locked within the Apple Empire, they're also vulnerable to me losing my hard drive. So I wanted to get them into real text files. Luckily, itunes lets you export playlists. Unluckily, it's in some bizarre janky format, when I really just want to extract the artist, title, and album for each song. Simple python script to the rescue.

Ah, but even after deleting some of the crud, I was left with a file in a mash of file formats! See, I had pulled out artist, title, and album, then concatenated them with commas, then written that to a file. But I hadn't paid attention to encodings, so I had some UTF-16 characters, then some UTF-8 commas, then more UTF-16 characters. But Python has an easy answer: just read in the one file as UTF-16, specify that your output file is UTF-8, and within your script deal with strings and don't worry about encodings.

Tim Bray explains UTF-8, UTF-16, and UTF-32 clearly; this is something I probably should have thoroughly understood a while ago.
Evan Jones has a nice overview of how to use unicode in Python.

And here's my script:


#!/usr/bin/env python
import codecs


for filename in open("filenames.txt"): # next time I'll learn
                                       # syntax for "for filename
                                       # in current directory"
        filename = filename.strip()
        outfilename = "output/" + filename.replace(" ", "_")
        outfile = codecs.open(outfilename, "w", "utf-8")
        for bigline in codecs.open(filename, "r", "utf-16"):
                lines = bigline.split("\r")
                for line in lines:
                        parts = line.split("\t")
                        if len(parts) < 4:
                                continue
                        song = parts[0]
                        artist = parts[1]
                        album = parts[3]
                        linetowrite = "%s, %s, %s\n" % (artist, song, album)
                        outfile.write(linetowrite)

Wednesday, July 6, 2011

vim: search and replace like breathing

One great thing about vim is how you can search/replace with just a few keystrokes. Being able to search and replace at light speed makes you feel very wizardly. Here are some commands I've been using frequently to do so.

(Note that these are all regexes, and furthermore vim regexes, which differ slightly from other regex implementations, and I won't get into that.)

/foo(enter)
(just type this, in insert mode, and you're instantly at the next instance of "foo". Then hit "n" to go to the next instance of "foo".)

/foo\c(enter)
same as the above, but case insensitive. (I guess you could do :set ic first instead of the \c there, but I don't like doing things that leave state lying around if I don't have to)

:s/foo/bar/g(enter)
Replace all "foo"s with "bar" on this line only.

:%s/foo/bar/g(enter)
Replace all "foo"s with "bar" in the entire file.

:%s/foo/bar/gc(enter)
Replace all "foo"s with "bar in the whole file, but ask for confirmation at each one. I like this one a lot.

Wednesday, June 29, 2011

Tracking users via cookies

Disclaimer: this is a "work in progress" or a "I don't know if this is good" post.

I have a simple web app called Sea Salt that serves a javascript game. I'd like to keep track of users at a very low level- just track them across requests, and maybe track if they come to the site again the next day but that's not super important. I don't want to make them log in or anything.

And it has a splash screen. I want the following behavior:
- first time you come to /, you get "welcome to this app, click to start"
- if you click that, you go to /play and I create a User entry for you.
- if you come to / again, you get "you've already started. click here to continue OR if that wasn't you, click here to restart."
- if you restart, I create a new User entry for you.

Very simplified App Engine python server code:
application = webapp.WSGIApplication([('/', Intro),
                                      ('/restart', Restart),
                                      ('/play', Play), ...
Set up the URL mappings.

class Intro(webapp.RequestHandler):
    def get(self):
        cookie_id = self.request.cookies.get('sea_salt_id')
        if cookie_id and User.get_by_id(int(cookie_id)):
            #(render already_started.html)
        else:
            #(render index.html)
Pretty simple. If you go to /, first check the cookie. If your cookie corresponds to a real user, then you must have been here before. already_started.html contains links to /restart and /play. Otherwise, you haven't been here, so show you the splash screen, which has just a form that posts to /play.

class Restart(webapp.RequestHandler):
    def get(self):
        self.response.headers.add_header(
            'Set-Cookie',
            'sea_salt_id=-1; expires=Thu, 01-Jan-1970 00:00:01 GMT')
        self.redirect('/')

If you to go to /restart, delete your cookie, and send you back to /.

class Play(webapp.RequestHandler):
    def get(self):
        cookie_id = self.request.cookies.get('sea_salt_id')
        if not cookie_id or not User.get_by_id(int(cookie_id)):
            self.redirect('/')
        #(render game.html)

    def post(self):
        cookie_id = self.request.cookies.get('sea_salt_id')
        if not cookie_id or not User.get_by_id(int(cookie_id)):
            user = User.create()
            user.put()
            id = user.key().id()
            self.response.headers.add_header(
                'Set-Cookie',
                'sea_salt_id=%d; expires=Fri, 31-Dec-2020 23:59:59 GMT' % id)
        #(render game.html)

This is the trickiest. If you go to /play via a GET (like typing it in the address bar), either let you keep playing (if you've already started) or redirect you to /. If you go to /play via a POST, either let you keep playing (if you've already started) or create a user for you and then let you play. I think this is right, because GETs should be read-only while POSTs can write, right?

This all seems a little too complex for its own good, but it seems to work. If you have any better ideas (or if I've made any mistakes), I'd love to hear them. Thanks!

Wednesday, June 1, 2011

.vimrc: colorcolumn

80 character line? No problem!

" displays a red column at 80 characters
set colorcolumn=80

Thanks to this stack overflow post.

EDIT: you should probably surround it with an "if exists" to avoid annoyance if you port your .vimrc to another machine that has an older version of vim (colorcolumn is new in 7.3). Here's the syntax:


if exists('+colorcolumn')
  set colorcolumn=80
endif


Thanks to this answer on that same stack overflow post.