A Python question: adding to an empty hash

slaniel | Uncategorized | Friday, March 31st, 2006

In Perl, you can do nice efficient things like this:

$hashName{$keyName}++; 

which says, “add 1 to the value corresponding to the key $keyName, in the hash called $hashName.” In Python, as far as I can tell, you have to be a bit more verbose:

hashName = {} if hashName.has_key(keyName): hashName[keyName] += 1 else: hashName[keyName] = 1 

Come to think of it, this points out three little annoyances in Python, the others being

  1. The absence of a ++ operator; you have to use += 1 instead. Not a huge deal, but every other language you’d care to use nowadays has a ++ operator.

  2. Data structures have to be initialized before they can be used: you can’t just start adding key/value pairs to a nonexistent hash.

Anyway, does anyone know if there’s a shorter way to do the dictionary addition?

P.S.: While I’m at it, here’s another Python oddity that I will probably get used to eventually, but which puzzles me now: you can write statements like

list = [1,2,3] print max(list) 

and get back what you would expect — namely “3”. But if you do

list = [1,2,3] print "The largest item in the list is " + max(list) 

you will get an interpreter error: the “+” operator won’t let you concatenate variables of type string (“The largest item in the list is”) with those of type int (“max(list)”).

The print function knows how to coerce ints into strings; why can’t the “+” operator do the same? The C++ approach would be to overload the “<<” operator for whatever type you’re trying to print, so that you can do (relatively) clear things like so:

cout << "The largest item in the list is " << max(list); 

and get back what you’d expect.

Memoirs of a Geisha, the movie

slaniel | Uncategorized | Friday, March 31st, 2006

I’m glad — and very surprised — to see that the movie version of Memoirs of a Geisha evoked many of the same feelings in Roger Ebert that I felt about the book. The book was atrocious. (I wrote a review of it on Amazon.)

“Windows is so slow . . . ”

slaniel | Uncategorized | Wednesday, March 29th, 2006

Thus spake the New York Times. They didn’t go into much depth about it, as you would expect. Here’s my question: my sense is that the Windows kernel has hundreds of system calls built in, because Windows integrates graphical components very tightly with the rest of the system. Does this explain at least part of the slowness, and the loss of agility in designing the OS? UNIX-family kernels — including Mac OS X, Linux and others — have a very limited number of system calls, and all the graphical stuff is in a totally separate layer (the X Window System for most Unices, something different for OS X).

Also, UNIX-style OSes treat everything as a file. Sockets, printers, executable programs and raw text files are all handled with the same interface, if I understand correctly; all these objects have to implement a read method, a write method, and so forth. The kernel knows generically how to write a byte to a file; if it turns out that that file is a device node corresponding to a printer, the kernel doesn’t care. It’s up to the printer driver’s manufacturer to explain what “write a byte” means in the context of a printer (namely, “send that byte to a printer attached to a given IP address, with these formatting instructions attached”). This pushes the complexity down to the developers of device drivers and out of the OS itself. Whereas my sense is that Windows treats all these different objects — printers, sockets, etc. — as different objects, with different methods for each object.

If Windows is indeed getting hard to develop, could this be the reason?

Note, by the way, that X is an incredibly complicated beast; real-world computing environments are hard, so of course the complexity will need to leak out somewhere. So I’m not claiming that the combination of UNIX plus X plus all the other components necessary to keep a standard UNIX desktop going is less complex overall than Windows is. My question is just whether Windows might need to be refactored.

The New York Times on FISA hearings

slaniel | Uncategorized | Wednesday, March 29th, 2006

The Times only gives passing mention today to the subtext underlying the hearings over Arlen Specter’s bill to amend FISA and bring the government’s illegal surveillance program under its wing. The subtext is this: Specter’s bill would retroactively make President Bush’s warrantless wiretapping legal. See Marty Lederman’s thorough analysis of the bill, and his followup on former Associate Deputy Attorney General David Kris’s testimony. It, in turn, follows up on Kris’s memo to the Department of Justice on the Administration’s FISA violations. Point in all of this being that Specter is actually giving the Bush administration all that it could ever want. It certainly wouldn’t land any Administration officials in jail for violation the Constitution they were sworn to uphold.

Holy crap

slaniel | Uncategorized | Wednesday, March 29th, 2006

A spelling bee for adults! I am so there.

Will to Believe, cont.

slaniel | Brief History of Time; Russell, Bertrand; Science; Will To Believe, The | Sunday, March 26th, 2006

In one of the more trivial reasons to smile at The Will to Believe, we have this chunk from “The Sentiment of Rationality” (p. 104 in the Dover reprint):

Like the old woman in the story who described the world as resting on a rock, and then explained that rock to be supported by another rock, and finally when pushed with questions said it was rocks all the way down, — he who believes this to be a radically moral universe must hold the moral order to rest either on an absolute and ultimate should, or on a series of shoulds all the way down.

This is only really notable because it adds a datum to Stephen Hawking’s well-known line from A Brief History of Time (p. 1). [*]

A well-known scientist (some say it was Bertrand Russell) once gave a public lecture on astronomy. He described how the earth orbits around the sun and how the sun, in turn, orbits around the center of a vast collection of stars called our galaxy. At the end of the lecture, a little old lady at the back of the room got up and said: “What you have told us is rubbish. The world is really a flat plate supported on the back of a giant tortoise.” The scientist gave a superior smile before replying, “What is the tortoise standing on?” “You’re very clever, young man, very clever,” said the old lady. “But it’s turtles all the way down!”

It’s a great phrase that — at least since Hawking — has taken on a metaphorical air: “turtles all the way down” is a derisive term for circular arguments, or arguments that replace one undefined term with another, or make more mystery out of less.

So it’s pretty clear that it wasn’t Russell who uttered it. Though an old woman may be central to the story. The way James talks about it, it was either a well-known story at the time, or an apocrypha, or who knows what.

[*] — By the way, it strikes me that ABHOT is one of those books that’s supposed to be brilliant, but whose brilliance no one can explain. As far as I can tell, Hawking’s effect on actual science has been minimal; isn’t his reputation based more on the profound disability he’s had to overcome than on the actual content of his work?

(I say/ask this as a non-cosmologist, so I fully expect to be corrected.)

Coffee, James, etc.

slaniel | Uncategorized | Saturday, March 25th, 2006

Some weeks ago, I decided to go more or less cold-turkey on coffee. It had been turning into a bad psychological crutch for me, such that I needed to drink more and more of it to get going in the morning, and sipped it more or less continuously throughout the day at work. So I cut it out completely, suffered nasty headaches and brainlessness for a few days, eventually got past that, and felt great without it.

But I do really love the taste of coffee, the ritual of obtaining it in the morning, the coffeehouse experience (reading books in a place filled with caffeine-jacked yuppies), the way my mind feels when I’ve been drinking it, and so on. I’ve built quite a set of enjoyable habits around coffee; the point should be to get rid of the bad habits and keep the good ones. Which I did in Cold-Turkey Stage 2, Wherein Our Protagonist Switches to 6/7 Cold-Turkeydom: now I only drink coffee on Saturdays, or very occasionally on both Saturdays and Sundays. I initially was doing Sundays only, but I found that this often left me with a mild headache on Monday mornings on my way to work; this simply Would Not Do. If I’m to have a headache, it shouldn’t interfere with my job. So now it’s mostly a Saturday-only thing.

All of which is by way of explanatory preface to explain my usual Saturday routine of waking around 7 (I really have no control over the matter), getting dressed and heading to Tryst or Murky Coffee (normally the former, because it’s within walking distance, though the coffee at the latter is indisputably better) around 9, and cheerily reading a book for a few hours. Coffee is much more special to me when it’s not a habit — as it had formerly become.

Today was a very good coffee day, accentuated by the brilliance of William James. I have to include a passage here which I just found brilliant, and which echoes — in more-general form, with much more literary brilliance than I could ever muster — thoughts that I’ve had for a while:

But more than that! it is often practically impossible to distinguish doubt from dogmatic negation. If I refuse to stop a murder because I am in doubt whether it be not justifiable homicide, I am virtually abetting the crime. If I refuse to bale out a boat because I am in doubt whether my efforts will keep her afloat, I am really helping to sink her. If in the mountain precipice I doubt my right to risk a leap, I actively connive at my destruction. He who commands himself not to be credulous of God, of duty, of freedom, of immortality, may again and again be indistinguishable from him who dogmatically denies them. Scepticism in moral matters is an active ally of immorality. Who is not for is against. The universe will have no neutrals in these questions. In theory as in practice, dodge or hedge, or talk as we like about a wise scepticism, we are really doing volunteer military service for one side or the other.

I have lots more to write about James, and lots of thoughts that are just taking shape. He’s a remarkable read, though. Well worth anyone’s time.

Dapper hosed again

slaniel | Uncategorized | Saturday, March 25th, 2006

I don’t know what did it, but a sequence of updates in Ubuntu’s latest development release — Dapper Drake — has completely hosed X.org. My graphical display looks like a test pattern on late-night television. All my keystrokes go through, so I can type “sudo chvt 1” to switch over to a virtual console — which works fine. (God bless the virtual console.)

Those of you who know UNIX might ask why I’m typing “sudo chvt 1” rather than just “Ctrl+Alt+F1”. The answer is that some keymapping or other got hosed during the development phase of Ubuntu’s last incarnation — Breezy Badger — such that Ctrl+Alt+F1 doesn’t work anymore.

Three immediate observations, to lay to rest the easiest criticisms that the above would invite:

  1. No, this has nothing to do with the stability of Linux generally, in any sense of “stability” that 99% of Linux users would ever encounter. Dapper is in early beta right now, probably closer to alpha. This does not reflect on Linux generally.

  2. As a moderately advanced Linux user (I hope!), I should be helping to fix these grave errors. Yes indeed, that is true. But at the same time, there is always a tradeoff between the desire to Just Get Work Done, and the desire to spend some time working to improve things.

  3. Really what I ought to be doing is running Dapper on a development machine, and Breezy (which is now stable) on my main workhorse machine. In time I’ll do this; for now I have but one machine, and I foolishly installed development software on it.

We recently got a few external DVD burners at work. Sometime very soon — perhaps this weekend, actually — I’m going to back up all my data onto DVD, then wipe my laptop, install Breezy on it, and restore the data.

Bush and “signing statements”

slaniel | Uncategorized | Friday, March 24th, 2006

It’s appeared in the news a couple times in recent months: apparently when Bush signs laws, he often attaches riders which assert that he needn’t follow the letter of those laws. Having recently signed the Patriot Act, he attached a signing statement that he’ll only feel obliged to meet the Act’s Congressional reporting requirements “in a manner consistent with the president’s constitutional authority to supervise the unitary executive branch and to withhold information.”

I can’t even imagine how this is constitutional. If one of Bush’s prized “strict constructionist” judges gets his hands on the signing statement, you’d think he’d dismiss it out of hand — the “plain language” of the statute clearly says what it says, and Bush can’t pick and choose which parts of it to enforce. Yet how does one bring this sort of thing before a court? Who has standing? That is, who can claim that he was directly harmed by Bush’s signing statements?

The Great Society Subway

slaniel | Uncategorized | Friday, March 24th, 2006

 . . . seems like it would probably be a damned interesting book.

Strong typing

slaniel | Uncategorized | Thursday, March 23rd, 2006

I’ve been taking a Python / Zope class for a week from a quite good teacher named Amos Latteier, and among other things I reaffirmed my appreciation for strongly-typed programming languages.

For those who don’t know, strong typing is a way for compilers to catch errors in computer programs. I write a program in C++, say, and I specify that this variable here is an integer, this variable here is a floating-point number, this one is an EmployeeRecord, and so forth. Every variable has a type. Then if I try to use a function that’s defined for only one type — for instance, I try to write something like employeeRecord1 + employeeRecord2 when “+” is only defined for numbers — the compiler won’t let me do it. The program won’t even get out of the gate.

Languages like Perl and Python don’t have strong typing. This is sometimes a bonus, but in my limited experience it seems like it mostly isn’t. You end up needing to build strong typing in, in any case. For instance, if you want to be really careful with your Python program, you need to check that those programs that are using your functions are passing in the right arguments. What happens if they don’t? In Python you throw an exception, normally (apparently) of type ValueError. This is nasty: if someone hands you the wrong argument and doesn’t handle it properly, their user will get some nasty unhandled-exception error. The programmer should be the only one ever to see this error; the user never should. But the point is that the programmer still has to handle the possibility of bad arguments, so careful programming will still require him to go through some labor. It doesn’t seem like getting rid of strong typing saves much time.

And for that matter it looks like Python forces you to cast your variables in a lot of cases. For instance, you can’t just write

print "I have " + numberoffingers + " fingers.\n" 

Instead you have to do

print "I have " + str(numberoffingers) + " fingers.\n" 

So the print function only knows how to handle strings anyway. Which is to say that print is typed.

Can someone explain to me what one gains by not strongly typing a language? I’m sure there’s a good reason, but it’s not particularly clear to me.

P.S. (10 April 2006): I had forgotten about the awesomeness of the Strong Typing And Perl talk. It’s quite great.

Kramerbooks’ phone number

slaniel | Uncategorized | Sunday, March 19th, 2006

For some reason Kramerbooks makes it very hard to find their phone number. Their website — whose design hasn’t changed since 1996 — doesn’t seem to list their phone number anywhere, and Switchboard.com only lists the café’s number. So in case you’re looking for it, (Googlebait up ahead) Kramerbooks’ phone number is 202-387-1400.

The most annoying open-source-software bug ever

slaniel | Uncategorized | Saturday, March 18th, 2006

I just discovered a fantastically annoying bug in Gnumeric, which is a lightweight and speedy spreadsheet that I love, but which just lost a lot of love with me. I’ve got a budget spreadsheet, and a cell named “paychecksperyear”; throughout the spreadsheet I compute my monthly, yearly, and per-paycheck expenses, so I have a lot of expressions that look like “500/paychecksperyear”. I just added a row to the budget for my $100-per-paycheck 401(k) contribution, and it completely blew apart the spreadsheet. Suddenly all the places where “paychecksperyear” had appeared changed to “#REF!”. This happened for no good reason, as far as I can tell: the name still should have pointed to a given cell, even if the contents of that cell changed. The worst that should have happened is that the calculation should have returned the wrong result, because the “paychecksperyear” cell now had a different value in it. Changing the location that the name pointed to (the “referent,” for purposes of concision) would have fixed that problem. But instead, all the cells now said things like “500/#REF!”, so I had to go through each cell and manually get it to use the right name.

That doesn’t even count as a bug; it’s an obvious design mistake. Grr.

P.S.: The fundamental problem seems to be that names don’t change their referents when cells change positions. In other words, if “name” refers to cell C2, and then you delete the first row, “name” should now point to B2. But it doesn’t; you have to manually change the name. This strongly encourages users not to use names, because they are highly sensitive to the structure of the spreadsheet. Instead, users should just point directly to cells — in the above example, they should point to “$C$2”. If you delete the first row, references to $C$2 will change to $B$2.

Principles of Psychology

slaniel | Uncategorized | Saturday, March 18th, 2006

I’m reading William James’s Principles of Psychology right now, and it occurs to me that what we need is an edition of the Principles annotated by Oliver Sacks. Because (at least up to the point where I’ve read) a lot of the book covers the neurological basis of sensation and higher mental functioning — areas whose intersection Sacks covered brilliantly in The Man Who Mistook His Wife For A Hat. It seems as though Sacks could tell us the places where James’s premises have been updated. Plus, Sacks’s writing is just as literary and cosmopolitan as James’s, so the styles would dovetail nicely.

The Flaming Lips

slaniel | Uncategorized | Saturday, March 18th, 2006

I’m re-listening to The Flaming Lips recently, because my friend Adam Gerard pointed me to a fight between Cat Stevens and them over the purported similarity of their amazing song “Fight Test” to his “Father and Son.” So I went back and re-listened to Yoshimi Battles the Pink Robots — an album which, other than having the bestest title EVAR, is just beautiful. If you’ve not heard it, I’d highly recommend it. The album used to be available in its entirety on the web, and I think it still is. The Soft Bulletin is also great. I think the Lips are generally just awesome.

Newfane’s impeachment vote

slaniel | Uncategorized | Saturday, March 18th, 2006

Dear liberals who take stands against President Bush,

Sometimes affirming your principles means making people unhappy. This is why they are called “principles.”

Love and kisses,
Steve

New Source Review

slaniel | Uncategorized | Saturday, March 18th, 2006

I don’t know all that much about New Source Review, the law which requires polluting factories to install new pollution-control equipment whenever they make a change that increases the pollution they emit. The language of the law, though, seems pretty clear, and it likewise seems pretty clear that the EPA, under the control of the Bush Administration, has reinterpreted that language to fit the needs of industry.

What I find great about all of this, though, is the tiny shred of possibility that George Bush’s conservative nominee to the D.C. Circuit, Janice Rogers Brown, is doing exactly what conservatives always claim they do — reading the “plain language” of statutes. Maybe Bush nominated a conservative because she’d be expected to toe the line, and she is toeing the line — it’s just that it’s a more principled, less pliable line. Good for her.

Sony DRM settlement

slaniel | Uncategorized | Saturday, March 18th, 2006

I had no idea that Sony had settled the issue of their DRM-flawed CDs, but apparently they have. Go and see whether they owe you anything.

Zappa redux

slaniel | Uncategorized | Monday, March 13th, 2006

I have come to the sad conclusion that I am not a Frank Zappa fan. Edward Jahn, who reads this blog and with whom I grew up, was kind enough to take me up on my challenge: make me a Frank Zappa mix to prove to me that the man is not an unfocused, self-indulgent noodler. He made me a wonderful mix, 16 tracks long, which I’m sorry to say doesn’t fundamentally change my view of Zappa. I will change one bit of my earlier suspicions: I don’t think Zappa is unfocused. I think he knows exactly where he is going, and he stays on that path continuously. The trouble is that I don’t find the path he chooses interesting. It’s a road to nowhere. It is technocracy with no soul. When he tries to write a non-ironic song with heart — which, as far as I can tell, he was trying to do on “Lucille Has Messed My Mind Up” — he understands the words but can’t read the poetry.

Zappa reminds me of Alfred Hitchcock at his worst, endlessly tinkering with camera lenses and depth of field. When Hitchcock put those technical devices into the service of real human feeling, he ended up with masterpieces like Rear Window — a product of obsession directed at the proper ends. Without Jimmy Stewart in Vertigo, I’m convinced it would have become a Stanley Kubrick film: “clear and cold and pure and very dead”.

That’s unfortunately how Zappa’s music sounds to me. I’d like to give many thanks to Edward for the devotion that went into the mix, and the diligence with which he tried to overturn my views of Zappa. But sadly, I just don’t think Zappa’s music is for me.

Belle and Sebastian concert, et seq.

slaniel | Uncategorized | Sunday, March 12th, 2006

I saw Belle and Sebastian in concert last Sunday. I was mildly obsessed with them before then, listening to Tigermilk and If You’re Feeling Sinister at least once a week. In the week since the show, it has been a nonstop crushing addiction: I’m pretty sure that 90% of the music I’ve listened to since then has been B&S, including a recording of the second night of their D.C. show. They’re just so good.

Next Page »

Bad Behavior has blocked 279 access attempts in the last 7 days.