Traveling from the Big Apple to the Big Easy via Amtrak Crescent

Amtrak Crescent

“That’s 30 hours on the train, don’t you get sick?” Well, I told them that the actual trip is 80 hours, 30 hours are just from New York to New Orleans via Amtrak Crescent, the longer journey is from New Orleans to Los Angeles, which is close to 50 hours.

Traveling by air is no fun. When you are at 30,000 feet high, there are only clouds accompanying you outside the small plane window. And no, you don’t get sick watching ever-changing landscape. What’s sightseeing!

This is the first part of the journey from the East Coast to the West Coast. Let’s get started.

The Route

There is a route guide, but I found it not be much useful. An iOS or Android app with GPS enabled voice guide could be nice.

The train travels from the Northeast to the South, crossing New York, New Jersey, Pennsylvania, Delaware, Maryland, DC, Virginia, North Carolina, South Carolina, Georgia, Alabama, Mississippi, and Louisiana (finally be able to spell them out without making a mistake). That’s a lot of states. But from Virginia to South Carolina, it is night time, nothing too see at all. I was feeling the 9-to-5 schedule, sleep at 9pm and get up at 5am to catch the sunrise.

The Train

Amtrak Viewliner

On the Amtrak Crescent line, the train is called Viewliner. Viewliner is small single deck comparing to Superliner. According to a train conductor, because of the tunnels in the East Coast, all the trains are Viewliners, but to the west of Chicago, there are all Superliners.

The top windows on the car are for people who sleeping on the upper bunk in the room. That is really helpful for me to catch the outside view without climbing up and down.

The Car and the Room

We are on the right side of the train, but the side does not really matter on this route.

Amtrak Viewliner Roomette

First step into my room, the room is not small at all. The thing you have to get used to is having a toilet next to your seat. But with the cover down, that is not a big deal. Flushing the toilet is just like in the airplane, pressurized system that sucks everything out.

Table, sink and toilet

The only thing I do not like is the burning smell during each start the train. I need to adjust myself to the smell, so went to the end of car for some coffee and juice. There are light coffee and some apple and orange juices in containers. Don’t expect any fancy even you are in the sleeping car.

The Food

During the stop on the Trenton, NJ, the dining service person came by for a dinner reservation. We booked the slot at 6:30pm. She was definitely from the south, the ascent tells it all.

The dining room is pretty standard. The table on each side can be seated by four people. The only complaint I had was the heat coming from underneath the table. Too much heat and too dry.

Steak and salmon

We ordered salmon and steak (medium rare). The steak did not look like a frozen food. But the sides probably are. We also ordered a small bottle of white wine ($6.50), enough for two glasses. I took a peek at the dining car kitchen, I saw the chef and the grill! That is a lot more than traveling on the plane.

The View

Talking about sightseeing. The ever-changing landscape can only be described by pictures.

There are many bridges and overpasses coming from the Northeast.

Bridges and overpasses

But once leaving the big cities, there are only lakes, trees and tracks waiting.

Large lakes and small ponds

Large lakes are really magnificent, but once a while there are small lakes or ponds hiding behind the trees. It is the never ending tree line.

Tree lines

And rolling green or yellowish grasses.

Grasses

Moving away from the natural beauty, houses and communities are seen along the route.

Houses

There are different structures (some are abandoned), a car factory (Honda) and tanks from Anniston Army Depot.

Structures and tanks

From the steady objects to moving things. When train is moving, cars stop.

Railroad crossing

Of course, there is the never ending blue sky.

Blue sky

Well it does end. After we get past Washington DC, the sun went down. At night, there is really nothing much to see. I was hoping stars, but all were scattered lights from desolated houses.

The Mobile Network

This is really important. Not just about checking Facebook or Twitter, but making a conference phone call. Unfortunately there is no WiFi service on board. And this is the case with the most of Amtrak trains. We have to rely on mobile network.

Once we got past Alexander, VA, the cell signal drops considerably, probably because that I was using T-Mobile, and frequently I was on AT&T network.

Without a good mobile network coverage, I think that this is the most frustrated thing traveling by the train. But if you are a reader, you can open up your Kindle or iBook and start reading. Talking about disconnecting yourself!

The Conclusion

Getting yourself comfortable is important. Even though the seat is much wider than in the plane, but the hours are longer. On large stations such as Birmingham AL, get a smoke break and take a walk on the station platform to stretch yourself.

Amtrak is frequently late, and the same happened to us. We finally got to New Orleans more than two hours late.

This is the road trip without driving. Driving is better, because you are in charge, the landscape will wait for you. But this is much better than flying. Let the scenery come to you, stop and take a picture with your phone and say wow, then let it roll by you.

Next: Traveling via Amtrak Sunset Limited

Immediately Invoked Function Expression in CoffeeScript

CoffeeScript only has function expression, there are no named functions nor function declaration, as almost everything in CoffeeScript is expression.

Anonymous function can be written as just a dash plus an arrow:

1
->

This will be compiled to JavaScript:

1
(function () {});

This anonymous function can be invoked immediately:

1
2
// (->)()
(function () {})();

The immediately invoked function expression (IIFE) syntax is different from the preferred format in JavaScript. But this is more likely due to the syntax and compilation of CoffeeScript.

Here is one useful example to show the syntax:

1
2
3
4
5
6
// (square = (n) -> return n * n)()
var square;
(square = function(n) {
return n * n;
})();

And a few more without compiled Javascript:

1
2
3
(->)()
(square = (n) -> return n * n)()
console.log (square = (n) -> return n * n)(10) # 100

Immediately Invoked Function Expression

What’s difference between:

1
2
(function(){}());
(function(){})();

This is function declaration:

1
function foo(){}

The identifier of the function declaration is required.

This is function expression:

1
var foo = function(){};

The right hand side of the assignment must be an expression. And function identifier is optional. Check the previous article about the difference between function declaration and function expression.

Now, come in the grouping operator, which return the result of evaluating an expression:

1
(function(){});

If we do it with named function:

1
2
function foo(){}
(foo);

or

1
(function foo(){});

But we haven’t done anything here, in another word, we haven’t invoked the function. We merely evaluate the function in three occasions. Function is object in JavaScript, when you’re evaluating an object, the result is still an object:

1
2
3
4
5
console.log(function foo(){}); // [Function: foo]
console.log(function (){}); // [Function]
function bar(){}
console.log(bar); // [Function: bar]
console.log({}); // {}

Now, let’s apply function invocation, and do it the traditional way:

1
foo();

The function has been invoked, and it will return the result of the function.

Replace the identifier with function declaration:

1
function foo(){}();

However, this does not work. Because interpreter treats it as a function declaration, and ( will become an unexpected token. Function declaration cannot be invoked immediately. So, we need to make it an expression, by using the grouping operator:

1
(function foo(){})();

The function identifier is no longer necessary:

1
(function(){})();

Since grouping operator return the result of the expression, we can just drop it:

1
function(){}();

But this statement becomes a function declaration again, so we need to place the grouping operator around it:

1
(function(){}());

Okay, but what’s difference between:

1
2
(function(){}());
(function(){})();

There is no difference, they are both function expressions being invoked immediately. Function invocation can only be done via function expression. But first one is more align with foo(), the traditional way. According to the Code Convention for JavaScript Programming Language by Douglas Crockford:

When a function is to be invoked immediately, the entire invocation expression should be wrapped in parens so that it is clear that the value being produced is the result of the function and not the function itself.

The invocation expression is function(){}(), and wrap it around parenthesis becomes (function(){}());.

Therefore, this first method is more traditional and preferred.

Function Declaration and Function Expression

In JavaScript, what is function declaration?

function square(n) { return n * n; }

Here we declare a function and name it “square”. But what is function expression?

var square = function (n) { return n * n; };

When you start a statement with keyword function, then the statement is function declaration, everything else is function expression.

Function expression can either be named or anonymous. The above is anonymous function, and here is a named one:

var square = function square(n) { return n * n; };

There is a variable square and function name square, but they are not the same. The scopes are different. The function name square of the function expression can be only used inside the function, mainly for debugging purpose. Accessing from outside the function, will throw ReferenceError:

var foo = function bar() {};
bar(); // ReferenceError: bar is not defined

We can also use property ‘name’ to differentiate a named vs. an anonymous function:

console.log(square.name); // empty string for an anonymous function

However, you cannot create an anonymous function declaration, for a very obvious reason:

function (n) { return n * n; } // SyntaxError: Unexpected token (

Another difference between function declaration and function expression is hoisting:

square(10); // 100
function square(n) { return n * n; }

Function defined by declaration is hoisted, but not for function expression:

square(10); // TypeError: undefined is not a function
var square = function (n) { return n * n; }

The variable declaration is hoisted, but not for the definition. Therefore, result in TypeError. However, for best practice, functions should be defined before being used.

In conclusion:

  • Function declaration must start with keyword function in the beginning of the statement. Everything else is function expression.
  • Function expression can be anonymous and named, but function declaration can only be named.
  • Function declaration is hoisted, but not function expression.

This function declaration happens inside a unreachable block.

square(10); // 100
if (false) {
  function square(n) { return n * n; }
}

There is no block scope in JavaScript. Spaces in the beginning of keyword function do not count. This is still a valid function declaration.

A simple way to turn function declaration into function expression is by wrapping around parentheses:

(function square(n) { return n * n; });

We are applying the grouping operator () here, which evaluates the function expression.

Another way:

foo(err, function(){});

Just think about , as ().

Other good reads:

Defining Correct Environment for CoffeeScript in Cron

I have written a bunch of CoffeeScript scripts that I would like to run them regularly. Cron is certainly the right choice in many situation.

The default executable path recognized by cron is limited:

* * * * * echo $PATH > /tmp/log/cron.log

This cron job will recognize the following path:

/usr/bin:/bin

However the default executable path for Node.js is usually at:

$ which node
/usr/local/bin/node

Therefore, if you attempt to run a cron job:

* * * * * node -v > /tmp/log/cron.log 2> /tmp/log/cron.err.log

It will return an error, where the executable is not found:

bin/sh: 1: node: not found

The easiest way to solve it is by specifying the fully qualified path:

* * * * * /usr/local/bin/node -v > /tmp/log/cron.log

To ensure the process is installed, we can check the file existence and permission before launching it:

* * * * * test -x /usr/local/bin/node && /usr/local/bin/node -v

But when working with CoffeeScript, the same method does not working:

* * * * * /usr/local/bin/coffee -v 2> /tmp/log/cron.err.log

Because CoffeeScript binary (coffee) use the following format:

#!/usr/bin/env node

Which does not specify fully qualified path on the shebang line, and will result in:

/usr/bin/env: node: No such file or directory

We can compile CoffeeScript into JavaScript and use fully qualified node executable. But this is not necessary. Since we are using Debian based system, which uses Vixie cron. It allows environment variables to be defined. We can make Cron aware of the custom path in environment variable:

* * * * * PATH=$PATH:/usr/local/bin coffee -v > /tmp/log/cron.log

Now the executable path include the one where both node and coffee commands reside.

We can also move it to its own line. But Cron is not shell, it does not expand the variable, so you have to specify all paths:

# Error: `PATH=$PATH:/usr/local/bin`
PATH=/usr/bin:/bin:/usr/local/bin
* * * * * coffee -v > /tmp/log/cron.log

The good practice is to set environment variables in a script:

1
2
3
4
5
6
#!/usr/bin/env bash
#
# This script is intended to be run as a cron job.
PATH=$PATH:/usr/local/bin
coffee -v

and run the script as a cron job:

* * * * * /path/to/script > /tmp/log/cron.log 2>> /tmp/log/cron.err.log

null

In JavaScript, you assign value null to an object property to indicate that the property is defined but with no value. But using null outside the JavaScript domain becomes tricky. For example, in URL query parameters:

?foo=null&bar=bar

after parsing the query:

{
  "foo": "null",
  "bar": "bar"
}

Should the value of foo be parsed from "null" string into null object? Unless you know the context.

Using null in both schema design and URL query gave me a few headaches. So, I have decided to use string and throw away null. As string is the most basic data type across many applications. For simplier design and greater compatibility and portability, use empty string instead of null.

Therefore, the value of query parameter foo should be:

?foo=null&bar=bar // "null"
?foo=&bar=bar     // ""

and:

"null" !== ""

HipChat

While I was learning more on distributed team and remote working. I saw many startups are using HipChat, a group chatting service. If you have been using IRC, you will feel right at home. But it is not just a group chat, you can also share files and source code. Here are a few things I like so far.

Virtual office

The most appealing is the concept of “virtual office”. This certainly will help a distributed team. It gives you a sense of being in the office at the same time but without constant disruption.

Reduce emails

The advantage it has over email is that all messages are within team only. Team messages should take priority over others. And you know that you cannot control your inbox. Hopefully this will cut down the unnecessary emails and facilitate quicker response.

Search past chat history

All chats are saved and indexed, so if you say that you are going to do something, you’d better do it, because it will be recorded and searcheable in the future. Meetings could be conducted in the chat room as well, as all details are saved, without pulling all people out of their seats at the same time.

Integration and API

I have integrated with BitBucket, so all commits will show up in one of our chat rooms. This chat room becomes our notification center. There are many other integration such as Basecamp, Evernote. And There is also an API that can be used to create custom integration.

Slash commands and emoticons

I also like the slash commands and emoticons.

So, I just got it started with my team, let me see how it goes.

Difference between HTTP HEAD and GET

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. - Method Definitions

I was a little bit confused when I encoutered the HTTP status code 204, which states that the response MUST NOT include a message body. The HEAD method contains no body content as well. Should I use 204 instead of 200?

The answer is NO. GET method should always return HTTP status code of 200. Since HEAD method is idential to GET, it should return 200 as well. Just keep in mind that the cost of processing both HEAD and GET requests are almost the same.

Not Ready for Xiaomi

When I was in the United States, I have heard of many good news about Xiaomi, a Chinese smartphone company. And people are comparing the founder Lei Jun to Steve Jobs. I was very excited when I got to China and eager to get my hand on a Mi3.

Mi3

Well, I didn’t get it, not saying that I did not try, maybe I didn’t try hard enough. But in some situations, this might be a good thing.

The phones were quickly sold out within minutes. The official number of phones sold is remarkable according the manufacturer. But first do you trust these numbers? Maybe I just dislike the marketing technique more. I have read many reviews, people are saying that the marketing technique is awful. While they keep up the demand by limiting the supply from the company website. You can actually buy higher price ones from other retailers.

Another problem is the quality of the phone. When I first asked my friend for the opinion of buying, he simply replied “trash”. When I asked another friend, she told me that she had two previous version Xiaomi phones, and they both broke down. I have used two iPhones and I have never had any problem with it.

It boils down to quality vs. quantity. Selling by creating a tricky marketing technique and with misleading information to boost the quantity without really focusing on the quality is sad. Without changing the DNA, the company is not going far, no matter how much money raises.

I am just happy with my Nexus for now.

A New NodeJS Web Framework - Koa

Taking the first spin on Koa, a new web framework designed by the team behind Express.

Requirements

  1. Node v0.11.9 or higher is required for generator support.
  2. --harmony flag must be used when running Node.

Without the --harmony flag, genertor function cannot be defined:

function *fn() {
           ^
SyntaxError: Unexpected token *
    at exports.runInThisContext (vm.js:69:16)
    at Module._compile (module.js:432:25)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)
    at Function.Module.runMain (module.js:490:10)
    at startup (node.js:123:16)
    at node.js:1031:3

So, set the --harmony flag in shell alias:

$ alias node='node --harmony'

To know more:

$ man node
--harmony (enable all harmony features (except typeof))
      type: bool  default: false

Harmony is the codename of ECMAScript 6, the next version of the standard.

Install

$ npm install koa

The footprint of the framework is small. Therefore, there is no executable binary like Express, and we do not need to install it globally.

Dependencies

Dependencies on version 0.2.1:

"dependencies": {
  "accepts": "~1.0.0",
  "type-is": "~1.0.0",
  "on-socket-error": "~1.0.1",
  "co": "~3.0.1",
  "debug": "*",
  "mime": "~1.2.11",
  "fresh": "~0.2.0",
  "koa-compose": "~2.1.0",
  "cookies": "~0.3.7",
  "keygrip": "~1.0.0"
}

Middleware

Middleware system is the core of either Express or Koa based application. This needs a separate post. Here just describes the difference in design.

In a simple assembly design, each unit passes control to the next one until the last one terminates and responses to the request:

    +-----+     +-----+     +-----+
--> |     | --> |     | --> |     | --o
    +-----+     +-----+     +-----+

Express middleware passes control to the next one like an assembly line, but each unit is capable of responding to the request:

       o           o           o
       |           |           |
    +-----+     +-----+     +-----+
--> |     | --> |     | --> |     |
    +-----+     +-----+     +-----+

Koa provides a traceback via generator, each unit is capable of working on the request twice instead of once as previous two designs. It is stack alike, where the first generator will also be the last one prior to responding to request:

       o
       |
    +-----+     +-----+     +-----+
--> |     | --> |     | --> |     |
    +-----+     +-----+     +-----+
       ^          | ^         |
       +----------+ +---------+

This is sort of an assembly loop, where the starting station is also be the ending station.

Usage

Here is one liner:

require('koa')().use(function *() { this.body = 'OK'; }).listen(3000);

app.use requires a generator function or function *(). Koa middleware uses this (context) instead of req and res in Express. It also encapsulates Node’s request and response objects. For example, this or context has the following properties:

[ 'request',     // Koa request
  'response',    // Koa response
  'app',
  'req',         // Node request
  'res',         // Node response
  'onerror',
  'originalUrl',
  'cookies',
  'accept' ]

Status and Body

Status can be used as a flag indicating whether a request has been processed or not:

app.use(function *() {
  console.log(this.status); // undefined
  this.body = 'processed';
  console.log(this.status); // 200
});

When the body is populated, status is automatically updated, probably via the nextTick method. So, we can use it as the flag to design a response such as a custom not found response.

Not Found

Create a custom Not Found in JSON content type:

app.use(function *(next) {
  yield next; // The operation is yet to start.
  if (this.status) { return; }

  this.status = 404;
  this.body = { message: 'Cannot find what you are looking for :(' };
});
app.use(function *() {}); // Do nothing to simulate not found.

Error Handling

Koa app is capable of catching the error event:

app.on('error', function (err, ctx) {
  // Log errors.
});

where ctx is a context instance. But you cannot modify the response body. This is more for server side logging and debugging purpose. The 500 Internal Server Error will be returned to the client.

We can use try..catch to define a custom error handling middleware:

app.use(function *(next) {
  try {
    yield next;
  } catch (err) {
    this.status = err.status || 500;
    this.body   = { message: err.message || 'Bad stuff happened!' };
    this.app.emit('error', err, this); // Enable error event handling
  }
});

Make sure to emit the error event and let the server log the error.

All non-operational middleware (e.g., not found or error) should be defined first, so it can be traced back as the last guards before sending response back.

Routing

Out of the box, Koa does not support routing, but it can be achieved via routing middleware, see examples.

Examples

Define an app with only one middleware generator function:

1
2
3
4
5
function *foo(next) {
console.log('foo');
this.status = 204;
}
require('koa')().use(foo).listen(3000);

Instead of using status code 200, we use 204 here, because the response contains no body. If using 200, the server does not know the total content length, will result in Transfer-Encoding: chunked header instead of Content-Length. See chunked transfer encoding.

This app simply prints out foo on the server side, and respond to a client with status code 204 and an empty body. We can even omit the next parameter, since we are not using it.

Now let’s use two middleware generator functions:

1
2
3
4
5
6
7
8
// Response: foo
function *foo(next) {
this.body = 'foo';
}
function *bar(next) {
this.body = 'bar';
}
require('koa')().use(foo).use(bar).listen(3000);

Since generator foo sets the body, generator bar will never be reached. We can change that by adding the yield:

1
2
3
4
5
6
7
8
9
10
// Response: bar
function *foo(next) {
this.body = 'foo';
yield next;
}
function *bar(next) {
this.body = 'bar';
yield next;
}
require('koa')().use(foo).use(bar).listen(3000);

This looks alot like Express, yeild next is similar to next(). Request travels through the middleware system first via foo then bar. But actually by using generator, it also returns back to foo as foo->bar->foo:

1
2
3
4
5
6
7
8
9
10
11
// Response: foo again
function *foo(next) {
this.body = 'foo';
yield next;
this.body = 'foo again';
}
function *bar(next) {
this.body = 'bar';
yield next;
}
require('koa')().use(foo).use(bar).listen(3000);

This is similar to a stack alike request model, where the first middleware should also be the last middleware to touch the request. There is a no-op middleware in the end to catch the last yield next produced by bar middleware generator and traces back the stack.

Debugging

Set environment variable DEBUG=koa* to enable Koa specific debugging information in development environment:

$ DEBUG=koa* node app.js

You will see a list of middleware. If a middleware is an anonymous function, we can set ._name to define a custom name:

function *foo(next) {
  // Middleware definition starts here.
}
foo._name = 'bar';
app.use(foo);

The middleware name will be bar instead of foo.

Resources

  1. Koa
  2. Koa | GitHub
  3. Koa Quick Guide
  4. Koa Middleware List