<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Francis Shanahan[.com] &#187; Web Development</title>
	<atom:link href="http://francisshanahan.com/index.php/category/computing/web-development/feed/" rel="self" type="application/rss+xml" />
	<link>http://francisshanahan.com</link>
	<description>Thoughts on technology from a citizen scientist</description>
	<lastBuildDate>Fri, 27 Jan 2012 14:18:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Sencha Touch 2.0 MVC in 5 minutes or less</title>
		<link>http://francisshanahan.com/index.php/2011/sencha-touch-2-0-mvc-in-5-minutes-or-less/</link>
		<comments>http://francisshanahan.com/index.php/2011/sencha-touch-2-0-mvc-in-5-minutes-or-less/#comments</comments>
		<pubDate>Fri, 21 Oct 2011 15:06:45 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=3274</guid>
		<description><![CDATA[I&#8217;ve shied away from JS frameworks on the mobile platform primarily due to performance. I had not been able to find one that came close to native performance on Android. This changed last weekend when I tried out the Sencha Touch 2.0 dev preview. Performance is vastly improved over Touch 1.0. Animations and transitions are smooth, even on my Android 2.2 device and I was able to get up and running very fast. 
Grab the Sencha Touch 2.0 Dev Preview here: http://www.sencha.com/blog/sencha-touch-2-developer-preview/
While I was able to get a basic app ...]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve shied away from JS frameworks on the mobile platform primarily due to performance. I had not been able to find one that came close to native performance on Android. This changed last weekend when I tried out the Sencha Touch 2.0 dev preview. Performance is vastly improved over Touch 1.0. Animations and transitions are smooth, even on my Android 2.2 device and I was able to get up and running very fast. </p>
<p>Grab the Sencha Touch 2.0 Dev Preview here: <a href="http://www.sencha.com/blog/sencha-touch-2-developer-preview/" target="_blank">http://www.sencha.com/blog/sencha-touch-2-developer-preview/</a></p>
<p>While I was able to get a basic app up and running quickly, unfortunately I spent a lot of time re-factoring into a proper MVC structure. The documentation on how to do this in Touch 2.0 is not there yet and there are some albeit small but killer differences between Touch1.0 and 2.0. To a novice like me they cost me a few hours. </p>
<p>Everything here was based off the Sencha ExtJS 4.0 walkthrough available here: </p>
<ul>
<li><a href="http://www.sencha.com/learn/architecting-your-app-in-ext-js-4-part-1/">http://www.sencha.com/learn/architecting-your-app-in-ext-js-4-part-1/</a></li>
<li><a href="http://www.sencha.com/learn/architecting-your-app-in-ext-js-4-part-2/">http://www.sencha.com/learn/architecting-your-app-in-ext-js-4-part-2/</a></li>
<li><a href="http://www.sencha.com/learn/architecting-your-app-in-ext-js-4-part-3/">http://www.sencha.com/learn/architecting-your-app-in-ext-js-4-part-3/</a></li>
</ul>
<p>The sample code is available on Github and you can go here and download the entire project in a single ZIP/TAR: <a href="https://github.com/FrancisShanahan/SenchaTouch2MVCHelloworld" target="_blank">https://github.com/FrancisShanahan/SenchaTouch2MVCHelloworld</a></p>
<p>Or you can fork the repo using git: <a href="http://help.github.com/fork-a-repo/" target="_blank">http://help.github.com/fork-a-repo/</a></p>
<p>Here are a few key points:</p>
<p>a) Let the app instantiate your controllers and any global stores your app needs. Notice how the initial layout is created using xtypes? These are created as aliases in the views.<br />
<script src="https://gist.github.com/1303996.js"> </script></p>
<p>b) Let your controllers instantiate your views and stores.<br />
<script src="https://gist.github.com/1304002.js"> </script></p>
<p>c) Use Component Queries instead of Ext.getCmp(&#8216;id goes here&#8217;). This&#8217;ll keep your code more manageable as the code base grows. Note, the &#8220;ref&#8221; name here is important as it&#8217;s used to generate getters for the view instances. E.g. a ref of &#8220;stationList&#8221; will create a getter on the controller of &#8220;getStationList&#8221;. </p>
<p><script src="https://gist.github.com/1304014.js"> </script></p>
<p>I&#8217;ve already heard from a few folks so it looks like this project is helpful. It&#8217;s also ready for dropping into a Phonegap shell. Fork it and update or let me know if there&#8217;s anything you&#8217;d like to see added. </p>
<p>Attribution: Today&#8217;s photo comes from Anxo Resúa&#8217;s stream on Flickr <a href="http://www.flickr.com/photos/anxoresua/4652943076/">http://www.flickr.com/photos/anxoresua/4652943076/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2011/sencha-touch-2-0-mvc-in-5-minutes-or-less/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Stream a webcam using Javascript, NodeJS, Android, Opera Mobile, Web Sockets and HTML5</title>
		<link>http://francisshanahan.com/index.php/2011/stream-a-webcam-using-javascript-nodejs-android-opera-mobile-web-sockets-and-html5/</link>
		<comments>http://francisshanahan.com/index.php/2011/stream-a-webcam-using-javascript-nodejs-android-opera-mobile-web-sockets-and-html5/#comments</comments>
		<pubDate>Mon, 19 Sep 2011 20:29:04 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Cool & Future Tech]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[Things I've Made]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=3265</guid>
		<description><![CDATA[With all the recent Goruck-ness it&#8217;s time to throw out a tech post. I&#8217;ve been prepping for a NodeJS presentation recently and wanted a unique demo. I had also come across the experimental build of Opera which supports accessing the native webcam of a mobile device. So I threw these two technologies together and came up with a Javascript powered way to stream a video camera from a mobile device to a bunch of desktop (or mobile) clients. 
HTML5 had originally laid out support for a new element (the &#8220;device&#8221; ...]]></description>
			<content:encoded><![CDATA[<p>With all the recent Goruck-ness it&#8217;s time to throw out a tech post. I&#8217;ve been prepping for a NodeJS presentation recently and wanted a unique demo. I had also come across the experimental build of Opera which supports accessing the native webcam of a mobile device. So I threw these two technologies together and came up with a Javascript powered way to stream a video camera from a mobile device to a bunch of desktop (or mobile) clients. </p>
<p>HTML5 had originally laid out support for a new element (the &#8220;device&#8221; element) but it appears this element has been scrapped now in favour of the &#8220;getUserMedia&#8221; API. So far I have only seen the Opera Mobile Experimental build support this but hopefully it&#8217;ll get into Dolphin and other mobile browsers soon. </p>
<p><a href="http://my.opera.com/core/blog/2011/03/23/webcam-orientation-preview">http://my.opera.com/core/blog/2011/03/23/webcam-orientation-preview</a></p>
<p>If you just want to cut to the chase here&#8217;s a video of the final result:<br />
<iframe width="560" height="315" src="http://www.youtube.com/embed/cjmuwA8l1LQ" frameborder="0" allowfullscreen></iframe></p>
<p>There are three moving parts here</p>
<ul>
<li>a) The client page which captures the video</li>
<li>b) the server which is a simple Node broadcast server </li>
<li>c) and the Client which is just a web page that renders the output. </li>
</ul>
<p>The client is just a copy-paste from Opera&#8217;s website. I take the video stream, render it to a canvas, then grab the canvas as a base64 encoded image. One image per frame. I could not find a way to limit the video&#8217;s size so the resulting image is fairly large (240&#215;400 on an HTC Incredible).  I down-sampled, cutting the image data to reduce the traffic over the wire. Framerates are still pretty poor but this is just an experiment. </p>
<p>The server is a generic websockets server and gets a message which is a raw data/base64 stream. It broadcasts this down the any connected clients. </p>
<p>The client then is the simplest of all, just connects to the socket server and renders whatever it gets to an <img> tag. </p>
<p>It&#8217;s all Javascript. </p>
<p>Client (this is a jade view). </p>
<pre class="brush: javascript">

h1
    Remote Webcam using NodeJS, Opera, Web Sockets and HTML5/Canvas
video(autoplay=true,id=&quot;sourcevid&quot;)
canvas(id=&quot;output&quot;)
div(id=&quot;log&quot;)
script
    var log = function(msg) {
       document.getElementById(&#039;log&#039;).innerHTML = document.getElementById(&#039;log&#039;).innerHTML + msg + &quot;&lt;br/&gt;&quot;;
    };
    var video = document.getElementsByTagName(&#039;video&#039;)[0],
        heading = document.getElementsByTagName(&#039;h1&#039;)[0];
    if(navigator.getUserMedia) {
        navigator.getUserMedia(&#039;video&#039;, successCallback, errorCallback);

        function successCallback( stream ) {
            video.src = stream;
        };

        function errorCallback( error ) {
            heading.textContent = &quot;An error occurred: [CODE &quot; + error.code + &quot;]&quot;;
        };
    } else {
        heading.textContent = &quot;Native web camera streaming is not supported in this browser!&quot;;
    };

    var back = document.createElement(&#039;canvas&#039;);
    var backcontext = back.getContext(&#039;2d&#039;);

    var ws;

    if(&#039;WebSocket&#039; in window){
        connect(&#039;ws://192.168.2.100:8080/&#039;);
    } else {
        log (&#039;web sockets not supported&#039;);
     }

    function connect(host) {
        ws = new WebSocket(host);
        ws.onopen = function () {
            log(&#039;connected&#039;);
        };

        ws.onclose = function () {
            log(&#039;socket closed&#039;);
        };

        ws.onerror = function (evt) {
            log(&#039;&lt;span style=&quot;color: red;&quot;&gt;ERROR:&lt;/span&gt; &#039; + evt.data);
        };
    };

    function send(msg){
        if (ws != null) {
            if(ws.readyState === 1) {
               ws.send(msg);
            }
        } else {
            //log (&#039;not ready yet&#039;);
        }
    }    

    cw = 120;//240;//video.clientWidth;
    ch = 200;//400;//video.clientHeight;
    log(&#039;width = &#039; + ch);
    back.width = cw;
    back.height = ch;
    draw(video, backcontext, cw, ch);

    function draw(v, bc, w, h) {

        // First, draw it into the backing canvas
        bc.drawImage(v, 0, 0, w, h);

        // Grab the pixel data from the backing canvas
        var stringData=back.toDataURL();

        // send it on the wire
        send(stringData);

        // Start over! 10 frames a second = 100milliseconds
        setTimeout(function(){ draw(v, bc, w, h); });
    }
</pre>
<p>The server. Simple Broadcast app.</p>
<pre class="brush: javascript">

var sys = require(&quot;sys&quot;),
    ws = require(&quot;./ws.js&quot;);

var clients = [];

ws.createServer(
	function (websocket) {

		clients.push(websocket);

		websocket.addListener(&quot;connect&quot;, function (resource) {
			// emitted after handshake
			sys.debug(&quot;connect: &quot; + resource);
		}).addListener(&quot;data&quot;, function (data) {

		// handle incoming data
		// send data to ALL clients whenever ANY client send up data
		for (var i = 0 ; i &lt; clients.length ; i ++ ) {
			clients[i].write(data);
		}

    }).addListener(&quot;close&quot;, function () {

		// emitted when server or client closes connection
		sys.debug(&quot;close&quot;);
    });
  }).listen(8080);

  sys.debug(&quot;Listening on port 8080&quot;);
</pre>
<p>The client. </p>
<pre class="brush: javascript">

&lt;img src=&quot;&quot; id=&quot;frame&quot; style=&quot;width:240px;height:400px&quot;/&gt;

&lt;div id=&quot;log&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;

	var img; 

	function Init() {

		img = document.getElementById(&quot;frame&quot;);	

	}

	$(document).ready(function () {

		Init();

	});

// Web socket connection stuff is next...	

	if(&#039;WebSocket&#039; in window){

		connect(&#039;ws://localhost:8080/&#039;);		

	} else {

		log (&#039;web sockets not supported&#039;);

	}

	var ws;

	function connect(host) {

		ws = new WebSocket(host);

		ws.onopen = function () {

			log(&#039;connected&#039;);

		};

		ws.onmessage = function (evt) {  	

            if (evt.data != null) {		

			  if ((evt.data[0]=== &quot;d&quot;) &amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp; (evt.data[1]===&quot;a&quot;) ) img.src=evt.data;	//log(&#039;got&#039; + evt.data);

			}

		};

		ws.onclose = function () {

			log(&#039;socket closed&#039;);

		};

		ws.onerror = function (evt) { 

			log(&#039;&lt;span style=&quot;color: red;&quot;&gt;ERROR:&lt;/span&gt; &#039; + evt.data); 

		};

	};

	function log(msg){

		document.getElementById(&#039;log&#039;).innerHTML = msg + &quot;&lt;br/&gt;&quot; + document.getElementById(&#039;log&#039;).innerHTML ;

	}
&lt;/script&gt;
</pre>
<p>Instead of broadcasting, you could store these frames in a MongoDB for assembly later. This would make the ultimate, storage independent video camera. Never run out of storage again!</p>
<p>I really need to start storing these snippets on github&#8230;</p>
<p>P.S. Everyone knows insects are clockwork which is why god made so many of them. Today&#8217;s image is from <a href="http://www.insectlabstudio.com/">http://www.insectlabstudio.com/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2011/stream-a-webcam-using-javascript-nodejs-android-opera-mobile-web-sockets-and-html5/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Mycellium Source Code Available</title>
		<link>http://francisshanahan.com/index.php/2011/mycellium-source-code-available/</link>
		<comments>http://francisshanahan.com/index.php/2011/mycellium-source-code-available/#comments</comments>
		<pubDate>Wed, 06 Jul 2011 14:08:35 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[canvas]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=3158</guid>
		<description><![CDATA[Last time [LINK] I discussed how virtual Worms could &#8220;eat&#8221; a picture, seeking out the lighter or darker areas as food and leaving a trail in their wake. I&#8217;ve dumped the source here: http://francisshanahan.com/demos/worms/test.html so you can interact, create your own images and figure out how it&#8217;s done. To be honest I haven&#8217;t had much time to clean this up as I&#8217;ve been focusing on other things and doing a bit of travel for work so be gentle. 
Just enter a URL of an image and click &#8220;create drawing&#8221; to ...]]></description>
			<content:encoded><![CDATA[<p>Last time [<a href="http://francisshanahan.com/index.php/2011/emulating-mycelium-hyphae-with-html5/">LINK</a>] I discussed how virtual Worms could &#8220;eat&#8221; a picture, seeking out the lighter or darker areas as food and leaving a trail in their wake. I&#8217;ve dumped the source here: <a href="http://francisshanahan.com/demos/worms/test.html">http://francisshanahan.com/demos/worms/test.html</a> so you can interact, create your own images and figure out how it&#8217;s done. To be honest I haven&#8217;t had much time to clean this up as I&#8217;ve been focusing on other things and doing a bit of travel for work so be gentle. </p>
<p>Just enter a URL of an image and click &#8220;create drawing&#8221; to being. The page will load that image into a hidden canvas and use it as reference to draw the picture. You should use Chrome of course but this should work in all HTML5 compatible browsers. </p>
<p>Room for improvement might be to place the code in an enclosure, cleaning up the global DOM namespace or  multi-thread it this using Web Workers although the current speed is acceptable. Web Workers in this instance might be overkill. </p>
<p>Enjoy. </p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2011/mycellium-source-code-available/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Node.js, Cygwin and Web Sockets</title>
		<link>http://francisshanahan.com/index.php/2011/using-node-js-cygwin-and-web-sockets/</link>
		<comments>http://francisshanahan.com/index.php/2011/using-node-js-cygwin-and-web-sockets/#comments</comments>
		<pubDate>Thu, 23 Jun 2011 20:40:28 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Cool & Future Tech]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=2995</guid>
		<description><![CDATA[If you have not heard of Node.js (or &#8220;Node&#8221; as Ryan Dahl calls it) [LINK] it is more fun than a barrel full of monkeys and faster than stink. Node.js is built around the Google V8 javascript engine and aims to solve the issues of concurrency and blocking IO which are prevalent in todays web servers. It also improves over traditional OS threading by using an event model to handle requests. This leads to the ability to handle many more concurrent requests but also handle them faster since less memory ...]]></description>
			<content:encoded><![CDATA[<p>If you have not heard of Node.js (or &#8220;Node&#8221; as Ryan Dahl calls it) [<a href="http://nodejs.org">LINK</a>] it is more fun than a barrel full of monkeys and faster than stink. Node.js is built around the Google V8 javascript engine and aims to solve the issues of concurrency and blocking IO which are prevalent in todays web servers. It also improves over traditional OS threading by using an event model to handle requests. This leads to the ability to handle many more concurrent requests but also handle them faster since less memory is allocated on the heap for each new call. </p>
<p>I spent some time last week looking at Web Sockets as a way to push information to the client. Web sockets need a custom server, not an HTTP server, so I used Nugget which is an open source implementation of the web socket protocol on CodePlex (http://nugget.codeplex.com/). Nugget worked great but with all the hype and interest around Node I felt I was missing something so I built the same thing again, this time around using Node.js on the server side. </p>
<p>Before get started you&#8217;ll need to build Node. This can be done </p>
<blockquote><p>&#8220;on Linux, Macintosh, and Solaris. It also runs on Windows/Cygwin, FreeBSD, and OpenBSD. The build system requires Python 2.4 or better. V8, on which Node is built, supports only IA-32, x64, and ARM processors. V8 is included in the Node distribution. To use TLS, OpenSSL is required. There are no other dependencies.&#8221;</p></blockquote>
<p>I used Cygwin on Wintel and installed g++, Python 2.7 and GNU Make. You also need OpenSSL if you plan on using Node with Web Sockets.</p>
<p>Here&#8217;s a comprehensive walkthrough of installing Cygwin and building Node from scratch: [<a href="https://github.com/joyent/node/wiki/Building-node.js-on-Cygwin-%28Windows%29">LINK</a>]</p>
<p>Web Sockets uses a funky little handshake protocol [<a href="http://en.wikipedia.org/wiki/WebSockets#WebSocket_Protocol_Handshake">LINK</a>] to establish the connection which I didn&#8217;t feel like implementing so I came across a WS Server implementation using Node.JS up on GitHub [<a href="https://github.com/miksago/node-websocket-server/">https://github.com/miksago/node-websocket-server/</a>]. This worked well with Node 0.2.5  testing from Chrome 12 which uses v-76 of the Hixie protocol.</p>
<p>Here&#8217;s my client which is based off the Dive into HTML5 example:</p>
<pre class="brush: javascript">
if(Modernizr.websockets){
	    connect(&#039;ws://localhost:3400/service&#039;);
	} else {
		log (&#039;web sockets not supported&#039;);
	}
	var ws;

	function connect(host) {
		ws = new WebSocket(host);
		ws.onopen = function () {
			log(&#039;connected&#039;);
		};

		ws.onmessage = function (evt) {
			log(&#039;recv :&#039; + evt.data);
			showNotification(evt.data);
		};

		ws.onclose = function () {
			log(&#039;socket closed&#039;);
		};

		ws.onerror = function (evt) {
			log(&#039;&lt;span style=&quot;color: red;&quot;&gt;ERROR:&lt;/span&gt; &#039; + evt.data);
		};
	};

	function log(msg){
		document.getElementById(&#039;log&#039;).innerHTML += msg + &quot;&lt;br/&gt;&quot;;
	}

	function send(){
		var msg = document.getElementById(&#039;status&#039;).value;
		ws.send(msg);
	}

	function RequestPermission (callback) {
		window.webkitNotifications.requestPermission(callback);
	}

	function showNotification(msg){
		if (window.webkitNotifications.checkPermission() &gt; 0) {
			RequestPermission(showNotification);
		}
		else {
			window.webkitNotifications.createNotification(&quot;alert.jpg&quot;, &quot;Test Notification&quot;, msg).show();
		}
	}
</pre>
<p>With this client-side scripe and Node running the ws-socket server I was able to get a simple echo running forth between the web page and the server.</p>
<p>Node has gained some ground since I first looked at it (back when Chrome was on version 8). Even Microsoft has announced plans to port it over to Windows [<a href="http://blogs.msdn.com/b/interoperability/archive/2011/06/23/microsoft-working-with-joyent-and-the-node-community-to-bring-node-js-to-windows.aspx">LINK</a>]. In the coming weeks I plan on looking at some of the templating engines (Like http://jade-lang.com/ and http://mustache.github.com/)  and web frameworks (like http://expressjs.com and http://geddyjs.org/ ) which have cropped up around it and will report back on whether it&#8217;s ready for prime time or not. Watch this space. </p>
<p>Attribution: Today&#8217;s image by Casch52 on Flickr [<a href="http://www.flickr.com/photos/casch/470563640/">LINK</a>]</p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2011/using-node-js-cygwin-and-web-sockets/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Emulating Mycelium Hyphae with HTML5</title>
		<link>http://francisshanahan.com/index.php/2011/emulating-mycelium-hyphae-with-html5/</link>
		<comments>http://francisshanahan.com/index.php/2011/emulating-mycelium-hyphae-with-html5/#comments</comments>
		<pubDate>Mon, 09 May 2011 21:00:23 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[fungus]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=3084</guid>
		<description><![CDATA[Mycelium (plural mycelia) is the vegetative part of a fungus, consisting of a mass of branching, thread-like hyphae. Hyphae are any of the threadlike filaments forming the mycelium of a fungus. And YES I had to look both of those up. 
Typically they travel and branch along a source of nutrients, following the source. I came across this awesome work of Ryan Alexander [LINK] whilst messing around with Processing one evening. Ryan used Processing which is similar to Java. Processing is a great sketch-language which makes whipping up graphical wonders ...]]></description>
			<content:encoded><![CDATA[<p>Mycelium (plural mycelia) is the vegetative part of a fungus, consisting of a mass of branching, thread-like hyphae. Hyphae are any of the threadlike filaments forming the mycelium of a fungus. And YES I had to look both of those up. </p>
<p>Typically they travel and branch along a source of nutrients, following the source. I came across this awesome work of Ryan Alexander [<a href="http://onecm.com/" target="_blank">LINK</a>] whilst messing around with Processing one evening. Ryan used Processing which is similar to Java. Processing is a great sketch-language which makes whipping up graphical wonders a doddle and is a favourite of interactive media artists. It&#8217;s really cool and I&#8217;ve been messing with it for a few years now. Check out &#8220;http://processing.org/&#8221; for more. </p>
<p>A few hours later I had the same thing implemented in Javascript and HTML5 using the Canvas element although mine is not as sophisticated as Ryan&#8217;s.</p>
<blockquote><p>Disclaimer: I know nothing of Mycelium or of Hyphae or how they branch and form. I merely tried to emulate how the branching works.</p></blockquote>
<p>Basically you take an image as input and a number of threads are created, I called them &#8220;worms&#8221; since &#8220;hyphae&#8221; seemed a but over the top. The worms have a trajectory and will move along it in search of food. Each iteration the worm decides where to move, favouring the light or dark portions of the image. Just as in Ryan&#8217;s Processing application the image acts as a source of food. If the worm ventures into a dark portion of the image, after a while without food, he dies.</p>
<p>I&#8217;m sure there&#8217;s a lot more to say on how this Mycelium stuff grows than what I&#8217;ve modeled here. For example I didn&#8217;t consider the amount of food contributing to the speed of the &#8220;worm&#8221; nor did I attempt to make the worms avoid each other. This was primarily an artistic endeavor and a creative outlet written over a beer one night. </p>
<p>I made a bunch of different images, Martin Luthor King, Bob Dylan, Willie Nelson, Clint Eastwood. For Clint&#8217;s I made a slight adjustment where any worm that died I&#8217;d re-spawn inside his eyes. Results were pretty nice. Here&#8217;s the Flickr Album: <a href="http://www.flickr.com/photos/10277648@N03/with/5704290009/" target="_blank">http://www.flickr.com/photos/10277648@N03/with/5704290009/</a></p>
<p><a href="http://www.flickr.com/photos/10277648@N03/5704290009/" title="clintbig3 by francisshanahan, on Flickr"><img src="http://farm4.static.flickr.com/3137/5704290009_9fd5455ccd.jpg" width="371" height="500" alt="clintbig3"></a></p>
<p>This technique works best on images with high-contrasting areas. Basically wrinkled old men. You&#8217;ll notice how the hyphae follow the wrinkles in Clint&#8217;s face.</p>
<p><a href="http://www.flickr.com/photos/10277648@N03/5704288959/" title="dylan by francisshanahan, on Flickr"><img src="http://farm4.static.flickr.com/3099/5704288959_58e2448027.jpg" width="393" height="500" alt="dylan"></a></p>
<p>Bob Dylan was surprising as the threads were never able to &#8220;break through&#8221; into the darker areas around his eyes. He just didn&#8217;t have enough wrinkles to feed them. </p>
<p><a href="http://www.flickr.com/photos/10277648@N03/5704856326/" title="willie2 by francisshanahan, on Flickr"><img src="http://farm4.static.flickr.com/3274/5704856326_d715484ccd.jpg" width="402" height="500" alt="willie2"></a></p>
<p>Willie Nelson, looking down. You can start to see his two braids forming in the weeds. </p>
<p>If you like these click over to the Flickr Album for more: <a href="http://www.flickr.com/photos/10277648@N03/with/5704290009/">http://www.flickr.com/photos/10277648@N03/with/5704290009/</a></p>
<p>Interesting factoid: At one point Mycelium was considered the largest living organism in the world! From Wikipedia:</p>
<blockquote><p>This 2,400-acre (9.7 km2) site in eastern Oregon had a contiguous growth of mycelium before logging roads cut through it. Estimated at 1,665 football fields in size and 2,200 years old, this one fungus has killed the forest above it several times over, and in so doing has built deeper soil layers that allow the growth of ever-larger stands of trees. Mushroom-forming forest fungi are unique in that their mycelial mats can achieve such massive proportions.</p></blockquote>
<p>In the coming days I&#8217;ll clean up the code and try to make it configurable so you can upload your own photos and play along. More to come on this one&#8230;</p>
<p>[UPDATE] Source code is now available here: <a href="http://francisshanahan.com/index.php/2011/mycellium-source-code-available/">http://francisshanahan.com/index.php/2011/mycellium-source-code-available/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2011/emulating-mycelium-hyphae-with-html5/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>How To Theme Sencha Touch with SASS on Windows</title>
		<link>http://francisshanahan.com/index.php/2011/how-to-theme-sencha-touch-sass-windows/</link>
		<comments>http://francisshanahan.com/index.php/2011/how-to-theme-sencha-touch-sass-windows/#comments</comments>
		<pubDate>Fri, 14 Jan 2011 22:55:44 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=3030</guid>
		<description><![CDATA[A good architect stays current with technology to better enable their team&#8217;s productivity. One often overlooked area is that of CSS, there have been many improvements. In this post I record the steps taken to successfully setup SASS (Syntactically Awesome Style Sheets) with Sencha Touch on Windows.
If you&#8217;re building a website with a non-trivial CSS file (aren&#8217;t we all),  SASS  makes managing the CSS a lot simpler.
&#8220;Sass is a meta-language on top of CSS that’s used to describe the style of a document cleanly and structurally, with more power than ...]]></description>
			<content:encoded><![CDATA[<p>A good architect stays current with technology to better enable their team&#8217;s productivity. One often overlooked area is that of CSS, there have been many improvements. In this post I record the steps taken to successfully setup SASS (Syntactically Awesome Style Sheets) with Sencha Touch on Windows.</p>
<p>If you&#8217;re building a website with a non-trivial CSS file (aren&#8217;t we all),  SASS  makes managing the CSS a lot simpler.</p>
<blockquote><p>&#8220;Sass is a meta-language on top of CSS that’s used to describe the style of a document cleanly and structurally, with more power than flat CSS allows. Sass both provides a simpler, more elegant syntax for CSS and implements various features that are useful for creating manageable stylesheets.&#8221;</p></blockquote>
<p>Sencha Touch uses SASS to manage its stylesheets. I&#8217;ve been researching this in my evenings and weekends and am at the point where I want to change how Sencha Touch looks. It&#8217;s not as simple as you&#8217;d think. Essentially I need to create a new theme. Hence a little SASS is warranted. </p>
<p>Unfortunately both the instructions on the Sencha site [<a href="http://www.sencha.com/blog/2010/12/17/an-introduction-to-theming-sencha-touch/" target="_blank">LINK</a>] and the SASS site [<a href="http://sass-lang.com/docs.html" target="_blank">LINK</a>] are a little out of date and buggy. Here now are the steps I followed to get this working on windows:</p>
<ol>
<li>Start by installing Ruby &#8211; <a href="http://rubyforge.org">http://rubyforge.org</a> grab the latest rubyinstaller-1.9.2-p136.exe &#8211; nothing to it and you&#8217;ll end up with c:\ruby192 and some Start-Menu items.</li>
<li>This comes with Gems  so you can skips the gems install. There is one snag though with Ruby 1.9.2-p136 that the install sets up an incorrect folder &#8211; c:\ruby192\lib\ruby\site_ruby &#8211; remove this one (just rename it to be safe) and gems will work. Maybe they&#8217;ll fix this in the next release.</li>
<li>Install Compass: at a Ruby command prompt type &#8220;gem install compass&#8221;. If you&#8217;re behind a proxy I found this works: &#8220;gem install &#8211;http-proxy &lt;proxyAddress:Port&gt; compass&#8221;</li>
</ol>
<p>Next create a new folder in your Sencha folders. If your directories look like this</p>
<p>c:\myWebsite\js\sencha-touch-1.0.1\resources\css</p>
<p>c:\myWebsite\js\sencha-touch-1.0.1\resources\sass</p>
<p>You&#8217;ll want to create this one:</p>
<p>c:\myWebsite\js\sencha-touch-1.0.1\resources\SCSS</p>
<p>Inside that create two files as per the Sencha website:</p>
<p>Config.Rb (a ruby file)</p>
<pre class="brush: csharp">
# Delineate the directory for our SASS/SCSS files (this directory)
sass_path = File.dirname(__FILE__)

# Delineate the CSS directory (under resources/css in this demo)
css_path = File.join(sass_path, &quot;..&quot;, &quot;css&quot;)

# Delinate the images directory
images_dir = File.join(sass_path, &quot;..&quot;, &quot;img&quot;)

# Load the sencha-touch framework
load File.join(sass_path, &#039;..&#039;, &#039;..&#039;, &#039;..&#039;, &#039;..&#039;, &#039;resources&#039;, &#039;themes&#039;)

# Specify the output style/environment
output_style = :compressed
environment = :production
</pre>
<p>No changes are needed to config.rb</p>
<p>Next create Application.scss(The file extension is important here)</p>
<pre class="brush: csharp">
// 1. Variable overrides, example:
// $base-color: #af2584;

// 2. Include Sencha Touch styles
@import &#039;c:\myWebsite\js\sencha-touch-1.0.1\resources\themes\stylesheets\sencha-touch\default\all&#039;;
@include sencha-panel;
@include sencha-buttons;
@include sencha-sheet;
@include sencha-picker;
@include sencha-toolbar-forms;
@include sencha-tabs;
@include sencha-toolbar;
@include sencha-carousel;
@include sencha-indexbar;
@include sencha-list;
@include sencha-layout;
@include sencha-form;
@include sencha-loading-spinner;

// 3. Define custom styles (can use SASS/Compass), example:
// .mybox {
//     @include border-radius(4px);
// }
</pre>
<p>The @import line is important. I changed it to the location of the default theme in Sencha Touch with the &#8220;all&#8221; appended. </p>
<p>Lastly, run SASS using &#8220;compass compile&#8221;. You&#8217;ll end up with a new file names &#8220;application.css&#8221; located under</p>
<p>c:\myWebsite\js\sencha-touch-1.0.1\resources\css\application.css</p>
<p>Now reference that new CSS file in your Sencha website and you&#8217;re all set. Refer to Sencha&#8217;s site for tips on customizing the Theme itself [<a href="http://www.sencha.com/blog/2010/12/17/an-introduction-to-theming-sencha-touch/">http://www.sencha.com/blog/2010/12/17/an-introduction-to-theming-sencha-touch/</a>].</p>
<p>SASS on its own is a boon if you&#8217;re doing serious CSS work. If not it&#8217;s probably over kill. You can do things like define variables and have those determine your CSS based on functions, you can nest elements for easier maintenance and even remove whitespace and combine multiple CSS files into one automatically. </p>
<p>Definitely one for the toolbox. </p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2011/how-to-theme-sencha-touch-sass-windows/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>RSS with SyndicationItem, Entity Framework and AutoMapper</title>
		<link>http://francisshanahan.com/index.php/2010/rss-syndicationitem-entity-framework-automapper/</link>
		<comments>http://francisshanahan.com/index.php/2010/rss-syndicationitem-entity-framework-automapper/#comments</comments>
		<pubDate>Fri, 31 Dec 2010 16:24:24 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[General Computing]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=2999</guid>
		<description><![CDATA[The otherwise excellent Kindle 3 doesn&#8217;t natively let you subscribe to RSS feeds. To me this is a major failing but we can write a simple service to aggregate feeds into an HTML file. If you email this file to @free.amazon.com Amazon will convert (for free) into an AZW file and deliver to your Kindle. Presto, free feed aggregation.  This is essentially what http://kindlefeeder.com does and I recommend this service if you don&#8217;t feel like writing your own. 
Since switching to WordPress I hadn&#8217;t looked at RSS in a ...]]></description>
			<content:encoded><![CDATA[<p>The otherwise excellent Kindle 3 doesn&#8217;t natively let you subscribe to RSS feeds. To me this is a major failing but we can write a simple service to aggregate feeds into an HTML file. If you email this file to <username>@free.amazon.com Amazon will convert (for free) into an AZW file and deliver to your Kindle. Presto, free feed aggregation.  This is essentially what <a href="http://kindlefeeder.com">http://kindlefeeder.com</a> does and I recommend this service if you don&#8217;t feel like writing your own. </p>
<p>Since switching to WordPress I hadn&#8217;t looked at RSS in a while. It&#8217;s not as Simple as it used to be. This was also a good opportunity to try the Entity Framework [<a href="http://msdn.microsoft.com/en-us/library/aa697427(v=vs.80).aspx">LINK</a>] with Automapper (<a href="http://automapper.codeplex.com/">http://automapper.codeplex.com/</a>). I created a simple EDMX file to store the feeds (draft below). </p>
<p><img src="http://francisshanahan.com/wp-content/uploads/2010/12/feedEdmx.png" alt="Simple Edmx to store Feeds" /></p>
<p>Then to read the feed I used System.ServiceModel.Syndication objects. Initially I used Argotic and NuGet (http://nuget.codeplex.com/) made this a snap to setup. (if you haven&#8217;t tried NuGet I highly recommend it). Argotic turned out to be overkill so I reverted to the native .NET classes within System.ServiceModel.Syndication.</p>
<pre class="brush: csharp">

// Load feed
SyndicationFeed  feed = SyndicationFeed.Load(XmlReader.Create(url));
</pre>
<p>You can augment your Entity Framework classes with partial classes and DataAnnotations like so: </p>
<pre class="brush: csharp">

 [MetadataType(typeof(FeedMetadata))]
    public partial class Feed
    {
        public Feed()
        {
            this.Created = System.DateTime.Now;
        }
    }
</pre>
<p>Then specify the DataAnnotations Metadata in the associated class: </p>
<pre class="brush: csharp">

public class FeedMetadata
    {
        [Display(Name=&quot;Feed (RSS) Url&quot;, Prompt=&quot;Enter a URL&quot;), DataType(DataType.Url, ErrorMessage = &quot;Invalid URL (try including the http://)&quot;), Required(ErrorMessage = &quot;Url is a required field&quot;),
        RegularExpression(&quot;^(http)\\://[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\\-\\._\\?\\,\\&#039;/\\\\\\+&amp;amp;amp;amp;amp;amp;amp;%\\$#\\=~])*$&quot;, ErrorMessage = &quot;Must be in the form &#039;http://&#039; and be a valid URL&quot;)]     

        public string Url { get; set; }

    }
</pre>
<p>So now we get to the meat of the post. Once the feed was loaded I needed to map to the SyndicationFeed object my Entity Framework Feed object and it made sense to use AutoMapper for this purpose. AutoMapper is very smart and can almost intuitively map your objects based on property name. </p>
<p>The feed items are loaded into SyndicationItem objects which have a Content property. Unfortunately in RSS2.0 there&#8217;s no such property. Here&#8217;s what the XML looks like: </p>
<pre class="brush: xml">
&lt;item&gt;
....
&lt;description&gt;&lt;![CDATA[Summary content...]]&gt;&lt;/description&gt;
&lt;content:encoded&gt;&lt;![CDATA[&lt;p&gt; Actual content here &lt;/p&gt;]]&lt;/content:encoded&gt;
...
&lt;/item&gt;
</pre>
<p>Notice the Content is actually an RSS extension, within the namespace of &#8220;http://purl.org/rss/1.0/modules/content&#8221;, so how to map this using Automapper?<br />
To access the extensions use the &#8220;ReadElementExtensions&#8221; generic on the ElementExtensions collection. Once I figured that out I could build the map like this: </p>
<pre class="brush: csharp">

Mapper.CreateMap&lt;SyndicationItem, Item&gt;()
   .ForMember(dest =&gt; dest.Content,
      opt =&gt; opt.MapFrom(
         src =&gt; src.ElementExtensions
            .ReadElementExtensions&lt;string&gt;(&quot;encoded&quot;, &quot;http://purl.org/rss/1.0/modules/content/&quot;).FirstOrDefault()));
                    Mapper.CreateMap&lt;SyndicationFeed, Feed&gt;();

Mapper.Map(sourceFeed, dbFeed);
</pre>
<p>So this is pretty clean, Entity Framework combined with AutoMapper and native .NET 4.0 Syndication Assemblies. </p>
<p>I tried Googling and looks like a number of folks have trouble even accessing the <strong>content:encoded</strong> element of the RSS so hopefully this post will help those folks as well as folks looking to setup a slightly complex map in AutoMapper. </p>
<p>Happy New Year!</p>
<p>* Bug picture from John Hallmen at <a href="http://www.morfa.se/">http://www.morfa.se/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2010/rss-syndicationitem-entity-framework-automapper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solving the Traveling Salesman Problem with Genetic Algorithms and HTML5 Web Workers</title>
		<link>http://francisshanahan.com/index.php/2010/html5-workers-genetic-algorithm-traveling-salesman-problem/</link>
		<comments>http://francisshanahan.com/index.php/2010/html5-workers-genetic-algorithm-traveling-salesman-problem/#comments</comments>
		<pubDate>Sun, 10 Oct 2010 01:51:00 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Cool & Future Tech]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[Things I've Made]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Web Experiments]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=2912</guid>
		<description><![CDATA[Irreducible Complexity &#8211; the world is too complex to have evolved!  Let&#8217;s see&#8230;
HTML5 introduces the ability to perform multi-threading in the browser using Javascript through the notion of &#8220;Web Workers&#8221;. So far I have only seen examples of using workers to calculate very high prime numbers. I took a fresh look at these from the standpoint of genetic algorithms and applied it to the Traveling Salesman Problem (a classic). The results are a multi-threaded implementation of the TSP in Javascript capable of converging on a solution for up to 200 ...]]></description>
			<content:encoded><![CDATA[<p>Irreducible Complexity &#8211; the world is too complex to have evolved!  Let&#8217;s see&#8230;</p>
<p>HTML5 introduces the ability to perform multi-threading in the browser using Javascript through the notion of &#8220;Web Workers&#8221;. So far I have only seen examples of using workers to calculate very high prime numbers. I took a fresh look at these from the standpoint of genetic algorithms and applied it to the Traveling Salesman Problem (a classic). The results are a multi-threaded implementation of the TSP in Javascript capable of converging on a solution for up to 200 cities, all with a zero-footprint.</p>
<p>This project was born on a plane over the Atlantic last week. With such a long title to this post I thought about breaking it up into multiple posts but got lazy and figured if you&#8217;re on this site to begin with, chances are you&#8217;re familiar with all these concepts already so here goes.</p>
<p>First a refresher:</p>
<blockquote><p>The <strong>Travelling Salesman Problem</strong> (<strong>TSP</strong>) is an <a title="NP-hard" href="http://en.wikipedia.org/wiki/NP-hard">NP-hard</a> problem in combinatorial optimization studied in operations research and theoretical computer science. Given a list of cities and their pairwise distances, the task is to find a shortest possible tour that visits each city exactly once.</p>
<p>The most direct solution would be to try all permutations (ordered combinations) and see which one is cheapest (using brute force search). The running time for this approach lies within a polynomial factor of <em>O</em>(<em>n</em>!), the factorial of the number of cities, so this solution becomes impractical even for only 20 cities.</p>
<p><a href="http://en.wikipedia.org/wiki/Travelling_salesman_problem">http://en.wikipedia.org/wiki/Travelling_salesman_problem</a></p></blockquote>
<p>Instead of Brute Force I will try to converge on the solution using a genetic algorithm.</p>
<p>At this point you may want to flip to the finished project using<strong> CHROME 7+ or Firefox 4+ or Opera 10+</strong></p>
<p><a href="http://francisshanahan.com/tsa/tsaGAworkers.htm" target="_blank">http://francisshanahan.com/tsa/tsaGAworkers.htm</a></p>
<p>Genetic algorithms are those which can be said to exhibit the characteristics of evolution, i.e. a coded sequence, mutation, a fit function and iterative progression. The typical flow is as follows:</p>
<ol>
<li>Develop a sequence of instructions (the DNA)</li>
<li>Develop a large number of these sequences (the population). In the code I called these &#8220;strands&#8221;.</li>
<li>Score the population for fitness.</li>
<li>Sort by fitness score and select the top-performers.</li>
<li>Generate a new population based off the top-performers.</li>
<li>Modify or mutate this new population and repeat the process with this new generation.</li>
</ol>
<p>Over time the population will tend to converge on a solution. This is a genetic algorithm and it&#8217;s not guaranteed to give the absolute best solution. As you can guess the rate at which the population converges on the best solution is determined by a number of factors:</p>
<ol>
<li>Population Size</li>
<li>Population diversity</li>
<li>Mutation Rate</li>
<li>Fitness Function</li>
<li>The number of generations</li>
<li>The number of &#8220;parents&#8221; selected to breed from.</li>
</ol>
<p>A closely related process is that of &#8220;Hill Climbing&#8221;. Hill Climbing I would say is more deterministic (less probabilistic). A typical hill climbing algorithm is as follows:</p>
<ol>
<li>Develop a sequence of instructions (the DNA)</li>
<li>Score the solution for fitness.</li>
<li>Modify or mutate this solution and score.</li>
<li>If the child is better than the parent it becomes the new parent.</li>
<li>Repeat the process (go back to step #2).</li>
</ol>
<p>So what&#8217;s the difference? Well for one, with hill climbing we only ever advance if the new descendant is better than the current solution. With each generation you always converge. With a Genetic Algorithm you advance regardless and hope for convergence over time. Convergence in a GA is not assured.</p>
<p>A more subtle difference is that the Hill Climbing algorithm is fixed on a specific path. It always chooses a better solution, even though there is a chance that this vector will not ultimately result in the absolute solution. However in a GA, the algorithm chooses a set of &#8220;good&#8221; solutions to breed from, and hence includes the possibility that a current inferior solution might ultimately lead to a better absolute solution overall.</p>
<p>This GA approach mimics real evolution much more closely. It allows for the possibility that a currently superior branch might die off and yield to a currently inferior solution. I think of this as more of a &#8220;strategic&#8221; solution than a &#8220;tactical&#8221; hill climbing solution.</p>
<p>Applying GA to the Traveling Salesman Problem I ended up with this:</p>
<ol>
<li>I create a set of random cities within a specific area.</li>
<li>Then I create a route through all cities (dna in the source code).</li>
<li>Then I score the route by calculating the overall length of the route.  A score + dna = a single strand.</li>
<li>Then I create a population of these strands.</li>
<li>I sort by fitness score and select the 5 best regardless of score.</li>
<li>I create a new generation based on these 5, mutating approximately 80% of the time.</li>
<li>A mutation is basically swapping two cities at random. There is no intelligence to the mutation.</li>
<li>Score this new generation and repeat the process (go back to step 5).</li>
</ol>
<p>This works nicely and is pretty trivial code in Javascript involving a little bit of math and a lot of array copies. In order to get decent results for a problem space of 100 cities or more it&#8217;s necessary to to repeat this process for at least 20-50 generations at a time. All processing is sequential and the browser hangs up whilst this is going on. To achieve solutions to a higher number of cities some other means of processing is needed.</p>
<p>Enter web workers.</p>
<p>Web Workers are new in HTML5 and in a nutshell they allow you to execute Javascript in a separate thread (in parallel) from the current browser thread. So far Chrome, Opera, Firefox have all implemented web workers. ). I&#8217;m not going to explain the basics of workers here as Mozilla has an EXCELLENT explanation of how to get started here: <a href="https://developer.mozilla.org/En/Using_web_workers">https://developer.mozilla.org/En/Using_web_workers</a></p>
<p>I&#8217;m using them as follows:</p>
<ol>
<li>Create a large population of possible solutions (my solution uses 1000)</li>
<li>Create a number of workers, my solution uses 10.</li>
<li>Split up the population across the workers, giving each 100 solutions to work on.</li>
<li>Mutate and score each one within the worker (10 threads operating in parallel).</li>
<li>Join back and Collect the results.</li>
<li>Sort the entire population and repeat.</li>
</ol>
<p>Couple of advantages here are that not only do we get parallel execution and finish processing quicker, we don&#8217;t hang up the UI thread so the browser remains responsive throughout.</p>
<p>Web Workers are great for processing but little else. They cannot access the DOM, the cannot generate page events, they cannot do much of anything. What they can do is receive information from the parent page, process information and send it back. This information is limited to strings. You can serialize your objects to a json string and then do an eval on the worker side but this ultimately will be done for you by the browser. So far only Firefox and Opera are capable of serializing JSON objects between the page and the worker thread. Hence the example solution only works in these browsers.</p>
<p>A couple of things I noticed in working with this approach.</p>
<ol>
<li>A larger population does not always guarantee a better solution. There is a balance for any given problem space and fitness function.</li>
<li>Mutation rate: You cannot simply change EVERYthing on each generation. You must maintain some of the core DNA in order to improve. Otherwise the solution is too random and does not converge.</li>
<li>Similarly, too little mutation and the solution converges too slowly.</li>
<li>Number of Breeders &#8211; you would think breeding from the single-best solution at any given point would be ideal. Surprisingly the system did better when a higher number, say 10% of the population is used to breed from. Too many and again you don&#8217;t converge. Too few and the system can be boxed into a dead-end solution ala the Hill Climbing approach.</li>
</ol>
<p>The key thing to remember is at no point have I written an algorithm to find the shortest distance. I&#8217;ve simply put pieces together in a closed system, assigned probabilities and set the thing in motion. Even still it&#8217;s pretty fascinating.</p>
<p><img class="alignleft" src="http://francisshanahan.com/tsa/tsp.png" alt="50 cities, 1000 generations" width="297" height="293" />Over the course of the past week I&#8217;ve run this thing many times. It&#8217;s the type of thing I can waste hours with. I tried various combinations of mutation rate, population size etc to get the right balance. Initially the system did not converge at all. Then I found it would converge but very quickly plateau and run out of ideas so to speak. Amping up the mutation fixed this but negatively impacted convergence, so I tweaked the number of breeders a little. Back and forth until I got it to where it is today. It&#8217;s fun to watch the code try to figure out new pathways, occasionally it&#8217;ll drop a segment in favour of a different route, only to bring that same piece back in later.  This is where my knowledge of GA falls short. I&#8217;m not sure I&#8217;ve gotten it right and to take it any further would require some heavy duty research. It&#8217;ll suffice for now.</p>
<p>This is a crude system with only 1 test for fitness and no competing goals. Imagine scaling this up to &#8220;earth&#8221; scale with billions of competing factors, each of varying weights, trillions of instructions per individual,  3.5 billion years of evolution and a system that feeds BACK on itself, altering the fitness functions as it goes. The possibilities are astounding.</p>
<p>As you can tell I had a lot of fun with this one. Genetic algorithms are a powerful concept, particularly when dealing with difficult to solve problems (e.g.  NP-hard). The outcome is highly probabilistic and how the algorithm progresses essentially mimics our own progression as life on planet earth. Too cool.</p>
<p>Now flip to the finished project using<strong> CHROME 7+ or Firefox 4+ or Opera 10+</strong></p>
<p><a href="http://francisshanahan.com/tsa/tsaGAworkers.htm" target="_blank">http://francisshanahan.com/tsa/tsaGAworkers.htm</a></p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2010/html5-workers-genetic-algorithm-traveling-salesman-problem/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Create CSS Rules from an HTML5 Canvas</title>
		<link>http://francisshanahan.com/index.php/2010/create-css-rules-from-an-html5-canvas/</link>
		<comments>http://francisshanahan.com/index.php/2010/create-css-rules-from-an-html5-canvas/#comments</comments>
		<pubDate>Sun, 25 Jul 2010 00:23:32 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Cool & Future Tech]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[Web Experiments]]></category>
		<category><![CDATA[css3]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=2687</guid>
		<description><![CDATA[Here I show how you can re-use your Canvas images as CSS backgrounds using another interesting feature coming in HTML5. You'll need a browser supporting CSS3 and Canvas, Chrome, Opera, Safari or Firefox will do. ]]></description>
			<content:encoded><![CDATA[<p>This thing caught me off guard but then I tried it, it worked so here it is: You&#8217;ll need a browser supporting CSS3 and Canvas for this post to make any sense. I tested with Chrome &amp; Firefox.</p>
<p>What&#8217;s the difference between the two blocks below?<br />
Answer: One&#8217;s a canvas and the other are div tags.<br />
<canvas id="canvas" width="120" height="120"></canvas></p>
<div id="box">
<div style="-webkit-transform: rotate(-10deg); -moz-transform: rotate(-10deg); transform: rotate(-10deg);">Hello</div>
<div style="-webkit-transform: rotate(15deg); -moz-transform: rotate(15deg); transform: rotate(15deg);">Canvas</div>
<div style="-webkit-transform: rotate(-4deg); -moz-transform: rotate(-4deg); transform: rotate(-4deg);">World</div>
<div style="-webkit-transform: rotate(8deg); -moz-transform: rotate(8deg); transform: rotate(8deg);">Que pasa?</div>
</div>
<p><script src="/js/dynamiccss.js" type="text/javascript">
</script><br />
<br/><br/><br/><br/><br/><br />
This might not seem that interesting at first so here&#8217;s the interesting bit: The Div&#8217;s background is actually taken from the Canvas. There&#8217;s only one Canvas on the page so how&#8217;s that working?<br />
Answer: A CSS class is dynamically created with its background set to the base64 output of the Canvas!</p>
<p>Yes, you can get the base64 encoding of any canvas element using canvas.toDataURL().</p>
<pre class="brush: javascript">
var base64 = canvas.toDataURL(&quot;image/png&quot;);
</pre>
<p>This was news to me but the connection was that the base64 data can then be used in a new CSS rule to with the data being the background, just like you&#8217;d do with a tiny image.</p>
<p>* Side note: It&#8217;s common to base64 encode images and directly embed them into the CSS file provided they are small enough. Base64 encoding is typically 33% larger than the binary data but you save the HTTP request. If you Sprite your images into one big file it&#8217;s less of a savings. Again, all things in engineering are a balance/compromise so do what makes sense for your situation. </p>
<pre class="brush: javascript">
var newClass = &quot;.newClass{  background:url(&quot;+base64+&quot;);} &quot;;
$(&quot;&lt;style type=&#039;text/css&#039;&gt;&quot;+size + newClass + &quot;&lt;/style&gt;&quot;).appendTo(&quot;head&quot;);
</pre>
<p>I then rotated the divs with CSS3 just for kicks. </p>
<pre class="brush: javascript">
&lt;div style=&quot;-webkit-transform: rotate(-10deg); -moz-transform: rotate(-10deg); transform: rotate(-10deg);&quot;&gt;Hello&lt;/div&gt;
</pre>
<p>Here&#8217;s the relevant code all in one piece: </p>
<pre class="brush: javascript">

// grab the data
var base64 = canvas.toDataURL(&quot;image/png&quot;);

var newClass = &quot;.newClass{  background:url(&quot;+base64+&quot;);} &quot;;

$(&quot;&lt;style type=&#039;text/css&#039;&gt;&quot; + newClass +&quot;&lt;/style&gt;&quot;).appendTo(&quot;head&quot;);

$(&#039;#box div&#039;).addClass(&quot;newClass&quot;);
</pre>
<p>So why would you ever do this? I suppose you might do this to avoid creating a lot of smaller canvas tags. I haven&#8217;t checked but I&#8217;d wager the overhead for a canvas is higher than that of a CSS rule. You can create one canvas image and then use it all over the place with CSS. </p>
<p>You could implement rounded corners with this but it&#8217;s probably the most complex way of doing rounded corners ever so wouldn&#8217;t recommend it there either. </p>
<p>One possible use of this is to take a copy of an image as it&#8217;s being built. E.g. Canvas images are bitmaps and there&#8217;s no &#8220;undo&#8221;. Unlike SVG, they don&#8217;t modify the DOM so you can&#8217;t add and remove elements of the image. Imagine a graph built using Canvas, if the user modifies the graph it might be useful to take a copy of it before the modification. You could do this by dumping the base64 data and displaying as a CSS image, rather than creating a 2nd canvas element. I&#8217;m reaching here but you get the idea. </p>
<p>I&#8217;m not sure this will ever have a practical application. For now it&#8217;s just an interesting tech experiment and another example of the cool stuff possible with HTML5. </p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2010/create-css-rules-from-an-html5-canvas/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Identicon5 – Identicons using HTML5 Canvas &amp; JQuery</title>
		<link>http://francisshanahan.com/index.php/2010/html5-identicons-using-canvas-jquery-plugin/</link>
		<comments>http://francisshanahan.com/index.php/2010/html5-identicons-using-canvas-jquery-plugin/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 22:30:31 +0000</pubDate>
		<dc:creator>Francis</dc:creator>
				<category><![CDATA[Cool & Future Tech]]></category>
		<category><![CDATA[Featured]]></category>
		<category><![CDATA[Headline]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Web Experiments]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://francisshanahan.com/?p=2656</guid>
		<description><![CDATA[What do you get when you combine Digital Identity, MD5 Hashes, the Canvas element, JQuery and Quilting? Answer: My first JQuery plugin &#8211; &#8220;Identicon5&#8243; for want of a better name.
Identicon5 is a JQuery plugin that takes an MD5 hash and  converts it to a unique image. It&#8217;s called Identicon5 since it works  through the HTML5 Canvas element.
Working Demo is here: http://francisshanahan.com/identicon5/test.html
Project page is here: http://francisshanahan.com/index.php/identicon5
JQuery Plugin page is here: http://plugins.jquery.com/project/identicon5
Identicons provide a nice visual representation of a user&#8217;s identity,  that&#8217;s unique to that user, without divulging any ...]]></description>
			<content:encoded><![CDATA[<p>What do you get when you combine Digital Identity, MD5 Hashes, the Canvas element, JQuery and Quilting? Answer: My first JQuery plugin &#8211; &#8220;Identicon5&#8243; for want of a better name.</p>
<p><strong>Identicon5</strong> is a JQuery plugin that takes an MD5 hash and  converts it to a unique image. It&#8217;s called Identicon5 since it works  through the HTML5 Canvas element.</p>
<p><strong>Working Demo is here: </strong><a href="http://francisshanahan.com/identicon5/test.html" target="_blank">http://francisshanahan.com/identicon5/test.html</a></p>
<p>Project page is here: <a href="http://francisshanahan.com/index.php/identicon5" target="_blank">http://francisshanahan.com/index.php/identicon5</a></p>
<p>JQuery Plugin page is here: <a href="http://plugins.jquery.com/project/identicon5" target="_blank">http://plugins.jquery.com/project/identicon5</a></p>
<p>Identicons provide a nice visual representation of a user&#8217;s identity,  that&#8217;s unique to that user, without divulging any private information. You&#8217;ve probably seen them in use on many social websites e.g. <a href="http://stackoverflow.com/" target="_blank">http://stackoverflow.com</a></p>
<p>Identicons are the little geometrical profile images for certain users. Normally Gravatar.com serves up an image based off the MD5 hash of your email address. If you&#8217;ve defined a profile image it&#8217;ll serve that but if not it&#8217;ll show your Identicon, this blog itself is Gravatar enabled as are most WordPress installations.</p>
<p>EXCERPT from Wikipedia</p>
<blockquote><p>An Identicon is a visual representation of a hash value, usually of the IP address, serving to identify a user of a computer system. The original Identicon is a 9-block graphic, which has been extended to other graphic forms by third parties some of whom have used MD5 instead of the IP address as the identifier. In summary, an Identicon is a privacy protecting derivative of each user&#8217;s IP address built into a 9-block image and displayed next the user&#8217;s name.</p>
<p>A visual representation is thought to be easier to compare than one which uses only numbers and more importantly, it maintains the person&#8217;s privacy.</p>
<p>The Identicon graphic is unique since it&#8217;s based on the users IP, but it is not possible to recover the IP by looking at the Identicon.</p></blockquote>
<p>If you have page with a lot of Users listed, either because there are a lot of contributors on the thread, you might end up with a lot of Identicon image links. Each image is small, about 1kb and carries an HTTP connection as additional overhead. This isn&#8217;t really a big problem given today&#8217;s bandwidth on the Desktop but on my Droid it becomes an issue. Besides, with HTML5 we can do better.</p>
<p>Identicon5 takes the same MD5 hash value and draws the image dynamically using a Canvas element within the browser. This eliminates the HTTP call and saves you 1kb per profile image. If Canvas is not supported it&#8217;ll degrade into a standard img tag linking to Gravatar.</p>
<p>How does Quilting enter into it? Don Parks came up with the notion of using small tiles, arranged in a 3&#215;3 grid per Identicon. The process uses a selection of smaller shapes in each 3&#215;3 grid square and either rotates it or colors it depending on the input value. This is essentially how quilts have been made for hundreds of years.</p>
<p>I&#8217;m sure this won&#8217;t be the most popular jQuery plugin ever but the idea of applying newer technologies such as HTML5 Canvas to solve a problem that would traditionally have been fixed with a network call was very interesting to me so just had to hack it together.</p>
<p>This is a very tangible example of how HTML5 will make the web more scalable.</p>
]]></content:encoded>
			<wfw:commentRss>http://francisshanahan.com/index.php/2010/html5-identicons-using-canvas-jquery-plugin/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

