Seven Girlfriends To The Perfect Spouse

What do walking sticks, card shuffling, and movie stars have to do with finding the perfect mate? They seem to support that you can find your spouse by seriously dating seven people.

When one goes to a technical conference on Java, perhaps the last thing you’d expect the a speakers’ lunch conversation turn to is mathematical selection of a mate.

I suppose it started simply because we had been talking about change. The topic started with source code change, changes at the office, and moved into changes in people. I offered up the classic observation that women get frustrated at their men because they don’t change, but that men get frustrated at their women because they do.

One gentleman was lamenting on his situation and admiring the subtle manipulation by his wife prior to his flight:
“Honey, ” he relates she began, “you should probably lose some weight, though I’d still love you if you were fat as a house.” And, after a momentary pause, she inquires, “Do you think I need to lose weight?”

Apparently his response of “I always love you, too” wasn’t quite what she was looking for.

Another speaker spoke up and added, “Well, I don’t have that problem at all. We’ve come to an agreement. I can be either fat or bald, but not both.”

Absolutely curious, I asked how that arrangement was sought. That just isn’t the kind of thing that normally just comes up as the finer points of marital negotiation.

He pondered and explained it started by as an ultimatum by her — unfortunately for her, she was engaging with one of the brighter logical minds…

“Honey, I’ve thought about it, and you can’t grow up to be fat and bald.”
“Really? Well, I have no control over being bald.”
“Oh. Well then you can grow up to be bald, but not fat.”
“Well, if I can be bald and not fat, then it’s only fair that I can also be fat and not bald.”
“makes sense, that sounds fair.”
“Then it’s settled, I can either be bald, or fat, but not both.”
“Agreed.”

And at that point, he took another bite of cake, stroking his head of hair with the other hand.

But this started a fantastic digression about how one knows when you have the right person in your life. We’d all just come out of meetings pertaining to measuring, quantifying, trend analysis, and metrics.

Based on rough calculations, to calibrate the scale and distribution of a sample size population, to do the best you could do, in a short period of time, it was concluded that you really needed to examine at least seven samples. At that point, you have a reasonable approximation for making a reasonable judgment call, and it was just a matter of how many standard deviations you were discriminating for.

A simple example is called for.

You’re walking in the woods and you’ve been given the task to pick up the best walking stick you can find. But the rule is, once you set it down, you can’t pick it up again.

So, you pick up the first stick you come to. However, you don’t know if this is the largest, or smallest. You have nothing to compare it to. With no basis for comparison, you set it down.

So, you pick up the next stick you come to. And you start to note more attributes, such as weight, shape, type of wood, etc. And again, you drop it.

So, you pick up the next stick you come to. As the attributes that interest you start to prioritize, you find yourself become more aware of the quality. You start looking at things like balance, general utility, wear, and things that come along with the stick, such as moss or termites. Some things are alterable, others are not.

As your go from stick to stick, each time you’re refining your assessment abilities and have gained more knowledge about what you’re looking at, as well as determining what you want.

After your six stick, depending on the breadth of the distribution you’ve encountered, you’ve started to formulate an accurate picture of of what you can reasonably expect. At this point you simply decide what criteria must be met, and the next stick that meets that criteria, you take. Permanently.

Oh sure, there might be something else better out there, but the effort, cost, time, dangers, and availability will more than likely offset the value you’d currently have. Trading your walking stick for something new, only trades existing faults with new unforeseen ones.

The same mathematical application applies to the dating scene.

Young couples find themselves inexperienced for selecting long term candidates and determining personal discriminators: there are unforeseen personality clashes, other options suddenly look more attractive, and if one settles too prematurely, it usually means being treated like a doormat or being taken advantage of financially.

Who among us didn’t stumble upon infatuation and think it was true love at sixteen? Or, find an exciting girlfriend only to discover character flaws that were obvious to our friends, family, and even our own 20/20 hindsight? Or, have everything wonderful and stable only to have it all turned on its ear for not explicable reason just as she turned twenty.

Unfortunately, for many, desperation or loneliness causes some people to settle well before their calibration process is complete; these people usually learn the hard lesson that being trapped in a bad relationship is worse than being lonely.

Alternatively, there are those that spend too much time in the calibration phase, and totally miss out on the longer term joys that are more rewarding.

It’s also interesting to note that we see microcosms of discriminating selection occur around when context and locality are ignored and we forget the more global nature of the chase.

One example may be the cruise ship filled with old geezers, of which in that context, some middle-aged person who’d never catch your eye looks fairly darn attractive in light of the situation. Same goes for co-workers, people met in bars, or even at parties — the limited selection forces expectations to be lowered.

This is why online dating services that give the illusion of many candidates keeps people seeking for perfection, while speed dating narrows the options and forces a compromised choice or none at all.

Of course, one might also say that it’s the reasoning behind things being in the last place you look, for once you make the find, the search is over.

Seven, however, lets you home in on a very acceptable choice that you can be genuinely be happy with, rather than waiting forever. For you too have a shelf life, and by the time you find the ideal through an exhaustive search, you may be too old to do anything about it.

I ponder, though, if there’s something more special going on.

For example, we’ve all heard of six degrees to Kevin Bacon, at that point you’ve traversed enough paths to get where you want.

Additionally, and I think this was in a story by Wired Magazine, a number of years ago, there was a mathematician who was going on a long horseback cattle drive. To amuse himself, he brought along a deck of cards, and spent the time shuffling it. At the end of his trip, he had mathematically deduced that for a deck to be sufficiently randomized (that is any card could be assured to physically be in any position), it required the deck to be shuffled seven times.

In both cases, we see that seven got us a good sampling — and with a good sample, an intelligent choice can be made.

Using In A JavaScript Literal

Today I got bit by a very interesting bug involving the tag. If you’re writing code that generates code, you want to know about this.

I’m currently working on an application that takes content from various web resources, munges the content, stores it in a database, and on demand generates interactive web pages, which includes the ability to annotate content in a web editor. Things were humming along great for weeks until we got a stream of data which made the browser burp with a JavaScript syntax error.

Problem was, when I examined the automatically generated JavaScript, it looked perfectly good to my eyes.

So, I reduced the problem down to a very trivial case.

What would you suppose the following code block does in a browser?

<HTML>
<BODY>
  start
  <SCRIPT>
    alert( "</SCRIPT>" );
  </SCRIPT>
  finish
</BODY>
</HTML>

Try it and see.

To my eyes, this should produce an alert box with the simple text </SCRIPT> inside it. Nothing special.

However, in all browsers (IE 7, Firefox, Opera, and Safari) on all platforms (XP/Vista/OS X) it didn’t. The close tag inside the quoted literal terminated the scripting block, printing the closing punctuation.

Change </SCRIPT> to just <SCRIPT>, and you get the alert box as expected.

So, I did more reading and more testing. I looked at the hex dump of the file to see if perhaps there was something strange going on. Nope, plain ASCII.

I looked at the JavaScript documentation online, and the other thing they suggest escaping are the single and double quotes, as well as the backslash which does the escaping. (Note we’re using forward slashes, which require no escapes in a JavaScript string.)

I even got the 5th Edition of JavaScript: The Definitive Guide from O’Reilly, and on page 27, which lists the comprehensive escape sequences, there is nothing magical about the forward slash, nor this magic string.

In fact, if you start playing with other strings, you get these results:
  <SCRIPT> …works
  <A/B> …works
  </STRONG> …works
  <\/SCRIPT> …displays </SCRIPT>, and while I suppose you can escape a forward slash, there should be no need to. Ever. See prior example.
  </SCRIPT> …breaks
  </SCRIPTX> …works (note the extra character, an X)

With JavaScript, what’s in quotes is supposed to be flat, literal, uninterpreted, meaningless test.

It was after this I turned to ask for help from several security and web experts.

Security Concerns


Why security experts?

The primary concern is obviously cross site scripting. We’re taking untrusted sites and displaying portions of the data stream. Should an attacker be able to insert </SCRIPT> into the stream, a few comment characters, and shortly reopen a new <SCRIPT> block, he’d be able to mess with cookies, twiddle the DOM, dink with AJAX, and do things that compromise the trust of the server.

The Explanation


The explanation came from Phil Wherry.

As he puts it, the <SCRIPT> tag is content-agnostic. Which means the HTML Parser doesn’t know we’re in the middle of a JavaScript string.

What the HTML parser saw was this:

<HTML>
<BODY>
  start
  <SCRIPT>alert( "</SCRIPT>
  " );
  </SCRIPT>
  finish
</BODY>
</HTML>

And there you have it, not only is the syntax error obvious now, but the HTML is malformed.

The processing of JavaScript doesn’t happen until after the browser has understood which parts are JavaScript. Until it sees that close </SCRIPT> tag, it doesn’t care what’s inside – quoted or not.

Turns out, we all have seen this problem in traditional programming languages before. Ever run across hard-to-read code where the indentation conveys a block that doesn’t logically exist? Same thing. In this case instead of curly braces or begin/end pairs, it was the start and end tags of the JavaScript.

Upstream Processing


Remember, this wasn’t hand-rolled JavaScript. It was produced by an upstream piece of code that generated the actual JavaScript block, which is much more complex than the example shown.

It is getting an untrusted string. Which, to shove inside of a JavaScript string not only has to be sanitized, but also escaped in such a way that the HTML parser cannot accidentally treat the string’s contents as a legal (or illegal!) tag.

To do this we need to build a helper function to scrub data that will directly be emitted as a raw JavaScript string.


  1. Escape all backslashes, replacing \ with \\, since backslash is the JavaScript escape character. This has to be done first as not to escape other escapes we’re about to add.
  2. Escape all quotes, replacing ' with \', and " with \" — this stops the string from getting terminated.
  3. Escape all angle brackets, replacing < with \<, and > with \> — this stops the tags from getting recognized.

private String safeJavaScriptStringLiteral(String str) {

  str = str.replace(“\\”,”\\\\”); // escape single backslashes
  str = str.replace(“'”,”\\'”); // escape single quotes
  str = str.replace(“\””,”\\\””); // escape double quotes
  str = str.replace(“<“,”\\<“); // escape open angle bracket
  str = str.replace(“>”,”\\>”); // escape close angle bracket
  return str;
}

At this point we should have generated a JavaScript string which never has anything that looks like a tag in it, but is perfectly safe to an XML parser. All that’s needed next is to emit the JavaScript surrounded by a <![CDATA[]]> block, so the HTML parser doesn’t get confused over embedded angle brackets.

From a security perspective, I think this also goes to show that lone JavaScript fragment validation isn’t enough; one has to take it in the full context of the containing HTML parser. Pragmatically speaking, the JavaScript alone was valid, but once inside HTML, became problematic.

BestBuy, You Did Something Right

BestBuy did something right… I hope they keep it up.

BestBuy, you did something right. Thank you!

The web is just littered with screw-ups by BestBuy, from its policies to indifferent workforce. However, this weekend I had quite the opposite experience, and I felt it worth sharing, for being in the moment, it was as if BestBuy returned to its original roots.

I was looking for a Wii game for my four year old nephew who had come to visit. I wanted something more complicated than Wii Sports and something not so intense as Tiger Woods PGA. The solution was sitting right there on the shelf, Super Swing Golf; the price looked right, so I grabbed it.

At check out, the person rang up my purchases, and the total seemed high — the game was registered as $49.95.

Casually I mentioned, “Is it $49.95? I thought it was $29.95.”

Rather than getting into an argument with me, siding with the computer, or such, the checkout clerk simply said “can you show me where you got it?” And then he flipped off his line light.

I escorted him to the game section, apologizing the whole time in that it most likely was my fault and that perhaps I missed something in my haste. I knew I was going to get the game no matter what the cost, and at this point felt I was wasting his time.

As we got over to the game area, there were three stacks of Super Swing Golf, and there were $49.95 price tags and banners all over the place.

I nodded that he was right, but then something on the second shelf caught my eye. I pointed, and he reached in and pulled in out. There it was a plastic game separator with a yellow label listing “Super Swing Golf $29.95.”

He pulled it out, took it back to the register, overrode the price, and gave it to me for the lower price. He could have just as easily said it was an old sticker, mistake, or misprint – which, to be honest, was what I was expecting.

Anyhow, I walked out of BestBuy more happy about the customer service than I was with getting a good price on the product. And, yes, I’ll be returning to BestBuy soon; I want to reward behavior like that.

An Advanced Crash Course in AJAX

So you know a little bit of JavaScript and you’re aware in general what AJAX is, but now you actually have to do it and things aren’t quite as smooth or as easy as you thought. Here’s a quick guide through some trouble spots.

Libraries, like Prototype and jQuery, abstract all this away…
Let’s say that you’ve got a basic understanding of JavaScript, you roughly know what AJAX is, and you can twiddle the DOM, but now it’s time for the rubber to meet the road and you want to get up to speed, know about the quirks, and learn hidden tidbits that come from head bludgeoning against the wall experience.

This guide is a quick romp through AJAX, stopping at all the little pieces that you might not know about.

Making a Request / Response


It turns out that basically every browser on the planet does XMLHttpRequest the same way, with the exception of the evil Internet Explorer, which uses ActiveXObjects distributed with the operating system, and even then it does so inconsistently. In theory, the new IE7 is supposed to conform to the “right” way, but given there are still so many 5.0, 5.0, and 6.0 IE browsers out there, this has made a rats nest out of what should have been simple code to start with. Here’s the fundamental code that returns a browser-neutral object:

function createRequest() {
  var request = null;
  try {
    request = new XMLHttpRequest(); // Everyone but IE
  }
  catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (failed) {
        request = null;  // Always check for NULL!
      }
    }
  }

  if ( request == null ) // Might as well check here
    alert("Error creating request object!");
  } else return request;
}

An aside: It turns out that Internet Explorer 5.x on the Mac (an old, broken, and discontinued product from Microsoft) doesn’t work — AJAX can’t be done, as there is no ActiveX control, and they don’t do it the “standard” way with the browser.

To use such a function in your pages, you’d do something like this:

function getSomething() {
  var request = createRequest();
  var url = "http://www.yourhost.com/serverside";
  request.open("GET", url, true );  // true = asynchronous
  request.onredystatechange = callback;
  request.send (null);  // or whatever data
}

Note: if you use POST, then you also have to set the request header, .setRequestHeader(), usually this will be “Content-Type” with a value of “application/x-www-form-urlencoded” when just sending form data. Otherwise the server has no idea what is being sent in the POST.

The callback function, which can be different for each request, needs to check a ready state and a status — as the call back gets called four times during the process:

function callback(request) {
  if ( request.readyState == 4 ) { // 4 = response downloaded
    if ( request.status == 200 ||  // 200 = success
         request.status == 304 ) { // 304 = not modified
      // Do something
      var response = request.responseText;
    }
  }
}

Note: readyState is a read-only property – you can’t set it.

Another Note: you can use responseXML instead of responseText for XML! You manipulate it just like the DOM, making use of getElementsByTagName(). This requires a Content-Type of “text/xml” from the server to work.

Libraries, like Prototype and jQuery, abstract all this away so that you simply provide the URL, GET/POST type, Asyc/Sync type, and a call back — with special forms to do common tasks, like filling in a DIV with pulled content with one call.

Note: if you find yourself calling getElementById(), you need to look at the $() function of these libraries. And, yes, a dollar sign is a legal identifier character, making a lone dollar sign a valid variable or function name.

Keep in mind, if you start adding other third-party Prototype libraries, they may fail if you use the jQuery enhancements. Fret not, because you can have your cake and eat it to. jQuery lets you unhook itself from the standard AJAX shortcut conventions.

It’s tempting to skim through this, assuming that “you get it” — but the devil is in the details.

Here’s where things get extra tricky.


Browsers Cache Dynamic Responses
Internet Explorer and Opera actually cache the response to a given URL request. That means if you do a GET, the first one will work, but subsequent ones will not. The browser will go “oh, I remember sending this before, here’s the response I got.” As such, you either need to use POSTs or attach a dummy variable, with something like new Date().getTime() as part of the parameters to force it to a unique URL each time.

Script elements need an end tag!
It’s often useful to put JavaScript into its own .js file. Note however that the SCRIPT tag, for historical reasons, expects content. It can be empty, but there must be containing something.

Illegal: <SCRIPT type=”text/javascript” src=”yourlib.js” />
Legal: <SCRIPT type=”text/javascript” src=”yourlib.js”></SCRIPT>

Never Use innerHTML
Additionally, you’ll find that a lot of examples use innerHTML to set the property of an element, like DIV. This is wrong. It is not part of the DOM specification, the W3C has deprecated it, and future browsers may not support it — in fact, some browsers already don’t support it now. Use DOM code, it works on any platform. Plus, libraries like Prototype and jQuery have special shortcuts making it possible to access elements by id, element, css type, XPath, and even as a collection. Seriously, the examples in your books are dated and wrong – look for methods like .text() and .html() instead.

Other useful values: document .documentElement (the root node), .parentNode, .childNodes, .firstChild , .lastChild, .nodeType* , .nodeName, .nodeValue , .getAttribute(), .setAttribute() .

* Once again, IE has problems, this time with the with the Node type.

Set Behaviors Elsewhere, If You Can
It’s also tempting to sprinkle code in onClick handlers, but that can make modification difficult for mass changes, not to mention making the HTML uglier. A library called Behavior solves this problem elegantly. You write regular, clean HTML and it will use JavaScript to add behaviors to the tags you specify after the fact. Simply define a set of rules and apply them.

Note: the onclick property of a DOM object is all lowercase, not camel-cased.

DOMs Reorganizes, They Don’t Copy
There’s also some other DOM magic that isn’t obvious. If you have a DOM tree and you get a reference to an element, and then you do an otherElement.appendChild(firstElement) to some other node element, since a DOM node can only have one parent, it actually gets moved. That is, you don’t have to delete anything.

Stuff About AJAX Libraries You Wanna Know


Drag’n’Drop …uh, no… Sortables
Drag’n’Drop in the browser world of AJAX means dragging DIVs and such to different locations on the screen, of which some of those locations can themselves be containers. If you’re looking to rearrange the elements within a container, that is called Sortables. These are container elements (like OL’s and DIV’s) which contain things (like LI’s, DIV’s, and IMG’s), and maintain the order of them. By far the best sortables example I’ve seen was done by Greg Neustaetter and he explains how he did it.

The HTML ID Does Matter!
Turns out many of the AJAX libraries do trickery based upon the ID of the elements. As you’re aware, every ID on a page must be unique in order to pass valid HTML. When the AJAX libraries go looking for elements, this must be true. Additionally, the IDs often have special meanings. For instance, in order to report sequences, the IDs had to be in a form of string underscore integer. ( e.g., Item_10). You can also use a dash instead. AJAX will let you serialize the numerical parts into a string. So, if your id happens to contain additional dashes, underscores, or forgets the numerics, bad things can happen.

Note: An HTML ID can start with a letter, dollar sign, or underscore. After that you can uses numbers, periods, and dashes. IDs are case sensitive, and though their technical size limit is 64K in size (wow!), though don’t count on your browser to honor that. Long IDs can make things slow and chew up memory.

Be Careful With Arrays
There’s a lot of clever overloading going on. Sometimes a parameter is an element, sometimes it’s a class name, and sometime it’s an array. When it comes to sortables (and drag’n’drop), often you need to provide a list of valid containers. This is done by creating an array of strings with the appropriate names and passing that to the AJAX call. As such, it isn’t mandatory to have an array to make things sortable, but only when you’re crossing containers.

Metadata
It is actually possible to pass collections of metadata inside of a class tag! This can be very handy.

<P ID="thing" class="foo bar { xyzzy: 'plugh', abc: 123 }" />

jQuery has a plug-in called metadata (the documentation is in the JavaScript code) that lets you access this.

$("thing").data().xyzzy returns "plugh"
$("thing").data().abc returns 123

AJAX Responses
If an AJAX response returns text, you can access it with .responseText. If an AJAX response returns XML, you can access it with .responseXML and read it just like you would the DOM. And, if the AJAX response send straight HTML, you can always inject it directly into an element with Prototype’s Ajax.Updater.

Currently, the hard part of the problem is taking an XML response from the server and transforming that fragment into HTML using XSLT on the client side.

Normally, a full XML document is transformed into HTML and loaded into the DOM, to which AJAX takes over. The problem is, while AJAX allows for modifying the content of an element, the phase of XML to HTML is already past. Just as XMLHttpRequest() has many different historical quirks, XSLT support and implementation is even worse.

Supposedly, however, there is a library called zXml, and it has a transformToText() function which, in theory, provides cross browser support.

XSLT and AJAX

See the benefits of XSLT. Download, unzip, and drag the .XML file into your browser.


XSLT Example
XSLT_Example.zip

This example separates content, structure, and presentation.

But let’s discuss XSLT in the contents of an entire page.

The magic of XSLT allows the transformation of any arbitrary XML to well formated HTML by rules that you define. And, what’s really spiffy is that you can use XSLT to automatically generate AJAX code as well. However, there are a few tricks to know and a few kinks to watch out for.

XSLT position()
This function returns the element’s position in the tree. The thing to look out for? Whitespace is also an element! As such, if you’re using an <xsl:apply-transformation />, you want to make sure the select statement specifically lists the kind of node you want, and not just some parent element.

XSLT replace() is XSLT 2.0
Turns out some browsers have a problem with XSLT v2.0. Evil. Just evil. And, along this line, so are variables. Some of the really nice features of XSLT might not be possible.

Firefox Hangs When XSLT Generates Scriptaculous
The
Scriptaculous effects library is very clever by being very modular. When you include it, dependencies allow just the pieces you want to load. This has the advantage of making the pages very light weight. It appears to do this feat of magic by injecting content into the DOM at the point you include the <SCRIPT>…</SCRIPT> tag. Only problem is, if the DOM is being generated on the fly by XSLT, bad things can happen. Surprisingly, this seems to be a Firefox-only problem — and I’ve reported the problem to the authors of Scriptaculous. If I get no response, I’m going to the Mozilla people next. IE does not appear to be affected, nor is Safari.

Containers Get Instances
I had some XSLT code which was building my arrays, and deferring initialization of sortable containers until page load completion time. The problem was, for some reason, the containers were not getting initialized at completion. The result was that certain elements weren’t functioning. When I tried initializing as I went, each container got an instance of the array. Follow that again slowly. Sortable containers don’t get a reference to an array, they get a copy of the array, and if the array (which contains all containers you’re allowed to interact with) isn’t fully initialized, your page is broken. Admittedly, a lot of this problem happened because the load order of things between libraries wasn’t clear. Each AJAX library usually hooks into the OnLoad() call, so you better not have one, but you’ll need to see if it put itself first, or last, in the chain.

That sums it up…


That sums up the mental core dump. If you happen to have any tidbits, trivia, or embarrassing corrections, I’d love to hear from you.

Understanding jQuery

jQuery – it’s a AJAX library that uses a very terse notation to do an awful lot in JavaScript. Here’s a good explanation for developers that are unfamiliar with the library — it explains a mental picture of what’s going on, enough that you can pick up the library and start using it for more than just trivial tasks.

I’ve been playing a lot with AJAX recently, and have discovered a library that I’m quickly falling in love with: jQuery.

To provide you with context, I’m a software engineer and have been developing commercial applications for well over twenty years. I’ve played with Javascript when it was young, and I was unimpressed. I played with JavaScript when it was a little more mature, but because of Microsoft’s horrific incompatibilities with Internet Explorer verses the way the rest of the world worked, I gave up. Perhaps prematurely. But, none the less, I didn’t pay any more attention to the world of scripting on the web than whatever problem I had to demanded.

Then along came Ruby on Rails. I was surprised to learn that someone had actually written a library to abstract away JavaScript differences — what a clever solution! To that end, I started looking at Prototype and became impressed at the cleverness of the helper functions. That got me to look at Scriptaculous, and suddenly the world of JavaScript didn’t seem so bleak.

But jQuery. Wow. This library resonated with me very quickly, and I started thinking in and doing more functional programming than I had ever done before (opposed to procedural and object oriented). The library was so easy to use, that I was able to do quite a lot with it without understanding it. That was months ago, but today something clicked. I started to see in my mind’s how exactly how jQuery does its magic, and in such a way as to describe it to someone who’s never used one of these AJAX libraries before.

Javascript, she ain’t that bad


Javascript allows one to define classes. Those classes can be extended — don’t think in terms of derived subclasses, but rather actually plastering on additional methods to a pre-established class. Additionally, those methods can have overloaded signatures. And for the sake of brevity, identifiers we’d never use in other languages, are perfectly acceptable short names. We’ve been taught that although identifiers can start with things like dollar signs and underscores, to stay away — these are for library writers and operating systems people. Even though a single dollar sign might be legally syntactically, one should never do it; though in the world where network speed and space matters, such short names are encouraged. Finally, blocks of code, the very stuff you would call functions, can exist all on their own — all you need is a reference to them, they don’t need a name.

Accept all the above as a given, and a tribute to what’s become of JavaScript while you’ve been playing in other languages.

Groking jQuery


Now at this point, I’ll express my conceptual view of jQuery, and while it may not be technically correct or even how it’s implemented, the mental model will give you gross insights has to how you ought to use the library.

Imagine if you will a class called jQuery. Rather than having to type out jQuery each time, we use an alias, a simple dollar sign (the shortest legal identifier that’s not alphanumeric). Its sole job, internally, is to maintain a collection of references to pre-existing elements in your DOM. This collection may be empty, contain one, or more elements. As the developer using jQuery, you need never see this list; you only deal with the jQuery object itself. Ever.

jQuery has many overloaded constructors, which is how it learns what elements to keep in its internal list. You can provide it a reference to an element, a kind of element, an id of an element, a CSS class used by elements, an XPath to one or more elements, straight blocks of HTML, etc. It can even use another jQuery object (which contains a list). jQuery has exotic syntax for picking very specific elements based on conditions and attributes; it even has filters to removing elements from the list.

The actual list isn’t important, because after it’s done with the constructor, all you have is a jQuery object. And the only thing you can do at that point is call jQuery methods. But, oh how clever is jQuery!

Anytime you call a method of jQuery, it does an internal for-each across its internal list, applying your method to every DOM element in its internal collection. Once more, when it’s done, it returns the very jQuery object that was just used.

Object oriented developers know what this means: you can chain methods, creating long strings of behaviors!

jQuery directly manipulates the DOM in a browser-specific manner under the hood, so that you get one, simple, transparent, elegant way of expressing what you want. The actual implementation details are no concern; if a method exists, it works the same way everywhere, regardless of browser.

And, because jQuery operates on numerous elements by twiddling the DOM, it’s possible to write a small piece of code but hook it in all over the place… a process that used to be quite tedious, but can now be done after the fact, meaning your raw HTML is uncluttered.

The Simple Example


Let’s look at a simple tutorial like example.


$(“.xyzzy a”).click(function(){
alert(“Magic!”);
return false;
});

Quite literally, this says create a jQuery object that is a collection of every anchor in containers with a class of ‘xyzzy’, then assign its onClick event handler to reference a function (that has no name!) that displays an alert message.

In Conclusion


That’s pretty much it. The two things to learn are the number of various constructs and types that can be passed to the constructors and filters, and the other thing is the various methods that affect those elements. That’s the meat of it.

jQuery has other helper functions and such, but those are easily mastered. And, once you’ve got those under your belt, check out the plug-ins that are additional methods bolted on to the jQuery object.

Tyson’s Brio? Nah. Let’s do something else.

The Brio in Tyson’s Corner gave us terrible service (admittedly, that’s unusual), but then indirectly found a clever way to charge us for the “free” dessert. I’m not going back, and it’s not about trying to get free food — it’s about the customer service and the misrepresentation and the handling of events.

When I go to Tyson’s Corner mall, which I can’t help since that’s where the Apple Store is, I usually find myself walking past the food courts and back where some of the finer restaurants are.

About 80% of the time, two choices fall out: Coastal Flats and Brio. We’re usually split about equal between them.

Until now.

While eating out provides a different venue and food selection, the real selling factor is customer service. Provide me with a slightly better than average customer experience, and I’ll bring you repeat business, referrals, large tips, and word of mouth / blogging advertising. Do something asinine, repeatedly, and I’ll vote with my feet and wallet by taking my business elsewhere. I’m not talking casual mistakes or someone having a bad day, I mean flat out asinine.

In the past, I’ve asked for a table that’s non-smoking, only to be put at, in front of, or behind the bar. I’ve asked for a table where I can spread out and hold a meeting, which involves conversation, and in turn been sat under speakers with music blaring so loud the waiter couldn’t hear our order. In both cases, I walked out before ordering, taking my business elsewhere – but not permanently. Clueless. Simply clueless. But that I can let slip.

Brio – you are no longer on my list of places I visit or recommend.

The story is simple, and it’s one of customer service.

On one visit, I ordered a cheese pizza and the waiter realized that what I was having was so simple, he offer to bring me a child’s meal instead, and billed me exactly what he brought me. We had a great meal, and I tipped insanely.

On my next visit, it took a very long time before we got any service. I assume it was a mere matter of the waiter being over worked, but as the even drug on, it was clear we weren’t exactly getting the quality of service one expects from the average trained waiter at Brio. Still, a bad experience with a waiter is not enough to make me scratch a restaurant.

We placed our order, to which I mentioned that I wasn’t all that hungry — and that a prior waiter had actually suggested the smaller sized pizza. I asked if that was alright, primarily because I didn’t want to pay for something only to take it home. He said it wouldn’t be a problem, and off he want.

And while the drinks didn’t come, nor the bread, for quite a while, eventually we got them, but then the food took even longer to come out. We watches as people were being seated after us, ordering their meals, getting them, eating them, and leaving, while we still waited on something as simple as a pizza and pasta salad.

Just as we were about to pay for our drinks and go somewhere else, they brought out the food — and screwed up my wife’s order. No problem, they’d make another. And needless to say, we were nearly finished by the time it got there.

The manager came over, apologized for the delay (though giving no explanation), and said they’d like to buy my wife dessert. Although, not surprisingly, even that came out after a long delay.

Here’s where things really started to bother me.

Normally, if a restaurant, especially one of this caliber, screws up, they attempt to repair the experience — just as our manager had done with the dessert.

The problem was that after our meal was over, the manager returned to the table, and explained that she was adding a “FEE” to our check. I asked why. The answer I got was that it was because I had the child’s pizza, and I was an adult.

Pause for a moment, because I feel this was a nasty bait and switch — and in particular, done to cover the cost of the “free” dessert, we’d been offered. Look, I’m not griping about trying to get free food; I wasn’t interested in additional food, but got manipulated into buying something I didn’t want under some pretty bad pretext. (It reminds me of the ex-girlfriend who asked for money, which was then used to buy me a token present, and then demanded to know what I had gotten her.)

Had the waiter explained to me that he’d have to charge me the adult price, I would have simply have taken the adult meal and brought left overs home. I wasn’t given that choice. Nor was I made aware there would be a “fee” until after the meal. It also was odd in that I had in my back pocket the receipt still from when there was no “fee” for the identical order — AND — that the fee was added in light of the obviously bad experience we were clearly having with the service.

I have a serious problem with child meals costing adults more. It cost the restaurant no additional materials, and I shouldn’t be charged some delta in what I might have ordered, especially in the context of announcing I wasn’t hungry to begin with and was looking for something light to munch on. Had a child been with me, and I ordered nothing, there should have been no fee. Had I simply elected to take the food to go for a child, there should have been no fee.

If they don’t want to sell me child portions, or want to do so at adult prices, they should clearly announce that and give me the option NOT to order.

It’s the deceptiveness of the matter that disturbs me.

I didn’t challenge the fee (though I easily could have), and instead opted to pay it. The waiter did not get an amazing tip, he got an average one (which was actually quite generous for the service we got); in fact the fee came out of it.

Yes, Brio, you got your fee. Good for you. However, take note — I’m not coming back, I’m vetoing every group lunch there, and I’ve got an interesting story to share about how you deal with customers.

For comparison, let’s look at an experience with Coastal Flats, which is right next door.

At Coastal Flats, I ordered a beef BBQ platter, and with it came a little cup of dipping sauce. The waiter said I’d like it. Well, I tried it, decided I didn’t like it, and simply set it aside and happily ate my food, which was spectacular as always. When the waiter came by, he asked what I thought, and I said, “it was a little to tangy for my tastes, but thanks.”

Within moments, the manager came over, and started profusely apologizing to me about having brought out something I didn’t like. I’m thinking to myself WTF? And I tell the manager and waiter it’s no big deal, the food is great, and I’m just not going to use the sauce. But the manager insists they’ve made a grievous error, and would like to comp my meal and buy me a dessert. I insist that’s not necessary, and he insists it is, and he wants to. I accept, but tell him I’m perfectly happy and that they’re going overboard. He smiles, and at the end of my meal, a dessert arrives with a ton of spoons. For that evening I tipped so heavily it hurt.

And I came back the next time to them, ordered the same thing, said I didn’t want the tangy sauce — thinking that if it wasn’t on my plate, they wouldn’t make a big deal about it. But the same thing happens again; I refuse the meal comp and they still bring the dessert! Only this time, while I’m getting my dessert free, other people at the table are ordering desserts of their own based on the last experience’s tasting. Interesting. We’re buying desserts when we usually don’t. Again, I tip heavily.

And, again, I come back and order the same meal, explain that I don’t want the tangy sauce, all is well, and they bring me my meal exactly as I asked for it. This time, I order dessert (as it’s now tradition), and I have additional friends with me. I’m telling them the story of what had happened last time, and again, tip very, very well.

Coastal Flats is smart — they understand the big picture. They recognize that if they make the customer feel like a king, he’ll spend like a king. I now visit more, and buy more, when I go to Coastal Flats; I also tip on the high end.

So, Brio — enjoy your fee — because I’ll be sitting over at Coastal Flats most likely, sharing customer service stories.

Walt gives the Brio a thumbs down.
Walt gives Coastal Flats a thumbs up.

iPhone will you have SSH?

Will the iPhone have SSH? Certainly it’s got everything that’s needed to do it — internet connection, virtual keyboard, a wide enough display. Question is, will Apple recognize that their geek audience is looking for network connectivity, not just access to their music collection?

I’m waiting for the article confirming that the “iPhone has SSH”, because that’s what’s going to push me over the edge. Yes, the iPhone is cool, and if it has a larger display, better interface, and all my iTunes stuff, I’m thrilled. But until I can sit on the beach and fire off remote jobs on my server via a command line, I won’t be as happy as I am now with my current phone.

Currently I’m using a T-Mobile SideKick, and I do few things with it: eMail and ssh to my servers. Web browsing, instant messaging, text messaging, photos, games, then phone come next — and in that order.

Oh, I don’t need super speed either.

In fact, if the iPhone had SSH and didn’t do voice telecommunications, I’d still be thrilled. Then again, we knew I was a geek.

UPDATE 27-JUN-2007: Here’s a list of things confirmed features the iPhone does not have. Songs as rings tones would be nice (or will it!), although I’d want to use my own .mp3 creations. No games; that’s a must as my iPhone may very well become a substitute for my iPod. No instant messaging is a show stopper to me. Not listed, but would be a killer app, would by Skype on the iPhone. GPS would be sweet, especially as it could tie into web apps; imagine pressing the “I’m lost” button. I need a removable battery, for places that insist the phone be physically off. And I don’t want a “real” keyboard, I think Apple got this one right. All the other stuff, I could give or take.

The good news is, according to another source, is that there will be 3rd party Cocoa apps on the iPhone. I think Steve Jobs did a disservice trying to pass off AJAX as the development API, and if the answer was simply that they needed to get some kinks out, work on some more security, and placate the phone providers, that would have been the better, more honest, and up front answer that would have gotten some serious respect.