A new kind of rowing stroke

A few months ago I got an idea for a different kind of sport Rowing stroke. I don’t remember the exact train of thought, but it had to do with swimming. Anyway, …

The physics of rowing and dynamics of the water are very complex. My idea is that you want to move the water past the boat faster, reduce the amount of oars in the water, and increase the glide of the boat. Thus, instead of all the rowers rowing at the same pace, the rowing is staggered.

At the beginning of the race, the traditional rowing stroke is used. We want the maximum power to accelerate the boat quickly.

In the middle of the race, a staggered stroke is used. Here the front rower begins the stroke and at the end of the “drive’ phase of the stroke, while the blade is still in the water, the second rower begins their stroke. This is repeated for each rower in turn.

Toward the end of the race, the traditional synchronized power stroke is resumed.

In essence the effect, if done smoothly, is the strokes become just one long stroke. As if only one person “drove” a very long stroke from bow to stern. Like birds in flight, the water becomes part of solution.

Advantages? I’m only guessing here.
- Rowers get more rest, and more energy available toward end.
- The glide of the boat is increased.
- Water is moved faster, velocity of boat.
- Less oars in the water so less friction.

– Josef

Further reading

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

JavaScript Promise example, reverse geocode location

In prior post we wrapped the Google Map API in a Promise. Now we wrap navigator.geolocation.getCurrentPosition in a similar promise. This allows us to to neatly chain these two to get the browser’s current address.

The example is using Dojo’s Promise implementation, but the approach is applicable to other Javascript Promise libraries or native support.

In listing 1 below I reproduce the former getGeocode function.

Listing 1, Get geocode using Google service

function geoCode(request) {
    var deferred;
    require([ 'dojo/Deferred' ], function(Deferred) {
        deferred = new Deferred();        
        new google.maps.Geocoder().geocode(request, 
          function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
            } else {
    return deferred.promise;

In listing 2 below we have a similar function

Listing 2, get browser location.

function getLocation(){
    var deferred;
    require([ 'dojo/Deferred' ], function(Deferred) {
        deferred = new Deferred();
            function navSuccess(position){
            },function navFail(){

    return deferred.promise;

Hmmm. The code is very similar. It seems that these two functions could be done using a Promise wrapper function, like toPromise(doFunction, onSuccess, onFailure). Is there such a beast?

Now we can use them together, as shown in listing 3. Here instead of a simple promise chaining we use the technique presented in “Break promise chain and call a function based on the step in the chain where it is broken (rejected)” to “catch” the correct error and not have it bubble up the ‘then’ chain.

Listing 3, get browser location, then reverse geocode

function findCurrentLocation(){
    var request;

    if (navigator.geolocation) {
            function navSuccess(position){
                request = {
                    'location' : 
                      new google.maps.LatLng(

                return getGeoCode(request).
                   otherwise(function geoCodeError(status){
                     throw new Error(status);
            }, function navFailed(err){
                console.log('navLocation() failed: " + err); 
                throw new Error(err);       
            .then(function geoCodeSuccess(results){
                    console.log('navLocation() success: " + results);

Above, .otherwise(onFailure) is just a shortcut for .then(null, onFailure)

Of course, the code doesn’t have error handling and actual use of the data obtained.

Further reading

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Wrap Google map geocoder.geocode in a Promise

Futures and promises are a programming construct to make asynchronous programming easier to apply. They are provided in many JavaScript libraries and frameworks. Below we use Dojo’s implementation to wrap a non-promised based async operation, getting a Geocode from the Google Map API.

The Google geocode service takes a request object (which contains address information) and a callback function that takes a results object and a status string. If status is ok, the results object contains the geocode information (and a lot of other useful information).

In listing one the geoCode function wraps this in a Promise. Inside the function we create a deferred object, then invoke the above async geocode service, then we return the Promise interface of the Deferred object. Note, this is taken from a working application code, and that code works, this below, not tested.

Listing 1.

var geocoder = new google.maps.Geocoder();
function geoCode(request) {
    var deferred;
    require([ 'dojo/Deferred' ], function(Deferred) {
        deferred = new Deferred();        
        geocoder.geocode(request, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
            } else {
    return deferred.promise;

You can use this as follows:

var promise = getGeocode(request);

Note that we don’t wait for the async operation to complete, or more correctly, invoke our callback function. The invoker of our geoCode function just gets a Promise object. So?

The Promise object is something that may get a value when it is fulfilled or it may get rejected. You find this out by reacting to those states. How? By using callbacks. So we are right back to where we started, after all the original geocode function also used callbacks. Ah, but here is the difference. With Promises, you are using something with more features and power. The Promise framework allows you to work with async code in a more frameworky way.

One of the nice features of Promises is that they can be “then’able”. “then” functions return a Promise, so they can be chained together: p.then(….).then(….).then(…..); Within each ‘then’, you supply a left and a right callback function, the left is for the resolved, the right is for the rejected state. Example:

var p = getGeocode(request)

You could also inline everything:

       var x = do_something_with_result(results);
       return x;
       throw "failed"

These left and right are not chains themselves, there is one chain, but the left or right could be invoked depending on whether the preceding “then” resolved or rejected the promise. Of course, there are more details and each Promise implementation adds their own terminology and features. For example, Dojo has an always function that accepts a callback to invoke no matter what the previous ‘then’ did with the promise.

Apparently moves are afoot to make ‘futures’ part of the core JavaScript standard. These may be following the Promises/A+ specification.

A future blog post will provide a very easy to understand intro to Promises. There doesn’t seem to be a Promise for dummies on the web.

Further reading


JavaScript Promises: Thinking Sync in an Async World

Redemption from Callback Hell

Times Developer Network – Promises, Promises

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

JavaScript focus event has wrong target?

I had an amusing debugging experience. Well, now it’s funny, then not so much. A focus event handler was getting events that said the same field was generating them. Even if other fields were selected.

I am using Dojo’s event API. This, like most other frameworks, make JavaScript event handling very simple, and most importantly handle the cross-browser issues.

The event tracer
I put a listener on a field’s ‘change‘ event using dojo/on, example:

on( theNode,'change',
          mode = 'rent';			

The callback handler just set a state variable. I also attached a listener to the ‘focusin’ event on a few other fields using the ‘on‘ method of Dojo’s NodeList:

	evt.stopPropagation(); // needed?
	if(mode == 'rent'){

This second handler used the value of the state variable. That is, I wanted to know that the user went from a particular field ‘A’ to another group of fields ‘B’. Hopefully someone can tell me the correct way to do something like this. Yes, a kludge, but it had to be done immediately, not on a single ‘submit’ button.

What should happen is that when the mouse leaves the first field (or user tabs away) and lands on one of the second fields, the status variable would have the correct value and be used by the second handler. It works!

Since the field setting is very fast, very few users could be faster. I know, async stuff; the browser could have a delay, etc. Don’t try this at home. Hmmm, but the browser is single threaded, so how could …. Anyway, in this app that would not be a disaster.

It stopped working
But, then I was developing something else on the same page using the Chrome debugger, and the above kludge stopped working. Huh? Even if I clicked on empty space in the browser, the event captured would be from the last field that the mouse was on. I re-read the Dojo docs, went back to the W3C stuff on Events, etc. Could find no web site where someone experienced a similar issue. I started blaming the Dojo toolkit, maybe there is a bug or the docs are incorrect.

I asked a co-worker, but they didn’t want to solve the problem just tell me that the app requirements were wrong, it’s too complex, blub, blub, blub. Most of the time feedback like this is important. One can get stuck in fruitless paths or need to see a different view of the goals. Perhaps, but in this case something obvious was wrong and I will probably face the same debug problem in the future.

Then I noticed that when I went from the Debugger back to the browser and clicked on another field, a very brief underline appeared in the previously selected field. Ah, how dumbskevisky, when I click on the browser anywhere, the previously selected field regains the focus and the focus event is generated. Obviously. The switch from debugger window to the browser window was the real change.

How did I confirm my observation? I closed the debugger window, and added console logging, like: console.log(“focus event on: ” + evt.currentTarget.name);

Take away

  1. Blame the tools last.
  2. Was working now not, what really changed?
  3. If it is hard to find a similar problem on web, your doing something wrong.
  4. Be careful which co-workers you ask for input.
  5. Debuggers, while useful, can cause problems. The console is your friend.
  6. Take a break and work on something else.

What’s next?
There just has to be a better way of satisfying my web page requirements. No app at any point in time wanted to know what was previously changed?


Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Template Method Pattern using JavaScript callbacks

JavaScript callbacks are usually discussed in terms of asynchronous behavior. Primary examples given of this are event handlers in the browser or XHR. Callbacks are used so much in JavaScript that there is even a new evil in the world, Callback Hell.

Callbacks are very useful for more familiar coding tasks and it doesn’t have to be about asynchronous services, or journeys into the compsci land of Functional Programming, or Monad this or that.

Template Method Pattern
The term ‘template’ is not related to templates as used in text substitution libraries. This pattern is used when an algorithm or operation has common behavior and the uncommon behavior can be ‘substituted” or deferred by various means.

Though this pattern is usually presented in terms of Inheritance in Class-based Object Oriented Programming, that is just an implementation example. JavaScript can and does implement this pattern; it is just not called by that name.

Simple example
Lets give a very very simple example of what this means. Lets say you have some widget on a web page that presents to the user some recipe based on some input conditions or properties. For simplicity, lets assume that this can be done in one function that consists of a series of statements that are the same except for a few steps.

The usual way to do this is to create multiple functions that change the widget in the required manner, or create one function that uses conditional statements to invoke the correct steps that vary for each type of recipe.

Below in listing 1, we have the behavior for the widget. Some statements come before and after the call of the doSomething() function. The problem with this code is that if we have to do different things, we must complicate the conditional or create other widgetRecipe type of functions that perform the recipe differently.

Listing 1, psuedo code of conditional use
functions widgetRecipe(){
statements before
statements after

Example with callbacks
Since we have a process that differs in only one or more “steps”, the Template Method Pattern is applicable.

The recipe function in listing 1, can be simplified by replacing the conditional statement with the actual function to invoke. Functions in JavaScript are objects, so can be assigned to a variable.

In listing 2, we use the argument name secretSauce for that function that will be passed in. Some tutorials out on the web use the name ‘callBack’ to make it obvious that this is a callback function. Note how the passed in function is invoked, using “()”.

Listing 2, psuedo code using callback
functions widgetRecipe(secretSauce){
statements before
statements after

We can define that function as: var bitterSauce = function(){ alert(“Add a dash of pepper”);}
Then invoke widgetRecipe like: widgetRecipe(bitterSauce);

One famous programmer, Chuck Moore, inventor of the FORTH language, said: don’t decide, compute. Here the function is computed elsewhere, perhaps a table of some kind.

Of course, you can have multiple callback arguments to a function, even an array of callback functions. You can even inline callback functions or make them anonymous. And, a callback function could have arguments too.

Used in certain ways, a Callback function is a Closure. This can have, if not used correctly, very subtle issues. In addition, if the callback function uses this internally, you have to invoke it a certain way.

Some of the links below give more information on how to use callbacks and things to watch for.

Real world use?
I am almost done solving a programming problem where I have a ‘Callback Hell’ situation, and to make matters worse, the various slices of this hell needed to be reused. I think I solved it by abstracting out the variable behavior into a callback. Lets see if it survives code review.

Since JavaScript is Object Oriented, but not via Classes as in Java, it can do inheritance, via prototypes. Thus, the Template Method Pattern can be implemented using prototypical inheritance. This approach is present here, JavaScript Template Method.


Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Google Play cannot access music on SD card

There are reports that on the latest Android devices you can now store your music on an SD card and the Google Play Music (GPM) app can play them.

This is incorrect. GPM can store cached music from its own service to an sdcard. That way you can play them offline without losing valuable memory on your device. It is also Google’s way to lock in content and services; maybe due to industry legalities?

Another music player app, Poweramp, can play music from an SD card.

Anyway, if the above is incorrect, please respond with directions on how to copy music from a device onto an Android phone and allow Google Play Music to access it.

I tried all this on a very recent tablet running KitKat.

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

‘The Big Bang Theory’, funny?

I guess I’m a geek. I’m into tech, read non-fiction science books, have more than two monitors in front of me at home, have a dull smart-ass sense of humors, etc. So I should love The Big Bang Theory show on TV. Everyone at work is always raving about it. Yet, I don’t. I was able to watch it once for five minutes.

I finally figured out one reason why. Its that obnoxious laugh track. It is so intrusive, and as loud as the commercial breaks. Why? Supposedly there is a studio audience.

There are YouTube videos showing some episodes without the laugh track. This made it even more evident another reason I don’t like the show, the characters are unlikable. Unlike with the “Seinfeld Show”, where you wouldn’t want to associate with the characters, but they were funny, with TBBT, you don’t want to associate with them, and they are not funny. Now that is funny. Que the laugh track.

I think the show is really aimed at faux geeks. Like what real geek or nerd would need to be told when to laugh? And in that sense maybe they should just create an app for that. When a supposedly funny thing is said on the show, the app can signal people when to laugh. Better yet, the app can be social, oooooooh, now you can signal all your true friends with a “haha”. I hereby copyright this idea.

Just to make sure I’m not weird, I searched to see if I’m alone in my view. Nope! Here is one example: 11 Reasons Geeks Hate The Big Bang Theory

And great shows like “Almost Human” get canceled? Maybe they should have added a laugh track.

*The other day I said that instead of developer I should have been a Tooththologist. Get it? Dentist. Oh well, you had to be there.

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

dojo on.emit won’t work in FireFox?

Seems simple enough, using the Dojo toolkit click a div and trigger an anchor tag on the page.

The code in listing 1 below works on:
Chrome version 35
Internet Explorer 11

Won’t work on FireFox ver 30.

Dojo’s dojo/on module has the emit() method that provides a normalized way to dispatch events. It is supposed to be cross-browser.

From the info on this page, Disabling native events when using Firefox with WebDriver, it sounds like Dojo may, like WebDriver, be using FireFox’s native event facilities and failing.

<!DOCTYPE html>
<html >
    <script>dojoConfig = {async: true, parseOnLoad: false}</script>
    <script src="http://ajax.googleapis.com/ajax/libs/dojo/1.10.0/dojo/dojo.js"></script>
    <style media="screen" type="text/css">
        .bold {font-weight: bold;}
        .box {border:1px black solid;margin-top:4em;margin-left:8em;}       
                var nde = query('#div123');
<body class="claro">
    <div id="div123" class="bold box">click me!</div>
    <div class="box">
     <a id="target" href="javascript:alert('hello')">will trigger this link</a>

Listing 1

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Groovy is a language

A few years ago I wrote a few Groovy language scripts to help with some configuration and testing needs. I discussed these with my co-workers. But, lo and behold, for weeks they thought I was saying that the scripts were Groovy, as in cool, not Groovy as in the JVM based dynamic language. They never heard of Groovy. We had a big laugh.

This situation made me think again that developers have differing interests in their field. No offense, but a certain percentage just go to work and do what is required and punch out at the end of the day. It is Java today, but it may as well be COBOL, there is always opportunity to copy and paste and do the minimum to “solve” the current business stakeholder requirements.

I’m sure this is only true for some corporate IT environments which have a top down rigid structure and legacy applications. Introducing change into the software process and tools is difficult. Stability and safety is paramount. Thus, the worker who toes the line and is not disruptive is an asset. Sure, there is talk of change and new techniques, but at the end of the day: “no, we can’t use that, we have this.” The new web businesses and open-source projects are different, of course.

BTW, Groovy is now slowly being used in my company. But, not sure many have heard of it yet.

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

Java reflection on a message using MethodHandle

Some code I was looking at recently had an overloaded method and each method just accepted a different type argument. With Generics there are probably ways to reduce this clutter, or not.

Anyway, I started thinking about the original concept of OO; it was all about ‘messages’. But what is the difference between a ‘message’ as per Alan Kay and Smalltalk and a method’, née “subroutine” in Java? I guess it’s intent, design, and the other features of OOP?

Following this line of thought I wound up looking at how to invoke a public method on a class and that method in turn delegates to private methods that match the data within the message. The public method is the destination of a ‘message’. So I searched the web and found mention of the usual Reflection, Proxies, instanceof, and finally MethodHandles. The package java.lang.invoke contains the new approach to reflection introduced in Java 7. MethodHandle is the new class that makes all this possible.

Not much on MethodHandle on the web (search instead for: java “method handle”), but the API docs are very good and this blog post, “A glimpse at MethodHandle and its usage”, is all you need to get started. Below in Listing 1, a simple example is shown. Class Server has a single method that takes a String message and a parser.

The message contains the data that is used to determine the actual method to invoke. Simple, but the point is that this could be a JSON/XML string or some other data container. The parser is just me experimenting with callbacks, here the callback gets the data in the message. Yeah, I know, if the client can get the data, why not just send it? It’s just a ‘hello world’ example.

In listing 1 the Service class exposes one method, send.

public class Service {	
	public Object send(String message, Parser parser) throws Throwable {
		Object pData = parser.parse(message);		
		MethodType methodType = MethodType.methodType(Object.class,pData.getClass());		
		MethodHandle mh = MethodHandles.lookup().findVirtual(Service.class, "call", methodType);		
		Object actual = mh.invoke(this,pData);		
		return actual;

	private Object call(String data) {
		System.out.println("in string method ...");
		return "string data";

	private Object call(Integer data) {
		System.out.println("in int method ...");
		return new Integer(42);
	public interface Parser{
		public Object parse(String s); 

Listing 1

In listing 2, the Main class sends the message to the Service class.

public class Main {    
    public static void main(String[] args) throws Throwable {
        Service app = new Service();
        Service.Parser parser = new Parser();   

        Object actual = app.send("some text", parser);
        assert actual == "string data" : "Should have returned 'some data' string";
        actual = app.send("number: 42",parser);
        Integer expected = 42;
        assert (actual.equals(expected)) : "Should have returned Integer with value 42";
    static class Parser implements Service.Parser{                  
        public Object parse(String s) {
                Integer i = Integer.valueOf(  (s.split(":")[1]).trim() );
                return i;
            return s;

Listing 2

Not earthshaking of course. The output is:
in string method …
in int method …

The example is somewhat like the javax.servlet.Servlet class, only one method, service(ServletRequest req,ServletResponse res) is also used, and usually one invokes other methods based on the “message” params.

I can see the use of MethodHandles leading to some powerful mojo.


Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.