August 19, 2010
Powershell Annoyance
I want to love Powershell. There is much that is cool about it, and it is certainly beats batch files or (gag) VBScript. I'm a beginner, and perhaps I'll eventually learn to accept its quirks, but I bump into annoyances frequently enough that Powershell and I are still just friends.
What frequently happens is that I get excited about a cool new concept or feature, but some detail of the execution mars it. I may post more later about a script I've been trying to write, but for now here is a simple example.
Users of bash and other Unix shells will be familiar with the $? variable. It stores the exit status of the last command executed. Generally a value of zero means "success", and anything else indicates an error of some sort:
$ ls modlist.txt
modlist.txt
$ echo $?
0
$ ls nosuchfile
ls: cannot access nosuchfile: No such file or directory
$ echo $?
2
In the first case, because the ls command succeeded, the value of $? is 0 . In the second, the value of $? is 2, indicating an error. This is not very helpful at the command line, but when writing a script you might use it to branch depending on whether a command succeeded or not (though there are more concise ways to accomplish that).
In Powershell, exit statuses aren't puny integers: They are full-fledged objects, of type ErrorRecord. And instead of automatically saving just the last one, there's a ring buffer array with the last 256 (by default) error objects! The most recent error is stored in the first element of the array (at index 0):
PS H:\> dir nosuchfile
Get-ChildItem : Cannot find path 'H:\nosuchfile' because it does not exist.
At line:1 char:4
+ dir <<<< nosuchfile
+ CategoryInfo : ObjectNotFound: (H:\nosuchfile:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
PS H:\> $error[0]
Get-ChildItem : Cannot find path 'H:\nosuchfile' because it does not exist.
At line:1 char:4
+ dir <<<< nosuchfile
+ CategoryInfo : ObjectNotFound: (H:\nosuchfile:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
PS H:\> $error[0].CategoryInfo
Category : ObjectNotFound
Activity : Get-ChildItem
Reason : ItemNotFoundException
TargetName : H:\nosuchfile
TargetType : String
PS H:\> $error[0].TargetObject
H:\nosuchfile
PS H:\> $error[0].Exception
Cannot find path 'H:\nosuchfile' because it does not exist.
PS H:\>
As you can see, I tried to dir a non-existent file, and this generated an ErrorRecord which was stored in $error[0]. I can go back and examine the properties of this object, like CategoryInfo, TargetObject, Exception, etc. Neato. So far, so good.
Before I continue, you need to know that PowerShell also supports tab-completion of property names (kind of like IntelliSense), another great feature. So I can reference a property name with the first few characters of the name, press the <TAB> key, and the PowerShell interpreter will finish it for me:
PS H:\> $name = "David"
PS H:\> $name.le # Press <TAB> here ...
PS H:\> $name.Length
5
PS H:\>
It even gives me the canonical capitalization. Well done, PowerShell. But having grown accustomed to this tab-completion, it's only natural that I would try to use it with $error[0]. Recall that $error[0].Exception is a perfectly legal expression: this is the value of the Exception property of the object stored in $error[0]. But if I type $error[0].Exc<TAB>, nothing happens. Even worse, if I then finish typing it by hand, I find that there is no Exception property anymore!
PS H:\> $error[0].Exc # Press <TAB> here ... no auto-completion :^(
PS H:\> $error[0].Exception # Fine, I'll type the extra six characters msyelf.
PS H:\> $error[0]
What happened? Everything's gone all crazy! Let's see what's in $error[0] now:
PS H:\> $error[0]
Unable to find type [0]: make sure that the assembly containing this type is loaded.
Now I'm really confused, because I can't tell whether the error message is simply the display representation of the ErrorRecord object stored in $error[0], or whether that error message is about the $error array itself. I'm pretty sure it's the former. Going back through the $error array, I eventually find my nosuchfile error at index 2:
PS H:\> $error[1]
Unable to find type [0]: make sure that the assembly containing this type is loaded.
At line:1 char:10
+ $_val=[0] <<<<
+ CategoryInfo : InvalidOperation: (0:String) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
PS H:\> $error[2]
Get-ChildItem : Cannot find path 'H:\nosuchfile' because it does not exist.
At line:1 char:4
+ dir <<<< nosuchfile
+ CategoryInfo : ObjectNotFound: (H:\nosuchfile:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
So not only doesn't tab-completion of property names work when indexing array variables, but it appears to silently generate an ErrorRecord object which is then stored in the $error array. Perhaps there's a very good reason why it has to be this way (if so, let me know), but it's quite annoying.
Long story short: don't try to tab-complete $error array properties. I recommend assigning $error[0] to a new variable (like $err), and then working with that:
PS H:\> dir blargh
Get-ChildItem : Cannot find path 'H:\blargh' because it does not exist.
At line:1 char:4
+ dir <<<< blargh
+ CategoryInfo : ObjectNotFound: (H:\blargh:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
PS H:\> $err = $error[0]
PS H:\> $err.Exception # Here tab-completion will work
Cannot find path 'H:\blargh' because it does not exist.
PS H:\>
Then you can use tab-completion to your heart's content.
July 15, 2010
Lamp-locked
While walking through the Math building rotunda this afternoon I looked up and in the lamp hanging directly overhead saw more than a few dead moths.
And at that moment I wondered: If augury is divination through the the observation of bird flight, what do we call predictions based on the patterns formed by dead moths? "Heteroceramancy" becomes entangled somewhere between my tongue and teeth whenever I try to say it.
July 5, 2010
Kristol vs. Kristol
You may have heard that William Kristol has called for Republican National Committee chairman Michael Steele to step down after the latter's comments regarding the war in Afghanistan. I will be saddened if Steele takes this advice, as his mouth is the gift that keeps on giving.
I doubt Kristol realizes how much he shares with Steele in this respect. I listen to Fox News Sunday primarily for the entertainment value Kristol provides during the panel discussion. Here he is on yesterday's program confirming his position on Steele in response to a question from guest host Major Garrett (cue spit-take):
And I think one thing as a Republican I think Republicans can be proud of is that we don't politicize foreign wars ...
And here is the same William Kristol a few minutes later, in his very next comment:
And [Obama will] have to win [the war in Afghanistan], unfortunately, over the doubts and opposition, almost, right, of almost two-thirds of the Democratic members of the House who voted late last week for a timetable to get out, which is really astonishing.
Nine Republicans voted against the president on this. Like 165 or something supported the president. A hundred sixty-five Republicans supported the president and General Petraeus in the attempt to win this war. Sixty percent-plus of House Democrats said, "No, Mr. President, we just want to get out."
Congressional Democrats seem never to have met a war that, when it gets tough, they don't want to get out of.
This is, presumably, an example of a Republican proudly not politicizing a foreign war. To quote Jon Stewart, "Oh, Bill Kristol, are you ever right?"
January 21, 2010
Walking
This week I've taken up walking to work. It's about 32 minutes each way, and a little under four miles round-trip. WolframAlpha tells me I'm burning over 500 Calories (that's kilo-calories for you Europeans). I hope to keep this up until hay fever season starts. It's enjoyable, saves money, and must be good for the environment.
What do I do while I walk? Sometimes I think. If I pass another person, I think about whether I should say "Good morning!" But instead, I do not. I wonder what they're thinking. Probably that I'm a ne'er-do-well. I want to tell them that, no, I'm an ever-do-well. But again, I do not.
I look at the newspapers piling up in front of one house. Perhaps these people are on vacation. "I should rob them tonight!" I think to myself. Just kidding.
Today I spent most of the walk with my head cocked back looking up at utility poles. From top to bottom you have primary power distribution lines, which feed into transformers (the big buckets-shaped devices). The transformers, in turn, feed into the secondary power distribution lines below, which supply electricity to homes. Farther down, underneath the power lines, are the telephone cables, the cable TV/Internet coax, and fiber optic lines. The telephone cable bundles are punctuated with bulging splice cases. And along the cable TV/Internet cables one sees the occasional amplifier, covered with heat fins.
How do I know so much about utility poles? It's called reading. Specifically, Infrastructure: A Field Guide to the Industrial Landscape. Highly recommended.
On the way to work, I stop at the local Starbucks. I drink coffee and read the paper, which I bring along with me in my black messenger bag.
Today I sat near a crazy old woman in a blue, hooded sweatshirt. When a young man in fatigues sat down, she announced, "We have a terrorist in here! Picking on little countries, don't see you invading China. Bitch. Just like a bully. Just like in school." The man quietly got up and moved to another section. "Bitch, that's right, walk away."
I went back to reading the paper. A few minutes later she pulled out an apple and started peeling it. She threw the peels against the front window, where they fell to the ground. I looked at her.
"What are you looking at? Bitch."
"You're littering," I responded.
"So? So what?"
"So other people have to sit there. You're giving that guy a hard time for being a bully, but you don't care about other people, either."
I immediately regretted saying "either." That's not what I meant. I got up and walked to another section myself.
Should I have kept my mouth shut? This woman is probably mentally ill. Maybe she's homeless and off her meds. Is she responsible for her actions? Or is she just a miserable, selfish human being? Then again, perhaps I caused a moment of reflection on her part, maybe even remorse.
Who am I kidding. I'm sorry, crazy woman. It's not your fault. The soldier was wiser than I.
September 24, 2009
An Open Letter to WETA
Dear WETA,
Allow me to set the stage. Having just finished viewing another excellent edition of the Newshour with Jim Lehrer, I was washing dishes with the TV still tuned — I thought — to WETA. I wasn't paying attention at first when I heard that nameless but instantly familiar movie commercial voice: "When all hope seems lost ... [Clive Owen and other actors speaking over inspirational music ...] what you need the most [more dialog and music] ... is closer than you think. This fall, from the director of Shine, and the producer of Billy Elliot: The Boys are Back, rated PG-13. Exclusive engagement starts September 25th."
At first I wondered why my TiVo had switched the channel to a commercial network. But when I returned to the TV, I saw that, no, this was indeed WETA.
What gives? If that wasn't a commercial then nothing is. Yes, I understand that no product claims were made, and there was no call to action, so that by your narrow definition this was not a "commercial" but an "underwriting statement." But whom are you kidding? Yes, this commercial didn't interrupt programming: it appeared between shows. This makes it slightly less irritating than most commercials, but that's the best one can say.
I'm a WETA member and have been for years. I'm not easily outraged (really!), but I am now. I'm seriously considering an end to my support of your station. Over the years I've put up with the ever-increasing encroachment of commercial messages into public television, but this crosses a line.
I realize you have difficult financial choices to make. But at some point you must ask yourself what principles are so important that you would forego revenue rather than violate them.
You've apparently made your decision. Now I must make mine.
September 3, 2009
Summer Sounds
It would appear that I have yet to update my bjournal this summer, and summer is almost gone.
As I write it is after ten at night. The weather is cool, and I have opened the windows. It feels like autumn is approaching, but the sound is still firmly summer's. Closing my eyes and focusing, I hear the steady background din of a thousand crickets, and the closer chirping of ten or so that are nearby. One of the crickets may in fact be a frog, but I'm not sure.
On the way to work, and on the way back, I still hear cicadas in the trees, and I occasionally see them resting on the ground or sitting on a staircase step. If I think one is likely to be trod upon and smushed, I gently move it out of harm's way with a twig. Cicada's don't like to be moved with a twig, as it turns out. They hold fast as long as they can (they're surprisingly strong), moving not at all. Perhaps the cicada hopes to convince me it is dead. But once forced to loosen its grip, it becomes angry and starts buzzing loudly. Some primal part of my brain immediately thinks "bee!" and I recoil like a child. I hope there is a cicada afterlife where the cicada deity shows the recently deceased a flashback of their entire life (mostly as larvae sleeping underground by tree roots), and the cicadas I encountered learn that I had good intentions, and think, "Aww, shucks."
In a few months, when it is cold, I will notice that silent is the night, and I will wonder when everything died, or burrowed underground. So this year, I plan to listen each night and pay attention as it happens. I may even report back. As of now, though: loud insects rule the night.
May 31, 2009
I like BPA because it's good for my baby!
What do you do when your industry depends on a much-maligned chemical, feared by the public and in danger of government regulation? Apparently you and your colleagues meet at the Cosmos Club and talk strategy. Not surprising, but this time the Post obtained a copy of the notes:
According to internal notes of a private meeting, obtained by The Washington Post, frustrated industry executives huddled for hours Thursday trying to figure out how to tamp down public concerns over the chemical bisphenol A, or BPA. The notes said the executives are particularly concerned about the views of young mothers, who often make purchasing decisions for households and who are most likely to be focused on health concerns.
...
Industry representatives weighed a range of ideas, including "using fear tactics [e.g. "Do you want to have access to baby food anymore?" as well as giving control back to consumers (e.g. you have a choice between the more expensive product that is frozen or fresh or foods packaged in cans) as ways to dissuade people from choosing BPA-free packaging," the notes said.
The attendees estimated it would cost $500,000 to craft a message for a public relations campaign, according to the notes. "Their 'holy grail' spokesperson would be a 'pregnant young mother who would be willing to speak around the country about the benefits of BPA,' " the notes said.
Those in attendance said the mainstream media are ignoring their side of the controversy, and attendees talked about how the group is focusing on "legislative battles and befriending people that are able to manipulate the legislative process," the document said."
To be honest, I don't know enough about the science, but the article goes on to summarize some of the research.
May 18, 2009
May 9, 2009
Skaffa Review
IKEA is known for providing affordable design to the masses. Or is that Target? In any case, IKEA appears to be proud of the design that goes its products. Walk into any IKEA and there on the wall you will find enormous portraits of the bespectacled, sweater-clad Swedes responsible for the sleek couches, bookcases, tables, desks, chairs, lighting fixtures, colanders, and egg timers found in each warehouse-store. If the photographs could speak they might say, "That $15 Lerberg shelving unit that you are seeing there? Yes, I produced that in in my office one frigid, overcast day in December over a large glass of Julmust."
This emphasis on design makes it all the more difficult to understand the shoddy performance of my Skaffa vacuum flask, purchased some months ago (for a very reasonable sum). As I see it, a vessel such as this should, at a minimum, fulfill the following functional requirements:
- Keep coffee hot
- Reliably decant coffee into cup
The Skaffa succeeds admirably in the former case, but fails miserably in the latter. The first and second cups pour elegantly from the spout in a compact, reliable stream. But beyond that, getting coffee in your mug, and not on your newspaper, is remarkably challenging. It is as if one has purchased a gag item from a novelty store. "Watch their faces as the coffee splatters unpredictably in all directions!"
As best I can tell, there is a critical parameter involving the angle of inclination needed for the liquid to reach the spout. Beyond that angle the fluid overshoots the spout, hits the bottom of the screw-on cap, and then leaves the Skaffa in what can only be described as a stochastic process. The defect may be intimately related to the shape of the curve forming the inner profile of the thermos, but that is a guess.
If anyone can recommend a better product, available in the United States, I would be most grateful.
April 17, 2009
2002
The Obama administration has released four classified Justice Department memos used during the Bush administration to justify "enhanced" interrogation techniques, including this newly revealed practice:
You would like to place Zubaydah in a cramped confinement box with an insect. You have informed us that he appears to have a fear of insects. In particular, you would like to tell Zubaydah that you intend to place a stinging insect into the box with him. You would, however, place a harmless insect in the box. You have orally informed us that you would in fact place a harmless insect such as a caterpillar in the box with him.
Somewhere in the upper reaches of the CIA there is, perhaps, a fan of George Orwell's 1984: [SPOILER ALERT]:
"The worst thing in the world", said O'Brien, "varies from individual to individual. It may be burial alive, or death by fire, or by drowning, or by impalement, or fifty other deaths. There are cases where it is some quite trivial thing, not even fatal."
He had moved a little to one side, so that Winston had a better view of the thing on the table. It was an oblong wire cage with a handle on top for carrying it by. Fixed to the front of it was something that looked like a fencing mask, with the concave side outwards. Although it was three or four metres away from him, he could see that the cage was divided lengthways into two compartments, and that there was some kind of creature in each. They were rats.
"In your case", said O'Brien, "the worst thing in the world happens to be rats."
A sort of premonitory tremor, a fear of he was not certain what, had passed through Winston as soon as he caught his first glimpse of the cage. But at this moment the meaning of the mask-like attachment in front of it suddenly sank into him. His bowels seemed to turn to water.
You can almost hear Zubayda screaming "Do it to Osama! Do it to Osama!".