NodeJS Tutorial – Part 2, Routing

Posted: May 31st, 2010 | Author: Rob Searles | Filed under: JavaScript, Tutorials | Tags: | Comments
Note: This is the second part of my NodeJS tutorial. You may want to go back to the first part of this tutorial if you haven’t already read it.

In the first part of this tutorial we looked at reading a document from CouchDB and keeping our markup separate from our code using Haml templates. We arrived at the point where we clicked on a link, but nothing happened. Today we are going to put that right with some very simple routing.

The URL Module

The basis of all routing is the URL. Fortunately, Node has some basic functions which handle reading the URL so we can then decide what the user is actually trying to do.

First, we want to make sure we have included the URL module.

var sys = require('sys'),
fs = require('fs'),
http = require('http'),
url = require('url');

The next step is to extrapolate the path name from the URL that the user has visited:

Read the rest of this entry »


NodeJS Tutorial with CouchDB and Haml – ErdNodeFlips

Posted: May 28th, 2010 | Author: Rob Searles | Filed under: JavaScript, Tutorials | Tags: | Comments

The aim of this tutorial is to create a Node powered web app using a CouchDB database and Haml based templates. I wanted something relatively simple that I could do in a couple of sittings, but complex enough to be of some actual use. In the end I opted for a “top 10 list” type application. The functionality being as follows:

  1. To list a number of items
  2. To remove an item from the list
  3. To add an item to the list

Obviously, before getting cracking with this tutorial I had to think up a name for this “killer app” of the Node world.

So I give you ErdNodeFlips! In honour of erdnussflips – the strangely addictive Wotsit type things that taste of peanut butter and stick to the top of your mouth. Yum! (OMG – they even have their own Facebook page!)

All code is available on GitHub.

Read the rest of this entry »


jQuery Validate URL, adding “http://”

Posted: May 27th, 2010 | Author: Rob Searles | Filed under: JavaScript, Tutorials | Tags: | Comments

A project we have going on here at ibrow towers involves quite a bit of jQuery Validation. Whilst the Validation plugin is great with the default functions it offers, what makes it truly excellent is the fact that it is easily extendable.

For example, one thing that has been bugging me is to validate a URL the user must type in the initial http://. But why? Can the validation not just assume that if, for example, www.robsearles.com is typed in, that the user actually meant http://www.robsearles.com?

Well, after a quick read of the documentation and a hack around this little irritant is now gone. It’s all down to addMethod() which lets you add a custom validation method. Lets create one called complete_url().

jQuery.validator.addMethod("complete_url", function(val, elem) {
    // will contain our validation code
}, 'You must enter a valid URL');

A quick word about return values. If the method returns true, everything is considered OK. However, if false is returned then validation is assumed to have failed.

Our new method needs to do three things:

  1. If no url, don’t do anything
  2. Check that the user had entered http:// in their URL, if not, add it in for them.
  3. Check that the URL is now valid. For this I just used the source for the original url validation method.

Lets translate this into some code:

jQuery.validator.addMethod("complete_url", function(val, elem) {
    // if no url, don't do anything
    if (val.length == 0) { return true; }
 
    // if user has not entered http:// https:// or ftp:// assume they mean http://
    if(!/^(https?|ftp):\/\//i.test(val)) {
        val = 'http://'+val; // set both the value
        $(elem).val(val); // also update the form element
    }
    // now check if valid url
    // http://docs.jquery.com/Plugins/Validation/Methods/url
    // contributed by Scott Gonzalez: http://projects.scottsplayground.com/iri/
    return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(val);
});

Validating the form with this new method is very straight forward:

$("#form1").validate({
    rules: {
        url: "complete_url"
    }
});

Feel free to use/copy/modify as you see fit. If you do use it, why not let me know, or drop me a trackback?

Have fun

Other jQuery Specific Posts


Easily Add Current File to SVN Within Emacs

Posted: May 14th, 2010 | Author: Rob Searles | Filed under: Emacs, Tutorials | Tags: | Comments

As I’ve now been using Emacs for quite a long time, I have picked up a few tips along the way. One thing I’ve been doing more and more is using the shell within Emacs. (For more details see here and here.)

Some of my most used shell commands are using SVN, such as add, revert etc. However, I couldn’t find anywhere to just add/revert the current file I am working on. Fortunately there is Stack Overflow! Someone with a very similar issue to me has had a couple of good answers, which I have “borrowed” and now adding files to my SVN repository is really easy.

First, add the following to your .emacs file

(define-key minibuffer-local-map [f3]
(lambda() (interactive) (insert (buffer-file-name (nth 1 (buffer-list))))))

Now either open up Emacs, or reload your .emacs file:

M-x load-file RET ~/.emacs RET

Now, when you are working on a new file you can easily add it to SVN with the following command:

M-! svn add F3 RET

Nice!


My Perfect Desktop Day 1 – The Base System

Posted: March 18th, 2010 | Author: Rob Searles | Filed under: Linux, Tutorials | Comments

arch-linux-logoSo today is the day I start building my perfect system. Before getting going,  I had a good think about which distro to use for the base install. I’ve been using Ubuntu for about 2 years now and love the ease of package management with apt and aptitude. I had a bit of a play around with Ubuntu Karmic yesterday and I must say it looks fantastic, and with Lucid Lynx only a few weeks away it might come as a bit of a surprise to discover that my choice is a distro I’ve never used before: Arch.

Why Arch?

There are three main reasons I’ve picked Arch over Ubuntu, or even Debian.

  1. I really like the idea of Arch’s rolling release system. My laptop is currently running Jaunty and in order to get the latest packages I would have to upgrade to Karmic. With Arch this is less of an issue.
  2. As mentioned in my initial post, the base system should be small, quick and light. With Arch you can pick and choose exactly what you want at installation time, keeping it bloat free.
  3. Finally, Arch will be something new to play with!

After downloading and burning a Net Install ISO I followed the excellent installation guide in the Arch Wiki.

Installation was relatively painless, the only two slight issues being:

I chose Auto prepare for partitioning, but I didn’t really know what filesystem to choose. Eventually I opted for Ext4, with so far, no ill effects.

During Boot Device Selection, again I wasn’t really sure what to do, but after some Googling I found this page, whose advice I followed, but just pressing enter.

I restarted and was greeted with a shell prompt. I quickly pinged Google and my network was still up and running through the ethernet on DHCP.

The next step up a non-root user and X. Again, the Arch documentation is excellent.

Setting up X was relatively simple. I originally decided to not opt for hotplugging, which was a mistake because I only have a USB keyboard and mouse, neither of which I could use in X (muppet of the day award goes to me). After turning off the machine and setting up hotplugging, all was fine!

I have been using the Awesome window manager for about a month now. Awesome is a tiling window manager which is heavily geared towards being keyboard friendly, and as it’s name suggests, it is pretty awesome.

Unlike Jaunty, installing the latest stable version of Awesome was a breeze, I simply ran:

# pacman -S awesome

and edited my ~/.xinitrc file adding:

exec awesome

at the bottom. When I started X again, Awesome was there without any problem.

Sound was equally as simple to install, which was a nice surprise.

So my base system is now setup, with my window manager of choice in place and sound ready and waiting for my music collection. And all this running under 100MB of RAM!

After my first foray into the world of Arch I’m pretty impressed. Pacman is very straight forward to use, after a bit of tweaking here and there it has just worked.

Next time, file management tools.


Installing PHP5.3 on Ubuntu Karmic

Posted: March 17th, 2010 | Author: Rob Searles | Filed under: Linux, PHP, Tutorials | Comments

Following my previous post about installing PHP5.3 on Jaunty, I have had a few requests about installing it on Karmic. I’ve never used Karmic before so I thought it would be a fun excuse to have a poke about whilst also keeping my blog (sort of) up-to-date.

After freshly installing Karmic (the desktop version looks very nice btw) on a new VirtualBox image and then updating with the latest, er, updates I was ready to begin.

The entire installation procedure is very simple, once all dependencies are met.

Firstly you must edit your sources list to include the DotDeb package repository and the old Jaunty security packages to meet dependencies.

$ sudo nano /etc/apt/sources.list
# php5.3
deb http://php53.dotdeb.org stable all
deb-src http://php53.dotdeb.org stable all
deb http://security.ubuntu.com/ubuntu jaunty-security main

Now update and upgrade Ubuntu

$ sudo apt-get update
$ sudo apt-get upgrade

You may find that you get the following warning:

WARNING: The following packages cannot be authenticated!
libevent-1.4-2
Install these packages without verification [y/N]?

I just answered Y and continued as normal

Once successfully upgraded then you can install Apache, MySQL and PHP as normal, feel free to cater the installation line to your tastes.

$ sudo aptitude install libicu38 apache2 apache2-mpm-prefork mysql-client-5.1 mysql-server-5.1 php5 php5-cli php5-mysql libapache2-mod-php5

You will get a warning about untrusted packages being installed but this simply means that the PHP5.3 stuff is not signed, so I typed in “yes” and carried on.

Robmorin commented in my Jaunty post that he had issues when installing PHP MCrypt. The answer can be found within the DotDeb comments

After you have installed everything you need to, test it out, either command line:

$ php -v
PHP 5.3.2-0.dotdeb.1 with Suhosin-Patch (cli) (built: Mar  9 2010 10:14:53)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies with Suhosin v0.9.29, Copyright (c) 2007, by SektionEins GmbH

Or by using phpinfo() page within your Apache installation:

$ sudo nano /var/www/info.php

<?PHP
phpinfo();
?>

then fire up http://localhost/info.php and at the top of the page you should see something along the lines of
PHP Version 5.3.2-0.dotdeb.1

Note: if your browser asks if you want to download info.php, simply restart Apache and try again:

$ sudo /etc/init.d/apache2 restart

All done. Not quite as simple as on Jaunty, but still better than compiling the source!

Post Script: Before starting this post, I did a quick search looking for tutorials to see if the work had already been done, but couldn’t find anything on installing PHP5.3 on Karmic. As there wasn’t anything I decided to continue with my tutorial and I ended up struggling for an hour or so with the dependency issues. Typically, after I had figured it out for myself, whilst searching for another dependency issue I found this post on the JMOZ blog about installing PH5.3 on Karmic Koala.  No idea why it’s not in Google, but either way, damn, I could have saved myself an hour or so!


Converting from Mac to Unix line endings

Posted: March 10th, 2010 | Author: Rob Searles | Filed under: Linux, Tutorials | Tags: | Comments

This is more a post for me than anyone else, but I thought I’d share anyway.

In our team we have a mixture of Linux and Mac users, and we are constantly editing the same files. One of the most irritating things is when a file is saved with Mac line endings instead of Unix line endings (displaying as ^M in Emacs). This happens very rarely, but on the occasion it does I can quickly convert back using the following commands on my Linux box:

$ tr '\r' '\n' < file-in-question.txt > tmp.file
$ mv tmp.file file-in-question.txt

Works perfectly

If you want to find more about the tr (Translate) program, visit the man page.


Understanding Bitwise Operators (hopefully)

Posted: December 4th, 2009 | Author: Rob Searles | Filed under: PHP, Tutorials | Comments

After the trouble I had with bitwise operators yesterday I found some time to really sit down and get my head properly around them. Let’s dive straight in.

We need to initially define our flags:

define('BASE', 0); // binary 00000000
define('F1', 1);   // binary 00000001
define('F2', 2);   // binary 00000010
define('F3', 4);   // binary 00000100

To start with we have no flags set, so if we set F1 using the following:

$f1_set = BASE + F1; // $f1_set = 1
echo "F1 set = $f1_set\n";

All is well and good, $f1_set = 1 as expected.

However, what if we set F1 again?

$f1_set_twice = $f1_set + F1; // $f1_set_twice = 2 !!! wrong !!!
echo "F1 set twice = $f1_set_twice\n";

As you can see, if we set F1 twice, it effectively “unsets” F1 and sets F2. Not what we were after.

So why is this? Well, it’s kind of obvious and I was being a bit of a muppet for not spotting it yesterday. The reason is pretty simple: 1 + 1 = 2. (I told you it was obvious!)

Clearly this is not what we want, but how can we solve this? By using the bitwise OR. If we change the statements slightly as follows:

$f1_or_set = BASE | F1; // $f1_or_set = 1
echo "F1 OR set = $f1_or_set\n";
 
$f1_or_set_twice = $f1_or_set | F1; // $f1_or_set_twice = 1 - huzzah!
echo "F1 OR set twice = $f1_or_set_twice\n";

As far as “unsetting” the flags if we use my original method we fall (again) into trouble.

$f1_and_f3 = BASE | F1 | F3; // $f1_and_f3 = 5;
$unset_f3 = $f1_and_f3 - F3; // $unset_f3 = 1
echo "Unset F3 = $unset_f3\n";
 
$unset_f1 = $f1_and_f3 - F1; // $unset_f1 = 4;
echo "Unset F1 = $unset_f1\n";

Now, if we try to “unset” F1 twice, we arrive at the problem.

$unset_f1 = $f1_and_f3 - F1; // $unset_f1 = 3;
echo "Unset F1 = $unset_f1\n";

Unsetting F1 twice here effectively turns off F3 and sets F1 and F2 – completely wrong!

Instead, if we use the &~ binary operator mentioned in Jesper’s comment all works as expected. (note: I can’t find mention of this operator in the PHP docs, please someone help me out)

$f1_and_f3 = BASE | F1 | F3; // $f1_and_f3 = 5;
$unset_f3 = $f1_and_f3 &amp;~ F3; // $unset_f3 = 1
echo "Unset F3 = $unset_f3\n";
 
$unset_f1 = $f1_and_f3 &amp;~ F1; // $unset_f1 = 4;
echo "Unset F1 = $unset_f1\n";

Even if we try to “unset” a flag twice, it still has the same results:

$unset_f1 = $f1_and_f3 &amp;~ F1; // $unset_f1 = 4;
echo "Unset F1 = $unset_f1\n";
 
$unset_f1_twice = $unset_f1 &amp;~ F1; // $unset_f1_twice = 4;
echo "Unset F1 twice = $unset_f1_twice\n";

Also in Jesper’s comment and original post was the use of the left shift operator: <<. After playing around with this it seems very simple to use, as follows:

$f1 = 1;    // 00000001
$f2 = 1<<1; // 00000010
$f3 = 1<<2; // 00000100
$f4 = 1<<3; // 00001000

Or to put it another way:

$f1 = 1;      // 00000001
$f2 = $f1<<1; // 00000010
$f3 = $f2<<1; // 00000100
$f4 = $f3<<1; // 00001000

After all this I think I am a little closer to understanding Bitwise operations, hopefully! Tomorrow I’ll have a crack at testing to see if a flag is turned on or not. Until then…


Bitwise Operators used for Flagging Items

Posted: December 2nd, 2009 | Author: Rob Searles | Filed under: PHP, Tutorials | Comments

Update: Thanks to Jesper Noehr of BitBucket fame for pointing out gaping flaws in my post below (see his comment). I strongly advise you disregard all I have said below, because it will get you into a mess, in much the same way it has me. I’m going to sit down when I have a spare 1/2 hour and try to work out exactly what is going on! Many thanks and big kudos to Jesper, I really appreciate the time you took to correct me.


I have always wondered what the point of Bitwise Operators were,to me they seem to belong to a distant past. However, after reading a couple of great blog posts I have at last an understanding of how they can be put to use, and have started playing around with them a bit (ba dum!).

Jesper Noehr has written about using bitwise operators for a flexible permissions scheme within Python  and Jonathan Snook has taken the bitwise concept further creating a great calendar app in Javascript. After reading these I thought I better dive in, and an opportunity came along yesterday when I had to code a flagging system within PHP.

Read the rest of this entry »


Emacs CSS-Mode Fix (adding to the chain!)

Posted: October 29th, 2009 | Author: Rob Searles | Filed under: Open Source, Tutorials | Tags: | Comments

After my week with Emacs I’m still struggling along. One of my main annoyances is the default way some of the modes indent the code. I think the worst offender of this is the default CSS-mode. After frustration when, yet again, I hit the tab key and the cursor rockets about 80 places to the right I decided to Google for a fix.

The internet is great! Clearly it wasn’t just me having a problem, Guido Stevens was also suffering and posted a fix, which he himself found on another blog post by Chris Miller, which Chris in turn found on StokeBloke.com which had been found originally on a now dead post.

Not bad! Four people all having problems with the same thing and posting a fix for others to share. So I thought I’d join the chain, and write this blog post.

Oh yes, and the fix itself:

;; fix css mode
(require 'css-mode)
(setq cssm-indent-level 2)
(setq cssm-newline-before-closing-bracket t)
(setq cssm-indent-function #'cssm-c-style-indenter)
(setq cssm-mirror-mode t)