expatiari expatria

Metar and TAF

Suppose you’re in the middle of nowhere (or at least anywhere in Greenland) and need to know the coming weather conditions. The typical five day forecast is not gonna cut it.

METAR (METeorological Airport Report) describe the current conditions as observed by the weather tower at an airport. These are reliable, updated frequently, although incredibly terse. Similarly, TAF (Terminal Aerodrome Forecast) report the coming conditions including trends and temporary changes typically for the next twelve to twenty-four hours. The format takes a little getting used.

I’ve compiled a number of reports for a select few cities in the north Atlantic and compressed them into a format the plays nicely with mobile telephones. For the benefit of humans, I’ve prepended the Metar decoded. Let’s check out the balmy Kangerlussuaq (Søndre Strømfjord):

Metar


BGSF 071750Z 04005KT 5000 -SN OVC035 M11/M12 Q1008

BGSF is the airport code (ICAO) followed by the time of the report at UTC. The first two digits represent the day of the month (in this case the seventh) while the next four are the hour (24-hour) and minute (Z refers to Zulu or UTC), thus 17:50.

The next three digits refer to the wind direction (the direction from which the wind comes) over 360 degrees, where 0 is north, 90 is from the east. The next two digits is the wind speed in knots (hence KT). Two knots is roughly one m/s. So 04005KT is roughly 2.5 m/s wind from the northeast. Sometimes you’ll see a G which refers to gusts, so 27020G30KT means 10 m/s gusting to 15 m/s from the west.

The next four digits refer to visibility in meters. 5000 means 5 km visibility. 9999 is typically used for visibility unlimited or at least 10 km.

Then there is the weather type, precipitation, etc. A minus (-) means light while plus is heavy. There are a huge number of codes. Just a few, SH showers, SN snow, FG fog, DZ drizzle, TS thunderstorms, BR mist, RA rain, and many more.

The next zero to many describe the layers of clouds. Scattered, broken, overcast, etc followed by the number of hundreds of feet. Why we mix metric with imperial, I have only guesses. OVC035 means overcast layer of clouds at 3500 feet.

The next numbers refer to the the temperature. The M means minus (below freezing). After the slash is the dew point, the temperature at which precipitation should be expected, or at least 100% relative humidity.

The number with a Q is the barometric pressure in millibar (mbs).

Gōngfu Chá Dào Animated

Exponential negation, aggregate product, and the financial crisis

I present an alternate theory as to the cause of the Icelandic financial crisis. Specifically, the negation and diversion of sub-zeros from database aggregate product calculations.

Just kidding. But, every once in a while there is a hack so circuitous it keeps one up at night. Literally. This is one of them. This hack has found itself in production code in banks around the world with no problems for several years. Until now. :)

When calculating sliding averages, adjusted duration, volatility, and other performance graphs, it is often necessary to multiply huge sets of values from a database. For example, the product of the daily change in the closing price of a stock over the past ten years. This is known as an aggregate product.

So, you would think that the leading database, Oracle, would handle an aggregate product. Some common aggregate functions include SUM, AVG, COUNT, MAX, MIN, etc. Oracle allows us to add, average, count, even calculate logarithms, but we can not simply multiply the rows in a table. Here’s a simplified solution at one bank, now going the way of the polar bear:

   select
      exp(sum(ln(abs(decode(COLUMN,0,1,COLUMN)))))*
      decode(mod(count(decode(sign(COLUMN),-1,1,null)),2),1,-1,1)*
      nvl(max(decode(COLUMN,0,0,null)),1)

Let’s reconstruct this. Put simply, we add up all the natural logs of each value and reapplying the exponential to the sum. The first line, exp(sum(ln(…))) relies on the fact that:

   e^(ln(x1) + ln(x2) + ... + ln(xn))
      == x1 * x2 * ... * xn, for all x >= 0

But this is only true for positive non-zero numbers. The abs(decode(…)) of the first line, reverses all negatives and ignores all zeros. The next two lines, handle negatives and zeros respectively.

   select
      e^(sum(ln(abs( [ ignore zeros ] ))))*
      ( count( negative numbers ) == even ? 1 : -1 )*
      ( have any zero at all ? 0 : 1 )

The second line multiplies the entire result by negative one if there are an odd number of negative numbers. The third and final line multiplies the entire result by zero if there is any zero.

Javascript Visibility

I often find myself reinventing the wheel and get lost around closures, prototypes, unscoped variables, and other OOP-like features of Javascript. So I created a Javascript ‘class cheat-sheet‘ with the several ways of instantiating and referencing objects therein. I’ve eliminated redundant styles and what I found useless (unscoped globals). Without further ado:

function Class() {
  //
  // PUBLIC INSTANCE
  // instance public variable and methods
  //
  this.instance_public = 2;

  this.instance_public_func = function() {
    return private_var +
      this.instance_public +
      this.prototype_public;
  }

  //
  // PRIVATE
  // private variable and methods
  //
  var  that = this;
  var  private_var = 1;

  function private_func() {
    return private_var +
      that.instance_public +
      that.prototype_public;
  }

}
//
// PROTOTYPE PUBLIC
// prototype public variable and methods
//
Class.prototype.prototype_public = 4;

Class.prototype.prototype_public_func = function() {
    // private_var (hidden from prototype)
    return this.instance_public +
      this.prototype_public;
}

What does it mean? Well, I am aware of three ways to declare a field (basic variable) within a constructor (class definition) and one in the prototype. These are:

function Class() {
  var private;
  this.public1;
  global;
}
Class.prototype.public2;

The var scopes a object within its surrounding { } block. Such objects are accessible (through closure) to any function within the same block, but invisible outside of the block.

In the example above, public1 and public2 have the same visibility. However, the latter is memory efficient. public2 acts somewhat like a static class variable except that it can be overridden by any instance. Explicitly referencing prototype.public2 is akin to a static member in other languages such as Java. The . (dot) before the variable name that binds it to an object and makes it public, whether that object is this, that or var hash = {}; hash.key = "value";.

Any unbound object (via dot (.) or var) is global. There are very few (perhaps no) good reasons to do this.

Caveats

Note that function x is shorthand for var x = function. The following two methods are equivalent.

  function private_method1() {
    return that;
  };

  var private_method2 = function() {
    return that;
  };

Private and global functions defined within a constructor do not have access to the implied new object reference this, but can access another reference such as var that = this;. Perhaps this is a ‘bug’ in the ECMA standard.

Private (var) and instance public (this.) members, may access all other members of a class, including prototype variables and functions. However, prototype members may not access private members defined within the constructor. The following will fail:

   function X() { var priv = 6; };
   X.prototype.proto = function() { return priv; };
   var x = new X();
   alert(x.proto());

Private and prototype functions may be called within the constructor before they have been defined. But instance public are only available (at runtime) after they’ve been instantiated. For example, “priv and proto” will be alerted, but an error will be thrown on line 3 because this.pub has not yet been defined.

 1    function X() {
 2      alert(priv() +" and "+ this.proto());
 3      alert(this.pub());
 4      function priv() { return "priv"; }
 5      this.pub = function() { return "pub"; }
 6    }
 7    X.prototype.proto = function() { return "proto"; };
 8    new X();

Variations

A singleton object has only one instance and there are thus no advantages of the prototype.

var s = new function S() {
  this.pub_var = 1;
  this.pub = function() {};
  var that = this;
  function priv() {};
}();

Slightly more exotic, is a singleton whose members are all public:

var h = {
  field : "public",
  method : function() { return this.field; }
};

Returning the singleton from a constructor, gives us access to private variables. Consider the “Module Pattern”:

var Namespace = {
  C : function() {
    var priv = "priv";
    return {
      field : "pub",
      method : function() { return priv +" and "+ this.field; }
    }
  }
};
var c = new Namespace.C();

Adiós Casa Xelajú

Sin duda hoy es un día muy triste para mí. Voy a echarlos de menos y voy a llorar mucho. Será la culpa de todas ustedes. Pero ha sido un corto tiempo muy sagrado. En realidad he ganada muchos amigos nuevos, conocimientos sobre español, experiencias culturales, especialmente bailando salsa, y yo he tenido cuatro profesores inspiradores.

Para terminar mi discurso yo les regalaré un secreto. Es muy simple. No se ve bien más que con el corazón. Lo esencial es invisible para los ojos.

Muchos gracias. Hasta pronto.