Thursday, November 10, 2016

ES6 review, part-2

Continuing (belatedly) from the previous review of some new language features of Javascript ES6.  Again, based upon ES6 & Beyond by Kyle Simpson  (O'Reilly, (c) 2016) and using chess annotations (!, ?, etc.) to rate the features.

Concise Properties!

Saves typing, especially if you use long, informative variable names, which encourages their use, which is a very good thing.  However, I'm a little concerned in all of these "shortcuts" about typos and or accidentally polluting the global name space.

Concise Methods!?

A shorter way to create function expressions.  The whole expression vs. declaration stuff gives me a headache, and, coming from a Java "like classes" background I tend to use the later.  So not sure how much I'll use the new feature.  

Also, these concise method expressions fall apart (and are tricky to debug) when you are nested deep withing other functions then calling things recursively.  To which I say don't do that!  The code for which they fail is extremely complex code which is probably best refactored.

Getter / Setter ?

I'm torn on this one.  Obviously, coming from a Java background, I like the concept.  However, I also like explicitness, and operator overloading is confusing and generally held to be a bad thing.  With the new getters/setters, when I go

   var x = foo.bar;

I don't know if this is simple trivial property lookup (which it sure looks like!), or this is calling a function that will spend 10 minutes calculating pi, then become self-aware and launch Judgement Day.  Following Zen of Python, Rule #2: "Explicit is better than implicit", I think it's preferable to show the function call:

   var x = foo.getBar();

Computed Property Names?!

Meh, again not so sure.  If I have a lot of properties (or methods) starting with "Hillary-", and another set with "Trump-", do I want them all mixed into a single object, or isn't it simpler to subdivide and have

var foo = {
   Hillary: {
      party: "democrat",
      taxes: function() { ... }
   },
   Trump: {
      party: "yes",
      taxes: function() { return undefined; }
   }
}


and access them via

  foo[name][property]?

I don't see any great advantage is mixing them all together with foo[name+property].  However, they are used a lot for symbols, and can be useful for concise methods and generators, so I'll keep my mind open.


Super!

hard to argue much with this.

Template Literals (a.k.a. Interpolated String Literals)

I agree with the complaint that these aren't "templates" in the sense that many use them.  They aren't Mustache, JADE, whatever.  However, the ability to use

"Hello ${firstname} ${lastname}!"

instead of

"Hello " + firstname + " " + lastname + "!";

strikes me as a very very good thing.  One can also put functions inside the braces, which, if used with discretion, is also great.

"Hello ${decodeURI(nameFromAForm)}"

Arrow Functions

I'll talk more later about these.  He does point out a lot of "gotchas" and limits the cases where they should be used.

for..of Loops!!

Why did it take a gazillion years to add this obviously great feature?  Yes, I guess the functional guys will say you could use forEach, but this is simpler for most.



Notes

Astute readers will note that I'm not using prism.js for syntax highlighting.  Seems to work well.  However, it's tedious in Blogger to go to HTML edit mode, and when I'm there I see that the HTML code is a disaster of crapola so it's hard to find the code you just types to surround it by the pre and code tags.  I'm going to start playing with Ghost and this blog is likely to migrate there soon.  And Blogger constantly changing my font size is just so annoying.









Friday, May 6, 2016

ES6 Review, part-1

This is a first post reviewing the new features of JavaScript ES6.  It is also a short review of ES6 & Beyond, by Kyle Simpson (O'Reilly, (c) 2016), which I'm using to learn most of the new stuff.  Also on GitHub.  I will rate things using chess annotations, where an exclamation mark is "good" and a question mark is "dubious".

As for my background and biases, for 20+ years I was a traditional desktop app programmer, mainly in C and Java.  I'm fairly new (~4 years) to JavaScript.  I often appreciate, but sometimes hate, the differences between it and Java.  I've used NodeJS and some of its most common modules (Express, Request), but otherwise, have used few of the mainstream JS libraries such as JQuery and Angular.


Intro

The book is moderate sized (~260 pages, trade paperback sized (6" x 9")) and meets O'Reilly's typical high standards for fonts, printing, binding etc. It's a little disappointing that they ran out of the traditional animal pictures to put on the covers.  :-)


Let's start with Chapter 2, which covers new Syntax.  There's a lot.

Block Scoping!!

Welcome to the 20th century JavaScript.  Anything that reduces the need for an IIFE hack is a plus in my book.

Let!!

Instead of var x, which is subject to the occasional bugs of hoisting, or polluting namespaces, using let x declares the variable with block scope from that point forward, much like C and Java.  Using that variable before it's declaration results in a ReferenceError from a "Temporal Dead Zone" (TDZ).  This sounds confusing and the terminology is off-putting, but the simple answer is to declare your variables before using them!  Just like almost every other language.

Unfortunately, the author goes off on a multi-page tangent describing his preferred version for let syntax, which is less conventional and differs from  C/Java tradition.  Since this alternate syntax was not adopted by ES6, the discussion is confusing and useless.  In general, I like the opinions expressed by Mr. Simpson in the book, but here was one case where he went off base.

Let with a For Statement!

A minor benefit of let over var in a loop is that let redeclares the variable each iteration, so it is "sticky" if used in a callback.  Mr. Simpson provides a precise and clear example of this benefit.

const!

Immutability has many advantages, and in ES6 declaring a variable const makes this clearer.  Note that in the case of a reference to an object, say an array, only the reference is immutable, not the contents of the array.  That limitation is unfortunate but the same as many other languages.  Mr. Simpson provides a concise and clear example.

Block Scoped Functions

Meh, o.k. If you write a lot of complex recursive stuff it's useful, but I don't see a huge need for this in typical code, and there are some incompatibility issues.

Spread!  Rest (a.k.a. "Gather")!!

Both of these use "..." in your code, which might be slightly confusing at first, but I think in practice you'll get used to it, and it mimics existing C and Java syntax, so it was a good choice.

When ... is used before an iterable (see later), such as an array, it "spreads out" the individual elements of that iterable.  Mr. Simpson provides nice examples of how this can be used to conveniently replace apply() or concat().

In alternative places, ... gathers a group of variable into an array.  The book calls this "rest" because it is gathering "the rest of the arguments".  I'd much prefer "gather" or "varargs".  Since a great place to use this syntax is to gather any variable arguments passed to a function at the end of the argument list.  e.g.

function foo(a, b, ...varargs) {}

This mimics behavior in other languages such as Python and Java.  Note that a common use case will be to rewrite code that used the deprecated "array-like" arguments array.  Instead of chanting the mantra "Array.prototype.slice.call":

function foo() {
  var args = Array.prototype.slice.call(arguments);
  // now args is a real array
}

Just do

function foo(...varargs) {
}

Note: This is not explicitly mentioned in the book, but if there are no "rest of" arguments to gather, varargs will be set to an empty array, not undefined.  IMO this is correct behavior.


Default Parameter Values!

These are superior to streams of
   x = x || 6;
in your code.

You can also call functions or invoke an IIFE in your default, but, IMO, this is probably getting too complex or cute.  The book hints at this and details several "gotchas".  But one nice use-case is to provide a default "do nothing" callback function in your function declaration, e.g.

function asyncFoo(url, callback=function(){}) {
}


Destructuring ?!

Have to say, I don't see the point in this, the book doesn't provide any "killer use cases", and it's confusing.  If anybody does have a killer use case, please let me know.  Until then, count me a skeptic.

Let's say a function returns multiple results, e.g. in an array or an object.

function get3DCoordinates() { 
  return [1,2,3]; 
}

function getLocation() {
  return {
     lat : 1;
     lon : 2;
  }
}


Before ES6, you'd go

var c3 = get3DCoordinates();
// use c3[0], c3[1], c3[2]as needed...

or

var loc = getLocation();
// use loc.lat, loc.lon as needed...


With ES6, you can go

var [x,y,z] = get3DCoordinates();
// use x, y, z instead...

or

var { lat: lat, lon:lon } = getLocation();
// use lat, lon instead...


The syntax with the variables on the left is a bit confusing, but I could get used to it.  Fundamentally, I question this usefulness of this.  When a function returns multiple values, those values usually belong together.  If they don't belong together, why is a single function returning them?  You are likely violating the Single Responsibility Principle.

What's the advantage of splitting apart things that belong together?

An another counterexample, what if you needed the location of two things?  What looks like better code to you?

var sanFran = getLocation(94101);
var seattle = getLocation(98101);
var dLat = sanFran.lat - seattle.lat;
var dLon = sanFran.lon - seattle.lon;

or

var { latSF, lonSF } = getLocation(94101);
var { latSeattle, lonSeattle} = getLocation(98101);
var dLat = larSF - latSeattle;
var dLon = lonSF - lonSeattle;

I prefer the old fashioned approach, but maybe your mind works differently.  What if you need the location of N things?

Pages 26-38 of the book cover many more complex cases of destructuring.  With, IMO, no killer use case.  For example, is

var { model : { User } } = App;

really any improvement over

var User = App.model.User;

No.  The new syntax is confusing, it's more typing (in this case), and, most importantly, it's very complex syntax in the typing.  Instead of a couple of dots, flowing left to right, in standard western 1,2,3 order, as we are all used to, you have to properly nest brackets, and the order of the fields is all mixed up - not even reversed, the order is 2,3,1!  The programmer has to think, usually a bad thing.

Until I see a good use case for destructuring, it seems like a confusing addition to the language with little usefulness.  Mr. Simpson provides an example where you can combine preferences/settings from two different objects, e.g. user-preferences and default values.  However, the example only works if you know ahead of time (and put in the code) all of the possible fields.  In my experience, preferences expand over time and come from different projects, so this would be difficult or impossible to maintain.  Without a good use case, I don't see much value in destructuring.  What do you think about it?

Next time, we will continue with even more syntax changes, starting with Object Literal Expressions.  See you then.







Thursday, March 24, 2016

Learning Google Maps

Inspired by the upcoming Race to Alaska, I put together a web page that integrates the nice JSON weather reports from the OpenWeatherMap API, plus some XML format reports from NOAA buoys.  These get drawn on a map with wind barbs.  You can scroll around to see various areas on the map, and click on a station to get more details.

It tracks the recent reports and attempts to compute an hourly rate of change for some statistics.  Depending on the time between reports this can be an inexact science.  But it helps to see if wind, pressure or temperature is changing rapidly.

The back end code is written in JavaScript using Node.js.  The front end is HTML and JavaScript and the Google Maps Javascript API.

Monday, December 29, 2014

Do Frameworks get in the way? A tale of Python and PayPal IPN.

I was writing some basic Python3 CGI code to handle PayPal IPN posts.   PayPal docs here.   The IPN message authentication protocol has PayPal first POST a message to your URL.  After sending back a quickie 200 OK in response to the POST, you then POST back the "complete, unaltered message", with "the same fields (in the same order) as the original message".  I'm not sure this really matters, as I have seen online code that doesn't seem to worry about ordering, that claims to work.  But, just to be robust, I wanted to follow the "correct" protocol.

If PayPal were sending a GET, one could use os.environ.get('QUERY_STRING').  But, for a POST, that returns None.  The Python cgi library provides a nice, standard, "handles lots of tricky cases" mechanism to read the POST fields, using cgi.FieldStorage().  However that returns a non-sorted dictionary, where the order is not preserved.  I reported this on a Stack Overflow question, and asked how one could get the data exactly as sent.  I mean, it was in a big String coming over the wire, e.g. "foo=bar&count=3",  right?  This should be simple.  HTTP can be complex, but this part isn't very tricky.

To my surprise, nobody answered, and not many people even viewed the question.  Maybe it was poorly worded.  I think the real reason might be that programmers are too used to using a library or framework, such as cgi.FieldStorage. or Django, and don't understand what's actually going on deep underneath.   Not picking on Python programmers here, I think the same is true in most languages.

After some playing around, the answer is astoundingly simple.  The POST data is coming over the wire as a String, so just read it from stdin.

query_string = sys.stdin.read()

To POST everything back to PayPal, use this simple code.  (Should I worry more about encoding?)

formData = "cmd=_notify-validate&" + query_string
req = urllib.request.Request(PAYPAL_URL, formData.encode())
req.add_header("Content-type", "application/x-www-form-urlencoded")
response = urllib.request.urlopen(req)
status = str(response.read())
if (not status == "b'VERIFIED'"):
    #complain/abort/whatever
else:
    #continue processing

There's one drawback: now you can't get cgi.FieldStorage() to work.  When it goes to read from stdin, there's nothing left, so it returns an empty dictionary.  (the Python cgi source code is here) .  So, it you also want the convenience of a dict for other purposes, such as checking on various IDs or the price they paid, you need to create your own dict.  But that is also trivial:

multiform = urllib.parse.parse_qs(query_string)

Just like cgi.FieldStorage(), this returns a dictionary where the values are lists of Strings, since it is possible for a key to be repeated in a query, e.g.  foo=bar&foo=car.  However, in practice, this is rare, and doesn't apply for the PayPal case.  I guess you could always ask for the 0th item in the list - FieldStorage has some special methods for this.  To simplify things, I created a nice, simple, single-valued form with Strings for keys and values:

form = {}
for key in multiform.keys():
    form[key] = multiform.get(key)[0]







Wednesday, November 12, 2014

Into the Clouds, deploying node.js with Modulus and OpenShift

My Agility website, www.nextq.info, is up and running on modulus.io.  I like Modulus.  It's easy to use, has been reliable, and you don't need to do a ton of heavy-duty Unix-ese command line stuff.  Their web interface does most of the work, and a simple command modulus deploy will update your codebase.  The main drawback is that they charge a small fee, $15 a month.  I haven't tried any scaling yet.

So lately I've also been playing with OpenShift.  It's free for small projects, and that even includes a little scaling.  It's definitely harder, more technical, and more "UNixy" than Modulus.  You deploy using git, and many commands must be done from the command line, not the web UI.  They have a free book to get you started, Getting Started with Openshift.  After some fiddling, I got things going.

One major issue is that Modulus and OpenShift use different environment variables for important settings like the port and ip address.  So, if you want code portable across both, you will need something like this in your node code:


function setupConfig(config) {
   if (process.env.OPENSHIFT_APP_DNS) {
      config.port = process.env.OPENSHIFT_NODEJS_PORT;
      config.ipAddress = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
      config.mongoURI = process.env.OPENSHIFT_MONGODB_DB_URL;
      config.isOpenshift = process.env.OPENSHIFT_APP_DNS;
   }
   else if (process.env.MODULUS_IAAS) {  // modulus
      config.port = process.env.PORT;
      config.ipAddress = '0.0.0.0';  // modulus doesn't need an ip
      config.mongoURI = process.env.MONGO_URI;
      config.isModulus = process.env.MODULUS_IAAS;
   }

   // possibly more here...
   
   return config;
}

And use these values when you create the server, i.e.

app.listen(config.port, config.ipAddress, function(){
  ...
});


I have the "isXXX" fields so that you can setup specific options like shutdown hooks.

For OpenShift you must change the package.json file to point to your main class.  OpenShift defaults to server.js, where most people use app.js.  Be sure to have the following lines in package.json with the correct name of your main file.

"scripts": {
    "start": "node app.js"
  },
"main": "app.js",

Finally, on a scaled platform, OpenShift (using the haproxy load balancer"pings" your app every two seconds, quickly filling up the log file with confusing junk.  There are even three (duplicate) bugs for this: 918783923141 and 876473.  Their suggested "fix" is to run a cron job calling rhc app-tidy once in a while to clear out your logs.  This fixes the "too much space" issue, but you still have a big problem using the log file, cause all this pings make it harder to see any real problems.  If you are brave, you could edit the haproxy.cfg file as hinted at (but not fully explained) in this StackOverflow post.  I chose an alternative.

My fix is to use Express to insert some middleware before the logger.  The "pings" can be recognized since they have no x-forwarded-for header.  Real requests should have that field, and that's also the value you want in the logfile.  At least, that works for me.

First, a function to ignore these pings and not call next().  Ever the fiddler, it is wrapped in another function so that it can still show a subset of the pings - you might want to see the pings every hour or so.


function ignoreHeartbeat(except) {
   except = except || 0;
   var count = 1;
   return function(req, res, next) {
      if (req.headers["x-forwarded-for"])
         return next();      // normal processing

      if (except > 0) {
         if (--count <= 0) {
            count = except;
            return next();
         }
      }
    
      res.end();
   }   
}
Then, in your app setup code, add this before you add the logger.  e.g. (Express 3 shown)


app.use(ignoreHeartbeat(1800));         // 1800 is once an hour
...
app.use(express.logger(myFormat));

Here's is example log data, where the ignoreHeartbeat was set to 10, so the pings should appear roughly every 20 seconds.  Note how the pings have no ip address.

Wed, 12 Nov 2014 22:08:36 GMT - - GET / 200 - 2 ms
Wed, 12 Nov 2014 22:08:56 GMT - - GET / 200 - 2 ms
Wed, 12 Nov 2014 22:08:59 GMT 50.174.189.32 - GET / 200 - 10 ms
Wed, 12 Nov 2014 22:08:59 GMT 50.174.189.32 - GET /javascripts/jquery-jvectormap-1.2.2.css 200 - 17 ms
  (more "real" GETs here...)
Wed, 12 Nov 2014 22:09:17 GMT - - GET / 200 - 3 ms
Wed, 12 Nov 2014 22:09:37 GMT - - GET / 200 - 1 ms

Monday, October 20, 2014

Web Scraping with node.js and Cheerio

I recently gave a talk at the BayNode Meetup, about my experiences web scraping for dog agility trials using node.js and the cheerio module.  The results are used for my website, www.nextq.info.

You can find the slides as Google Docs here:  Web scraping with cheerio.  Enjoy!


Wednesday, July 23, 2014

Groovy-Like XML for Java. Simple and Sane.

Parsing and navigating through XML in Java is a pain.  The org.w3c.dom.* classes are numerous, messy, and "old style", with no Collections, no Generics, no varargs.  XPath helps a lot with the navigation part, but is still a bit complex and messy.

Groovy, with XMLParser and XMLSlurper and their associated classes, makes this amazingly, dramatically easier.  Simple and Sane.  For example, Making Java Groovy Chapter 2 has an example to parse the Google geocoder XML data to retrieve latitude and longitude.  Below is the essentials of the code.  The full code, which is not much longer, is on GitHub here.

String url = 'http://maps.google.com/maps/api/geocode/xml?' + somemore...
def response = new XmlSlurper().parse(url)
stadium.latitude = response.result[0].geometry.location.lat.toDouble()
stadium.longitude = response.result[0].geometry.location.lng.toDouble()
The parsing is trivial, and navigating to the data (location.lat or location.lng) is also simple, following the familiar dot notation.

Can you do something anything like this in pure Java?  Not quite.  So I wrote a small library, xen, to mimic much of how Groovy does things.  The full Geocoder.java code is here, snippet below:


String url = BASE + URLEncoder.encode(address);
Xen response = new XenParser().parse(url);

Option 1: XPath slash style, 1 based indices
latLng[0] = response.toDouble("result[1]/geometry/location/lat");
latLng[1] = response.one("result[1]/geometry/location/lng").toDouble();

Option 2: Groovy dot style, 0 based indices
latLng[0] = response.toDouble(".result[0].geometry.location.lat");
latLng[1] = response.one(".result[0].geometry.location.lng").toDouble();
Pretty close, eh?

The main difference is that we can't use the dot notation directly from an object, but we can use a very similar slash notation based upon XPath syntax. If you use XPath notation, one major difference from Groovy is that array indices in W3C XPath are 1-based, not 0-based.  Therefore note that we access the 1st element of result, not the 0th.  However, if the "path" starts with a . and a letter, as in the final example, the path is treated as a Groovy / "dot notation" style, with 0-based indices.

So, if you want to greatly simplify parsing and navigating through XML, and/or you love how Groovy does things, please check out my (very beta!) xen library which allows you to do it in Java.  Currently it is compiled vs. Java 6 but I think it should be fine in Java 5.  So if you need to support some Android device, or can't or don't want to integrate Groovy into your Java projects, this could be very useful.

Xen library
JavaDocs
README

The README discusses various design decisions, particularly, how my design converged upon many aspects of the Groovy design.   More discussion will appear in later posts.  And, be warned, this is still a very early version, 0.0.2, so there are probably bugs, some mistakes, and upcoming API changes.


Node for Java Programmers

At a recent BayNode Meetup, I gave a 15 minute presentation on "Node for Java Programmers".  Mainly notes on common things I did wrong coming from the Java world, and ideas or idioms to deal with them.

I got some good feedback and positive responses, and recently edited the presentation.

Here is a link to it.   (on Google Docs).

Thursday, June 12, 2014

Coding by Convention is Great

... except when it isn't.

"Coding by Convention" (a.k.a. "Convention over Configuration") attempts to simplify programming by telling the programmer the preferred way to name or organize things.  It often saves a lot of time and hassle.  Without it, you write extra configuration files, typically in XML.  Spring and J2EE used to require way too much configuration, with lots of stupid redundancies, something like "When I say Foo bean I mean you to use a Foo.class, when they go to myCompany.com/order/books use the com.myCompany.order.books servlet".  On the other hand there can be too much convention - I've never used Maven, but hear that it is particularly dictatorial and hard to modify.

I'm developing a lot in JavaScript / node.js lately, and wanted the ability to save my data as either csv files or iCal (.ics) files.  Searching the NPM registry finds several candidates.

In csv files, the header line contains the name for each column.  If using convention, this would be taken from the property key.  And the property would map directly to the data in the following lines.  Sometimes you would want to change this.  Can you, or is it all done by convention?  As I understand their documentation:

to-csv      convention only
fast-csv    allows for transformation, but over an entire row
json-2-csv  convention only
json-csv    allows for flexible transformations

I ended up using json-csv, though one drawback of it's power is that it takes more work to use.

On the iCalendar side, the question is how to setup or create the complex VEVENT information.  One could use properties named DTSTART, UID, etc.  But it's extremely unlikely that your object has properties with those unusual and capitalized names, and the correct values.  Plus, DTSTART has a complex format with a possible "DATE-TIME" option and a time format of YYYYMMDDTHHMMSSZ.

cozy-iCal       builds VEvent objects programmatically
ical-generator  convention (uses .start .end for DTSTART DTEND)
icalevent       convention (also uses .start, .end etc)
icsjs           builds programmatically
icalendar       builds VEvent objects programmatically

So, it's a mishmash. And convention, while simple and convenient, doesn't always do the trick.  For example, in my CSV data I'd like to include the distance from the user's location.  This is obviously not even a field in the data, since it is calculated on the fly per user from the respective latitudes and longitudes.  The CSV should not include the latitude and longitude - not very useful to the end user.  My start and end dates are also not fields, they are stored in an array.  So I definitely can't use convention.

Unless...

The obvious work-around is to create a new temporary object, that meets the required convention, from the fields and data in the original, "real" object.  In many cases, you would just wrote custom code to do this, especially if speed is a concern.  There are also some modules that vaguely do this.  (Did I miss some???)  But they are pretty limited.   For example object-adapter can only copy values from a source object (renaming the fields), not apply any functions.

So, I wrote my own general-purpose module, remodeler.  For convenience there are copyKeys() and excludeKeys() methods for properties you simply want to copy as-is or ignore.  For the fancy stuff, you provide key / value pairs.  The key is the new property name, and the value is a "transformation".

If the transformation is a String, it means to copy the value from the old object, using the string as property name. For example, "UID", "uid" would mean to create a UID property by copying the previous uid property.

If the transformation is a function, it will be called via function(oldObject, key) and the result used as the new value.  In practice, the key argument is often ignored.  For example,

"SUMMARY", function(o,k) { return 'name:' + o.name + ' date:' + o.date[0]; }

would mean to create a new SUMMARY property by concatenating two existing values.

In many cases, you are still better off writing your own custom code.  On further thought, I'm not sure how useful my module will be, since in JavaScript, it is just so easy to go

var newthing = {
   newkey: oldObject.oldKey,
   ...
}

Other times you can follow the conventions, or use the programmatic interface.  However, if you want a quick way to "remodel" your domain object, this module might meet your needs.  Let me know what you think.  I think I'm going to try using this with ical-generator.






Thursday, April 3, 2014

I'm a Web Magnate

Well, one can dream.  :-)

I've spent the past few months developing a web site / app using a bunch of new (to me) stuff: node.js, Express, mongoDB, along with HTML5, CSS3, and a little JQuery for a cool map using jVectorMap.  All with JavaScript of course. Learned a lot along the way, and now feel somewhat competent with most of the technology.  It's even hooked into Google Maps, Google Analytics, and AddThis for social networking.

Check it out here at nextq.info.  What is it?  It is a search service to find upcoming dog agility trials.  My main hobby.

For hosting, I looked into a few cloud services such as Heroku and Nodejitsu, but decided to use Modulus.io.  So far I've been extremely pleased.
  • You get one month free, thereafter the "typical" $15 a month.
  • Their dashboard is cool-looking and, more importantly, fairly useful.
  • Creating and hooking up a small Mongo Database is simple, even a newbie like me can do it.
  • Uploading your code is simple, even a newbie like me can do it.
  • Linking their site to my domain name server was fairly straightforward, even a... (you get the idea).
  • On a crash it will send you an email (easy to configure) or text, then restarts.
There were a couple of minor gotchas.  I forgot to route both nextq.info and www.nextq.info.  It took me a little while to learn about the .modulusignore file that tells the upload to ignore unnecessary or test files.  (Though it is smart enough to ignore your node_modules folder.)

So far so good.  I especially enjoyed making up agility-centric custom 404 (and 400 and 500) pages.  I'm finding that jVectorMap is a little flaky on some devices, so there is also a much simpler, somewhat "mobile friendly" search page.  But the main parts seem to work fine and some of my agility friends are already using it.

Sunday, January 19, 2014

Yet Another Example Demo Node.js / Express Project

I'm working on an app that finds upcoming events and locations, and wanted a quick link bring up the weather for that city.  Which takes a little work.  What I came up with make a very nice little node.js / express "example" or "demo" program.

Thought I'd try it as a Google Docs presentation.

Source code is on GitHub.

I'll likely add some more commentary here in the near future.

Thursday, December 19, 2013

From Node.js back to Java, Part 1: EventEmitter and Callbacks

There were a lot of features of Node.js and JavaScript that I liked.  Why not bring them to Java?  That's what I'm working on with Nava, "Bringing good ideas from node.js into Java".  So far, I have implemented a fair amount.  The code can be compiled against Java 6, Java 7, and Android 2.2, and presumably later versions of Android.

The emit package is a pretty direct port of a node.js EventEmitter to Java, and can be used in a very similar manner as in node.js.  The main difference is that the event handler cannot be a closure, (cause we don't have closures!) it must implement a simple interface, Emit.IListener, with one method, handleEvent().  Producers of events would subclass or delegate to Emitter, much like the node class would extends or delegate to EventEmitter.  This code essentially replaces Java's EventListenerList and associated classes and interfaces.  There are several major advantages:

  1. The code does not depend on Swing, so it could be used in Android. 
  2. The "events" that get fired need not extend EventObject.  They could be Strings or voids.  However, in many cases, subclassing EventObject makes sense.
  3. Generics are used to obviate the need for a lot of boilerplate, such as declaring a bunch of Listener subclasses and their respective delegation methods addFooListener(), removeFooListener(), etc...
There are also a few disadvantages, noted in the documentation. The main one is that everything is more loosely typed, as you'd expect as this is based upon JavaScript.  Underneath, there are unchecked casts.


The callback package is a rough port of JavaScript / node.js style callbacks.  Your callback "closures" must implement the Callback interface, or extend from AbstractCallback.  Callbacks can be "chained together", either manually using setNextCallback(), or programatically with the utility method Callbacks.chainUp().

You could then "submit" the callback directly by calling the first one, but that would happen synchronously, in-line, and, other than for initial testing, probably isn't worth it.  The more "node-like" technique would be to create a CallbackExecutor (probably application-wide) and use submitCallback(), passing the first callback and it's data.  Your thread will then continue, just like in node, with no need to await the completion (good) and no knowledge of the result (sometimes annoying).

For example, if you had a Reader that read a File into a String, and a Counter that counted words, the skeleton Java code would be:

      Reader reader = new Reader();
      Counter counter = new Counter();
      Callbacks.chainUp(reader, counter );
      CallbackExecutor cex = new CallbackExecutor(2,1);
      cex.submitCallback(reader, theFile);
      // your code then moves on (or just stops...)

As opposed to actual JavaScript/Node, which would look something like:

      fs.readFile(theFile, function(err, data) {
         if (err) throw err;
         // normally the counting code would be in-line here
         // but for modularity similar to the Java
         countWords(data);
       });
       // your code then moves on (or just stops...)


There's more, but that's a start for today.  Check out the readme file, javadocs, and JUnit tests for more information.

Thursday, December 5, 2013

Javadocs on GitHub for Dummies

GitHub has a feature to allow you to upload supporting documents, such as Javadocs, into a gh-pages branch, for easy access by people browsing your project.  The problem is that it's a huge PITA to configure, especially if you are new to git.  Here's how I did it.  This is for a Windows machine and a typical java project.  YMMV.

For example, if you are working on ProjectFoo in GitHub, somewhere there will be a ProjectFoo folder on your local disk that contains a README.me, .gitignore, and folders such as src and test.  I will assume that this has been done, plus your project, in this state, already exists on GitHub as github.com/UserName/ProjectFoo.git.

You want your javadocs to go into a completely separate folder from your main project.  Otherwise you are constantly switching back and forth.  I have organized my projects as follows, splitting my "master" GIT_FOLDER into master and gh-pages subfolders:

  GIT_FOLDER   (all git projects go here)
    master
      ProjectFoo
      ProjectSomeOther
    gh-pages
      ProjectFoo
      ProjectSomeOther

You don't have to follow this arrangement.  But the important thing is to get the javadocs separated from the main project so the branches don't keep stepping on each other.

Initial Setup

cd to GIT_FOLDER/gh-pages  (or, if you have a different setup for the gh-pages branch, to the corresponding folder) and open a Command Window.

Checkout your main branch there

>git clone https://github.com/UserName/ProjectFoo.git

This will create a folder GIT_FOLDER/gh-pages/ProjectFoo.  CD there and check your branch.

>cd ProjectFoo. 

>git branch
* master

Do not create a gh-pages branch yet!  Instead, checkout a new orphan branch named gh-pages

>git checkout --orphan gh-pages
Switched to a new branch 'gh-pages'

In my experience, git still says you are on master if you go git branch, but ignore that for now, it will eventually figure things out.

A directory command (dir /A /B) should show your Java code, with src and possibly test folders, something like:

.git
.gitignore
LICENSE
README.md
src
test

All you want here are the javadocs.
  1. Delete the LICENSE file, and the src and test folders.
  2. Create (or copy) the javadocs to a folder named javadocs.
  3. Double check that .gitignore isn't doing anything too goofy
Your folder should now contain:

.git
.gitignore
javadocs
README.md

Check your git status.  It should now have the correct branch.  Your list of deleted files will vary.

>git status
# On branch gh-pages
# Changes not staged for commit:
#   (use "git add/rm ..." to update what will be committed)
#   (use "git checkout -- ..." to discard changes in working directory)
#
#       deleted:    LICENSE
#       deleted:    src/com/company/package/SomeFile1.java
#       deleted:    src/com/company/package/SomeFile2.java
#       deleted:    src/com/company/package/package-info.java
#       deleted:    test/com/company/package/SomeFile1Test.java
#
# Untracked files:
#   (use "git add ..." to include in what will be committed)
#
#       javadocs/

Add javadocs to the repository.  You may see warnings about line endings.

>git add javadocs

Commit them.  You may see warnings about line endings.

>git commit -m "1st checkin of javadocs"

Now, commit everything else to delete the src and test folders

>git commit -a -m "deleted src from gh-pages"

As a final check, git status should now be clean and git branch shows the new branch:

>git status
# On branch gh-pages
nothing to commit, working directory clean

>git branch
* gh-pages
  master

Finally, push to GitHub.  

>git push origin gh-pages
Username for 'https://github.com': UserName
Password for 'https://UserName@github.com':
Counting objects: ...
... reused 0 (delta 0)
To https://github.com/UserName/project.git
 * [new branch]      gh-pages -> gh-pages

Now, you can login to GitHub with your browser, and you should see the new branch.  Assuming you want a prominent link to these javadocs, go to the main branch and add this line somewhere in the README file:

[JavaDocs are here](http://UserName.github.io/ProjectFoo/javadocs/)

For an example, see my Nava project.

Later on, how to update the JavaDocs:


  1. Generate (or copy) them into that javadocs folder
  2. Open a command window there
  3. git status to see whats going on.  You should be on the gh-pages branch!
  4. You will probably need to add some new docs:  git add .
  5. git commit -m "some comment"
  6. git status   (if you are paranoid)
  7. git push origin gh-pages
  8. git status  Everything should be clean.

Wednesday, November 20, 2013

Leaping into node.js and JavaScript, the Conculsion

In three weeks I've gone from node.js newbie to beginner  to having a module on npm.  Despite the off-beat field of endeavor (Flow Cytometry), it has dozens of downloads.  I think some are robots harvesting the net.

Things I liked:
  • WebStorm made working with GitHub simple and painless.  No more series of three commands to add files, commit locally, and push to the remote site.
  • Integration with Travis-ci was nearly painless.  The main gotcha was in pasting the cute little "the build is passing" icon back into the GitHub readme.  Capitalization matters.  If your repository is CamelCase, the links to travis-ci must be CamelCase.
  • The package.json file and conventions.  Simpler, and much less verbose, than your typical web.xml descriptor.  Use npm init to create a good template, and then it's simple to edit by hand.  I found the online docs fairly inscrutable.  Better to look at various package.jsons from other npm projects, then reread the man pages with the benefit of examples.
  • Publishing to npm was also painless.  My preference is to use a text editor, not npm commands, to edit the package.json file.  Once you have logged in for the first time to npm, just go   npm publish 
  • Using simple JavaScript "objects" { } to hold incoming options, and to return multiple values from a method.
  • JavaScript "short-circuit or" syntax to test for nulls and use defaults.  e.g.  encoding = options.encoding || 'utf8';
  • JavaScript's first class functions, combined with node.js Buffers, were superb in reading binary data from a file, handling various data sizes (16, 32, 64 bit) and endianness.
  • JavaScript's optional function arguments, most of the time.
Things that worked "o.k.":
  • All the node.js callbacks.  It is a huge mental shift.  A few times I got stuck with just too many callbacks to figure things out.  Still don't know how to read a Stream synchronously, since the basic rs.read() method doesn't work.  Rethinking or refactoring so that the callbacks were distributed across more methods helped.  In other words, instead of one function with three callbacks, consider refactoring into three functions, each with one callback.
  • Closures.  O.K., yes, they are nice.  For node.js, required.  But writing line after line ending with  function() {  and then adding all the }); at the end, and getting it right, gets old.  And verbose.  And these closures in general have no names, so they lose out as self-documenting.
  • Because it seemed cool and trendy, I used mocha for unit tests, instead of the more "JUnit-like" nodeunit.  But I couldn't run it well from WebStorm 7.0.  Lo and behold, one of the features of WebStorm 7.0.2 is improved support for Mocha!  Problem largely solved, I can run my unit tests from the IDE.  Code coverage is still an issue.
  • Not sure I'm a fan of Mocha's "literate" style.  In JUnit, I'd name my test method something like testReadFCSFile().  In Mocha, you use describe to wrap the anonymous function, e.g.   describe('Read an FCS File', function() ...)  JUnit is simpler and more concise.  OTOH, Mocha definitely encourages you to think about what the results should be.
Things that didn't work or were annoying:
  • "this" changes in a closure.  So you have to go  self = this, and remember to use self!
  • JavaScript thinking that it "O-O", but the terminology is pretty fuzzy and loose.  For example, those handy { } thingies that just hold a few snippets of data - what do you call them?  "Object" is just plain wrong, since they hold no real behavior, and "hash", (or "Map" or "Dictionary" or even "Key/Value pairs") which I greatly prefer, doesn't seem all that standardized.  Let's push for "hash" or "map"!
  • The documentation for setting up your test scripts is all Unix based, not Windows.  For example, their script suggested for mocha testing is  "test": "./node_modules/.bin/mocha"  which doesn't work at all under Windows.  I played around for an hour and found a workaround, "node node_modules/mocha/bin/mocha".  Turns out that there is a super-simple way, "test":"mocha". But I had to find this out by asking on StackOverflow.
  • I still haven't figured out how to get test coverage for mocha.  Looks like I might need to install Karma, then Istanbul, then whatever...  More to come.  I'm concerned that just as Windows has DLL Hell and Java has JAR hell, node may turn into NPM hell.
  • The documentation is still, er, "young".  Maybe as you expect, node.js is only in version 0.10.  A lot of times you have to make educated guesses, or look via the debugger, as to what events a Stream will emit.  Looking at the node source is helpful, but it is daunting for a JavaScript beginner and there are distressingly few comments in there.  Many are of the "here be Dragons" type around tricky code, not "here be the parameters".  Java and Javadocs are far superior here.
  • At least for methods, I really miss Java's "verbose" style, where you know the types of the arguments and the return value.  And the JavaDocs.  Too often in JavaScript / node you are guessing, or, once you are experienced, using your instincts, as to whether an argument is a String, a hash, or an object.  And often the answer is "all of the above".
  • A common Java practice is to have an "all-powerful" method (or constructor) with all possible parameters, and "convenience" methods that provide some default parameters.  Currying.  This proves to be very awkward in JavaScript, with ugly code like     
            [].unshift.call(arguments, moreArgs);
            allPowerful.apply(this, arguments);


Friday, November 15, 2013

Leaping into node.js and JavaScript, part deux

Well, I'm making a lot of progress since my post of two weeks ago.  Might be starting to get the hang of this JavaScript and node.js stuff.  First, a few followups from last post.


  1. I like WebStorm.  Well worth the small fee for a personal license.  Even just the way it makes Git and GitHub painless is almost worth the price.  And for a relative newbie blundering along it's great.  Especially since a lot of the node.js documentation is a bit sketchy.  Setting breakpoints and looking at fields is wonderful.  My only complaint is that sometimes it gets very very slow.  I'm using version 7.0.  There's a 7.0.1 upgrade available, not sure what it fixes.
  2. The SAMs book Teach Yourself node.js in 24 Hours has been pretty useful - much better than many of the "in 24 Hours" books.
  3. Professional Node.js: Building JavaScript Based Scalable Software is o.k., but a bit disappointing compared to most of the other WROX books I have read.
A few more resources I have found that seem useful:
  1. JavaScript the Definitive Guide is essential.  Get it.
  2. Manuel Kiessling is developing a Node Craftsman followup book.  I't still pretty early in development but might be useful. 
  3. A free download of JavaScript the Good Parts.  I'm temporarily ignoring some of his advice, but it's still a good reference.
  4. Of course, Stackoverflow, within limits.  Many of the responses are very client-HTML-ish (not node.js serverish) and not all are good.  But you can dig to find good information.
Javascript

  I'm coming from 20+ years of Java experience, and my JavaScript shows it.  I put in semicolons.  Looping over arrays I use a for-next with indices, not each().  I'd like to use for (var x in theArray)more, except that stupidly returns all the indices in the array, not all the values.  Sorry, makes no sense for an array, but since JavaScript arrays aren't real I understand whats going on.  But still been burned there several times.  And I still often mistype my loops as for (int i=0; i<....).  Where the "int" should be "var".  Of course, when I go back to programming in Java I'll surely make the opposite mistake.  :-)

  Creating a JavaScript class is fraught with way too much danger.  There are too many ways to do it, all the examples are different, and you can run into religious wars.  Frankly, I think a lot of the people writing have no clue about OOP classes.  I ended up using "classical" style, partly cause it worked well with node's CommonJS module structure to simplify the namespace and export issues, and mainly cause it felt most natural to me.  With more experience this may change.  Classical style uses the .prototype field a lot.  It is well described in JavaScript the Definitive Guide, 6th ed. in section 9.3, "Java-Style Classes in JavaScript".  Example classical style code below:

I'll talk more about working with node.js in future posts...

Tuesday, October 29, 2013

Leaping into node.js and JavaScript, part1

A close friend with tons of tech experience had been urging me to learn JavaScript.  He uses it all the time and loves it.  Last week the local library had a Sams book, Teach Yourself node.js in 24 Hours.  So I checked it out.  How hard could it be?  :-)  I have over twenty years experience in Java, and more before that in C, C++, Pascal etc.  All your classic strongly typed, O-O / procedural languages.  But I have zero experience in node.js, or anything.js, and JavaScript.  Let the adventure begin.

I always had the bias that JavaScript was a "toy language" just for browsers.  At least the second half is wrong.  The node.js guys took Google's Chrome JavaScript runtime engine out of the browser, so you can run JavaScript, for example, from the command line.  Just like a JRE lets you run Java.  Cool.  There is an npm installer to search for and download additional libraries.  It's very quick to get a toy "Hello World" HTTP server up and running.  So far, so good.

A couple of problems.

Many of the examples are of the silly "Hello World" variety.  Data is collected all well and good, and then they use console.log(theData) to output to the console.  Now, very few real-world apps are going to do that.  More importantly, doing it this way glosses over some issues with all the callbacks that are the bane, or blessing, of node.js.  (For a good time, do a Google search on "node.js cancer")  Depends on your brain.  In a real application, you want to pass this data on to something else, such as an HTTP reply, an HTTP/XML/JSON parser, etc...  And this gets tricky.  Simply logging to the console obfuscates some of the key themes of node.js control flow.

Many generic intro Javascript blogs or books have crappy code too.  All the code is glommed into a single huge file, variables are named "$", and prints to the console happen.  This is not proper software engineering!  Javascript / node.js may be the hot new nailgun that lets you build sites quickly and easily, but you still need to put studs in the wall and use electrical boxes.

I found the following site pretty useful:  How to Learn Javascript Properly, along with Learn Node.js Completely and with Confidence.  He's opinionated but I agree with a lot of them.

He suggests that you get "the absolute best editor (IDE) for programming JavaScript", JetBrains' WebStorm.  I agree completely.  It's free for 30 days, thereafter very affordable.  Don't know about you, but my time and sanity is worth way over $49.  And for a "traditional" Java programmer moving over it's great to be able to have some syntax help and a nice graphical debugger.  JavaScript is one of those loosely typed everything is an Object languages.  So many times opening up a variable to see "what the heck type is this?" and "what fields can I access?" is simply the best way to blunder along.

I had separately discovered the Leanpub online ebook, The Node Beginner Book by Manuel Kiessling, which you can buy along with Hands-on Node.js in a $9.99 bundle.  Do so.  So far I found both useful.  They actually talk a bit about how to structure your source code for a realistic application.  Not dumping everything into one huge file with $s as variable names!

Anyway, since he also recommends these books, another tip of the hat to him.  Since I like what's he's saying so far, I took his advice and ordered a more advanced book, Professional Node.js: Building JavaScript Based Scalable Software.  I'll let you know what I think once it arrives.

Finally, stealing a phrase from Bruce Eckel, a word about "Thinking in node.js".  Code flow does not flow in the normal sense.  There are callbacks.  You don't have an option.  If you can't buy into or grok the callbacks, don't use node.js.  It's gonna take me a while...  For example, here was some of my first, ignoramus code.  (It's using a popular request library to do basic http requests)

var googleBody = 'not there';

Request.get('http://www.google.com', function (error, response, body) {
    googleBody = body;
});

doSomethingWith(googleBody);  // like parsing the HTML...

This doesn't work!  You have to remember that the callback executes at some indefinite time in the future, so the googleBody passed to doSomethingWith is very likely to be 'not there'.  I really should have known this, and, when I realized it a couple of hours later after some struggles, it was a real Homer Simpson "Doh" moment.  But I'm learning.  More to come.