2009/03/17

Scripting News: 3/17/2009

Scripting News: 3/17/2009:

"to the assembled educators -- you owe it to the next generations, who you serve, to prepare them for the world they will live in as adults, not the world we grew up in. Teach all of them the basics of journalism, no matter what they came to Cal to study. Everyone is now a journalist. You'll see an explosion in your craft, but it will cease to be a profession."


Emphasis added, etc.

2009/03/16

[CentOS-virt] CentOS 5.1 guide for VMware Fusion

I just installed CentOS 5.2 for x86_64 under VMware Fusion 2.0.2. Most things worked without tweaking, but the mouse cursor was always offset from the host system mouse, even when VMware was running full-screen.

This post took care of the problem. If I'm reading correctly, the problem was in X11 configuration, and the fix was to use the vmmouse driver with the "CorePointer" option.

Thanks, Bradley Sepos!

2009/03/13

d(rank)/dt > 0

PolitiFact | 8th graders are in 9th, but showing improvement, not falling:

"We considered giving the president partial credit since American students did come in 9th. But the point of his statement was that they had 'fallen' to that position and that mathematics performance in the U.S. is getting worse relative to other countries. And that's just plain False."

Change you can see through

Obama Administration Declares Proposed IP Treaty a 'National Security' Secret | Threat Level from Wired.com:

"...now, like Bush before him, Obama is playing the national security card to hide details of the controversial Anti-Counterfeiting Trade Agreement being negotiated across the globe."
"...the proposed trade accord would [likely] criminalize peer-to-peer file sharing, subject iPods to border searches and allow internet service providers to monitor their customers' communications."


Not good.

2009/03/08

The TSA oversteps its bounds. Again.

.:: Aero-News Network: The Aviation and Aerospace World's Daily/Real-Time News and Information Service ::.:

It presently appears that anyone on the ramp without a TSA ID is subject to fines or convictions in unknown amounts and arrest or detainment by unknown persons...


It is clear the Montrose Airport Appreciation day [...] could be a bit of an issue and the TSA suggested local law enforcement could somehow staff the escort necessities on the field. How exactly do you escort a large milling crowd?


[2009/03/11]

"As for our common defense, we reject as false the choice between our safety and our ideals." If the President really meant what he said, then he will act quickly to rein in the TSA.

2009/03/05

Web Hooks ≈ callback URLs

WTF is a Web Hook?:

"In short, a web hook, or "http callback" allows you to subscribe to another website's events with a URL. You tell a website, "Hey, when some event happens, send some information about it to this URL". Why? It doesn't matter, it's up to the developer to decide what to do with that information."


(low-lumen) Enlightenment

I begin to see how to apply component-oriented techniques to distributed/federated web application development. Thanks to John Herren (bwo Tim O'Reilly) for the clue.

Stainless for OS X Leopard

Stainless for OS X Leopard:

"A prime example is parallel sessions, which allow you to log into a site using different credentials in separate tabs at the same time. This new technology is woven throughout Stainless, from the private cookie storage system, to session-aware bookmarks that remember the session in which they were saved."


That would be useful for website development, whether testing authentication or propagation of messages/event notifications among users.

Guess I should download and give it a try. So many new tools, so little time...

2009/03/04

FF3.1b2, Safari 4b, and html 5 canvas, continued

The previous post described improved support for the HTML 5 canvas. It turns out the latest betas of both Firefox and Safari also support the canvas toDataURL method.

An obvious use for this method is to let users easily copy and paste rendered depictions into other applications.

    function saveToBitmap() {
var canv = $('#canv');
var img = $('img#bitmap');
img.attr('src', canv[0].toDataURL());
};


toDataURL_result.png

Firefox 3.1b2, Safari 4 Beta and HTML 5 canvas text

This will be useful for depicting chemical structures using HTML5 canvas: both Safari 4 beta and Firefox 3.1b2 support the HTML5 canvas text rendering APIs.

There are still rough edges, e.g. it's hard to measure text dimensions and therefore hard to position text properly. Still, it's great to see!

$(document).ready(function() {
function redraw() {
var canv = $('#canv');
var w = canv.width();
var h = canv.height();
// Let canvas know how big CSS wants it to be.
canv.attr("width", w);
canv.attr("height", h);
var ctx = canv[0].getContext("2d");

ctx.clearRect(0, 0, w, h);

var msg = "Hello, Safari text.";
var fontSpec = "24pt Verdana";

// Find out the dimensions of the rendered msg.
var e = $('<span style="visibility:hidden;font:' + fontSpec + '">' +
msg + '</span>');
$('body').append(e);
var tw = e.width();
var th = e.height();
e.remove();

ctx.save();
ctx.translate(w/2, h/2);
// Indented to highlight transformation state.
ctx.save();
ctx.rotate(-45 * Math.PI / 180.0);
ctx.translate(-tw/2, th/2);
ctx.font = fontSpec;
ctx.fillText(msg, 0, 0);
ctx.restore();
ctx.restore();
};
redraw();
});

2009/03/03

Ubuntu 8.10 and Intel i845 chipsets

Today I tried to install Ubuntu 8.10 on an old Dell Inspiron 1100 laptop. Most of the process went well, but when I tried to login the screen went black.

Okay, sometimes it went to the default amber Ubuntu background color. No matter: I never got any windows or menus. Since I was unfamiliar with Ubuntu's key bindings, the only way out was to cycle power.

It turns out that compiz, which provides the default Ubuntu 8.10 window manager, does not like the old i845 graphics chipset.

Google eventually turned up a way to disable compiz. Here's what worked for me.

Summary

Login using a Failsafe Terminal session, remove compiz and compiz-core, then logout and log back in using an Xclient script session.

Details

  1. Boot as usual.
  2. Before logging in, click the Options link at the bottom left of the display.
  3. Click Select Session...
  4. Click the Failsafe Terminal radio button.
  5. Click the Change Session button.
  6. A dialog will pop up, explaining that this is the Failsafe xterm session. Click OK.
  7. An xterm will open. At its prompt, type
    sudo apt-get remove compiz compiz-core
  8. Enter your password, etc. and confirm the package removal.
  9. When the removal completes, type
    metacity --replace &
    (I'm not sure this is necessary.)
  10. Exit the shell.
  11. When the login screen re-appears, click Options.
  12. Click Select Session...
  13. Click the Run Xclient script radio button.
  14. Click Change Session.
  15. Login again.


TODO

When I get more free time I need to repeat the entire installation process, this time collecting detailed information on the failure. Given enough info, I bet the Ubuntu and/or Compiz teams would be able to fix this problem.

2009/02/25

Japan's boffins: Global warming isn't man-made - The Register

Japan's boffins: Global warming isn't man-made — The Register:

The Register's title is an understatement. The report from The Japan Society of Energy and Resources goes beyond questioning human origins of global warming. It also claims that the pattern of warming since the mid-20th century has ceased.

Excerpts:

One of the five contributors compares computer climate modelling to ancient astrology. Others castigate the paucity of the US ground temperature data set used to support the hypothesis [emph. added], and declare that the unambiguous warming trend from the mid-part of the 20th Century has ceased.


The article includes a translation of parts of the report.
Global mean temperature rose continuously from 1800-1850. The rate of increase was .05 degrees Celsius per 100 years. This was mostly unrelated to CO2 gas (CO2 began to increase suddenly after 1946. Until the sudden increase, the CO2 emissions rate had been almost unchanged for 100 years). However, since 2001, this increase halted. Despite this, CO2 emissions are still increasing.


There is no prediction of this halt in global warming in IPCC simulations.


Hm, I thought there was. Certainly the halt has been discussed online — fun example here — and it has been attributed to a trough in sunspot activity...

But the report addresses this point, too, and goes on to say
...climate change and solar activity's relationship is inconclusive. It is necessary to increase research efforts into the relationship between Earth's climate fluctuations and solar activity.

2009/02/24

ADC - CSS Recipes for WebKit

Safari 4 Beta has some nice features. Some have apparently been around since Safari 3, but I didn't notice. For example:

ADC — CSS Recipes for WebKit:

"Getting columns right on webpages using pure CSS instead of HTML tables has always been tricky. Since the CSS3 properties for multi-column layout are implemented in Safari and WebKit, you can clearly define the number of columns [and] the gap between the columns...

This code defines that the HTML in the columns div tag should be presented in three columns. Each paragraph is its own column."


Wow, that's nice! It means you can define a fluid multi-column layout and have content flow between those columns.
safari_4_columns_1.png

Granted, the layout can do some strange things when images bleed across columns.
safari_4_columns_2.png

Maybe one of the -webkit-column-break-* properties can control this.

[Update: Of course Firefox 3 supports most of these column properties as well, via -moz-column-*. Firefox 3.1 beta 2 extends support to properties such as -moz-column-rule.]

2009/02/18

Canvas for a Text Editor?

Canvas for a Text Editor?:

The HTML 5 specification includes an API to render text on a canvas. Unfortunately, this portion of the canvas API has only been implemented by Firefox, though it's already in WebKit nightly builds (and thus will very likely be in a future version of Safari) and Chromium nightlies (from which Chrome versions are derived). We expect Opera will soon as well.


Support for canvas text in browsers other than Firefox will be a great thing for web applications. I've built 2D chemical structure viewers using Canvas, and the clunkiest aspect has been the overlaid text divs for atom labels. (Thank goodness for TextCanvas. Without it, I wouldn't have made the effort.)

You don't really notice text overlays are being used unless you accidentally click-drag your mouse over a depiction, or you set your browser preferences to disallow text smaller than a set size.

2009/02/17

Flex: Stopping event propagation from itemRenderers | kahunaburger

Flex: Stopping event propagation from itemRenderers | kahunaburger:

"My problem was that whenever I clicked on one of the menu items (the four icons at the bottom of the right tile), the mouse event would not only execute the action associated with the menu-item, no, the event would propagate up the chain and would result in the current tile being selected as well. Not good - this has to stop. "


Kahunaburger just saved me a lot of effort. The posted solution works for DataGrids as well.

macosxhints.com - 10.4: Use Automator to batch add Spotlight comments

Edited lightly:

macosxhints.com - 10.4: Use Automator to batch add Spotlight comments:

10.4: Use Automator to batch add Spotlight comments

By: cafemomo on Wed, May 18 2005 at 6:24AM PDT

In Automator, create the following workflow:

1. Finder > Get Selected Finder Items

2. Spotlight > Add Spotlight Comments to Finder Items

2.1. Keep 'Append to Existing Comments' checked

2.2. Open the Options disclosure area and check 'Show Action When Run' so you can set comments each time

3. In Automator, go to File > Save as Plug-in..., enter 'Add Spotlight Comments' as the 'Save Plug-in As:' name, and make sure 'Plug-in for:' is set to 'Finder'

4. Save and close Automator (if it asks you to save again, do so)

Now in Finder, select some items you want to add comments to and right-click (or control-click) and select 'Add Spotlight Comments' from the 'Automator' submenu.


Handy, e.g. for tagging related travel video clips which have been imported with Final Cut Pro.

Juxtaposition

Op-Ed Columnist - Yes, They Could. So They Did. - NYTimes.com:

It's a plug-in electric car that is also powered by rooftop solar panels -- and the two young women, recent Yale grads, had just driven it all over India in a 'climate caravan' to highlight the solutions to global warming being developed by Indian companies, communities, campuses and innovators, as well as to inspire others to take action.


Charging ahead with energy independence - SantaFeNewMexican.com:
Zappy is an all-electric vehicle under construction in Dan Baker's garage off Old Santa Fe Trail. Baker -- known around town as an avid cyclist -- also is a big solar-energy and electric-vehicle proponent. He'll run Zappy off the 5-kilowatt solar photovoltaic system he had installed on his roof last September.


Purpose Built Vehicles - Bright Automotive (of Indiana):
[Our vehicle] operates in all electric mode for the first 30 miles, then operates in hybrid mode with a full range of 400 miles. Bright Automotive's smart vehicle architecture is also designed to return stored energy back to the electrical grid - potentially reducing peak energy demand.

2009/02/16

Mozilla Webdev » Blog Archive » Native JSON in Firefox 3.1

Mozilla Webdev » Blog Archive » Native JSON in Firefox 3.1:

"Pretty easy huh? And here’s how to get a JSON string from an object:

var personString = JSON.stringify(person);"


As a long-time fan of Python's pickle and shelve, I hope JSON.stringify properly handles JavaScript object graphs. And I hope jQuery exposes a similar API.

I think jQuery provides only .param, which is designed as a helper for forms serialization and which does not handle nested objects. For example, in jQuery 1.3.1 this:

var graph = {
'item': {
'name': 'bob',
value:42
},
'index': 1};
$('#msg').html("Graph: " + $.param(graph));


produces this:
Graph: item=%5Bobject+Object%5D&index=1

2009/02/15

Change Happens

Change Happens:

"I won't say that this entry has that much spice, but I hope you can take a moment with me to see through time to allow wonder and delight to replace fear of change."


Tim O'Reilly's recent posts make for satisfying reading. He surrounds his ideas in a thick context of personal and family history.

Former astronaut scoffs at global warming - SantaFeNewMexican.com

Former astronaut scoffs at global warming - SantaFeNewMexican.com:

'As a geologist, I love Earth observations,' [Harrison Schmidt] wrote in his Nov. 14 resignation letter. 'But, it is ridiculous to tie this objective to a 'consensus' that humans are causing global warming when human experience, geologic data and history, and current cooling can argue otherwise.'

"We're very skeptical about the crisis that people are proclaiming in global warming," [said Dan Williams, publisher with the Heartland Institute, which is hosting the second International Conference on Climate Change in New York]. "Not that the planet hasn't warmed. We know it has or we'd all still be in the Ice Age. But it has not reached a crisis proportion and, even among us skeptics, there's disagreement about how much man has been responsible for that warming."
[Schmidt] said he is heartened that next month's conference is made up of scientists who haven't been manipulated by politics, possibly because they are not dependent on government funding.


The debate continues about the causes of global climate change. (See also Dr. John Theon's expression of skepticism.)

What interests me most about the debate is its effect on U.S. energy policy. If it spurs us to improved energy efficiency — e.g. in home heating and cooling and reduced contention for foreign oil — it seems beneficial to act as though climate change has some human causes, whatever the uncertainties in our understanding.

On the other hand, if the debate leads us to cover the wilderness with wind turbines, solar farms, and superconducting transmission lines [update: lucky timing - here's an example], then maybe we should start demonizing termite methane emissions :)

2009/02/13

VoodooPad and TextMate

VoodooPad's new HTML-savvy application-specific URLs are a great way to retrace your steps in TextMate.

I keep my worklog in VoodooPad. I do most of my code editing in TextMate. When I'm trying to understand a new chunk of code, I often need to jump around through the code base.

It's hard to keep track of where I've been, so I can back out of a code path once I understand what it does. Until now I've just jotted down pathnames and line numbers in my worklog, so I could manually retrace my steps.

Puzzle Pieces


  • VoodooPad URLs. They let you inject HTML content — including hyperlinks — into an open VoodooPad document.
  • TextMate URLs of the form txmt://open?url=file://pathname&line=lineNum;column=colNum. Open one of these URLs and TextMate will open a window showing the specified line (and column, if specified) of the specified file.
  • Textmate commands and key equivalents.
    TextMate lets you define custom commands and trigger them with keyboard shortcuts that you specify.


Put these all together and what do you get?

Scenario
  • Select some code of interest in TextMate
  • Type your keyboard shortcut
  • A hyperlink pointing to the selected code is inserted into your VoodooPad document

Later, when you want to get back to that chunk of code, just click on the hyperlink in VoodooPad. TextMate will open the document and jump to the line of code referenced by the hyperlink.

Granted, you're probably going to edit that code someday; and then your bookmarks will break. But this is a handy way to leave a trail of breadcrumbs while you're trying to decipher a new body of code.

Code

Here's a Python script which implements this "Bookmark in VoodooPad" capability in TextMate. You can use it by opening TextMate's Bundle Editor (Bundles -> Bundle Editor -> Show Bundle Editor), creating a New Command using the tool menu at the bottom left of the Bundle Editor window, and pasting it into the resulting Command(s) text area:

#!/usr/bin/env python2.6
import os, datetime, urllib, subprocess

escape = urllib.quote

# What Textmate location are we bookmarking?
path = os.environ["TM_FILEPATH"]
lineNum = os.environ["TM_LINE_NUMBER"]
_tmURLTemplate = """txmt://open?url=file://{path}&line={lineNum}"""
tmURL = _tmURLTemplate.format(path=path, lineNum=lineNum)

# Which VoodooPad worklog page should we add it to?
vpPageName = escape(datetime.date.today().strftime("%Y-%m-%d"))

# What text should Voodoopad show for the link?
currLine = os.environ.get("TM_SELECTED_TEXT", os.environ["TM_CURRENT_LINE"])

# How should the HTML be formatted?
_vpHTMLTemplate = '''<a style="font:12px helvetica" href="{tmURL}">{currLine}</a>'''
vpMarkup = _vpHTMLTemplate.format(tmURL=tmURL, currLine=currLine)

# What URL do we open to inject the HTML into VoodooPad?
_vpURLTemplate = """voodoopad:html={vpMarkup}&page={vpPageName}"""
vpURL = _vpURLTemplate.format(vpMarkup=escape(vpMarkup), vpPageName=escape(vpPageName))

subprocess.check_call(["open", vpURL])


Specify a key equivalent such as ⌘-T (Command-T) and you're off to the races.

VoodooPad bookmarklets now support HTML

VoodooPad bookmarklets are very useful. But they let you paste only plaintext from your web browser into your document — until now.

VoodooPad Application URLs

VoodooPad understands application-specific URLs of the form voodoopad:description=encoded_text&page=name_of_VoodooPad_document_page. When you open one of these URLs, VoodooPad inserts the encoded text into the indicated page of the current VP document.

You can open voodoopad: URLs from other applications, such as a web browser. That's what's so cool about VP bookmarklets -- they let you quickly select some text in your web browser and paste it into a VP document, along with other information such as the URL where the text originated.

The only problem is, the description parameter can contain only plain text. So if you've selected part of a web page that contains hyperlinks, those hyperlinks won't come along for the ride.

New Feature

Gus Mueller, VoodooPad's creator, recently released a new build. It adds a new html parameter to VoodooPad URLs. Now you can select part of a web page and transfer it as HTML into your VoodooPad document.

Gus summarized the new feature thus:

The format of the bookmarklet is like so:
voodoopad:page=junk&html=<b>hello</b>%20world!
Here's expanded code for a JavaScript bookmarklet which takes advantage of the new parameter. It works in both Safari and Firefox 3.0.x:

javascript: function pad(v) {
var res=String(v);while(res.length<2) {
res='0'+res;
}
return res;
};
var d=new Date();
var page=(String(d.getFullYear())+'-'+
pad(d.getMonth()+1)+'-'+ pad(d.getDate()));
function selHTML() {
var wr=document.createElement('div');
var c=window.getSelection().getRangeAt(0).cloneContents();
wr.appendChild(c);
return wr.innerHTML;
};
location.href='voodoopad:html='+encodeURIComponent('<div style="font:12px helvetica">'+location.href+'<br/>"""<br/>'+selHTML()+'<br/>"""</div><br/>')+'&page='+page;


Worth noting: in this snippet the html content is wrapped up in a div which has an explicit font specification. The bookmarklet is transferring a chunk of HTML, but that chunk doesn't include any of the CSS from the original web page. So if you don't specify a style for the wrapper div, VoodooPad will use its own default style for the current VP page. (I think that's something like Times Roman 10px.)

2009/02/12

Technology Review: Neanderthal Genome Unraveled

Technology Review: Neanderthal Genome Unraveled:

"Using previously sequenced genomes from other species was also crucial, says John Hawks, a biological anthropologist at the University of Wisconsin. 'Bootstrapping computer information about genomes really made all of this possible,' he says. 'To be able to take snippets of DNA of 50 base pairs or less and have the computer say that it's the same as a bacterial sequence has enabled the reconstruction of genuine Neanderthal sequence.'"


I wonder how this relates to recent findings about horizontal gene transfer? Are all of those 50-base-pair sequences unique to bacteria, or are they just "most likely to occur" in bacteria?

2009/02/11

Call This Progress?

Call This Progress?:

"Five years of ‘action’ and only one country out of five so-called advanced European nations — all of which fought with the USA to get it to sign the Kyoto Protocol — has managed to reduce its emissions by more than 5%."


The article claims that the U.S. increased its emissions by 2.4% in the measured period. That's better than Kyoto signatories France (2.9%) and Spain (12.4%).

2009/01/30

Blue light kills MRSA 'superbugs' - The Register

Blue light kills MRSA 'superbugs' - The Register:

"American medi-boffins say they have developed a way to kill so-called 'superbugs' - deadly infections which can't be cured using antibiotics - by simply shining a certain wavelength of blue light on them. They believe the technique could be used safely on patients infected with MRSA [Methicillin-Resistant Staphylococcus aureus].
'It is inspiring that an inexpensive naturally visible wavelength of light can eradicate two common strains of MRSA. Developing strategies that are capable of destroying MRSA, using mechanisms that would not lead to further antibiotic resistance, is timely and important for us and our patients,' says Chukuka S Enwemeka PhD of the New York Institute of Technology."

2009/01/28

Cheap, super-efficient LED lights on the horizon - New Scientist

Cheap, super-efficient LED lights on the horizon - tech - 29 January 2009 - New Scientist:

"Humphreys reckons that the UK government encouraged consumers to drop tungsten bulbs too soon. 'We should have stayed with tungsten for another five years and then switched to LEDs,' he says."

I'm a sceptic now, says ex-NASA climate boss - The Register

I'm a sceptic now, says ex-NASA climate boss - The Register:

[Theon said] "My own belief concerning anthropogenic climate change is that the models do not realistically simulate the climate system because there are many very important sub-grid scale processes that the models either replicate poorly or completely omit. Furthermore, some scientists have manipulated the observed data [emphasis added, etc.] to justify their model results. In doing so, they neither explain what they have modified in the observations, nor explain how they did it.
"They have resisted making their work transparent so that it can be replicated independently by other scientists. This is clearly contrary to how science should be done."

So he's a skeptic about man-made global climate change. I wonder what he thinks about climate change trends in general. E.g. do the data indicate long-term warming, regardless of cause?

Aside: I quit reading treehugger.com a few years ago, after the reporter in one of their so-called "news" videos mocked a claim that some climate change was due to the sun. "That's right: the sun. [snort]" As if fluctuations in our largest energy source could not affect our climate...

More from The Register:
"Hansen has called for energy industry executives to be jailed for dissenting from the man-made warming hypothesis."

I didn't know that. The Guardian confirms it:
"James Hansen, one of the world's leading climate scientists, will today call for the chief executives of large fossil fuel companies to be put on trial for high crimes against humanity and nature, accusing them of actively spreading doubt about global warming in the same way that tobacco companies blurred the links between smoking and cancer."

2009/01/26

Obama's Order Is Likely to Tighten Auto Standards - NYTimes.com

Obama's Order Is Likely to Tighten Auto Standards - NYTimes.com:

"It would also pay for 3,000 miles of new or modernized transmission lines as part of a new national electric grid as well as 40 million 'smart meters,' which provide instant readouts of electricity uses, on American homes. The money would also help refurbish two million homes and 75 percent of federal building space to better guard against the weather"


Electricity consumption isn't my home's problem. My home's problem is natural gas consumption.

2009/01/21

Why Darwin was wrong about the tree of life - life - 21 January 2009 - New Scientist

Why Darwin was wrong about the tree of life - life - 21 January 2009 - New Scientist:

"Other cases of HGT in multicellular organisms are coming in thick and fast. HGT has been documented in insects, fish and plants, and a few years ago a piece of snake DNA was found in cows. The most likely agents of this genetic shuffling are viruses, which constantly cut and paste DNA from one genome into another, often across great taxonomic distances. "

2009/01/20

Django snippets: DebugFooter middleware with textmate links

Django snippets: DebugFooter middleware with textmate links:

"This version adds TextMate links : if you are working on your local machine and using TextMate you can click on the template paths and they will be opened in TextMate. This speeds up development time considerably!
also, this works with django 1.0"


Very useful.

ack -- better than grep, a power search tool for programmers

I've been using "Ack in Project" in TextMate for awhile. It works so well, I'd like to start using it from the command line.

Luckily it's easy. Paraphrasing from the author's website:

ack -- better than grep, a power search tool for programmers:

curl http://ack.googlecode.com/svn/tags/latest/ack-standalone > ~/bin/ack && chmod 0755 ~/bin/ack

BBC NEWS | Asia-Pacific | Fresh warning on China bird flu

BBC NEWS | Asia-Pacific | Fresh warning on China bird flu:

"Hong Kong's secretary for food and health, Dr York Chow, said this was a cause for concern.
'There are two main areas we are concerned about: one is that if there is no avian flu outbreak in poultry and yet there are human cases, does this mean the virus has changed?
'Secondly, we are worried about whether there are more so-called 'slightly infected' chickens that actually might be carrying the virus and transmitting the disease, and yet do not show any symptoms or die from those illnesses,' Dr Chow said."

2009/01/14

jQuery 1.3 Live Events

Release:jQuery 1.3 - jQuery JavaScript Library:

"Live Events

jQuery now supports 'live events' - events that can be bound to all current - and future - elements. Using event delegation, and a seamless jQuery-style API, the result is both easy to use and very fast."


If I read this correctly, now you can reload parts of your page and have any replaced controls wired up automatically. No more need for post-processing callbacks on $.load() or $.getJSON()?

Outstanding!

(And the description, "Live Events", is concise — much better than the term "path-based bindings" that I've been using.)

2009/01/11

Work on Stuff that Matters

Work on Stuff that Matters: First Principles - O'Reilly Radar:

"Our economy has many elements of a ponzi scheme. We borrow from other countries to finance our consumption, we borrow from our children by saddling them with debt and using up non-renewable resources."

2009/01/07

iWork '09: Numbers

Numbers '09 has some significant improvements.

  • It supports axis transformations — linear, log-scale (okay, that's probably not new).
  • It supports overlays, including a host of curve-fits, with annotations (formula, R-squared error, etc.)
  • Unlike its predecessor, Numbers '09 provides an AppleScript dictionary.


Impressive!

Picture 1.png

2009/01/05

VoodooPad Bookmarklets

VoodooPad bookmarklets make it easy to log search results.

I keep a worklog in VoodooPad. Notes for each day are stored in a page with a name of the form 'yyyy-mm-dd'.

When I'm searching for info on the web, I like to include relevant results in my worklog. I tend to record results in this format, to make it easier to find the results again in future:

http://url.of.interest/:
"""
Excerpt
"""


It's tedious to format these excerpts. At least two visits to the browser application are needed:
  1. Copy the URL
  2. Copy the text of interest


Luckily VoodooPad supports application-specific URLs, and you can create JavaScript bookmarklets to open such a URL, with the URL and any selected text for the page you're currently viewing.

Here's an almost human-readable example of a bookmarklet which adds an excerpt from the current web page, formatted as above, to the current worklog page in VoodooPad.

javascript:
var d = new Date();
var padded = function(v) {
var res = v.toString();
while (res.length < 2) {
res = '0' + res;
}
return res;
};
var page = [
String(d.getFullYear()),
padded(d.getMonth() + 1),
padded(d.getDate())
].join("-");
location.href = ('voodoopad:description=' +
encodeURIComponent(location.href + '\n"""\n' +
window.getSelection().toString() +
'\n"""\n') +
'&page=' + page);


Here's the same bookmarklet formatted for inclusion in your browser's menubar:
javascript:var%20d=new%20Date();var%20padded=function(v)%20{%20var%20res%20=%20v.toString();while%20(res.length%20<%202)%20{res%20=%20'0'%20+%20res;}%20return%20res;};var%20page%20=%20[String(d.getFullYear()),%20padded(d.getMonth()%20+%201),%20padded(d.getDate())].join('-');location.href='voodoopad:description='+encodeURIComponent(location.href+'\n"""\n'+window.getSelection().toString()+'\n"""\n')+'&page='+page;

2008/12/09

Unintended Consequences

Op-Ed Contributor - The Terrorists Want to Destroy Pakistan, Too - NYTimes.com:

"The world worked to exploit religion against the Soviet Union in Afghanistan by empowering the most fanatic extremists as an instrument of destruction of a superpower. The strategy worked, but its legacy was the creation of an extremist militia with its own dynamic."

2008/11/26

The government crash

Doc Searls:

The amazing thing about crashes is that you can see them coming...
Now we’re about to see the U.S. government crash, for the same reason.


The U.S. government is about to spend roughly 1/2 GDP to "fix" the economy.

It was a surprise this autumn to see foreign investors rushing to buy up more of our debt. Will we still look like a good bet after we've taken out a loan this big?

2008/11/20

Waxman topples Dingell for key panel chair - Yahoo! News

Waxman topples Dingell for key panel chair - Yahoo! News:

"Rep. Henry Waxman — a liberal ally of Speaker Nancy Pelosi — has wrested the chairmanship of the powerful House Energy and Commerce Committee from veteran Rep. John Dingell when the new Congress convenes in January."


I'm no fan of Waxman, but this could portend positive changes for the U.S. auto industry. Presuming, of course, that the best solution to our oil and carbon-emissions problems entails continued use of automobiles.

2008/11/18

LIFE photo archive hosted by Google | Photodoto

LIFE photo archive hosted by Google | Photodoto:

"LIFE has released over 10 million images on a new hosted image service from Google and in Google Image Search. They claim [...] that the collection contains ‘some of the most iconic images of the 20th century.’
LIFE is selling fine art prints (in partnership with Qoop it seems) of the collection and the photos are only available online as 1 megapixel scans."


Outstanding.




(I've seen a large print of this Margaret Bourke-White photo in a local gallery. A computer screen can't do it justice, not by a long shot.)

“New chapter” on climate change

From President-elect Obama promises “new chapter” on climate change | Change.gov:

The Global Climate Summit is a "2-day event arranged by California Governor Arnold Schwarzenegger to break gridlock on the issue ahead of next month's United Nations Climate Change Conference in Poznan, Poland."

President-elect Obama posted a short video expressing enthusiasm for the summit:

"...too often, Washington has failed to show the same kind of leadership. That will change when I take office."


Interesting times. It's easy to imagine this bit of cross-party consensus as the beginning of Friedman's e-tech economy.

Can't debug after updating to Flex Builder 3.0.2

I'm evaluating FlexBuilder 3, and have just installed the Flex Builder 3.0.2 update. All of a sudden I can't debug my AIR project.

The error dialog displays a lengthy message which ends with:

error while loading initial content


Thanks to Google and Adobe's public bug database, the fix is straightforward: edit the project's *-app.xml file and change the namespace (2nd line) to 1.5:


<application xmlns="http://ns.adobe.com/air/application/1.5">

2008/11/17

Prophesy of economic collapse 'coming true' - environment - 17 November 2008 - New Scientist

Prophesy of economic collapse 'coming true' - New Scientist:

Changes in industrial production, food production and pollution are all in line with [the predictions in "Limits to Growth"] of collapse in the 21st century, says Turner.
According to Herman Daly of the University of Maryland, Turner's results show that we 'must get off the growth path of business as usual, and move to a steady state economy,' stopping population growth, resource depletion, and pollution."

2008/11/14

.:: Aero-News Network: The Aviation and Aerospace World's Daily/Real-Time News and Information Service ::.

.:: Aero-News Network: The Aviation and Aerospace World's Daily/Real-Time News and Information Service ::.:

"United Airlines will become the first US carrier to demonstrate how next-generation technologies could save more than two thousand gallons of fuel and cut up to 55,000 pounds of carbon emissions on a single, trans-Pacific flight."
Within minutes of landing, United will calculate and publish the actual savings realized on this flight.


As a recovering private pilot I find this fascinating...

A former colleague has been working on a related software project, using genetic algorithms and frequently updated weather data to help commercial flights decide how to alter their routes — diverting in all three dimensions as necessary &mdash to find the cheapest path between two points. I wonder if he's involved in any way in this test flight.

2008/11/12

Why it's hard to reduce gross energy use

un_pop.png


Good news: we appear to be near an inflection point:)

Our numbers are huge, and a good fraction of us are trying to improve standards of living in a way which increases per capita annual energy expenditure. But at least our population growth is slowing.

Stewart Brand in Technology Review:
...in 2002, [the UN] adopted a new theory that shocked many demographers: human population is leveling off rapidly, even precipitously, in developed countries, with the rest of the world soon to follow...

The world's women... had fewer kids because they moved to town.

Cities are population sinks-always have been... A global tipping point in urbanization is what stopped the population explosion...

The environmentalist aesthetic is to love villages and despise cities. My mind got changed on the subject a few years ago by an Indian acquaintance who told me that in Indian villages the women obeyed their husbands and family elders, pounded grain, and sang. But, the acquaintance explained, when Indian women immigrated to cities, they got jobs, started businesses, and demanded their children be educated.

Solving for the Unknowns: The Pickens Plan

This Yahoo! News article has me wondering again about the pros and cons of the Pickens Plan:

"Billionaire T. Boone Pickens expects to know within 100 days of Barack Obama taking over as president in January whether the U.S. government is going to adopt part of his ambitious and controversial energy plan.
The plan calls for an eventual overhaul of the power grid and Pickens is also betting on huge growth in wind power. But he said, as a start, the United States can move toward using natural gas in trucks as well as more renewable power."

A couple of months ago the Climate Progress blog posted a criticism of the Pickens Plan. According to the author, Earl Killian, the proposal to build out a wind energy infrastructure is attractive, but converting ground transportation to compressed natural gas makes no sense.

CNG Trucking

For Pickens, converting long-haul trucking to CNG is probably the most attractive part of the plan. Killian asserts that, in order to make a dent in foreign oil dependency, we would also need to convert small cars to alternative fuels.

I think Killian may have set up a strawman, although he does provide evidence that Pickens is talking about both trucks and small cars. Regardless, his analysis is really interesting.

Killian finds that plugin hybrids would get more range from a given volume of natural gas, converted to electricity by a power utility, than would cars which ran directly on CNG:
It seems pretty straightforward that electric vehicles beat CNG vehicles almost 2:1, even using existing NG power plants. If the US upgraded its NG power plants to be 60% efficient, instead of 39% efficient, we would have 54% more TWh, or even better, use less 35% less NG.

As noted, Pickens is focusing on big trucks, not small cars. It would be interesting to see an assessment based on data from existing CNG truck and bus fleets.

Wind

Killian and others have a more favorable view of Pickens' wind power proposal. They are concerned that wind power could be unreliable and unpredictable since, well, wind varies. The Pickens Plan addresses this problem by building excess capacity into the wind grid, and by pointing out that it's unlikely the entire midwest wind corridor would be calm at any given time.

This seems reasonable given the experiences of other countries. For example, Wikipedia notes that Denmark, which derives 20% of its electricity from wind power, has suffered "no major problems" with wind variability.

Killian focuses on energy potential, so he doesn't assess the environmental consequences of building out the wind corridor. Aside from the wind turbines themselves, we'd also need lots of long-distance transmission lines, much of it running through land which has so far escaped damage by humans.

Sideline: Rail

I thought that rail was more fuel efficient than trucking for long-haul shipment of goods, and that trucking came to prominence by way of regulation. If so, that would beg questions:
  1. What would be the benefits of changing those regulations to reward efficiency?
  2. Would we be better off building up rail infrastructure, than converting trucking fleets to CNG?

Google says my memory of regulatory history is wrong. From "Basic Economics", by Thomas Sowell:
[The I.C.C.] sought — and received from Congress — broader authority under the Motor Carrier Act of 1935, in order to restrict the activities of truckers [emph. added]. This allowed railroads to survive under new economic conditions, despite truck competition that was more efficient for various kinds of freight hauling.

The CSX website claims that rail freight is three times more fuel efficient than long-haul trucking.
Since 1980, through technology and innovation, the railroad industry has improved locomotive fuel efficiency by over 80%.

So question 2 is still worth asking.

2008/11/06

TextMate CamelCase

Because I keep forgetting: In TextMate, you can toggle the selected text from lowercase_with_underscores to camelCase by typing Control-Shift-Minus (^_).

At last, an antidote to USA Today

When the lights go on at the New York Times, our work can start:

"But the Times is attracting an all-star team of information architects, interactive graphics designers, programmers, and media producers. And according to Gabriel Dance and Shan Carter, these folks are increasingly collaborating with reporters to marshall complex information in ways that make the newspaper’s stories deeper and more open to independent analysis and interpretation."

Jon's statement made me realize: NYT is providing an antidote to USA Today.

When USA Today first appeared, it was criticized for emphasizing glitz over substance. Its articles often oversimplified complex issues. Its graphics were colorful and, almost always, misleading.

USATodayParody.png


NYT is getting it right, especially with interactive graphics. Sure, they're often glitzy. But they also communicate clearly. And they make it easier to understand the data which they present, in part by making it easier to explore.

2008/11/05

One-line web server in Python

From Ed Taekema's weblog, a reminder[1] about how to create a web server in one line of Python:

python -c 'import SimpleHTTPServer;SimpleHTTPServer.test()'


This starts a server listening on port 8000, serving files from its launch directory. If you just hit the server (http://localhost:8000/) it will by default serve index.html; if index.html doesn't exist, it will give you a directory listing. Also, the server will provide only those files residing in or below the current working directory; e.g. http://localhost:8000/../ resolves to the default document.

Wish I'd seen Ed's note this morning...

This is handy when you want to experiment with things like interactions between Flex applications and JavaScript, or other situations in which you can't get by with simple file:/// URLs. This would be handy as a jqUnit test, as well.



[1] Reminder? It's been a long time since I read "Internet Programming with Python" :-)

2008/11/01

Removing old man pages from OS X Leopard

Back in January I posted about Leopard, 'ls -l' and extended attributes. The gist was that my man pages were out of date, so they didn't explain what the @ character represented, in 'ls -l' output.

Some threads on the Apple discussion boards have investigated why the man pages don't get updated. The conclusion is that Leopard installs a lot of gzip-compressed man pages without deleting the corresponding uncompressed man pages. (It may be that this is true only for upgrade installs.) A recommended workaround was to scan through the man page directories with a shell command, re-locating all uncompressed man pages which had corresponding compressed man pages.

I decided to be cowardly in doing this. Here's a Python script which moves each uncompressed man page only if it is older than its corresponding gzipped man page.

The script must be run with superuser privileges, e.g.

sudo python mv_old_man_pages.py

It processes all of the man pages under /usr/share/man, moving old, uncompressed man page files to ~/tmp/old_man_pages.

I would post this to the Apple discussion forums, but it's really overkill. The short shell scripts already posted should work fine, if you ignore the harmless error messages and process each man/man* directory manually.


#!/usr/bin/env python
# encoding: utf-8
"Remove obsolete uncompressed man pages on an OS X Leopard system."

import sys, os, logging

def candidateOldManPages():
os.chdir("/usr/share/man")
for dirpath, dirnames, filenames in os.walk("."):
for f in filenames:
if f.endswith(".gz"):
fOld = f[:-3]
if fOld in filenames:
yield os.path.join(dirpath, f), os.path.join(dirpath, fOld)

def findOldManPages():
for p, pOld in candidateOldManPages():
s = os.stat(p)
try:
sOld = os.stat(pOld)
except os.error, info:
# Some man pages may be broken symbolic links
logging.warn("Can't stat (%s, %s): %s" % (p, pOld, info))
if os.path.islink(pOld):
yield pOld
else:
if s.st_mtime > sOld.st_mtime:
yield pOld

def mvOldManPages():
topDestDir = os.path.expanduser("~/tmp/old_man_pages")
for relpath in findOldManPages():
dirname = os.path.dirname(relpath)
filename = os.path.basename(relpath)

destDir = os.path.join(topDestDir, dirname)
if not os.path.exists(destDir):
os.makedirs(destDir)
logging.debug("mv %s %s" % (relpath, os.path.join(destDir, filename)))
os.rename(relpath, os.path.join(destDir, filename))

def main():
"""Mainline for standalone execution"""
logging.basicConfig(level=logging.DEBUG,
format="%(levelname)s: %(message)s")
mvOldManPages()

if __name__ == "__main__":
main()


2008/10/24

Let Google do the syntax highlighting

Guido recently posted some sample code to his new blog. The first comment complained that the code was "really crappy", improperly indented and hard to read.

Surprisingly, something good came of the rude complaint. Subsequent commenters described how to make simple changes to the blog template which would delegate code syntax highlighting to a Javascript library, google-code-prettify, which is hosted on Google Code.

This looks a lot simpler than the procedure I've been using, which involves embedding a lengthy blog template stylesheet and, whenever I want to post highlighted code, a 2-3 step incantation from within TextMate.

Anyhoo, this post is a test to see if I can incorporate google-code-prettify into this blog.

def genURLs(station):
tmpl = ("ftp://ftp.ncdc.noaa.gov/pub/data/asos-fivemin/6401-"
"{year}/64010{station}{year}{month:02d}.dat")
today = datetime.date.today()
year = 2004
month = 6
while True:
d = datetime.date(year, month, 1)
if d > today:
return
yield tmpl.format(year=year, month=month, station=station)

month += 1
if month >= 13:
month = 1
year += 1

And another -- this time in C++
#include "test_qt_sample.h"

void TestQString::toUpper() {
QString str = "Hello";
QVERIFY(str.toUpper() == "HELLO");
}

QTEST_MAIN(TestQString)

One more, with long source lines.
#!/usr/bin/env python
# encoding: utf-8

msg = "Surprisingly, something good came of the rude complaint. Subsequent commenters described how to make simple changes to the blog template which would delegate code syntax highlighting to a Javascript library, google-code-prettify, which is hosted on Google Code."

print len(msg.split())

I love the Python community. It is filled with people who respond to every complaint and criticism with courteous, useful solutions. (Google Code ain't bad, either :)

2008/10/22

FRONTLINE: nuclear reaction: Why the French Like Nuclear Energy

FRONTLINE: nuclear reaction: Why the French Like Nuclear Energy:

"French technocrats had never thought that the waste issue would be much of a problem. From the beginning the French had been recycling their nuclear waste, reclaiming the plutonium and unused uranium and fabricating new fuel elements. This not only gave energy, it reduced the volume and longevity of French radioactive waste. The volume of the ultimate high-level waste was indeed very small: the contribution of a family of four using electricity for 20 years is a glass cylinder the size of a cigarette lighter."


The French seem to be leading the world in managing nuclear power and its waste products. So how big, in terms of volume, is their waste storage problem?

Let's assume all of France's electricity is generated by French nuclear plants (it's not -- Wikipedia says the number is about 88%) and that they use all of their generated electricity. (Wikipedia says they export a lot of it.) The population of France is about 64,473,140. So that's about 16 million family-of-four equivalents. In 20 years, they'll need to store 16 million cigarette lighters. What is that, about 7 million cubic feet?

Assuming that's in the ballpark, and assuming you can store that waste without having to space it out to avoid assembling a critical mass, that'd be a cube about 19 feet on a side, every twenty years. Pretty small. The Bat Cave could probably handle 20 years of waste...

2008/10/21

Another success for cancer immunotherapy

For cancer patients, personalized treatment offers a new range of options -- and hope - Los Angeles Times:

"Those words could serve as the new mantra in medicine. After having his tumor removed and undergoing chemotherapy and radiation, he received a novel treatment that was designed using his own white blood cells and proteins taken from his tumor to prod his immune system into recognizing and attacking more cancer in his body."


Many credit Dr. William B. Coley for pioneering cancer immunotherapy, in the late 1800s and early 1900s. Coley focused on triggering bacterial infections in cancer patients, because his review of case histories showed that these infections often caused tumors to shrink. He surmised that the infections stimulated patients' immune systems to attack the tumors as well as the bacteria.

2008/10/16

CMake

Last spring I evaluated waf as an alternative to SCons (and its 3rd party Qt4.py plugin) for Qt4 projects. I've finally settled on CMake.

waf's wscript files could be beautifully concise. Alas, support for Qt4 applications was unstable, and the support for building OS X application bundles was both rudimentary and unstable. (By "unstable" I mean that the qt4 and osx tools would break periodically, and/or that the internal APIs would change so much between releases that my own customizations would break.)

The final straw was that I could not control the library order when linking static Qt4 libraries. That made it impossible for me to build Qt4 apps which used QtSvg.

I wish I had time to document these problems properly -- no doubt waf's maintainer(s) would prefer bug reports to detail-free claims that "it doesn't work."

In any case, CMake seems to be doing the job. It can perform out-of-line builds, supports defining and running unit tests, and doesn't get in the way of writing integration tests in Python, to drive e.g. C++ programs. It knows how to build Qt4 applications and lets me control the link order for static libraries. And it works well on OS X and Linux.

Go Vote Now

I'm Bob Schieffer of CBS News, and I will leave you tonight with what my mother always said: Go vote now. It will make you feel big and strong.
:)

The New York Times (registration required?) has video, a transcript, and some fact-checking on last night's debate.

2008/10/15

PolitiFact | Beating a retreat on a lavish retreat

PolitiFact | Beating a retreat on a lavish retreat:

Obama's comments suggest a misunderstanding of the details behind AIG’s collapse, or a deliberate effort to skip over the realities of AIG's corporate structure in order to make a good point. Also, Obama slams AIG for two junkets at a time when the company had only held one. AIG might have had a tin ear when it came to organizing corporate events. But Obama’s wrong to lay blame for the financial meltdown on a highly regulated, profitable part of the business that sells life insurance. We rule the claim Barely True."


Turns out the AIG junket involved a business unit which dealt in insurance, not the unit which lost all that money on mortgage-backed securities. And many of the attendees were independent AIG insurance agents, not employees of AIG. And of course the cost of the junket was several orders of magnitude smaller than the cost of the AIG bailout.

Even in the financial crisis, there are few simple truths.

2008/10/11

Lake Peak

Last month I got to spend time in the mountains above Santa Fe. The resulting video is up at Vimeo now.


Lake Peak from Mitch Chapman on Vimeo.

The compression is bad. Then again, Vimeo is free :) And they provide hyperlinks to the original uploaded video.

2008/10/07

We Are Too Many: 1/4 of World's Mammals Face Extinction

One Quarter of World's Mammals Face Extinction: Scientific American:

" Deforestation, along with hunting or gathering food are the prime causes of the rapid declines in land mammals, such as elephants in Asia; most endangered marine mammals, like the vaquita in Mexico's Gulf of California, are killed by fishing nets, ship strikes or pollution."
"Vast tracts of tropical rainforest have been replaced by palm oil plantations for food and biofuels, satellite imagery reveals."

2008/08/13

Put a feather in his cap...

Wikipedia: maccaroni

So that's what the lyrics are about.

2008/08/05

GPS cellphones to unleash gamers onto the streets - tech - 05 August 2008 - New Scientist Tech

GPS cellphones to unleash gamers onto the streets - tech - 05 August 2008 - New Scientist Tech:

"But being able to discover the physical location of other people has downsides. Researchers at Portsmouth University have had to abandon GPS games projects because they cannot get approval from the ethics committee.
'Already there are social networking applications for the GPS iPhone which let you see where other iPhone users are,' says Andy Bain, lecturer at Portsmouth University's School of Creative Technologies. 'If I were a thief I'd abuse that knowledge right away to get myself more iPhones.'
Commercial games developers are not subject to the same ethical scrutiny as academics, he adds. It could be left to their customers to work out how to avoid anti-social gamers."

I don't know anything about gaming or social activities — I'm an old-school geek. But... Given that phone GPS is supposed to be accurate to within a few meters only, it's easy to imagine "wave function" games which rely on GPS. Such games might show the locations of participants as spheres, to indicate the GPS error. It would fall to the players to collapse the wave functions (find the other players).

I could lose a lot of money creating dull GPS-based games. "Never mind whether it's alive or dead, where is Schrödinger's Cat?" "Bohrtherford — Find the electron." Etc.

Best to lie down until the urge goes away.
"But think about this. Supposing you were to introduce a psychic, someone with clairvoyant powers, into the experiment — someone who is able to divine what state of health the cat is in without opening the box. Someone who has, perhaps, a certain eerie sympathy with cats. What then? Might that furnish us with an additional insight into the problem of quantum physics?"
"Dirk, this is complete nonsense."

-- Dirk Gently's Holistic Detective Agency, Douglas Adams

2008/08/03

Compiling subversion 1.5.1 on OS X 10.5.4

I've just tried to compile the subversion 1.5.1 client from its two source tarballs (subversion-1.5.1-tar.bz2 and subversion-deps-1.5.1-tar.bz2). I took care to first hide the /usr/local libraries from my existing subversion installation. Even so, the compilation failed, complaining

/usr/lib/libexpat.a: No such file or directory


The workaround was to temporarily move the system's /usr/lib/libexpat* dynamic libraries, and then to rebuild.

Here's the build script which worked for me:
#!/bin/sh
set -e
VERSION=1.5.1
rm -rf subversion-${VERSION}
tar xjf subversion-${VERSION}.tar.bz2
tar xjf subversion-deps-${VERSION}.tar.bz2
cd subversion-${VERSION}
./autogen.sh
./configure --without-apxs --with-ssl
make
sudo make install
sudo make install-swig-py

2008/08/02

New TextMate bundles

These aren't really new. I just wasn't aware of them.

JavaScript Tools


The JavaScript Tools bundle helps you lint, format and compress your JavaScript code, and convert code to and from JavaScript bookmarklets.

My favorite feature: whenever you save a JavaScript file via Command-S, the bundle automatically runs it through jslint. If any errors or warnings are found, a tooltip appears which shows the number of warnings/errors.

If you run a full validation using Control-Shift-V, you'll get a popup window showing "compilation" results -- complete with syntax errors and clickable links to take you to the offending source code.

Installation


I installed under ~/Library/Application Support/. It may be better to use /Library/Application Support/.
$ cd ~/Library/Application Support/TextMate/Bundles
$ svn export http://bundles.bundleforge.com/trunk/bundles/JavaScript%20Tools.tmbundle/

BTW I'm not sure why export is preferred over checkout.

If TextMate is already running, you can load the bundle by selecting Bundles->Bundle Editor->Reload Bundles.

Sproutcore


I haven't done much with Sproutcore yet, but it does already have its own TextMate bundle which provides a few tab-completion snippets.

Installation

$ cd ~/Library/Application Support/TextMate/Bundles
$ curl --location --get http://github.com/sproutit/sproutcore-tmbundle/tarball/master -o sproutcore-tmbundle.tar
$ tar xf sproutcore-tmbundle.tar


The curl --location option is required, since github will issue a redirect.

The extracted tarfile will have a root directory name of the form sproutit-sproutcore-tmbundle-.*, so a directory rename is needed.
$ mv sproutit-sproutcore-tmbundle-blah-blah.../ Sproutcore.tmbundle



2008/07/29

Google Calendar supports CalDAV

Google Calendar has added support for CalDAV. For Mac weenies, this means you can share calendars across multiple Macs, adding and removing events via iCal. And you can do it without paying for MobileMe.

Wonderful stuff!

2008/07/24

Terminal.app hangs at startup

I just got bit by this bug, under OS X 10.5.4. The symptoms are that sudo hangs, and Terminal.app hangs when opening a new tab or when starting up. Console.app shows messages of the form

7/24/08 7:04:44 AM kernel devfs: ttys001: name slot allocation failed (Errno=17)


rprr posted a workaround in the above thread which worked for me. I don't know how to link to specific messages in the discussion thread (or whether that's even allowed under the terms of use, egad), so here's a recap:
1. Started Terminal. It hung up. Did Force Quit and Sent Crash report to Apple.

2. Since I had a working X11 application, I used it to open about 10 xterms using the Applications->Terminal Menu of X11.app

3. I started Terminal again. Now it works.

Anarchogeek: Beyond REST? Building Data Services with XMPP PubSub

Anarchogeek: Beyond REST? Building Data Services with XMPP PubSub

Addresses a few problems which I've never had to face. Still, lots of interesting ideas to chew on. Hints at techniques that could be applied even to low-volume web services which involve long-running server-side computations.

Many little parasites add up to one big biomass - earth - 24 July 2008 - New Scientist Environment

The main point of the article is that parasites are much more populous than previously believed. But this quote was the most interesting:

Many little parasites add up to one big biomass - earth - 24 July 2008 - New Scientist Environment:

"Dobson says he has work in press showing that parasites contain between 10 and 1000 times more pollutants than their hosts. He suggests parasites might play an important role in cleaning up the animals they inhabit."


So they castrate you, but they also keep you clean...

2008/04/22

Served up in a fine china Meatri Dish

Love the Steak and Save the Cow:

"PETA offers a $1 million prize to whoever can come up with tasty, edible, lab-grown meat, an advance they say would save billions of animals while still satisfying our carnivorous cravings."


Of course there's another solution, courtesy of the late, great Douglas Adams:
The animal staggered to its feet. It gave a mellow gurgle.
'A very wise choice, sir, if I may say so. Very good,' it
said, 'I'll just nip off and shoot myself.'
He turned and gave a friendly wink to Arthur.
'Don't worry, sir,' he said, 'I'll be very humane.'

2008/04/17

Why Lockheed Martin signed on w. the Spaceport

From KRQE in Albuquerque: Spaceport launch tests future spacecraft




"It looks a bit like the space shuttle and would fly to space and return the same way. But even the big version would not carry people, just satellites.

The goal is to get to orbit faster and cheaper thanks to an automated reusable spacecraft run by its own computers and just a handful of people for a launch crew."

New Scientist: Revealed: the Asian source of the annual flu epidemic

Revealed: the Asian source of the annual flu epidemic - health - 17 April 2008 - New Scientist:

"Better surveillance in east Asia should lead to better predictions of how flu is evolving, and what is likely to be needed in next year's flu vaccine, says Smith."

2008/04/08

Thank you, wsgi

Thanks to all of the developers behind wsgi.

When I first heard about it, wsgi struck me as an unnecessary complication. Then someone showed me how it could simplify testing of web applications. And now:

High-Scalability:

Google App Engine supports any framework written in pure Python that speaks CGI (and any WSGI-compliant framework using a CGI adaptor), including Django, CherryPy, Pylons, and web.py. You can bundle a framework of your choosing with your application code by copying its code into your application directory.

2008/04/04

Visual Web Developer "Failed to start monitoring changes"

I keep forgetting about this...

I'd like to do development on an ASP.NET web application which resides in a VMware Fusion shared folder. Unfortunately, as noted in the Microsoft Forums, Visual Web Developer 2005 Express Edition (at least) does not support hosting on a UNC share.

So, AFAICT, the only option is to do development in a local folder. To access that folder from the host operating system, it needs to be shared from the Windows VM.

VMware Fusion, OpenSUSE 10.3 x64, copy and paste

I recently installed a 64-bit OpenSUSE 10.3 virtual machine under VMware Fusion. Everything worked fine except cut&paste -- the vmware-user executable was not launching when X11 started.

ldd showed a dependency on libexpat.so.0, in addition to libexpat.so.1. I installed that using yast, rebooted, and -- huzzah -- cut&paste now works.

yast_install_libexpat.png

More details are available in the VMware Fusion discussions forum.

2008/03/26

Five Open Tools for 2D Structure Layout (aka Structure Diagram Generation)

Five Open Tools for 2D Structure Layout (aka Structure Diagram Generation)

Good summary of several alternatives. I've been using CDK of late, but am partial to tools written for CPython. I wonder if any of the alternatives make it as easy to extract coordinates as does CDK?

2008/03/21

TUAW Terminal Tip: Safari 3.1 brings true one-window mode

Terminal Tip: Safari 3.1 brings true one-window mode:

...true one-window mode is finally, finally, here for Safari. All you need to enter is the command below into Terminal, hit enter, and you're sorted.

defaults write com.apple.Safari TargetedClicksCreateTabs -bool true


Yay!

Functest

Writing Functests:

"This is where functest really shines. When you run functest against any directory or file the collector actually compiles a dependency chain which includes any valid python modules in all the parent directories..."


Hm. So functest would let me dispense with this nonsense boilerplate in my test modules?
import sys
import os
thisdir = os.path.abspath(os.path.dirname(__file__))
def relpath(p):
return os.path.abspath(os.path.join(thisdir, p))
sys.path.insert(relpath("../"))



I wonder if nose does/will provide similar facilities? It's pretty nice in other respects...

Twill, CherryPy 3 and testing with internal servers

Twill can test CherryPy web servers "in process", without having to run them as servers. I've used twill this way with CherryPy 2, but when I recently tried to do the same thing with a CherryPy 3 server everything broke.

I had based my code on an old CherryPy 2 tutorial by Titus Brown, and was trying to grep through the CherryPy 3 code tree to figure out how to patch it up. Bad idea :)

Yesterday Google finally turned up a solution, from a talk Titus gave at PyCon 2007.

The upshot: don't use cherrypy._cpwsgi.CPWSGIApp. In CherryPy 3, your application itself is already a WSGIApp. What's more, I think cherrypy._cpwsgi.CPWSGIApp may be broken. For sure, it and twill have incompatible ideas about the correct type of the 2nd constructor argument.

Anyway, thanks to Titus, here's an example of how to connect twill to a CherryPy 3 application for in-process testing:

import twill
import cherrypy
...
wsgi_app = cherrypy.tree.mount(myApp, "/", myConfig)
cherrypy.engine.start(blocking=False)
twill.add_wsgi_intercept('localhost', 8080, lambda: wsgi_app)


[Update 2008/03/24] Ditched the cherrypy.server.quickstart() invocation, per fumanchu's comment. Reported as Ticket #801.

2008/03/10

waf build errors

I'm evaluating waf to see if it's easier to use than SCons (especially for Qt projects). So far the results are encouraging. In particular, waf reports many kinds of problems using straightforward (color-coded!) error messages, rather than Python tracebacks.

target 'build_info' does not exist

Sometimes waf does spew an unintelligible Python traceback reminiscent of SCons. For me, these typically end with a KeyError:

File "/path/to/.waf-1.3.2-blah/wafadmin/Task.py", line 290, in must_run
prev_sig = tree.m_sig_cache[key][0]
KeyError: -214303645


This error always translates to "you are trying to build a file which is part of your source tree."

My SConscripts work in situ, creating object files etc. in the same directories where the source code resides. waf prefers to put build products in a separate build/ subdirectory. When waf is instructed to generate an output file in its build tree, and when that file already exists in the source tree, waf fails with the KeyError traceback.

I'd bet this problem is most common in software projects which started life using build systems like Make or SCons -- tools which default to building in situ.

For example, I'm trying to use waf in a subversion workspace where I've been doing SCons builds for years. To make matters worse, one of the build products is a header file, containing revision number and date for the current build. This looks like a source file, so it's likely that I never checked whether it was properly removed by scons -u -c.

In retrospect, I should have started with a clean check-out...

2008/03/07

Rogue Amoeba: Code Signing and You

Code Signing and You:

"Code signing itself is a neutral technology, but it gives incredible power to the system vendor, and that power is just waiting to be exercised and abused."


It's possible that Apple intends to close off the OS X platform. If that happens, I'll go back to Linux.

2008/03/06

DailyTech - Researcher: Basic Greenhouse Equations "Totally Wrong"

From DailyTech:

"NASA refused to release the results.  Miskolczi believes their motivation is simple.  'Money', he tells DailyTech.  Research that contradicts the view of an impending crisis jeopardizes funding, not only for his own atmosphere-monitoring project, but all climate-change research.  Currently, funding for climate research tops $5 billion per year.
"

"The equations also answer thorny problems raised by current theory, which doesn't explain why "runaway" greenhouse warming hasn't happened in the Earth's past. The new theory predicts that greenhouse gas increases should result in small, but very rapid temperature spikes, followed by much longer, slower periods of cooling -- exactly what the paleoclimatic record demonstrates."

"Miskowlczi has used his theory to model not only Earth, but the Martian atmosphere as well, showing what he claims is an extremely good fit with observational results."


Hey, at least we still have peak oil.

2008/03/03

Intermittent Pickle Problems in Jython

The previous post mentioned "integrating" Jython and CPython by transmitting a stream of pickles between the two. I encountered one intermittent problem with this approach, and I'm unsure of its cause. (Hm, and I should probably post this to a Jython mailing list...)

Problem


In Jython I'd pickled the str() of a java.io.StringWriter, into which I'd just written the SD representation of a CDK molecule. Jython could create the pickle alright. But when I tried to unpickle it in CPython, sometimes, for some molecules, I got a traceback:
File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/pickle.py", line 970, in load_string
raise ValueError, "insecure string pickle"
ValueError: insecure string pickle


The error occurred consistently in my application code, always on the same input structure. But I couldn't derive a simple test script to demonstrate the problem.

Investigation


Examination of the problematic pickle data showed that a Python unicode string literal marker had somehow been inserted, and the type code for the item was somehow S (for string) rather than V (for unicode):
...
sS'sdf'
p3
Su'ZINC00000181\n CDK...
^ What the... ?


Workaround


Google turned up a usable workaround: encode the offending string as utf-8 before trying to pickle it.


import codecs
enc = codecs.getencoder('utf8')
...
sdf = enc(sdf)
...


Ted Leung: The Sun is going to shine on Python

Congratulations to Ted Leung (and to Frank Wierzbicki):
The Sun is going to shine on Python.

Their work at Sun will extend well beyond Jython, but Ted's post reminded me of my recent experiences. Jython 2.2 sure made it pleasant and easy[1] to get what I needed out of CDK, and to integrate the results into a CPython app via pickle and subprocess.

I did miss some language features such as yield which have appeared in CPython since 2.2. Maybe at some point Ted and/or Frank will have time to re-sync Jython with CPython?

[1] I had one intermittent problem with this approach. See the next post.

2008/02/26

New Scientist: Fatal brain cancer tamed by gene therapy

Fatal brain cancer tamed by gene therapy - 25 February 2008 :

Previous attempts to treat glioblastomas with gene therapy failed because some tumour cells survived and regrew. The new treatment overcomes this problem by permanently priming the immune system to pick off any straggler tumour cells.

A harmless virus that only infects fast-dividing cancer cells is injected directly into the brain... One gene, HSV1-TK, kills the cancer cells by activating ganciclovir...


And here's the cool bit:
...a second gene, Flt3L... summons immune "dendritic" cells from the bloodstream into the brain.


(How does it do that?)

[The dendritic] cells engulf the debris and transport it back to lymph nodes, where they re-prime the immune system to attack any remaining tumour cells during and after treatment.


Lymph nodes seem like a gunnery school for white blood cells: you go there to learn how to distinguish friend from foe. (BTW fevers seem to help lymph nodes do their jobs.)

2008/02/25

Doc Searls: The FCC and the Giant Zero

The FCC and the Giant Zero:

"Message to Verizon and the rest: the Internet is not about ‘consumer choice’. We produce as well as consume. We need to be able to run our own servers. [emph. added] We need to be able to exercize supply as well as demand. We need symmetricality, not just neutrality."


Amen to that.

I live in Santa Fe. As far as I can tell, my choices are Earthlink (via Qwest DSL @ 1.5Mbps) and Comcast. If I want a static IP address, a useful step to server-hood, then my rates would go up by 30%. Bah.

Netgear WAN MTU Size

(Not sure why I haven't written this up yet. It sure was a problem for a long time...)

I used to work "offsite" -- outside the home -- several days a week. When offsite my laptop could perform subversion operations against a repository on my home network, with good performance. But when the notebook was "inside" the home network, those same operations would take forever.

Eventually I stumbled on the fix, clearly explained in the help sidebar of the WAN Setup page of my Netgear WGR614 router: change the MTU to 1492. (Shades of Christopher Columbus!)

Nobody reads documentation :\

The normal MTU (Maximum Transmit Unit) value for most Ethernet networks is 1500 Bytes, 1492 Bytes for PPPoE connections, or 1436 for PPTP connections.


2008/02/14

Site-specific browsers and web-app testing


 ?


Site-specific browsers should simplify testing of some types of web applications, e.g. those which support multiple registered users. On platforms such as Mac OS X, which typically run only one instance of each application, SSBs should allow you to launch multiple, distinct applications which point to the same website.

Is anyone doing this? Is it better (and does it always suffice) to simply run multiple copies of a twill script, and to dispense with browser-based tests?

I haven't tried Fluid yet, since my main work machine is still running Tiger.

Alas, I guess basic Prism apps won't do the job:

prism_one_copy.png


Technorati Tags:
, , ,


2008/02/13

DNA Articles du Jour

Next-generation pathogen sequencing

http://www.technologyreview.com/Biotech/20191/

454 Life Sciences have figured out how to isolate pathogen RNA from human tissue samples, and have used the process to identify previously-unknown pathogens as the likely cause of death for three transplant recipients.

In the 1980s, my brother's neighbor almost died from an illness whose cause was never determined. More recently, local doctors have been unable to figure out why a friend's daughter had a fever for three weeks. This process may make it possible to diagnose the causes of many more illnesses.

"...the sequence of the new virus was different enough that existing methods could not have detected [it]..."


"As many as 40 percent of cases of central nervous system disease cannot be traced back to a specific culprit. For respiratory illness, the figure is 30 to 60 percent."


"Usually, PCR requires some advance knowledge of the sequence in question because it relies on molecular primers that match the string of code to be amplified. But 454 sequencing avoids that problem by using a large number of random primers."



Combining DNA from >2 "parents"

http://www.dailytech.com/article.aspx?newsid=9835

I didn't know people could have problems with their mitochondrial DNA.

"...[the] research involved implanting the DNA from a [woman] with a mitochondrial disorder into the egg of a [woman] with healthy mitochondria. Thus the woman with the genetic disorder passed on the rest of her genetic legacy, while the other woman contributed only [healthy mitochondrial] DNA."


Ethical firestorm to follow...

2008/02/10

Installing PVM under MacPorts on Leopard

I've been having trouble getting PVM 3.4.5 to install under MacPorts on Leopard. The conf/DARWIN.def configuration file defines the FAKEXDRFLOAT preprocessor symbol; it may be needed for OS X 10.4, but it causes a compiler error w. GCC 4.0.1 under 10.5:

../../src/pmsg.c:785: error: static declaration of 'xdr_float' follows non-static declaration.


The workaround is simple: install the Darwin8 variant.

$ sudo port install pvm +darwin_8

2008/02/09

DailyTech - Solar Activity Diminishes; Researchers Predict Another Ice Age

DailyTech - Solar Activity Diminishes; Researchers Predict Another Ice Age:

Researcher Dr. Timothy Patterson, director of the Geoscience Center at Carleton University, shares the concern. Patterson is finding "excellent correlations" between solar fluctuations, a relationship that historically, he says doesn't exist between CO2 and past climate changes. [emphasis added] According to Patterson. we shouldn't be surprised by a solar link. "The sun [is] the ultimate source of energy on this planet," he says.


Oh no! Is it too late to start increasing our greenhouse gas emissions, to keep the planet from freezing over? ;)

Whatever is the truth about how we affect our environment, it's good to be reminded of our insignificance — and our uncertainty.