Ramblings of a
Semi-Retired Programmer

12/10/2010 - Another IE Feature, Applying innerHTML to a <pre> Element.

There are some poems of a sort on the BEV web site, and in the course of working on the site I decided it would be good to have the poems saved as plain text, so they would be easier to edit. So I decided that on pages that would show them, I would just put them in a <pre></pre> block.

At one point, I wanted to do this dynamically, so I pulled the plain text from the site using AJAX, then stuffed them into the block with:


document.getElementByID("poem-pre").innerHTML = responsetext;
FireFox, fine, works a treat. IE8, yuk - all the formatting removed. I had to test for IE, and then change all occurrences of "\n" to "<br />"

   if (ie)
      poem.replace(/\n/g,"<br />");
9/10/2010 How to control paragraph spacing and other padding in HTML

For years, in web pages when I wanted to control spacing between paragraphs, or between text and an image or whatever, I would use:


<br><img src="trans.gif" height=5><br>
But then when I started coverting pages to XHTML, and ran them through the W3C validator, I had to change to:

<br /><img src="trans.gif" height="5" alt=""><br />
This began to strike me as unsightly, so I looked around for another way of doing the same thing, and eventually found that the following works reasonably:

<p style="margin-top:5px" />
But this is still no good for spacings smaller than the browser default paragraph spacing. You can use a margin-top like -10px, but the spacing you get is dependent on the font size, so this can produce some really ugly effects if you get the negative number wrong.

There's also a problem with this approach if the thing following the padding is wrapped in a DIV. Block elements like DIV are not allowed inside a P tag, and apparently:


<p style="margin-top:30px" />
<div>Some text</div>
breaks that rule. So eventually I got down to padding with:

<div style="height:5"></div>
This is still more succinct than the transparent GIF approach, and works without any ancillary image file. You can play with the various things I tried using the source from the IFRAME below.

Surfacing from the haze for a moment after this exercise it dawned on me that I could be much more succinct if I used H1 - H6 for many of the purposes I was trying to cover.

30/9/2010 Smoothly Shrinking and Expanding Web Page Content

You may have wondered how the nifty slow shrink and expand of parts of many web pages work.

As I've said on the main page, I have been doing a makeover on that which incorporates some of these effects. I Chose to use the jQuery library, but found to my dismay that using its standard methods worked fine on Firefox, but failed on IE8 - portability or what!

So for the expanding paragraphs I had to roll my own. In principle it is very straightforward - you wrap the relevant HTML in a <div>, then change the div's height at short intervals by setting the style value:


for (;;)
{
   if (currentHeight == 0)
      break;
   currentheight--;
   mydiv.style.height = ""+currentheight+"px";
   pause(briefly);
}
There are a few stumbling blocks. The first is that JavaScript does not have a pause() function - you have to use something like:

repeatAtIntervals()
{
   //  do something
   setTimeout("repeatAtIntervals()", interval);
}
Another is how to get and remember the size of the stuff before we shrunk it, and other state data, and the third is to ensure that the content actually gets curtailed by the shrinking div.

The HTML in outline can look something like this:


<body>
<h2 onclick="slowToggle('thediv')" style="cursor:pointer;">Click here</h2>
<div id="thediv" class="expando">
<content />
</div>
</body>
</pre>
I have given the shrinkable <div> a distinctive class so that it can be set up appropriately at initialization time. What we need to do then is something like:

thediv.shrinkinfo = new shrinkinfo(thediv, ...);
thediv.style.overflow = "hidden";       // make sure the div clips the content
thediv.style.height = "0px";              // let's start with it hidden
You can use document.getElementsByTagName() to get all the divs in your page, then iterate over the array tweaking any div that has class "expando".

The div also has an ID so we can refer to it specifically.

So what is the shrinkinfo? Well here, I've defined a constructor function that takes the div element object as its first argument. (I know it is fashionable these days to use object literals - you are welcome to classify me as old-fashioned.):


function shrinkinfo(d, interval, step)
{
   this.ch = 0;                     // current height
   this.th = d.offsetHeight;    // max height
   this.busy = false;             // guard against simultaneous operations
   this.step = step;              // optimization for the effect
   this.interval = interval;       // how often to change the height - similar
}
The div or divs can be set up in a document.ready handler, or as I've done here for simplicity, in body.onload. So now all we need is a bit of scripting to implement slowToggle(). This seems to work:

function shrink(divid)
{
   var d = document.getElementById(divid);
   var so = d.shrinkinfo;
   if (so.ch == 0)
   {
      so.busy = false;
      return;
   }
   if (so.ch < so.step)
      so.ch--;
   else
      so.ch -= so.step
   d.style.height = so.ch+"px";
   setTimeout("shrink('"+divid+"')", so.interval);
}

function expand(divid)
{
   var d = document.getElementById(divid);
   var so = d.shrinkinfo;
   if (so.ch >= so.th)
   {
      so.busy = false;
      return;
   }
   if (so.th-so.ch < so.step)
      so.ch++;
   else
      so.ch += so.step
   d.style.height = so.ch+"px";
   setTimeout("expand('"+divid+"')", so.interval);
}

function slowToggle(divid)
{
   var d = document.getElementById(divid);
   if (d.shrinkinfo.busy)
      return;
   d.shrinkinfo.busy = true;
   if (d.shrinkinfo.ch == 0)
      expand(divid);
   else
      shrink(divid);
}
Notice that we pass the shrink and expand functions a simple string argument. This makes it simple to construct the first string argument to setTimeout(). We could pass a shrinkinfo object, but then we'd have to serialize the values into json to construct the argument. In any case we already have a captive copy of the data on our div object. The slowToggle() function just sets the busy guard, then sorts out which of the two to call.

The functions that do the work simply retrieve our div element object, check to see if it has reached its target size. If it has, they just clear the busy guard, and return. If not, they use the shrinkinfo.step and shrinkinfo.interval settings to increment or decrement the current height, and set the style on the div appropriately. The coding here is what you can tweak to change the appearance of the size change.

That's it. You can get the code from the working example here.

17/3/2010 Dead Page?.

Well yes, it does look that way. Perhaps I should do a reorganization of my software ramblings.

This year I've mostly been interested in the current state and future of GDC, that's the GCC D compiler based on the DMD front end. If you are at all interested in this, please visit.

Yes, I really should reorganize!

31/12/2009 - Back To D Future - GDC, MinGW, and Code::Blocks.

Somehow I got back to D and my DCat project. I was originally trying to write this in a way that would build with D1 and D2, but D2 has, I think, escaped from this possibility. In any case, it is now clearly refered to as an alpha, so I'm backing off to D1.

To simplify it, I want to be able to dynamically load shared libraries under Linux. To do this at present, I must use the GCC D compiler (GDC for short), since the DMD compiler for Linux does not generate position independent code. So I thought I would continue the development on Windows, but use the Windows build of GDC under MinGW so I'd be pretty sure that what I had would build on Linux when I get that far.

I chose Code::Blocks basically because it isn't Java, which suits one of my irrational prejudices, and because it already recognizes GDC. OK, so a simple aim, but getting there turned out to be something of a tortuous path.

The last official build of GDC was at Feb 2008, and from what I saw in the Windows version documentation, that was for GCC core 3.4.5. In contrast, the MinGW download site was offering core versions inthe 4.x.x range, so I was a bit dubious about the two together. Fairly arbitrarily I installed the latest release version of MinGW. Then I found a later build of GDC at blog.zuu.dk that claimed to work with core 4.3.0, so I downloaded that. Unfortunately the build seemed to have been built with Dwarf exceptions instead of SJLJ exceptions, so the linker was seeing unsatisfied externals with the standard 4.3.0 core build (SJLJ for MinGW).

By that time, I felt the installation was too much of a mixture. Then I found an alternative build of MinGW that was quite positive about the exceptions it used at Twilight Draon Media, so I installed that - very straightforward and up to date (you want the SJLJ version). I plastered the install of the two year old GDC over that, and it almost worked. It was not finding crtbegin.o and crtend.o, and it turns out you have to copy these from MinGW\lib\gcc\mingw32\4.4.1 to MinGW\lib. Then it worked.

So then I got to Code::Blocks. That went well up to a point, but when I asked it to compile a D file with some warnings and errors, the build messages I got were nonsense, and the markup of, and jump-to error lines didn't work. After a while I figured out what was going wrong.

Both DMD/GCD (1.30) produce error/warning messages that are not notably consistent. For example, if there is an error, with DMD you see something like:

fixups.d(50): unrecognized declaration
but for a warning:
warning - fixups.d(37): Error: implicit conversion of expression (atoi(t)) of type long to int can
cause loss of data
The messages from GCD are similar except that they use another colon and no parentheses for the line number.

These messages are pretty confusing to me, let alone to Code::Blocks when it parses the messages. The first case, which is an error, does not contain the word error, but the second, which isn't, does. Whatever the exact cause, the effect is that the file name in the message window appears as 'warning - fixups.d', the message is shown as an error - red, and the error/warning count is incorrect. It also screws up the ability to click on the message and have the editor jump to the indicated line number, and marking of error/warning lines. There might be similar problems with debuggers.

The GCC C compiler in contrast produces error and warning messages as follows:

hello.c:13: error: expected expression before '}' token
hello.c:13: warning: control reaches end of non-void function
Disambiguation and structure in this case are quite clear. When I found the part of the compiler and debugger settings that was relevant (Settings->Compiler & Debugger->GDC D Compiler->Other Settings->Advanced Options->Output Parsing) it was clear that the regular expressions used to parse the compiler output expected a similarly rational output.

To get it working properly I had to do several things:

  • Move Compiler Warning and Compiler Error to the top of the list (I'm not likelytouse the other itms anyway),
  • Change the warning RegEx to: ^warning - ([{}() \t#%$~A-Za-z0-9_+/\.-]+):([0-9]+):[ \t]Error: (.+)
  • Change the error RegEx to: ([][{}() \t#%$~A-Za-z0-9_+/\.-]+):([0-9]+):[ \t](.+)
  • Make sure that the warning one was first in the list
If the warning isn't first in the list, then 'warning - fixups.d' is seen by the error RegEx as a valid file name, the line number is OK, but the message includes "Error: ....". The incorrect file name - I presume - messes up the system of marking the error point in the file and clicking on the message to get to it. So now that is working also.

I have another small gripe about the DMD/GCD messages though. If you choose to see warning messages

dmd -w -c x.d
gdc -Wall -c x.d
You only see them if there are no errors. If there are errors, you only see them, even if there are preceding code lines that would produce a warning. This isn't Code::Blocks, it's the compilers. Consequently you only ever see 'N errors, 0 warnings' or '0 errors, N warnings'.

What is Code::Blocks' fault I think, and I have not found a way to deal with yet, is that you can't turn warnings off. There's an 'Inhibit all warnings' option, but it seems to use -w, which actually turns warnings on, and it does not have any effect on the compile output.

A Happy New Year to anyone out there who happens to read this in the near future.

25/11/2009 - Most Popular Programming Languages.

I was looking at Tiobe again today, and wondered what the index would look like if it were restricted to languages that are almost exclusively used for web programming. I exclude from that category the use of languages for writing web servers or web application frameworks, so Apache, Tomcat, and so on don't count - the needs of systems of that sort are different.

My guess is that the top end of the resulting list would be something like:

  • PHP
  • Javascript
  • Java
  • Python
  • Perl
  • yada yada.
What do you think?
23/11/2009 - Javascript Exceptions - Design Flaw?

It has always surprised me that many computer programming languages that have conventional try ... catch exception handling, will allow you to throw pretty much any value or expression. Java may be an exception, since I believe it has a class 'Throwable', and in Java, I would expect that only objects derived from that would compile in throw statements.

Javascript follows the 'throw anything' paradigm. When I was looking at this the other day, I discovered what appears to be a design flaw, and possibly a bug in the Mozilla Javascript implementation, and or the ECMAScript spec. The following code demonstrates what I mean (this is written to output debug information to the Firebug console):


<html><head>
<script>
// This is how I would expect to derive my own error object from Error
function MyError(s)
{
   this.message = s;
   this.name = "MyError";
}
MyError.prototype = new Error();

// Here's an alternative that does not involve derivation
function MyError2(s)
{
   var me = new Error(s);
   me.name = "MyError2";
   return me;
}

try
{
   throw Error("something wrong");
}
catch (x)
{
   if (x instanceof Error)
      console.log("Exception %s: %s", x.name, x.message);  // Gets here as expected
   else
      console.log("Exception of unexpected type, info is: %s", x.toString);
}
try
{
   throw RangeError("something wrong rangewise");
}
catch (x)
{
   if (x instanceof Error)
      console.log("Exception %s: %s", x.name, x.message);  // Gets here as expected
   else
      console.log("Exception of unexpected type, info is: %s", x.toString);
}
try
{
   throw MyError2("something wrong with my code");
}
catch (x)
{
   if (x instanceof Error)
      console.log("Exception %s: %s", x.name, x.message);  // Gets here as expected
   else
      console.log("Exception of unexpected type, info is: %s", x.toString);
}
try
{
   // Note that this does not match preceding examples - uses new
   throw new MyError("something wrong with my code");
}
catch (x)
{
   if (x instanceof Error)
      console.log("Exception %s: %s", x.name, x.message);  // Gets here as expected
   else
      console.log("Exception of unexpected type, info is: %s", x.toString);
}
try
{
   throw MyError("something wrong with my code");
}
catch (x)
{
   if (x instanceof Error)
      console.log("Exception %s: %s", x.name, x.message);
   else
      console.log("Exception of unexpected type");  // Gets here?
   // Worse still, the else code won't compile if left the same as the other cases
   // - x is undefined
}

</script></head>
<body>Body</body></html>
The ECMAScript spec makes it clear that, unusually, 'Error("message")' and 'new Error("message")' are equivalent. But when I derive my own error type from Error, it is neccessary for me to use the 'new MyError("message")' form. So it seems like either the spec should be changed to require 'throw new Error("message")' for all the error types, or the Mozilla Implementation should be changed so there is enough information in Error.prototype to allow code to be generated that does not require 'new' in front of the derived error creation function that uses it.

While I'm at it, I would like to see the spec changed so that anything that was thrown that was not derived from Error should be converted to a string and implicitly fed as an argument to vanilla Error(). This would simplify the code of catch blocks, and I don't care if code is 100% full speed at that point. If something has already gone wrong, then slow code is acceptable.

As a practical poicy, if you want to use custom error types derived from Error, make it a habit to use 'new' in all cases.

23/11/2009 - Javascript Little Known Facts #4 - Constructors and Inheritance.

If you intend to do object-oriented programming in Javascript, you'll have to forget a lot of the stuff you learned in strongly typed languages like C++ or Java. This is not neccessarily bad - just a different way of doing things.

Let's start with the usual quick review of how to create your own object. If you want a singleton object, you can create it is follows:


var o = new Object();
o.opposite = 3;
o.adjacent = 4;
o.hypotenuse = function() { return Math.sqrt(this.opposite*this.opposite+this.adjacent*this.adjacent); }
o.toString = function() { return "[object RightTriangle]"; }
However, there is no particular benefit in doing this over simply using an object literal:

var o = {
   opposite: 3,
   adjacent: 4,
   hypotenuse: function() {return Math.sqrt(this.opposite*this.opposite+this.adjacent*this.adjacent); },
   toString: function() { return "[object RightTriangle]"; }
};
The latter is a little more terse and involves slightly less typing.

If you will need to create a number of similar objects, but with different initial values for their properties, then you should use a constructor function. You could use:


function RightTriangle(adjacent, opposite)
{
   var o = new Object();
   o.opposite = 3;
   o.adjacent = 4;
   ...
   return o;
}

var o = RightTriangle(3, 4);
But since Javascript already provides a corresponding facility, this would just be confusing to readers of your code. A constructor function for RightTriangle should take the form:

function RightTriangle(adjacent, opposite)
{
   this.adjacent = adjacent;
   this.opposite = opposite;
   this.hypotenuse =
           function() { return Math.sqrt(this.opposite*this.opposite+this.adjacent*this.adjacent); };
   this.toString: function() { return "[object RightTriangle]"; }
   // no return value
}

var o = new RightTriangle(3,4);
You can think of this as being like:

function RightTriangle(this, adjacent, opposite)
{
   ...
}

var o = new Object();
RightTriangle(o, adjacent, opposite);
By the way, the name of the constructor function is just documentation. It does not cause typeof(theObject) to be RightTriangle or anythying magic like that - "What's in a name? A rose by any other name would smell as sweet!" You could just as well use function __12345A() - and if you use an obfuscator, you probably will.

If you feel the need to have several constructors, like you might in C++, or Java, forget it. Defining:


function RightTriangle(adjacent) { ... }
function RightTriangle(adjacent, opposite) { ... }
will just leave you with the single later version of the function (functions at global scope are properties of a hidden Global Object, so the second definition merely overrides the first one.) To get the same effect, use the arguments array that's available within the constructor function:

function RightTriangle(adjacent, opposite)
{
   // set some default values
   this.adjacent = 1;
   this.opposite = 1;
   this.hypotenuse =
         function() { return Math.sqrt(this.opposite*this.opposite+this.adjacent*this.adjacent); };
   this.toString: function() { return "[object RightTriangle]"; }

   switch (arguments.length)
   {
      case 2:
         this.opposite = arguments[1];
         // fall through
      case 1:
         this.adjacent = arguments[0];
   }
}
Then you can do:

oa[0] = new RightTriangle();
oa[1] = new RightTriangle(3);
oa[2] = new RightTriangle(3, 4);
OK, so that should be enough for you to create all kinds of unrelated objects. But what if you want to specialize objects by inheritance? The classic example is some sort of shape drawing system like you might want to use with the <CANVAS> tag.

Let's say we have a Shape object that already has some very useful properties, like the ability to translate, scale, and rotate coordinate sets:


function Shape()
{
   this.position = [0, 0];
   this.points = 1;
   this.coordinates = [];
   this.translate = function() { // I'll leave the difficult stuff };
   this.scale = function() { ... };
   this.rotate = function() { ... };
   this.render = function() {};		// Rendering the base class has no effect
   this.hidden = false;
   this.zOrder = 0;
}
Now I want to derive a slew of other shapes, like Polygon, EquiPolygon, and so on. The sure and simple way to do this is:

function Polygon(position, vertices)
{
   this.position = position;
   this.coordinates = vertices;
   this.render = function() { // More difficult stuff };
}
Polygon.prototype = new Shape();

function EquiPolygon(position, sides, side)
{
   this.position = position;
   this.sides = sides;
   this.side = side;

   function CalculateCoordinates() { // populate this.coordinates }
   // We don't need a different render() method as we will inherit that from Polygon
}
EquiPolygon.prototype = new Polygon();
We modify the prototype property of the constructor function to reflect the type that we want to inherit from. Note, again, the relevant prototype property is that of the constructor function. This is fine, but if you want a more on-the-fly approach for some reason, you could just define the constructor functions and then try this:

if (typeof Object.deriveFrom !== 'function')
{		// We or someone else haven't already done this
    Object.deriveFrom = function (parent, ctor, args)
    {
        var o = new parent();
        var a = Array.prototype.slice.call(arguments, 2);
        function $() { ctor.apply(this, a); }
        $.prototype = o;
        return new $();
    };
}

var polygon = new Polygon();
var equiPolygon = Object.deriveFrom(Polygon, EquiPolygon, 6, 50);
18/11/2009 - Minimally Intrusive Javascript.

Tidying up TFC got me going, and I'll probably apply this to it soon.

OK, so as far as understanding the language is concerned, you're a guru. You've written this cute piece of script that implements the ultimate mousetrap. Naturally, you're keen that others should use it.

There are a number of things that can piss people off about your mousetrap:

  1. It's not very good at catching mice,
  2. If you install it as per the instructions, it doesn't work,
  3. It is difficult to install.
You'll never fix all of these for everyone. Number one is a killer - back to the drawing board - you may think it's wonderful, but sadly, the customer is always right. The other two are largely down to you.

One of the principal reasons why number two might crop up is because you have used variable or object names in your code that are already in use where the mousetrap is to be installed. Maybe you called your mousetrap object 'Mousetrap'. Your user already had a pretty good mousetrap on her page, and she's not ready to totally abandon that yet, and it is called 'Mousetrap' too. Alternatively you may have used gobbledygook names to avoid conflicts, and failed to spell them consistently.

OK, so that's simplistic - nobody would be fool enough to do that! But maybe in the code that builds your mousetrap object there are variable names that are already in use in script on the user's page?

Your mousetrap code won't be popular if it involves downloading an enormous script either - from all of these points of view it needs, as well as catching mice well, to be minimally intrusive.

OK, so let's take these points in order. First, how do you give your implementing object a unique name? Well, the URL of your (you, the author's) web site stands a good chance of being unique, so you could try:

var mydomain.com/mousetrap/V1.0 = new mydomain.com/mousetrap/V1.0("cheese");
But of course, that's not going to work. Neither is:
document["mydomain.com/mousetrap/V1.0"] = new mydomain.com/mousetrap/V1.0("cheese");
However, it's a step in the right direction. All we need to do now is completely hide the details of the creation of the object from the host page. This can also take care of the 'accidentally used variables' problem, though some discipline is required to achieve that.

Consider the following:


if (document.getElementById("mydomain.com/mousetrap/V1.0:trigger"))
{
   (function()
   {
      document["mydomain.com/mousetrap/V1.0"] =
         { bait: "cheese", action: function() { alert("sucker for "+this.bait+", snap!"); } };
   })();
}
Here we execute an ephemeral nameless function that creates our mousetrap object, which itself is also initially anonymous. We execute the function only if the page contains a tag with an appropriate ID indicating that we are actually using the mousetrap.

If variables and functions are required to support creation of the mousetrap object, we can define them within the ephemeral function, taking care to define them using 'var', as in:


var bait = "whatever"
var springStrength = function() { ... };
The 'var' ensures that these are variables local to the ephemeral function, so they won't pollute the user's namespace.

The snag here of course is that we have hard coded the bait - it's always cheese. But we don't need to make the user write any Javascript to deal with that limitation. Instead we can just use a familier construct, a hidden input tag, something like this:

<input type="hidden" id="mydomain.com/mousetrap/V1.0:params"
    value='bait: "cheese"'>
Note that this input tag does not need to be within a form tag - we will address it only by its ID. We can then pick up the initialization parameter(s) and fill in any placeholder variables in our mousetrap object:

if (document.getElementById("mydomain.com/mousetrap/V1.0:trigger"))
{
   (function()
   {
      var mousetrap = { bait: "", action: function() { alert("sucker for "+this.bait+", snap!"); } };
      var params = eval("({"+document.getElementById("mydomain.com/mousetrap/V1.0:params").value+"})");
      mousetrap.bait = params.bait;
      document["mydomain.com/mousetrap/V1.0"] = mousetrap;
   })();
}
A page using our mousetrap with the script inline now looks like:

<HTML>
 <HEAD>
  <TITLE>The better mousetrap</TITLE>
 </HEAD>

 <BODY>
 <input type="hidden" id="mydomain.com/mousetrap/V1.0:params"
    value='bait: "cheese"'>
 <button type="button" id="mydomain.com/mousetrap/V1.0:trigger"
    onclick='document["mydomain.com/mousetrap/V1.0"].action()'>
 Here mousie
 </button>

 </BODY>
<script>
if (document.getElementById("mydomain.com/mousetrap/V1.0:trigger"))
{
   (function()
   {
      var mousetrap = { bait: "", action: function() { alert("sucker for "+this.bait+", snap!"); } };
      var params = eval("({"+document.getElementById("mydomain.com/mousetrap/V1.0:params").value+"})");
      mousetrap.bait = params.bait;
      document["mydomain.com/mousetrap/V1.0"] = mousetrap;
   })();
}
</script>
</HTML>
Of course the script would likely be loaded dynamically so in practise this would be:

<HTML>
 <HEAD>
  <TITLE>The better mousetrap</TITLE>
 </HEAD>

 <BODY>
 <input type="hidden" id="mydomain.com/mousetrap/V1.0:params"
    value='bait: "cheese"'>
 <button type="button" id="mydomain.com/mousetrap/V1.0:trigger"
    onclick='document["mydomain.com/mousetrap/V1.0"].action()'>
 Here mousie
 </button>

 </BODY>
<script src="http:somedomain.com/script/mousetrap-1.0.js"></script>
</HTML>
Note that we stick the script block after the </body> end tag so that the HTML tags we depend on are defined when the script runs. Notice also that doing it this way we have not required the user to write any Javascript, just a couple of HTML tags whose purpose should be fairly clear to your web page designer, and the script include.
18/11/2009 - BEV Tiny Feedback Component - Simplified Installation.

In the course of investigating some of the more advanced Javascript techniques I decided I could do better with respect to the effort required by a user to install TFC in a web page. It's not a radical change, but I think it's worth having - read about it.

16/11/2009 - Javascript Little Known Facts #3 - Labels.

My gut attitude to this topic is that since Javascript does not have a goto statement, why would it need labels? But that's just me - there are several reasons. A good one relates to the use of nested loops. For example:


xxx: while (a)
{
   while (b)
   {
      if (whatever) break xxx;
   }
}
The break to a label here, gets you out of the outer loop. it means you don't need to declare and check some boolean variable in the outer loop, programming that always looked like shit in C to me. I like this label idiom - it gets you the direct action of goto without the dangers. You can do the same sort of thing with continue - in that case the code just continues with the next item in the outer loop.

Surprisingly, you don't even have to be in a loop to use this trick. Consider those cases where you need to test quite a number of conditions before you go on to do something. You could use if statements, have your code disappear off the right side of the screen:


var ok = false;
if (condition1)
{
   if (condition2)
   {
      if (condition3)
      {
         // ok - do what we want to do
         ok = true;
      }
   }
}
What I don't like about this is that the main thread of your logic resides in the middle of all these if blocks. It seems more logical to do a sequence of tests, then if all was well perform the required operation. For this, Javascript allows:

var ok = false;
nogo: {
   if (!condition1) break nogo;
   if (!condition2) break nogo;
   if (!condition3) break nogo;
   // do what we want to do
   ...
   ok = true;
}
If you try with continue here you will hopefully find that the compiler tells you that's only allowed in a loop. In other languages I have used do .. while, which gets pretty close, as in:

var ok = false
do {
   if (!condition1) break;
   if (!condition2) break;
   if (!condition3) break;
   // do what we want to do
   ...
   ok = true;
   break;
} while (true);
But the label is more elegant - and it's so easy to forget that last break. Another place that labels crop up (Maybe - are these labels, or a completely different use of the colon?) is in object literals, like:

go = {
   a: 12,
   b: 22.4,
   c: function() { return this.a*this.b; }
}

var t = go.c();
If these were truly labels then I would expect, by analogy, to be able to write:

a: 12;
b: 22.4;
c: function()  { return .a*.b; }

var t = .c();
But no, it doesn't work, then I guess it would be a different language.
13/11/2009 - Javascript Little Known Facts #2 - Nested Functions and Closures.

Since it has been pissing it down again, and outside is a sea of mud, I'm back to this. My next topic relates to nested functions.

It's perfectly OK in Javascript, and many other languages, to define functions within functions, so:


function mul2(n)
{
   var m = 2;

   function x2()
   {
      return n*m;
   }

   return x2();
}
although pointless, is completely legal. The other salient point is that the inner function has access to the local variables of the outer function, including the arguments that were passed to it.

So, what might you use nested functions for? Well, I am sure there are as many answers as there are programmers, but one situation where I've used them is in parsing things, particularly when there are a number of state variables associated with the process. You can store the state variables in the body of the outer function, then write nested functions for working on little bits of the parse without having to pass them a load of state variables as parameters. This approach also avoids littering the module scope with functions that aren't really of any value outside the context of a particular operation. For example, in trivial date parsing code you could write:


function parseDate(s)
{
   var sml = [ 0,0,0,1,0,1,0,0,1,0,1,0 ]
   var y, m, d;
   var a = s.split("/");
   y = parseInt(a[2]); m = parseInt(a[0]); d = parseInt(a[1]);

   function isLeap()
   {
      return (y%400 == 0) || (y%100 != 0 && y%4 == 0); // or whatever it is
   }

   function checkDay()
   {
      if (d < 1) return false;
      if (m == 2)
         return d <= (isLeap()? 29: 28);
      else
         return d <= 31-sml[m-1];
   }
   if (m < 1 || m > 12) return false;
   return checkDay();
}
Which I think is significantly better than something like:

function isLeap(y)
{
   return (y%400 == 0) || (y%100 != 0 && y%4 == 0); // or whatever it is
}

function checkDay(d, y, m)
{
   var sml = [ 0,0,0,1,0,1,0,0,1,0,1,0 ]
   if (d < 1) return false;
   if (m == 2)
	  return d <= (isLeap(y)? 29: 28);
   else
	  return d <= 31-sml[m-1];
}

function parseDate(s)
{
   var y, m, d;
   var a = s.split("/");
   y = parseInt(a[2]); m = parseInt(a[0]); d = parseInt(a[1]);

   if (m < 1 || m > 12) return false;
   return checkDay(d, y, m);
}
OK, so we have nested functions. Now a function can of course return any valid Javascript type, and that includes a function, or for that matter, an array of functions. So what happens when we do this?

function provider(a, b)
{
   function inner()
   {
      return a*b;
   }

   return inner;
}
Well nothing drastic. We can assign the return value of the function to a variable, and then we have a function of some sort. What sort? Well, it's called a Closure - this is in the sense that we have sealed up the original function call, frozen it, or closed it. A closure has state, so although we call the returned function with no arguments, the closure has a basis for returning some meaningful value.

var closureFunction = provider(2,3);
WScript.echo(closureFunction());
So when do you use closures, well that's a matter of programmer ingenuity. But once again, if you need to set up a load of state variables, and then use them to implement some complex algoritm on different inputs, then nested functions in the form of closures are useful. Then you'd have something like:

function setupTransform(a)
{
   var factor = a;
   var offset = 3*a;

   function transform(x)
   {
      return x*factor+offset;
   }
   return transform;
}

var a = new Array(.....);
var transform = setupTransform(2, 3);
for (var i = 0 i < a.length; i++)
   a[i] = transform(a[i])
Actually, you don't need even to give the nested function a name in cases like this - it's never called within the provider function. You can just have:

function setupTransform(a)
{
   var factor = a;
   var offset = 3*a;

   return function(x) { return x*factor+offset; };
}
12/11/2009 - Javascript Little Known Facts #1 - Array Slicing and Function Call.

Having had some exposure to the D programming language, and more recently looked at Python, I have been looking at the darker corners of Javascript to see what facilities it has that I have previously overlooked. The examples here are written to be run the in the command-line version of the Windows Scripting Host which I believe comes automatically with various versions of IE. Just open a command prompt, and invoke your Javascript file with:


cscript javascriptfile.js
D and Python have the concept of array slicing, with a nifty notation like a[1:3]. This expression returns a new array consisting of a[1] and a[2]. In Javascript you can get the same effect using a.slice(1,3).

Since slice is a function associated with the Array object, which we can access as a distinct entity via Array.prototype, and since functions are objects, that have methods of their own, there is an equivalent expression 'Array.prototype.slice.call(a, 1, 3)'. Try this:


var a = [ 1,2,3,4,5 ];

var b = Array.prototype.slice.call(a, 1, 3);
WScript.echo(b); // result should be 2,3
The first argument to call is an object to provide the 'this' context to the function's operation. In this case, it's an array, which is what slice expects to work with. Now that in itself seems pretty pointless, but it is interesting to find that it works with another entity that is not really an array, but behaves like one in the appropriate context. Consider:

var slice = Array.prototype.slice;

function thingie(a, b, var_args)
{
   var a = slice.call(arguments, 2, 4);
   WScript.echo(a);
}

thingie(1,2,3,4,5); // result should be 3,4
The magic variable 'arguments' within a function behaves like an array of the arguments supplied when the function was called, and slice works perfectly well with that. Note that there is nothing special about the variable name var_args - it's just a self documentation hint that our thingie() function might expect to get two arguments for sure, and then an indefinite number of further arguments.

Since the arguments can be anything you like, you can do interesting things like:


function buildCall(func, obj, var_args)	// execute func with obj as this and arguments from var_args
{
   var a = slice.call(arguments, 2, 4);
   func.apply(obj, a);
}
The apply method of function objects is similar to the call method except that it expects the arguments in an array. A contrived example of how this contrived function might be used is:

var slice = Array.prototype.slice;

function myobj(x, y)
{
   this.x = x;
   this.y = y;

   this.foo = function()
   {
      var s = "";
      for (var i = 0; i < arguments.length; i++)
      {
         s += (arguments[i]*this.x+this.y) + " ";
      }
      return s;
   }
}

function another(x, y)
{
   this.x = x;
   this.y = y;
}

function buildCall(func, obj, var_args) // execute func with obj as this and the arguments from var_args
{
   var a = slice.call(arguments, 2);
   return func.apply(obj, a);
}

var mo = new myobj(1, 2);
var func = mo.foo;
var other = new another(5, 6);
var rv = buildCall(func, other, 2, 3, 5);
WScript.echo(rv); // should be "16 21 31"
I leave it to you to come up with a real application for this stuff. If you read the Javascript source for ExplorerCanvas (below), you'll see this sort of thing in action.
11/11/2009 - Tiny Feedback Component Documentation.

OK I have done something on this now it is here.

It would be a miracle if the installation instructions were right first time, so I'd really appreciate it if someone with access to a server with PHP and MySQL could try it out and let me know what I've got wrong.

10/11/2009 - VML Version.

Maybe I could restructure my Dragon Curve code to suit VML, but my impression is that the way it works is just bound to be inefficient if you need to generate some complex figure. The CANVAS tag allows me to use the (x, y) points that I generate from the sequence of left or right turns (a long string of ones and zeroes that can be generated efficiently) to directly generate the individual strokes. In VML, I have to append the (x, y) to yet another long string, and then the browser has to decompose that string to generate the individual strokes

Then, to further compound the misery, VML used directly does not do much better than ExplorerCanvas. It may be a little faster, but it's still slow, and it still does not make it past a 12th order Dragon Curve. I also hate the obscure VML syntax. If you're interested, the VML page is as follows:


<html>
<head>
<style>
	v\:* { behavior: url(#VMLRender); position:absolute }
</style>
<xml:namespace ns="urn:schemas-microsoft-com:vml" prefix="v"/>
<object id="VMLRender" codebase="vgx.dll" classid="CLSID:10072CEC-8CC1-11D1-986E-00A0C955B42E">
</object>
<script>
function flip(s)
{
   if (s == "1")
      return "0";
   var t = (s.length-1)/2;
   var c = s.charAt(t);
   c = (c == "0")? "1": "0";
   return s.substr(0, t)+c+s.substr(t+1);
}

function draw(order, step, startx, starty)
{
   var seq = "1";
   var direction = 1;
   var x = startx;   // trial and error here
   var y = starty;
   var left = [ 3, 0, 1, 2];
   var right = [ 1, 2, 3, 0 ];
   var i = 0;

   for (; i < order; i++)
      seq = seq+"1"+flip(seq);;

   var path = "m "+x+","+y+" l ";

   for (i = 0; i < seq.length; i++)
   {
      direction = (seq.charAt(i) == "1")? left[direction]: right[direction];
      if (direction & 1)
         x += (direction-1)? -step: step;
      else
         y += direction? step: -step;
      path +=  x+","+y+" ";
   }
   path += "e";
   var vmlpath = document.getElementById("dpath");
   vmlpath.v = path;
}
</script>
</head>
<body onload="draw(12, 4, 350, 180)">
   <v:shape style='width:100;height:100' strokecolor="black"
                           strokeweight="1px" coordsize="200 200">
   <v:path id="dpath" v=""/>
   </v:shape>
</body>
</html>
The other point which I wondered about, and I haven't pursued it to a conclusion, is how does the <CANVAS> tag manage to work with IE. The answer is there to be found in excanvas.js, but I was more interested in how browsers handle unknown tags, and what you can do with them. What happens if I have a tag <glob></glob>, and I try to access it in script? Here's a test page:

<html>
<head>
<style>
.crappy { }
</style>
<script>
function doIt()
{
   var glob = document.getElementById("theglob");
   glob.innerHTML = "The quick brown fox";
   var x = glob.title;
   glob.title = "glob";
   alert(x);
   alert(glob.style.fontFamily);
}
</script>
</head>

<body onload="doIt()">
   <glob class="crappy" style='font-family:"whatever you like \"you\" x=12; y=23;"'
                                      id="theglob" title="one two three"></glob>
</body>
</html>
Interestingly, you can retrieve a reference to the <glob> tag in the script, and you can reference three of the four attributes that all tags are supposed to have - id, class, style, and title. In Firefox, only class did not appear to work. In IE6, nothing worked. I have still not managed to download a later version of IE.

If you wanted to custom things with a tag, that gives you two spots where it seems you can pass an arbitrary string, a) as a font-family value in the style attribute, or as title. If you pick up the content of title in onLoad(), you can then give it some innocuous value to show the user when she mouses over the thing.

10/11/2009 - Things I Didn't Know.

I once wrote a trivial Windows program to draw the 'Dragon Curve'. The source code got lost along the way, and I could not remember exactly how I had done it. This was annoying me, so I attempted to retrace my steps, and I think I got, more or less, to the same algorithm. When it came to drawing it though, I didn't fancy creating yet another Windows executable, but wanted to draw it on a web page.

At that point I discovered something I did not know - that HTML5 has a '<canvas>' tag that is very straightforward to use. The snag is that it isn't supported by IE - Microsoft have their own invention VML. This is mildly annoying, and has obviously annoyed others, since there is a piece of Javascript called ExplorerCanvas, that aims to make it simple to use the canvas tag in pages destined for IE.

All you need is a line in your file like:

<!--[if IE]><script type="text/javascript" src="./excanvas.js"></script><![endif]-->
What? I hear you cry - what's with the [if IE] bit? Well that's something else I didn't know. Microsoft - way back in IE5 - invented the 'conditional comment'. You'll see that the above is a valid comment for most browsers, but in IE it can be used to isolate sections of your page that correspond to IE's non-standard ways of doing things. Microsoft must have been prescient - having the non-standard browser support this non-standard behaviour is ideal ;=)

So anyway you include the funny line, but otherwise your page can be just as it would be for Firefox el al. Here's the Dragon Curve:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Dragon Curve </TITLE>
<!--[if IE]><script type="text/javascript" src="excanvas.js"></script><![endif]-->
<script>
function flip(s)
{
   if (s == "1")
      return "0";
   var t = (s.length-1)/2;
   var c = s.charAt(t);
   c = (c == "0")? "1": "0";
   return s.substr(0, t)+c+s.substr(t+1);
}

function draw(order, step, startx, starty)
{
   var seq = "1";
   var direction = 1;
   var x = startx;   // trial and error here
   var y = starty;
   var left = [ 3, 0, 1, 2];
   var right = [ 1, 2, 3, 0 ];
   var i = 0;

   for (; i < order; i++)
      seq = seq+"1"+flip(seq);;

   var canvas = document.getElementById('canvas');
   var ctx = canvas.getContext('2d');
   ctx.beginPath();
   ctx.moveTo(x, y);

   for (i = 0; i < seq.length; i++)
   {
      direction = (seq.charAt(i) == "1")? left[direction]: right[direction];
      if (direction & 1)
         x += (direction-1)? -step: step;
      else
         y += direction? step: -step;
      ctx.lineTo(x, y);
   }
   ctx.stroke();
}
</script>
</HEAD>

<BODY onload="draw(13, 3, 280, 200)">
  <canvas style="border:1px solid black" id="canvas" width="800" height="800"></canvas>
</BODY>
</HTML>
The only snag with this appproach is that if you draw a Dragon Curve of greater that order 12, IE6 crashes - I can't speak for later versions. Also it's a bit slow compared to the genuine canvas tag.

Here's what it does - order 12, so it should work in IE:

Since the actual graphics coding is trivial - moveTo(), lineTo() ... I may use the [if IE] trick to draw the curve directly using VML and see how that works with a higher order. But anyway, I learned some new things.

2/11/2009 - BEV Tiny Feedback Component.

I have now got this into a state where it works OK with FireFox 3 and IE 6. I'm about to update to IE 8, and I'll tell you about that in due course. The example of its use can be seen here.

I have changed the client side Javascript so that it now implements an object. Adding the component to a web page is now very straightforward.

You need to pull in the Javascript for the object, and then create an instance of the BEV_tfc object:


<script src="http://www.britseyeview.com/script/BEV_tfc.js"></script>
<script>
__tfc = new BEV_tfc("http://www.britseyeview.com",
           "Leave a comment on this month's BEV page",
           "/php/savecomment.php", "/php/listcomments.php", "/php/gettopics.php", true);
</script>
Then in the actual HTML, you need to define a DIV that locates the component, and add an onload handler in the body tag:

<body onload="__tfc.emitHTML()">
<div id="tfc:outerdiv">
</div>
TFC assumes that your reader will invoke the feedback component if she wants to use it, so you also need some link or button in your code that will make it visible:

<a href="javascript:__tfc.toggleCommentDiv()"
              >Show the BEV Tiny Feedback Component - TFC</a>
Another script include initialises some Javascript variables that give you information about the location of the user. And of course, there are also some PHP files, and a database table. I'll write some documentation and post that shortly.
31/10/2009 - Reloading an IFRAME.

There seem to be as many opinions on this as there are articles, and I found it a difficult thing to get working reliably even on just two browsers.

Here are the salient points, I'll give more details below:
  • Use whatever overkill you can think of to prevent the browser or some proxy from caching the frame's current content,
  • Get a reference to the IFRAME object in the most obvious way - document.getElementById("iframeid");
  • Forget about the reload() methods - just reassign the source to myiframe.src,
  • Make sure that the new content has not also been frozen by cacheing by the browser or a proxy.
My problem was with the simple PHP feedback system. In my PHP script, I pull the feedback records from a MySQL database, and use them to generate a table to be populated into an IFRAME. When the user adds a feedback item, the IFRAME should be refreshed by a newly generated table.

In the version that eventually worked (with IE 6 and Firefox 3) the PHP generated headers:


header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Expires: Sat, 03 Oct 2009 09:31:00 GMT"); // i.e. in the past
It also emitted META tags in the HTML:

echo "<META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\">";
echo "<META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\">";
Like I said - overkill!

To do the actual refresh, I found that the best way was to ignore the reload() functions mentioned in many articles, and instead to use a Javascript sequence in the client code like:


var textframe = document.getElementById("my_iframe");
var t = textframe.src;
textframe.src = 0;	// Yes, it's weird, but I swear if you leave it out, it doesn't work!
textframe.src = t;
My last salient point, as above, was illustrated because I was being lazy, and calling the PHP code that had just put the new feedback into the database by simply loading it's empty response into a hidden image:

var dummyimage = document.getElementById("dummyimage");
dummyimage.src = "/php/savecomment.php";
Of course, on many occasions, the browser was cacheing this response too, so the PHP code never got called, and the database had not been updated. At the user end, this is indistinguishable from a failure to reload the IFRAME - drrrr! I bit the bullet and used AJAX.
31/10/2009 - What Future for the D Programming Language.

I was looking at Tiobe yesterday, where I noticed that D has taken something of a dive since I last looked. This prompted me to take a look at the D Forum for the first time in a while. It seems to be stuck in an "oomigooly" manouver - flying round and round in ever decreasing circles...

I was really keen on D for some time, as witnessed by my work on Dcat, but if the bickering about language features goes on indefinitely I can't see how it is going to get anywhere. This, and the fact that at times I have to spend time developing our compound in Arusha, is what put Dcat into a frozen state.

30/10/2009 - Roughly Screening a CSS Style.

In one of the things I was doing, I was soliciting input of a CSS style to be wrapped around site hit information, and wanted to check that it bore some resemblance to CSS. The best I could do for a regular expression was:

/(^[^:;]+:[^:;]+;$)|(^[^:;]+:[^:;]+$)|(^[^:;]+:[^:;]+;)(\s[^:;]+:[^:;]+;)*(([^:;]+:[^:;]+;$)|([^:;]*:[^:;]+$))/;
Actually looking at this now, it's wrong. The first [^:;] chunk for each style element should probably be [^:;\s]. Then this should tell you at least that the user has entered something with the appropriate number of colons and semicolons. Has anyone got an open-source better suggestion?
If you can see this, you probably have JavaScript disabled, and BEV 3 will not work as designed."

Squash This List

What is BEV?

Brits Eye View is an Englishman's personal blog, started in January 2003. It's currently about life in Arusha (Tanzania), and previously in Bangalore, Manhattan, and the Bronx. It deals with life in general, building a house, food and drink, computer programming, opinion on current affairs, 20th century history, and so on. It may give you some insight into what life is like in 'the third world', or encourage you to visit Tanzania.

There is also a retrospective view of the latter half of the 20th century, currently spanning 1942 - 1975 so far.

My wife and I run a small but very pleasant guest house in Arusha - Adia's Place - check it out!

To list the posts available on this blog, click the next list item to expand it.

Software Blog Postings List.

These are posts from late October 2009 to December 2010. Some have substance, and some not. I have not edited them for inclusion in this revised version of the page - WYSIWYG.

Why a Software Page?

Well, I was involved with computer programming from the late 60s onward, spanning early FORTRAN to D.

I retired in 2007, but somehow I can't get out of the habit, and still get occasional flashes of "I wonder what would happen if?", or "How do they do that?", or libraries that don't work and I have to fix for myself.

GDC Newbie Summary.

I spent some time earlier this year (2010) attempting to create a version of the GDC compiler for the D programming language, based on GCC - the Gnu Compiler Connection. I was new to GCC and existing versions of GDC at the time, so I started to keep a record of the things I discovered. The results are here.

I was successful to a degree, but as with many other things I've done, there was a resounding lack of interest, so I did not feel it was worth continuing. The work I did was subsequently used by one of the Ubuntu contributors - Iain Buclaw - to make a GCC 4.4 based compiler for D version 1.

DCat Summary.

For a long time I had this idea of writing a web application server in a compiled language that would be in the same general class to its language as TomCat is to Java. It's additional feature was that a web application, or set of applications would have the inter-page logic defined entirely in XML.

I tried it years ago in C++, using FastCGI, and got quite a long way, but nobody was interested. Then when I got into the D programming language, I thought I would have another go, this time with a D implementation of the AJP13 protocol between the web server and the application engine.

I got quite a long way with that too, but was stymied by the lack of capability of D to produce and dynamically load DLLs or shared libraries, or to dynamically load object files.

DCat has a set of associated D utility classes for things like logging, Windows event logging, property files, parsing XML, creating a Windows service, and so on.

You can read more about it here, see its (now somewhat outdated) changelog, or download a zip file for the Windows version.

Hits'n Stats Summary.

I used to use a third party hit counting service on the BEV pages, but it did not really do what I wanted. So I rolled my own

Hits'n Stats has less focus on hit counting, and more on discovering who your readers are, and presenting that information in a simple and convenient form.

It's written for the classic PHP/MySQL combination, so it's easy to install on most shared hosting systems.

You can read more about it here. Using the pages referenced here, you can sign yourself up to try out the system on your own site. If you want to use it, get in touch, I have not put together a distribution of it yet.

TFC-Tiny Feedback Component.

I tried a variety of ways of collecting feedback from users: A bulletin board, and a news-reader approach, but they got hacked, or the newsgroup magically disappeared or something. So once again I did my own thing.

You can click on the 'Comment' link in the toolbar to see what it does.

It's written for the classic PHP/MySQL combination, so it's easy to install on most shared hosting systems.

You can read more about it here, and download a zip file.

You can get the general idea from these, but if you want the latest stuff that works with jQuery, and has some other changes, please email me. I will do a revised document when I have reimplemented it as a jQuery plug-in.

MySqlD.

This is the DDocs generated documentation for a set of classes in the D programming language that constitute a wrapper around the MySql C library.

You can get the source code and the other bits you need to build and set up MySqlD here.

Publicity Summary.

At the beginning of the 90s, the only Windows application that specialized in printing labels, business cards and such, was one called Avery Labelpro. I did not think that it was particularly good, so I tried to do better

A lot of people thought I succeeded, but I failed to sell enough copies to stay in business with it - didn't have the financing for advertising etc. So eventually it became freeware. It is definitely legacy software, and I don't support it any more, but is still quite good at what it does. You can read more about it here, view its user documentation, or download a setup executable.