Election fun

March 17th, 2010

Heavens, we’re in a lot of debt

March 8th, 2010

Or are we?

I read this article today, arguing that the constant headlines of “largest ever deficit” in the UK are alarmist and that it’s pretty abysmal that both main political parties aim to cut public spending in order to cut the national debt, when there are strong arguments to not do so. There’s a recession on, you know!

Which got me thinking about whether the national debt really is all that big. Of course it’s a big round figure (I’d type it out but am scared my ‘0′ key will break through overuse) but equally our earnings, and therefore the government’s tax revenues, are much greater than most periods in history too. What really matters is the ratio of debt to how much money is in the country, surely. So I found this graph:

UK national debt vs GPD graph

Another graph on the same page demonstrates that current national debt is at around 60% of GDP, which I don’t think is too bad given that the ongoing global economic crisis is considered to be at around the same order of magnitude as the 1930s great depression, and back then national debt hovered between 150 – 200%. I know we live in a very different, more competitive world, but I doubt it’s anywhere near as catastrophic as the papers and the politicians would have us believe.

And another thing, I grew up in a northern town with mines, steelworks and baths that don’t take half an hour to pronounce, so naturally I hated Thatcher. But then the rhetoric of the past 10 years – that she may have been harsh, but by God she prepared us for the harsh, competitive world to come – has, if not softened, at least confused that view a little. But I recently came to the realisation that she was one of the chief instigators of this new harsh world. Claiming she’s alright because she prepared us for it is like saying the guy who pushed you in front of the train is alright really because he gave you a mattress to hide behind.

It’s not what you say, it’s which font you say it in

March 3rd, 2010

I’m redesigning this site at the moment and one thing I wanted to pay closer attention to this time around was choice of fonts. Notwithstanding the fact that web browsers were, until recently, pretty shoddy at allowing you to use the fonts you wanted to, the main reason I hadn’t paid much attention to fonts in the past was that it’s so darn hard picking one, for a number of reasons:

  1. There’s so damn many of them
  2. There’s no relation between names and appearance (as opposed to, say, #f60283 being guessable as a garish pink, closer to red than to mauve)
  3. They’re difficult to preview and compare

So in the interests of productivity, quality and, dare I say it, working smarter, not harder, I’ve devoted some time to sorting out how I choose fonts, reduced to the following four steps:

  1. Organise your fonts in themed folders
  2. Find a good stand alone font previewer i.e. don’t rely on photoshop and windows’ poor tools
  3. Narrow down to a short list
  4. Use javascript to make quick comparisons easy

Read on if your curiosity is piqued.

1. Organising the fonts

Windows’s default font collection (and, I imagine, Apple’s too) and the collection of 2000 fonts I also use are organised alphabetically which is rubbish. Unless you have web design OCD you’re unlikely to want to narrow down your choice of font by it’s first-letter. But, on the other hand, it is difficult to categorise fonts; I’m yet to see a website do it effectively, and I’m not entirely happy with my choice. But in the end I plumped for the following: serif, sans-serif, script, stylised, symbol, stencil.

Stencil could easily fall within stylised, and stylised could easily be split into subfolders (Art Deco, Gothic, Celtic …), and I realised part way through that I should have a subfolder within symbol for fonts depicting alphabets other than Roman, but I think a minimal folder system would be serif, sans-serif and other. In the serif and sans-serif folders I included only sensible fonts you could print a book not aimed at children in, which I think is a useful distinction to make; often the hardest task when picking fonts is to find the one which is subtly different to other ordinary fonts, but somehow suits the design better than almost indistinguishable alternatives. Cutting out all the fancy fonts makes this task a lot easier.

So once you have all these folders put a copy of each font you have in one of them, and you’re ready for the next step. You don’t need to bother with installing them yet.

2. Previewing your fonts

My criteria for a good font-previewer are:

  1. Choice of text to use for the preview
  2. Choice of text-size and colour
  3. Ability to organise fonts how you want them organised
  4. Speed and ease of switching between one font and another
  5. Ease of installing a font

Windows’ control panel fails to meet conditions 1 and 2, and Photoshop’s built-in font selector fails to meet 3 and 4, and they both force you to install a font before using it. The best free solution I’ve come across for Windows which meets all 5 conditions is Fast Font Preview.

3. Short-listing

Once you’ve got Fast Font Preview installed you can start picking your shortlist. Simply browse to your organised font folders, click on settings to type in your sample text, adjust the font-size to what you want, and double click on any contenders. Once the font is opened you can install with one click. While the font is open you’ll also want to jot down its official font name.

4. Use javascript to make comparisons

This is where I stop being pedantic and hopefully can be of some use. Insert the following script into the head of your web-page-in-need-of-a-font, substitute your list of font names and the id/tag name of the elements to be affected and, hey presto, a handy font-switcher should appear, making choosing exactly the right font much easier. If your web page already uses javascript then add the body of the function to your existing onload event. (NOTE: It tends to work better in Google Chrome than other browsers as Google Chrome seems to be a bit more forgiving when it comes to font names).

window.onload = function() {
 var body = document.getElementsByTagName('body')[0];
 var id = '';
 var tagName = '';
 var fonts = 'Comma,separated,list,of font,names';
 fonts = fonts.split(',');
 var elements = (id)      ? [document.getElementById(id)] :
                (tagName) ? document.getElementsByTagName(tagName):
                            [body];
 var switcher = document.createElement('DIV');
 switcher.setAttribute('style','position:absolute;top:0;right:0;background:white;z-index:200;padding:10px;');
 for(var i=0, il = fonts.length;i<il;i++){
   createButton(i);
 }
 body.appendChild(switcher);
 var buttons = switcher.childNodes
 loadFont(0);

 function createButton(pos) {
   var button = document.createElement('a');
   button.innerHTML = fonts[pos];
   button.setAttribute('style','display:block;padding:2px;');
   button.setAttribute('href','#');
   button.onclick = function() {loadFont(pos);};
   switcher.appendChild(button);
 }

 function loadFont(pos) {
   for (var i=0,il=elements.length;i<il;i++)
   {
     elements[i].style.fontFamily = fonts[pos];
   }
   for (var j=0,jl=buttons.length;j<jl;j++) {
     buttons[j].style.backgroundColor='';
   }
   buttons[pos].style.backgroundColor='yellow';
   return false;
 };
};

Cooking with SQL

February 26th, 2010

SQL was the sight of my first forays into programming, back in the days when I managed records for an educational project and came to the heretic conclusion that MS Access was better suited to the task than Excel. But that’s more or less where my learning of SQL stopped, and even then it was limited to SELECT, WHERE and ORDER BY statements (I let Microsoft’s wizards do all the hard work of building multiple table queries).

Fast forward to yesterday and I decided to finally bite the bull by the horns. The back-end of my latest educational endeavour was, I guessed, suffering in speed due to the fact that I made no use of JOIN on my MySQL tables; each time I wanted to get records related to records in another table I would use nested loops in php to get the related records for each row.

In my defence, I largely chose this approach due to another 3 major flaws in  Zend Framework\’s documentation:

  1. It doesn’t explicitly mention that when you build a Zend_Db_Select query based on a Zend_Db_Table class (ie a Model) the FROM clause of the query is automatically filled in. Attempting to fill it in yourself causes an error.
  2. It doesn’t mention anywhere that in order to use JOIN within a Zend_Db_Select query based on a Zend_Db_Table class you need to use the ->setIntegrityCheck(false) method. Without this all manner of confusing errors occur.
  3. This wording: “You can not specify columns from a JOINed tabled to be returned in a row/rowset. Doing so will trigger a PHP error” , coupled with the fact I was getting lots of errors led me to believe that Zend had neglected to add JOIN functionality to its models, so I dropped that line of attack. (In fact, all that quote means is that you cannot change the default behaviour, which is to fetch all columns).

But now I have of course overcome all this, and have managed to eg reduce about 30 lines of code (get a teacher’s classes, then get these classes’ assignments, then get all the attempts at these assignments, and for each of these get the individual puzzle solutions submitted) to a single line using 3 RIGHT JOINs and one INNER JOIN. It’s much neater, and I can only guess at the vast improvements in speed it brings; my guess is “oodles”.

As well as improving my application, learning about Zend_Db_Select (the documentation to this is remarkably well written, considering the surroundings), via the __toString() method, has increased my understanding of the underlying SQL to the point where for the first time I can write non-trivial queries from scratch – eg updating a field based on a join with another table – , which is a great addition to my programming armoury.

Display:run-in – why would you?

February 22nd, 2010

A while (about 2 years) ago I was reading quirksmode’s page on support for CSS display properties in browsers when I came across a hitherto unknown type of display – display:run-in;

Something with display run-in, if followed by a block level element, becomes the first inline-block of the next block-level element.

So if you have the code

<div style="display:run-in;font-weight:bold;">My run-in box</div>
<div style="display:block">My block box</div>

it should display as follows (though doesn’t in firefox or ie yet):

My run-in box My block box

Quirksmode poses the question: ‘Why would you want to do this?’

Well, I can think of a very good reason: starting a paragraph with a heading, such as the following:

Conclusion: display:run-in can provide a more semantic way of representing a paragraph which has it’s heading as the start of its first line. At present I bet everyone just wraps the heading in <strong> tags, but that’s not really what <strong> is for.

Or also for a definition list

Second argument in favour of display:run-in: Using display run-in, imagine this is a <dt> followed by a <dd>. How would you get the <dt> to appear inline with the <dd> without display:run-in?

So given that display:run-in is useful it’s surprising that firefox are yet to implement it, especially given that ie8 has already done so.

How I’d teach myself programming, if I could do it all over again

February 17th, 2010

As I mentioned the other day, web development as a career is rare in that you can just pick it up off the internet unlike, say, luxury pet grooming. But it took me a while to find good strategies to learn what I wanted to learn. If I had a time machine I’d go back and tell myself the following*.

Don’t buy beginners guide programming books

I bought a couple of these on php/mysql and javascript. I won’t say they were a complete waste of money as I did learn the basics from them, but there are several good reasons not to rely on them for your starting point:

  1. These books are almost always a long-winded, incomplete version of the programming language’s documentation (which is normally available for free online) structured around building an example application which probably bears little resemblance to something you would like to build, e.g a quiz about the Simpsons
  2. Unlike online resources these books are not searchable with lots of easy to follow cross-references
  3. Online tutorials are more up to date

Find a good online tutorial

For any programming language there will be loads of beginner’s tutorials online; just search Google for “[language name] beginner’s tutorial”. the top results won’t however generally be the best, so open up lots of tutorials in lots of tabs, narrow it down to a few of the best and then bookmark them, before starting to follow one of them. If you get stuck on a section you can always try the explanatiosn given in your other bookmarked tutorials or search google for “[programming language] [topic] explained”. Below are some of my favourite tutorials:

Learn to use documentation

It took me a long time to realise that most programming language documentation follows  the same structure, and once you understand this you are able to teach yourself any language. Roughly, a programming language (at least, the ones I know) is a collection of types of thing (objects, strings, arrays, numbers etc…) and processes (loops, conditionals, functions) for manipulating things, and some things have built in sub-things (properties) and their own dedicated processes (methods), and most processes will only work on certain types of thing (arguments of the correct type).

Well written documentation will list all the above information systematically (together with the basic syntax and rules of the language), so that if you create a variable of a certain type you can find out what you are able to do to it, or if you want to use a function you can find out what conditions its arguments need to meet. An understanding of object oriented programming also goes a long way to being able to grasp documentation, but isn’t essential for a beginner.

Use libraries… lots of libraries

Not the ones with books. A library (sometimes called a framework) is a collection of software written by somebody else that takes care of some tedious/difficult processes for you. The classic example at the moment would have to be jQuery. Without jQuery the differences between browsers’ implementations of javascript would make developing javascript web applications a specialised and difficult task with unreliable results. Because jQuery is a collection of code that thinks about all the cross-browser differences for you (as well as doing lots of other useful tasks) creating reliable javascript applications is now something even beginners can take on. Some libraries also have thriving communities that build plug-ins to extend the functionality further.

And to make use of all this all you have to do is include a file (or collection of files) and get to grips with the library’s documentation (often called an API – Application Programming Interface) which, no matter how daunting it may seem at first, is guaranteed to be easier than writing all the code yourself.

Invest in some expert/advanced books

Beginner’s guides may have been made redundant by the internet, but there is still room for more advanced books. Yes, the information is probably on the internet somewhere but structured tutorials aimed at more advanced users are far less common than beginner’s tutorials. I won’t recommend any books myself as I don’t consider myself enough of an expert to judge, and I also don’t own many yet, but the ones I do have are full of techniques I couldn’t have worked out for myself.

And that’s how I should have done it!

*Like hell I would. Straight to the bookies it’d be.

Remove text nodes function

February 17th, 2010

Here’s a fairly useful function for when you’re using javascript in a web page without using  library like jQuery to take care of the nitty gritty.

It tackles problems that occur when you get the child nodes (eg myList.childNodes) of a DOM node, but there is whitespace in the html. Each of these whitespaces gets counted as a DOM node of its own, a text node, so if you run code to iterate through eg all the children of a <ul> you will find that your code throws an error as not every node is an <li> as you expected.

function removeTextNodes(nodeList) {
  list = Array.prototype.slice.apply(nodeList);
  for(var i=0, il=list.length;i<il;i++)
  {
    if(list[i].nodeType == 3)
    {
      list.splice(i,1);
      i--;
      il--;
    }
  }
  return list;
}

var myUL = document.getElementById('myUl');
var myLIs = removeTextNodes(myUL.childNodes);

I haven’t tested it in any browsers apart from firefox as I’m a bit busy, but if you find it’s buggy in Internet Explorer or elsewhere leave a comment.

(By the way, if you’re wondering about eth relevance of the image, if you search for “too many children” in flickr it throws up lots of photos of a very serious looking texas school board meeting. Too many children in Texas, apparently!).

Deletious

February 14th, 2010

Well, this has to be the quickest I’ve ever gone from idea to publishable (albeit limited functionality) website.

Deletious is my new site for simultaneously viewing a page bookmarked in Delicious and deciding whether to keep or delete the bookmark. I’ve had quite a lot of fun using it the last few days, rediscovering all sorts of articles, games, tools and other long forgotten sites. As well as wasting a lot of time reacquainting myself with all these I’ve also managed to de-clutter my Delicious account; all the CSS articles from 2-3 years ago giving an introduction to topics I now know inside out are gone from my bookmarks, as are all those gimmicky websites I can’t believe i found funny at one time.

Disappointingly, I’m having problems uploading the logo to the website’s folder, but it’ll be sorted sometime soon I hope.

So please do give it a go and let me know what you think.

North Downs animal tracking

February 14th, 2010

Just been for a walk in the slightly snow-drenched North Downs woods (which, confusingly, are south of London). Lots of wildlife not around:

Badger

Woodcock

Grey Squirrel (which I thought was a weasel till I got home and checked on internet)

Roe Deer

Rabbit

Pheasant

Fox

Picking the jewellery out of the trash

February 12th, 2010

One upshot of the Delicious garbage collection utility I’ve just built is it highlights gems I’d bookmarked years ago but forgotten. Some are useful, but most are rip-roaringly funny or entertaining. Here are two of the best… so far

  1. Copter – a simple, single mouse button game which kept me entertained through a very dull summer at work once. I’m yet to regain my previous form, but it’s so addictive I believe I will. (*edit: top score now at 1026)
  2. A cartoon to illustrate what happens when too many summers build up, one of the milder frames of which is below: