Archive for March 2009

Facts Fail To Impress The Superstitious. Film at 11.

Andrew Cooper, a local astronomer, laments the continued belief in astrology, which apparently is so detached from the facts that they’ll print “The Sun has entered Aries,” when, due to precession, the Sun is still well inside Pisces.

Hawai’i is a place of deep spirituality, both mainstream and New Age. A few years ago Tina and I went to a public-comment meeting on regulations for dolphin-human swimming. Spinner dolphins rest during the day in certain coves along the Kona coast (not every cove will do — the dolphins like to rest over sand bottoms that are between, say, 40 and 120 feet deep). There’s no question that dolphins’ behavior is “disrupted” by swimmers or divers (they swim deeper under swimmers and they turn away from divers). If the Marine Mammal Protection Act were followed to the letter, large sections of several of the most popular swimming and diving locations would necessarily have to be entirely closed to humans. So some kind of compromise is needed. Tina and I have friends in both the commercial SCUBA industry and in the conservation community, so we went to this meeting expecting to hear some reasonable talk.

Well. The public testimony was entirely dominated by people explaining that dolphins were: 

  • alien beings
  • transdimensional beings
  • beings of pure spirit

One way or the other, apparently it is the dolphins’ greatest pleasure to seek out humans and swim with them, especially those that pay $75 to drive in high-speed inflatables owned by bed & breakfasts that specialize in “enlightened” New Age tourism. Uh huh. At one point, Tina leaned over and said “You know, I once had a telepathic link with a dolphin. It said… ‘leave me the fuck alone.’” 

Anyway, word has it that after the meeting, the poor researcher whose job it was to respond to these comments had to take two weeks vacation, he was so dismayed.

From Theory to iPhone, Pt. 3: A Diversion Into Ruby

As far as I know, you cannot program the iPhone with Ruby. However, you can program OS X Cocoa applications with Ruby and, as a learning experience, it’s very helpful.

I am coming to believe that the biggest barrier to learning how to program Cocoa are tutorials that emphasize the toolset rather than providing any context. This is a decades-old complaint of mine with programming tutorials, but that’s a subject of another post.

In the case of my Ruby code, here is the object structure:


Which is about as classic an MVC triad as you can hope for, the only variation from the classic structure being the use of the singleton NSNotificationCenter rather than a strict OO Observer pattern.

Initialization also follows the classic sequence: the “main()” in the case of a Cocoa app is this Ruby code, executed outside of a class definition:

# set up the application delegate
delegate = ApplicationDelegate.alloc.init()

This will set in motion the initialization, which will eventually call back to the function applicationDidFinishLaunching(sender) in the just-created instance of the ApplicationDelegate class:

require 'osx/cocoa'
require 'MyModel'
require 'MyView'
require 'MyController'

class ApplicationDelegate < OSX::NSObject
  def applicationDidFinishLaunching(sender)
    model = MyModel.alloc().init_cocoa()

	#View will subscribe to model notifications. View creates Controller
	view = MyView.alloc().initWithFrame_model([30,20,600,300], model)

	#Do something that will propagate through connections
	model.text = "Hello, MVC!"

The applicationDidFinishLaunching(sender) method follows the classic MVC initialization sequence:

  1. Create the Model
  2. Create the View
  3. Pass the Model to the View
    1. View creates its own Controller
    2. View passes Model to Controller

I then manipulate the Model (by setting its text) in order to show how things are wired up.

But before we review that, let’s take a look at the View initialization function initWithFrame_model(frame, model)

#This is inside class MyView
def initWithFrame_model(frame, model)
	#Create a UI
	styleMask = OSX::NSTitledWindowMask + OSX::NSClosableWindowMask + OSX::NSMiniaturizableWindowMask + OSX::NSResizableWindowMask
	@window = OSX::NSWindow.alloc.initWithContentRect_styleMask_backing_defer(frame, styleMask, OSX::NSBackingStoreBuffered, false)
	@textview = OSX::NSTextView.alloc.initWithFrame(frame)
	@window.setTitle("Ruby Cocoa MVC")

	#Make controller. Note this must follow initialization of "controlled things" (e.g., @window)
	controller = MyController.alloc.initWithView_model(self, model)

	#Associate with model. Listen to model updates via NSNotificationCenter
	@model = model
	@notification_center = OSX::NSNotificationCenter.defaultCenter()
	@notification_center.addObserver_selector_name_object_(self, :on_model_updated, 'MyModelUpdatedNotification', @model)

	return self

First, we setup the View itself using all those Cocoa calls. Then we instantiate the Controller, passing the model along (we’ll return to MyController.initWithView_model(self, model) shortly). The last step of MyView initialization is registering a callback for when the model posts notifications. In this case, the parameters to addObserver_selector_name_object_() mean “When the @model sends a notification called ‘MyModelUpdatedNotification’ call the function self.on_model_updated()”:

#This is inside class MyView
def on_model_updated(notification)
	puts "MyView.on_model_updated() called"

Very straightforward: this the callback made after the model has been updated. In this case, the View reflects the model’s text attribute. It’s a very simple Model and a very simple View!

class MyModel < OSX::NSObject
	def init_cocoa
		@text = "initial text"
		return self

	def text=(t)
		puts "Setting text: #{t}"
		@text = t
		#Model notifies observers
		notification_center = OSX::NSNotificationCenter.defaultCenter()
		notification_center.postNotificationName_object_("MyModelUpdatedNotification", self)

	def text()
		return @text

This is almost deceptive, in that the most complex aspect of MyModel is the use of the NSNotificationCenter. One hopes that in the real world, there are all sorts of domain objects. In case it’s not obvious, NSNotificationCenter.postNotificationName_object_() is the complement to NSNotificationCenter.addObserver_selector_name_object_() discussed previously.

So we’ve got a simple Model that concerns itself with problem domain and a simple View that concerns itself with output. So now let’s return to the initialization sequence and the Controller, which concerns itself with input.

#This is in class MyController
def initWithView_model(view, model)
	@view = view
	@model = model
	#View is manipulated by Controller

	#Controller listens for updates from Model via NSNotification Center
	@notification_center = OSX::NSNotificationCenter.defaultCenter()
	@notification_center.addObserver_selector_name_object_(self, :on_model_updated, 'MyModelUpdatedNotification', @model)

	return self

Here, we see again the specification of a callback for when the Model notifies of changes. In this case, I just made an function that simply logged itself to the console (“Does input care if the text changes? Mmm… Not really…”). Really the only important piece of code here is the attachment of the view’s window‘s callbacks to the MyController. To fill that out, I had to write some simple functions to handle events associated with the window closing and the application terminating.

Easy-peasy, and here is the program running:


Pragmatic Bookshelf Goes Kindle-Compatible

The Pragmatic Bookshelf  is going Kindle and iPhone compatible, with support for .epub (iPhone) and .mobi (Kindle) formats. 

I just downloaded RubyCocoa on the Kindle and it looks excellent — with listings in monospaced font! – but most of my other books are not yet available in Kindle format. 

Pragmatic Programmers have also begun selling tutorial screencasts. I’ve yet to take a look at any of those, but I think it’s a good idea.

 Kindle support from Pragmatic Programmers is a big deal. In my mind, PragProg has become the new O’Reilly. Not that O’Reilly has gone the way of the dinosaurs (or, say, Miller Freeman), but Safari access on portable devices is such a huge and obvious plum that the very fact they haven’t plucked it makes me think that they must be facing internal issues.

My Most Popular Posts

In response to a request from the esteemed Director of the FBI Blogs, these are some of the blog posts that have gotten the most traffic through the years:

Unfortunately, my recent move from the Das Blog engine to WordPress has left all my embedded links broken. I’ll get around to fixing that someday (sure), but only after I do something about my blog theme. 

And that will have to wait for a weekend that is not sunny…

FBI Bloggers: From Big Island



I’m honored to be part of the FBI Blogs link-cycle. Although, having lived here only five years, I still feel very much a newcomer to the island.

I don’t blog much about Hawai’i or the Big Island because I figure that most people subscribe to this site in order to read about software development. On the other hand, since I lost most of my old content and articles when switching from Das Blog to WordPress and since I have hardly had time to write any blogposts in the past year or so, it’s probably a moot point.

One of the many interesting things about Hawai’i is how much smaller the community is than, say, the San Francisco Bay Area, where I lived for 17 years. In the Bay Area, you have lots of eyes on government and business. In Hawai’i, and especially the “neighbor islands” (not Oahu, where 90% of the state’s population lives), the government is used to “reporting” that consists of a well-known reporter showing up at official meetings and transcribing rote answers to rote questions. The reporting of “citizen journalists,” with their unrestrained voices and inconvenient attention to the world outside of council meetings, is actively clashing with a system that is unabashedly a political machine / old-boys network.

Simultaneously, the state and the Big Island are microcosms of the most interesting global challenges: environmental change and energy. Just yesterday, a report came out saying that 1/3 of the nation’s endangered birds live in Hawai’i (and many native species have already been driven to extinction). Accelerated rising of the sea-level will be a huge problem for Oahu. And our coral reefs are under threat from ocean acidification and warming. Meanwhile, this state could easily be carbon-neutral with existing technology. We have ample amounts of essentially every form of renewable energy except hydroelectric: wind, solar, geothermal, OTEC (my favorite), wave, and current.

Obviously, the infrastructure to support electric vehicles is much easier to build on an island, where a handful of charging stations is all that is required to ensure one is always nearby.

Yet we pay the highest electric rates in the nation and our energy company runs roughshod over a spineless and/or complicit Public Utilities Commission.

These are issues of interest to me, but whether this domain is the place to speak of them or not, I’ve not decided. What do you think?

Oslo Column Now Available…

My latest SD Times column is the first of a short series on Oslo.

Idea: Solar Energy Test Kit

I wish that I could put something the size of, say, a briefcase on my roof, leave it there for a month, bring it down, plug in a USB cord, and read “A solar water heater would have generated X% of your hotwater needs. A PV installation of X panels would have generated Y KwH.”

Basically: a single solar cell plus a data logger. I see a market in Hawaii (small) and the Southwest mainland (big).

Make it cheap enough and sell it to the geek market even. I suppose for the geek market you’d have to add WiFi connectivity.

Ultrafast Battery Recharging Breakthrough

The Ars Technica article lithium breakthrough could charge batteries in 10 seconds reports on a Nature article describing a very fast way to charge or discharge batteries. The upshot is that an electric-car battery could be charged in five minutes (“which would make electric vehicles incredibly practical”) but would pull 180,000 Watts (“which is most certainly not practical.”). I would think you could use a two-stage process (whereby the filling station’s bank of batteries would “trickle” charge from the grid and then discharge them rapidly), but I would also think that would generate huge amounts of heat unless you had a handy room-temperature-superconducting charging cord.

Kindle for iPhone: Nice But Not Comparable

Amazon has released a Kindle application for the iPhone. It nicely synchronizes with your Kindle library (which is all stored “in the cloud”) but, strangely, it seems to only pick up books and not periodicals or blogs.

The display is okay (I mean, it’s the iPhone display. Duh.), nothing compared to the Kindle’s eInk. The big win, though, is that the iPhone supports color, so this might make the iPhone good for reading Kindle content with images.

It appears that there’s no facility for taking notes or highlighting, which is a fairly big deal for technical readers (on the other hand, since it’s the iPhone I can flip over to Evernote, take a note there, and it synchs up with all of my Evernote databases). (P.S. Evernote is no OneNote, but there is no OneNote for the Mac, which is a huge disappointment.)