Delicious Python

October 31, 2006

Organizing bookmarks is too hard. Does Backcountry Maps go under Maps or Backpacking? Does Hot Library Smut go under Libraries or Pornography? And how am I supposed to keep my bookmarks synched across 5 computers? I’m a busy guy, I don’t have time to figure this stuff out.

That’s why I’ve wanted to use del.icio.us for a long time. I was really excited when they announced their import tool. A few minutes later I was staring at 1000 poorly tagged bookmarks. Oops, should’ve cleaned them up before importing. After failing to find any way to batch process the mess, I dejectedly went back to my hierarchy.

I checked again today and there’s still no “Delete All” (the FAQ helpfully suggests canceling & remaking my account). Time to do it myself. I looked at the API docs (oh, I see, I’m not supposed to flood the server…) and grabbed pydelicious. Fired up ipython and had my bookmarks deleted in no time. Sharing all of my bookmarks turned out to be simple too: Since pydelicious doesn’t seem to understand private bookmarks [1] it shares everything. Changing my mind and deciding that I really should have tagged all my new bookmarks “import” (oops, again) was similarly easy. Hooray!

[1] It is unfortunate that the del.icio.us team doesn’t provide up-to-date libraries in a few languages. In a lot of ways I think that officially maintained libraries are an ideal answer to the SOAP vs. REST arguments


Tags:

Animated housing maps

August 30, 2006

http://www.housingmaps.com/ is basically Google maps + Craigslist. Cool use of Google maps. Since it lets you pick a price range, it is super easy to make animated maps, showing the distribution of both affordable and luxury housing. Here’s one of downtown San Jose:
animated housing map

and one further up the peninsula:
animated housing map


Tags:

steal the mouse back from SDL

August 22, 2006

I hate it when a poorly-behaved SDL app (usually mine) grabs the mouse, crashes, and doesn’t give the mouse back. Great, now I’m stuck in X with no mouse. Here’s a handy python script to get it back:

#!/usr/bin/env python
# get the mouse back after an SDL app crashes

import pygame
pygame.init()
pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
pygame.quit()


Backpacking at Noble Lake

August 3, 2006

Last weekend my brother, Yana, and myself went backpacking at Noble Lake. This was the 2nd time we’d gone up to the Ebbett’s pass area (last time we went to Spicer Reservoir). I really like the area, especially Lake Alpine. Lake Alpine is simply gorgeous, and probably worth the drive all in itself.

We hiked in Saturday and found a campsite on a hill above the main lake. It was windy during the evening, and rained a little bit so we moved camp to a lower, more sheltered spot. Sunday morning we decided we would try to climb Highland Peak before going home. We didn’t expect to make it before our self-imposed noon deadline but ended up making really good time. We followed the trail towards Bull Lake, but at the saddle turned left and climbed the ridge towards the peak, which unfortunately meant we had to climb up and over Peak 9741. Next time, I would cut straight to the saddle between Highland Peak and 9741.

From the 2nd saddle, there was a faint trail up the ridge to Peak 10824. Mostly class 2, with a little class 3 near the top. We ended up not going past Peak 10824. Highland Peak was probably another mile away, but only 100 feet higher, and it didn’t seem worth it. We ate lunch on top and then headed back down. There was enough loose rock near the top to run down in great sliding leaps. We made it back down to the lake by around 3 and headed home.


More Photos


You can’t steal WiFi

July 28, 2006

Every time the legality/morality of using open wireless comes up, we are treated to yet another uninformed debate. People get worked up that someone might be “stealing” WiFi by accessing it without authorization but the analogies they use to explain why this is wrong reveal a stunning ignorance about how WiFi works. [1]

These are all actual analogies I have seen used to argue that using WiFi without express permission is akin to stealing:

  • If you left your door unlocked, does that give me authorization to enter?
  • If you left your bicycle in the driveway, am I authorized to ride it?
  • If you don’t have a gate on your garden, am I authorized to wander around it?
  • If you leave a hose on, does that authorize me to drink the water?

Those analogies suck. WiFi is nothing like a door, or a garden, or a hose, or a bicycle. As a public service, let’s look at the basics of open WiFi:

  1. The router actively advertises the open connection
  2. The user’s computer asks to use the connection, and the router authorizes the request.

The conversation goes something like this:

Router: Hey, free Internet over here! Come and get it!
Computer: Hey, can I have a connection?
Router: Sure, here you go.

You want a good analogy for using open WiFI? Open WiFi is like using a web site. Do I have to call up Google and ask permission [2] before I do a search? No, because behind the scenes my computer is asking for me:

Computer: Hey google.com, can I have a list of pages about “tour de france?”
Google’s web server: Sure, here it is

My computer asks Google for a service, their server grants the request. That’s no different from using open WiFi: my computer asks your wireless router for a connection, and your router grants it. [3]

You still want to use a hose analogy? At least keep it accurate:
I stand on the corner with a hose yelling “Hey, free water! Come and get it!” A man walks up and asks “Can I have a drink?” I give him one. Did he steal the water?

You can’t steal WiFi.


[1] I only hope the people who finally decide on the legality of using open WiFi understand the technology. The recent “series of tubes” debacle doesn’t raise my confidence.

[2] At least I know who runs google.com. My computer sees 6 routers from my living room. If I wished to seek permission, which neighbors would I ask?

[3] Some argue that Google intends for their servers to be public, while ignorant owners of open WiFi do not. This is likely true, but the situation is really no different from if you posted a photo online without realizing it was publicly available. Would it be wrong for me to view the photo? No.


Tags:

XCode & Python Resources

July 13, 2006

Some resources for using XCode with Python. A few introductory sites plus the ones I find most useful on a day-to-day basis:


Tags:

XCode & Python Hints

July 13, 2006

Here are a few hints about how I set up XCode for Python development.

Run your program from XCode

Some versions of PyObjC have a bug so when you make new projects, XCode doesn’t know how to run them. Make a new custom executable & point it build/Development/myProgram.app.

No, don’t quit!

Having the keyboard shortcut to quit XCode be the same shortcut as quitting your application (cmd-Q) is a recipe for annoyance when you accidently hit it twice. Instead, go into XCode’s preferences and change the key binding to quit XCode to something like cmd-option-Q.

Faster builds

You can shave a second or two off the build-test-fix cycle if you set up a dummy “No Build” target. The Development build target will run every time but behind the scenes it isn’t copying files, it is just making aliases (py2app’s –alias option). Set up a new shell script target which runs /usr/bin/true and you can save the effort.

You have no debugger, but at least use PDB

If you set the USE_PDB environment variable, PyObjC will dump you at a PDB prompt when there is an unhandled exception. You can set this on the “Arguments” tab of the custom executable.


Tags:

XCode & Python

July 13, 2006

Introduction

XCode is the IDE that Apple ships with OS X. Although primarily targeted towards C++, Objective C, and Java it also plays well with Python. It is excellent for writing OS X applications in Python thanks to good integration with Apple’s Interface Builder and py2app (the OS X distutils packager).

If you want to write OSX applications using python, XCode is the tool you want. This is thanks to solid integration with Apple’s Cocoa application framework and Interface Builder.

Debugger

First, the bad news: no debugger. XCode has a debugger but it doesn’t work with Python. You’ll have to use another tool like PDB instead.

Environment

xcode.jpg

Except for the debugger, the rest of the environment is nice. The UI feels like a proper OSX app, with all the standard keyboard shortcuts and controls, so you’ll feel right at home.

The UI is very flexible, and can accommodate a single fullscreen window or multiple separate windows for each file.

Editor

editor.jpg

Standard features here. Syntax highlighting, split panes, menus to jump straight to a class or function. Content assist exists, but leaves something to be desired. I have yet to see a content assist for python that is able to keep up with the dynamic nature of Python classes, however.

Source Control

diff.jpg

XCode knows about Subversion, Perforce, and CVS. File comparisons are done using Apple’s File Merge tool so you get nice side-by-side views.

Finding Stuff

“Find in Project” lets you search your entire project. Bookmarks let you quickly jump to common sections of code

Making OSX Apps

XCode is a great environment for Cocoa development. PyObjC provides the Cocoa bindings for Python, and once it is installed XCode knows how to make a new Python project. The distutils setup.py script is handled for you and you can create your .app bundle by clicking Build

newproject.jpg

Drag-and-Drop your interface…

guides.jpg

Interface Builder lets you set up your widgets. Helpful guides pop up to help you position your widgets according to the Aqua guidelines.

…and then Drag-and-Connect your buttons

buttons.jpg

Hooking up buttons to actions in your Python objects is just a matter of ctrl-dragging from the button to the object.

Conclusion

If you want a Python IDE for your Mac, XCode is a good choice. If you also want to develop OSX applications in Python, XCode is a very good choice.


Tags:

Magnetic Sense

July 9, 2006

A month ago Wired ran a story about people implanting tiny magnets in their fingertips so they can feel magnetic fields. Suddenly they can sense AC current in electrical cords, electric motors, the fields given off by transformers, and anti-theft gates in stores. Very intriguing, but stories of infected fingers and broken magnet pieces embedded under the skin didn’t sound fun.

Today as I was cleaning junk off my desk I found a tiny magnet. This suggested an experiment: would simply gluing the magnet to my finger be enough for me to feel magnetic fields? Super glue seemed the obvious choice but after two dried-out tubes I had to settle for wood glue.

Surprisingly, it actually worked. I could feel the motors running inside my electric razor. I could sense the AC current in the cord for our toaster oven, and could feel when the oven’s thermostat clicked on & off. The strongest field I found was from the AC adapter for our handheld vacuum. I could feel it from several inches away. Very, very cool.

Update: Lots of question from diggers, so let’s get some answers up:

Why? Because the idea of feeling magnetic fields intrigued me. What? You’ve never wanted to sense invisible magnetic fields? Never been jealous of geese with their internal compasses? Probably one of those things where if you have to ask, you’ll never understand.

Did I rip off my skin? No. It was only wood glue for goodness sake. I could barely get to to stay on my finger. I was originally going to try super glue but I couldn’t find any (all my tubes of super glue were dried out…why does that always happen?). Super glue isn’t that bad, though. The worst outcome is that you have a stupid magnet stuck to your finger for a few days. (I’m not responsible if you use too much glue and hurt yourself, don’t be stupid).

What about damaging your TV/floppy disks/credit cards/hamster? Well, just don’t go near your TV or credit cards while you have it glued on your finger. And who uses floppy disks anymore? Just use a little common sense: if you wouldn’t do it with a magnet, don’t do it with a magnet which is glued on your finger.

Why not use tape/band aid/something else? I tried tape, it didn’t seem to work. I think the glue did a better job of transmitting vibrations to my skin

What did it feel like? It felt like the magnet was buzzing, like a cell phone on vibrate but weaker. Another way to describe it is as a slight tingling.


Tags:

Skiing at Carson Pass

May 23, 2006

We went skiing at Carson Pass on Saturday and found some nice corn below Elephant’s Back that worked well for practicing tele turns.

After the last time I went skiing, I posted some pictures to the telemarktips.com forums and asked for advice. Everyone said “shorter poles (so you can get lower)” and several people recommended reading Paul Parker’s Free Heel Skiing. I followed both bits of advice and it worked. I was able to link turns together this time, starting to get a feel for the flow between turns. It was awesome!

More photos


Tags:

Kenwood anti-theft security: only for show?

May 12, 2006

After I replaced our car battery a few weeks ago, the stereo asked for the security code. Supposedly this makes it worthless to thieves because they won’t know the code. Cool.

Except, I don’t know the code either. I must have forgotten to write it down. Oops.

Kenwood’s website tells me the dealer can reset it but the 3rd Google result for “kenwood 519 security code” tells me how to reset it myself. So, it turns out the radio is only worthless to thieves who don’t know how to use Google. You can go look up the details yourself. It basically involves entering KCAR using the stereo’s remote. But don’t tell anyone: it’s a secret.


Tags:

Super Happy Dev House

May 3, 2006

The new work

Attended my first Super Happy Dev House on Saturday night and had a great time. The house was packed with energetic people devoted to getting stuff done. Even though most of the people were strangers working on their own projects, it was really motivating to be surrounded by so much activity.

My project was getting boost.python working on my iBook. I wasn’t able to stay all night and didn’t reach my goal*, but I did learn about iPython from the people sitting next to me. Someone (not sure who) had designed a great poster for the event and they had printed up stickers & pins so there was even some schwag. I’m looking forward to the next one.

* My problem was I was trying to use the boost packages from fink. Turns out they delete a bunch of the files you need to use bjam. The answer? Download the source directly from boost.org (not sure why I didn’t think of that right away, actually). Mission accomplished.


Find new music: a song a day calendar

April 18, 2006

So, here we are 108 days into the year and if you haven’t found some new music this year, it is time you check out CC365. It is a song a day calendar featuring exclusively Creative Commons music. Grant Robertson is doing a great job picking a wide selection of tunes: Jazz, electronica, j-pop, hip-hop, country, you name it. And since the artists encourage you to share their music, they don’t find themselves in the awkward position of suing their fans, grandmothers, and 12-year-old girls or installing hacker’s tools on your computer.

Free Music Daily - Indieish.com


Tags:

Perplex City

April 18, 2006

Last month, TR bought a Perplex City starter kit for my wife and I. What a cool game! There are so many levels you can play at. You can solve puzzle cards by yourself. You can join up with others online and solve cards together (including some really hard cards requiring group efforts). The city itself has a lot of depth, with record companies, pharmaceutical companies, schools, blogs, and newspapers. Some of these “companies” run ads in London newspapers, and puzzles from the game have shown up in newspapers and magazines. Finally, you can hunt for the stolen cube and try to get the $200K reward.

Many of the puzzles make fun programming challenges. I’ve been doing them in python, since that is such a great language for rapid programming. Sweet Dreams (#85) makes an obvious candidate:

#!/usr/bin/env python

a = 1
b = 1
while a < 400000:
    c = a + b
    a = b
    b = c
    print c

My wife solved Rickety Old Bridge (#106) much faster than I was able to write the program (although the program found that there are two similar solutions, not just one). This was a good one to learn generators with:

#!/usr/bin/env python

class bridge:
    people = { "kurt":2, "scarlett":5, "violet":1, "sente":10 }
    states = [ {"near":people.keys(), "far":[], "moves":[]} ]

    def move(self, source, dest):
        """ yield all new states formed by moving
            a person from source -> dest """
        for state in self.states:
            for person in state[source]:
                yield {source:  [s for s in state[source] if s != person],
                       dest:    state[dest] + [person],
                       "moves": state["moves"] + [person] }

    def to_far(self):
        self.states = [s for s in self.move("near", "far")]

    def to_near(self):
        self.states = [s for s in self.move("far", "near")]

    def score(self, state):
        times = [self.people[name] for name in state["moves"]]
        total_time = max(times[0], times[1]) + times[2] + \\
                     max(times[3], times[4]) + times[5] + \\
                     max(times[6], times[7])
        return total_time, state["moves"]

    def print_scores(self):
        scores = [self.score(s) for s in self.states]
        scores.sort()
        scores.reverse()
        for s in scores:
            print s[0], s[1]

    def run(self):
        self.to_far()
        self.to_far()
        self.to_near()

        self.to_far()
        self.to_far()
        self.to_near()

        self.to_far()
        self.to_far()

        self.print_scores()

if __name__ == "__main__":
    b = bridge()
    b.run()

The program I came up with for solving Magic Square (98) takes a long time to run but eventually starts finding candidate solutions about 2.2 million squares into its search:

#!/usr/bin/env python

def comb(nums, n):
    if n == 0: yield [], nums
    else:
        for i in range(len(nums)):
            for tail, remaining in comb( nums[:i] + nums[i+1:], n-1):
                yield [nums[i]] + tail, remaining

def rows(nums):
    if not nums: yield []
    else:
        for row, remaining in comb(nums, 4):
            if sum(row) == 34:
                for other_rows in rows(remaining):
                    yield [row] + other_rows

def check(grid):
    magic = True
    for i in range(4):
        if sum([row[i] for row in grid]) != 34:
            magic = False
    if sum([grid[i][i] for i in range(4)]) != 34 or \\
       sum([grid[i][3-i] for i in range(4)]) != 34:
        magic = False
    return magic

count = 0
for grid in rows(range(1, 17)):
    count += 1
    if count % 100000 == 0:
        print count / 1000, "K"
    if check(grid):
        print grid

Throwing tops

April 2, 2006

18th century toys? Help me, Internet

Several years ago I got an old-fashioned wooden throwing top for Christmas. Unfortunately no one in my family knew what do with it. We couldn’t figure out how to get it to spin, so it went into the back of the closet. TR’s post about yo-yo videos finally made the light go on: The Internet knows…

Sure enough, there are sites with video tutorials showing how to throw tops.

I never would have figured it out on my own…you wrap the string around a different part of the top than I was trying, and you throw it upside down (it flips over in the air). This is the kind of thing that makes the Internet more valuable than a library to me. Sure, I probably could have researched these tops at a library and gotten an instructional video through interlibrary loan. But not in 15 minutes.


Tags:

Effort Threshold

April 2, 2006

I’ve noticed something: If frequent tasks take too much effort they don’t get done. Unless it is dirt simple, people procrastinate. It’s as if there is an effort threshold. Easy tasks slip under the threshold and get done. Involved tasks…well…maybe we can start on them tomorrow.

I’ve seen this happen with all sorts of things:

  • Running unit tests: If it takes more than a single command or button-press to run tests, developers will only run them once a project. If you’re lucky.
  • Committing code: if your check-in process has too much red-tape, developers avoid checking in. Result? You might as well not be using version control.
  • Paying bills with checks instead of online: Putting checks in envelopes? Maybe tomorrow.
  • Editing digital photos before posting them to Flickr: I still don’t have a smooth enough workflow so photos sit on my computer unprocessed for way too long.
  • Writing blog posts: And now we get to the real point of this post…

Posting to Blosxom took just a little too much effort. TR posted some articles back in November and December I wanted to respond to, but I haven’t gotten around to. Admittedly, this was partly my fault because my CoolURI scheme added a few extra steps to posting. I like Blosxom and it was great software for starting out but it was time for something with more features. So, I switched to WordPress. The out-of-box experience is great:

  • simple installation
  • web-based interface for posting
  • web-based configuration interface
  • Larger user base so plugins and themes are plentiful
  • comments
  • pages load a lot faster than before (again, my fault because my CoolURI plugins slowed Blosxom down)
  • tags (well, categories but you can use them like tags if you like)

So, let’s see if this allows blogging to slip under the effort threshold again…


Tags: