<?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/"
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>I'm pretty sure that's what I mean</title>
	<atom:link href="http://whatimean.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://whatimean.wordpress.com</link>
	<description>Mostly work-related technical ramblings</description>
	<lastBuildDate>Fri, 23 Oct 2009 16:55:20 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='whatimean.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/6d3d033144affa9e95d3d29a9a24ceae?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>I'm pretty sure that's what I mean</title>
		<link>http://whatimean.wordpress.com</link>
	</image>
			<item>
		<title>Finding All the Paths In a Graph With Haskell</title>
		<link>http://whatimean.wordpress.com/2009/10/21/finding-all-the-paths-in-a-graph-with-haskell/</link>
		<comments>http://whatimean.wordpress.com/2009/10/21/finding-all-the-paths-in-a-graph-with-haskell/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 17:22:58 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[graph theory]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=108</guid>
		<description><![CDATA[Here&#8217;s an interesting problem&#8230;

Given an undirected graph, find all the paths (not just the shortest) between two nodes that are less than some given length.


I decided to attack this problem using Haskell.  Simply because I&#8217;ve been trying to get to grips with the language and felt that this was a nice &#8220;real&#8221; problem for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=108&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h3>Here&#8217;s an interesting problem&#8230;</h3>
<p>
Given an undirected graph, find <em>all</em> the paths (not just the shortest) between two nodes that are less than some given length.
</p>
<p>
I decided to attack this problem using Haskell.  Simply because I&#8217;ve been trying to get to grips with the language and felt that this was a nice &#8220;real&#8221; problem for me to practice my fledgling skills on.  I&#8217;ve chosen to model a graph as a list of edges which are described as a simple pair (see the end of the following source code).  I have therefore made the following assumptions in the code;
</p>
<ul>
<li>An entry in the list <font face="courier">(&#8216;a&#8217;,'b&#8217;)</font> explicitly states that an edge exists between the nodes &#8216;a&#8217; and &#8216;b&#8217; and further this implies that the edge <font face="courier">(&#8216;b&#8217;,'a&#8217;)</font> exists since the graph is undirected.</li>
<li>An entry <font face="courier">(&#8216;a&#8217;,'a&#8217;)</font> implies that a node &#8216;a&#8217; exists that does not have any edges, rather than an edge exists that self-references the node &#8216;a&#8217;.  Nodes are not allowed to have edges to themselves.</li>
</ul>
<p>
The following code does work, and returns the correct number of paths given my test data and the requests I make of it.  I can&#8217;t escape the feeling, though, that my Haskell could be made more simple and efficient.  I just don&#8217;t know Haskell well enough yet to work out how!
</p>
<h3>The Solution</h3>
<p><em>Edit 1:  code to apply Hlint comments</p>
<ul>
<li>Only HLint error: use of &#8220;not (elem &#8230;)&#8221; rather than &#8220;notElem &#8230;&#8221; has been fixed</li>
<li>HLint warning: use of &#8220;[p] ++ (some list)&#8221; rather than &#8220;p : (some list&#8221; has been fixed</li>
<li>HLint warning: unnecessary parenthesis used in a few places, most of these have been fixed</li>
</ul>
<p></em></p>
<p><em>Edit 2: corrected some cut and paste mistakes</em></p>
<p><code><br />
import Data.List</p>
<p>-- finds all the paths with length &lt;= l from u to v in g<br />
findAllPathsTo l u v g<br />
&nbsp;&nbsp;&nbsp;&nbsp;= filter endsAt (findAllPaths l u g)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;endsAt ps = (last ps) == v</p>
<p>-- finds all the paths with length  &gt;= l from u in g<br />
findAllPaths l n g<br />
&nbsp;&nbsp;&nbsp;&nbsp;| notElem n (allNodes g) = []<br />
&nbsp;&nbsp;&nbsp;&nbsp;| otherwise&nbsp;&nbsp;= allPaths' l g [[n]]</p>
<p>-------------------------------------------------------------------------------<br />
-- Supporting functions below<br />
-------------------------------------------------------------------------------</p>
<p>appendNeighboursToPath l p g<br />
&nbsp;&nbsp;&nbsp;&nbsp;= append ns p<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ns = neighbours n g<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;n = last p<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;append [] _  = []<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;append (n:ns) p = flatten (appendToAll l [p] n) : append ns p</p>
<p>neighbours a g<br />
&nbsp;&nbsp;&nbsp;&nbsp;= reverse (foldl step [] g)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where step acc (u,v)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| u == a&nbsp;&nbsp;&nbsp;&nbsp;= v : acc<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| v == a&nbsp;&nbsp;&nbsp;&nbsp;= u : acc<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| otherwise&nbsp;= acc</p>
<p>allNodes                     :: (Eq a) =&gt; [(a,a)] -&gt; [a]<br />
allNodes []                    = []<br />
allNodes [(u,v)]            = [u,v]<br />
allNodes ((u,v):gs)        = nub (u : v : allNodes gs) </p>
<p>allPaths' l g acc<br />
&nbsp;&nbsp;&nbsp;&nbsp;| length acc == length paths&nbsp;= acc<br />
&nbsp;&nbsp;&nbsp;&nbsp;| otherwise&nbsp;= allPaths' l g (nub (acc ++ paths))<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;paths = nub (appendNeighboursToPaths l acc g)</p>
<p>appendNeighboursToPaths l [] _ = []<br />
appendNeighboursToPaths l  (p:ps) g<br />
&nbsp;&nbsp;&nbsp;&nbsp;= p : nub (appendNeighboursToPath l p g ++ appendNeighboursToPaths l ps g)</p>
<p>appendToAll l [] _	= []<br />
appendToAll l (x:xs) y	= maybeAdded : appendToAll l xs y<br />
&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;maybeAdded&nbsp;&nbsp;| elem y x = x<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| length (x) &gt; (l-1) = x<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| otherwise	= x ++ [y]</p>
<p>flatten = foldl (++) []</p>
<p>-------------------------------------------------------------------------------<br />
-- Test code below<br />
-------------------------------------------------------------------------------</p>
<p>test=do putStr "\n"<br />
	putStr "Simple tests to check return length of path lists\n"<br />
	putStr "1  == length (findAllPaths 100 'a' g0)?  " ;<br />
		print (1 == length (findAllPaths 100 'a' g0))<br />
	putStr "5  == length (findAllPaths 100 'a' g1)?  " ;<br />
		print (5 == length (findAllPaths 100 'a' g1))<br />
	putStr "9  == length (findAllPaths 100 'a' g2)?  " ;<br />
		print (9 == length (findAllPaths 100 'a' g2))<br />
	putStr "9  == length (findAllPaths 100 'a' g3)?  " ;<br />
		print (9 == length (findAllPaths 100 'a' g3))<br />
	putStr "4  == length (findAllPaths 100 'a' g4)?  " ;<br />
		print (4 == length (findAllPaths 100 'a' g4))<br />
	putStr "21 == length (findAllPaths 100 'a' g5)?  " ;<br />
		print (21 == length (findAllPaths 100 'a' g5))<br />
	putStr "\n"<br />
	putStr "2 == length (findAllPathsTo 100 'a' 'f' g5)? " ;<br />
		print (2 == length (findAllPathsTo 100 'a' 'f' g5))<br />
	putStr "1 == length (findAllPathsTo 6 'a' 'f' g5)?   " ;<br />
		print (1 == length (findAllPathsTo 6 'a' 'f' g5))<br />
	putStr "0 == length (findAllPathsTo 100 'a' 'z' g5)? " ;<br />
		print (0 == length (findAllPathsTo 100 'a' 'z' g5))<br />
	putStr "\n"<br />
	putStr "Has all paths  [\"abcdf\",\"abcjklmnf\"] in (findAllPathsTo 100 'a' 'f' g5)? " ;<br />
		print (checkSameContents (findAllPathsTo 100 'a' 'f' g5) ["abcdf","abcjklmnf"])<br />
	putStr "Has all paths  [\"abcdf\"] in (findAllPathsTo 6 'a' 'f' g5)?               " ;<br />
		print (checkSameContents (findAllPathsTo 6 'a' 'f' g5) ["abcdf"])</p>
<p>g0=[('a','a'),('b','b'),('c','c')]<br />
g1=[('a','b'),('b','c'),('c','d'),('d','e')]<br />
g2=[('a','b'),('b','c'),('c','d'),('c','e'),('d','f'),('e','f')]<br />
g3=[('a','b'),('b','c'),('c','d'),('c','e'),('d','f'),('e','g'),('g','h'),('h','i')]<br />
g4=[('a','b'),('b','c'),('b','d')]<br />
g5=[('a','b'),('b','c'),('c','d'),('c','e'),('d','f'),('e','g'),('g','h'),('h','i'),('c','j'),('j','k'),('k','l'),('l','m'),('m','n'),('n','f')]</p>
<p>checkSameContents&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:: (Eq a) =&gt; [a] -&gt; [a] -&gt; Bool<br />
checkSameContents a b<br />
&nbsp;&nbsp;&nbsp;&nbsp;= (length a == length b) &amp;&amp; (length b) == (length (takeWhile f a))<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f x = elem x b</p>
<p></code></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/108/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=108&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2009/10/21/finding-all-the-paths-in-a-graph-with-haskell/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Playing with Servos and SUN SPOTS</title>
		<link>http://whatimean.wordpress.com/2009/09/07/playing-with-servos-and-sun-spots/</link>
		<comments>http://whatimean.wordpress.com/2009/09/07/playing-with-servos-and-sun-spots/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 14:06:06 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Sun SPOT]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Servo]]></category>
		<category><![CDATA[SUNSPOTS]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=99</guid>
		<description><![CDATA[Introduction

I&#8217;ve managed to find some time recently to get playing with my SUN SPOTs again, so I figured I&#8217;d start by wiring up one of the servos from my ancient remote control cars to it.  Although, there seems to be a lot of information about doing this on the web (mostly the wiring diagrams) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=99&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Introduction</h2>
<p>
I&#8217;ve managed to find some time recently to get playing with my SUN SPOTs again, so I figured I&#8217;d start by wiring up one of the servos from my ancient remote control cars to it.  Although, there seems to be a lot of information about doing this on the web (mostly the wiring diagrams) I hit a snag with getting the full motion range out of my servo.  So I figured I&#8217;d put something up here in case anyone else encounters the same.
</p>
<h2>Scenario</h2>
<p>
To control my servo I wrote a very quick GUI that allowed me to send float values through the connected base station to the free range SUN SPOT.  That SPOT was wired up to a battery pack and servo and the servo moved when I hit the GUIs button.  Simple, but a nice first step.
</p>
<h2>The Setup</h2>
<p>
I mostly copied the wiring of the servos from <a href="http://fantastickobe.blogspot.com/2008/05/servo-car-sun-spot-app-3.html">&#8220;Fantastic Kobe&#8221;</a> and this <a href="http://blogs.sun.com/davidgs/entry/how_to_attach_servo_motors">offical SUN blog</a>.  There&#8217;s not a lot to the wiring, as you can see from this picture.
</p>
<div id="attachment_100" class="wp-caption aligncenter" style="width: 460px"><img src="http://whatimean.files.wordpress.com/2009/09/imgp3485.jpg?w=450&#038;h=337" alt="Shows the wiring from the battery pack and SUNSPOT to the Servo" title="Servo Wiring" width="450" height="337" class="size-full wp-image-100" /><p class="wp-caption-text">Shows the wiring from the battery pack and SUNSPOT to the Servo</p></div>
<p>
I not going to go into detail about what connects where, because that information can easily be found on either of the above two links.
</p>
<h3>Setting the Servo Bounds</h3>
<p>
One of the things I found was using the <font face="courier">setPosition(float p)</font> method on <font face="courier">Servo</font> wasn&#8217;t giving me the full range of motion.  To fix this you need to set the bounds of your particular servo.  I didn&#8217;t know the &#8216;correct&#8217; way to do this, so instead I went with a trial-and-error approach.
</p>
<p><code>    private int servoPin = EDemoBoard.H1;</p>
<p>    private void initServo() {<br />
        servo = new Servo(EDemoBoard.getInstance().getOutputPins()[servoPin]);<br />
//        for(int i=250; i&lt;2300; i+=10) {<br />
//            servo.setValue(i);<br />
//            out(&quot;value=&quot;+i);<br />
//            Utils.sleep(100);<br />
//        }<br />
        servo.setBounds(250, 2300);<br />
    }</code></p>
<p>
In the above code, the starting value of &#8220;i&#8221; was originally zero and the end value was 10000.  Then, by using changing these values so that when <font face="courier">initServo()</font> was called the servo didn&#8217;t groan in protect, I was able to set the bounds as shown.  Having done that, <font face="courier">servo.setValue(0.5);</font> puts the servo in the middle as expected.  With values of 0 and 1.0 taking the servo to its extremes.
</p>
<p>
I expect that most people&#8217;s servos are going to be different.  Mine is a Futaba FP-S148.  And now I can move a servo around, I can start to do something useful (or at least fun) with it!
</p>
<h2>The Code (Free Range SPOT)</h2>
<p>There is only one class in the application that sits on the free range SPOT.<br />
<code>import java.io.IOException;</p>
<p>import javax.microedition.io.Connector;<br />
import javax.microedition.io.Datagram;<br />
import javax.microedition.io.DatagramConnection;<br />
import javax.microedition.midlet.MIDlet;<br />
import javax.microedition.midlet.MIDletStateChangeException;<br />
import com.sun.spot.sensorboard.EDemoBoard;<br />
import com.sun.spot.sensorboard.peripheral.Servo;</p>
<p>public class MainApplication extends MIDlet {<br />
&nbsp;&nbsp;&nbsp;&nbsp;private final String BASE_STATION_ID = "0014.4F01.0000.103E";</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private int servoPin = EDemoBoard.H1;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private Servo servo;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private DatagramConnection toBaseStation = null;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;protected void destroyApp(boolean arg0) throws MIDletStateChangeException {}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;protected void pauseApp() {}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;protected void startApp() throws MIDletStateChangeException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;initComms();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;initServo();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void initComms() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;toBaseStation = (DatagramConnection) Connector.open("radiogram://" + BASE_STATION_ID + ":100");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;startListenerThread();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (IOException ex) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out("EXCEPTION: "+ex.getMessage());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void initServo() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;servo = new Servo(EDemoBoard.getInstance().getOutputPins()[servoPin]);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;servo.setBounds(250, 2300);<br />
//        for(int i=200; i&lt;2300; i+=10) {<br />
//            servo.setValue(i);<br />
//            out(&quot;value=&quot;+i);<br />
//            Utils.sleep(100);<br />
//        }<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void startListenerThread() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Thread t = new Thread(new Runnable() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;public void run() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while(true) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;listenForMessage();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;});<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.start();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void listenForMessage() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Datagram dgIn = null;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dgIn = toBaseStation.newDatagram(toBaseStation.getMaximumLength());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;toBaseStation.receive(dgIn);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleMessage(dgIn.readUTF());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (IOException ex) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out(&quot;EXCEPTION LISTENING: &quot;+ex.getMessage());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ex.printStackTrace();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void handleMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out(&quot;NEW MESSAGE [&quot;+message+&quot;]&quot;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(message.startsWith(&quot;SERVO:&quot;)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleServoMessage(message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleUnknownMessage(message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void handleUnknownMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out(&quot;UnknownMessage [&quot;+message+&quot;]&quot;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendMessage(&quot;UNKNOWN MESSAGE [&quot;+message+&quot;]&quot;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void handleServoMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int cutAt = message.indexOf(&quot;:&quot;)+1;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String txtValue = message.substring(cutAt);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;float value = Float.valueOf(txtValue).floatValue();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(value  1.0) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendMessage("SERVO VALUE REJECTED.  OUT OF BOUNDS 0.0-1.0 ("+txtValue+")");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;servo.setPosition(value);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendMessage("SERVO: New Value Set="+servo.getValue());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (NumberFormatException nfe) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendMessage("SERVO VALUE REJECTED.  NOT A VALID FLOAT ("+txtValue+")");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void sendMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out("Sending: "+message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Datagram dgOut = null;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dgOut = toBaseStation.newDatagram(toBaseStation.getMaximumLength());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dgOut.writeUTF(message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;toBaseStation.send(dgOut);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (IOException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out("EXCEPTION SENDING TO BS: "+e.getMessage());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} finally {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(null != dgOut) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dgOut.reset();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void out(String msg) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(msg);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>}</code></p>
<h2>The Code (Base Station)</h2>
<p>
The code on the base station is simple enough, in fact too simple to warrent posting and spending the time formatting it here.  The only interesting bit is the following line which is one of the first lines in the <font face="courier">public static void main(String[] args)</font> method;
</p>
<p><code>OTACommandServer.getInstance().start();</code></p>
<p>
The rest of the code is either UI/Swing code or normal Java/SUN SPOT code.  In fact, the initComms, sendMessage, startListenerThread and listenForMessage methods are identical to those that run on the free range SPOT.  The only difference is the SPOT address that the DatagramConnection is opened with.  Obviously, on the free range SPOT it is opened with the address of the base station, and the reverse for the code on the base station.
</p>
<h2>Aside</h2>
<p>
Disclaimer: Obviously, soldering is dangerous to yourself and the components you&#8217;re working on/with.  Any damage or injury you sustain following this advice is entirely at your own risk and I accept no responsibilty for it.
</p>
<p>
&#8230;that being said; if you don&#8217;t have a decent breakout board for your SUN SPOTs (and you&#8217;re in the UK) then Maplin do some PCB socket connector things* that you can buy and solder into your SUN SPOT.  This gives you the ability to use bread board connector cables to easily connect up different sockets from the SUN SPOT without having to do any resoldering.  The soldering its self is a bit fiddly, so I recommend getting a decent magnifying glass and a soldering iron with a fine tip.  I&#8217;m definitely not the worlds best solder-er but I managed it okay.
</p>
<p>
* &#8211; I forget the actual name or catalogue reference, they&#8217;re pretty cheap (less than a pound I think) and are sold in rows of about 20 or so.  You just snap off two rows of 10 each and get on with it.</p>
<h2>Useful Links</h2>
<ul>
<li><a href="http://www.sunspotworld.com/docs/Purple/javadoc/index.html?com/sun/spot/sensorboard/peripheral/Servo.html">SUN SPOT API Doc</a></li>
</ul>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/99/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=99&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2009/09/07/playing-with-servos-and-sun-spots/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>

		<media:content url="http://whatimean.files.wordpress.com/2009/09/imgp3485.jpg" medium="image">
			<media:title type="html">Servo Wiring</media:title>
		</media:content>
	</item>
		<item>
		<title>Playing with the Sun SPOT Radio</title>
		<link>http://whatimean.wordpress.com/2008/12/18/playing-with-the-sun-spot-radio/</link>
		<comments>http://whatimean.wordpress.com/2008/12/18/playing-with-the-sun-spot-radio/#comments</comments>
		<pubDate>Thu, 18 Dec 2008 15:31:13 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Sun SPOT]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=72</guid>
		<description><![CDATA[I have recently been lucky enough to borrow a set of very cool Sun SPOTs, so I immediately began thinking of all the amazingly clever and brilliant things I could do with them.  However, with the exception of making the LEDs light up like a Cylon&#8217;s eyes (or Knightrider&#8217;s Kit as per your preference), [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=72&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I have recently been lucky enough to borrow a set of very cool <a href="http://www.sunspotworld.com/">Sun SPOTs</a>, so I immediately began thinking of all the amazingly clever and brilliant things I could do with them.  However, with the exception of making the LEDs light up like a Cylon&#8217;s eyes (or Knightrider&#8217;s Kit as per your preference), all my ideas required one spot to be able to talk to another.</p>
<p>So what I figured the first thing to do would be to create a simple way to do this.  Basically, each SPOT you want to talk to another instantiates a <font face="Courier">Buddy</font> object and asks it to look for another buddy (<font face="Courier">myBuddy.lookForPair()</font>) this will then start the buddy broadcasting and looking for a fellow.</p>
<p>It&#8217;s probably important to note at this point that I have <em>not</em> tested this code with more than two SPOTs, I certainly haven&#8217;t tested any edge cases where multiple SPOTs start up and all start looking for buddies on different ports.  This is code is for my own use, I&#8217;m very happy for anyone to download, modify and use it (it is GPL&#8217;d) as long as you remember that it only works for the nicest of use cases.</p>
<p>Once two buddies (on different SPOTs) have connected you can send a message from one to the other by typing;</p>
<pre class="brush: java;">
myBuddy.sendMessage(&quot;my message&quot;);
</pre>
<p>Recieved messages are handled by a <font face="Courier">BuddyListener</font> which your SPOT application should have given to it&#8217;s Buddy instance.  Recieved messages come in from the following method on that interface;</p>
<pre class="brush: java;">
void messageRecieved(String message);
</pre>
<p>There&#8217;s lots of ways this code could be improved, for example the initial broadcast port is hardcoded into the Buddy code itself, this should really be parameterised.  Also, the sleeps and waits that the Buddy endures while trying to connect to another one and so on.  These should probably be pulled out to fields so that they can be tweaked more easily.</p>
<p>The good thing about this code is that it makes paired communication very simple (although you do have to be careful with the threads that are listening to incoming messages).  You can also use your own language/protocol that the SPOTs will interpret on top of this Buddy mechanism very easily.</p>
<p><b>radio.Buddy</b> &#8211; This is the meat of the project.  To easily connect two SPOTs each must have an instance of one of these.  Once connected to each other sending and recieving messages between the two is very easy.</p>
<pre class="brush: java;">
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package radio;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;

import com.sun.spot.io.j2me.radiogram.RadiogramConnection;
import com.sun.spot.io.j2me.radiostream.RadiostreamConnection;
import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.util.IEEEAddress;
import com.sun.spot.util.Utils;
import com.sun.squawk.util.StringTokenizer;

public class Buddy {

	private static final String NEED_BUDDY = &quot;BUDDY_REQ&quot;;
	private static final String I_WILL_BE_YOUR_BUDDY = &quot;BUDDY_ACK&quot;;

	private long thisAddressAsNumber = RadioFactory.getRadioPolicyManager().getIEEEAddress();
	private String addyStr;

	private RadiostreamConnection listenOn;
	private RadiostreamConnection sendOn;

	private DataInputStream listenOnInputStream;
	private DataOutputStream sendOnOutputStream;

	private int portOut;
	private int portIn;

	private BuddyListener buddyListener = new NullBuddyListener();

	private int initialBroadCastPort;

	private boolean foundBuddy = false;

	private RadiogramConnection broadcastConnectionIn;
	private DatagramConnection broadcastConnectionOut;

	private int MAX_BROADCAST_SIZE;

	public Buddy(int broadcastPort) throws IOException {
		this.initialBroadCastPort = broadcastPort;
	}

	public void lookForPair() throws IOException {
		IEEEAddress addy = new IEEEAddress(RadioFactory.getRadioPolicyManager().getIEEEAddress());
		addyStr = addy.asDottedHex();

		System.out.println(&quot;I am &quot; + addyStr);

		broadcastConnectionIn = (RadiogramConnection) Connector.open(&quot;radiogram://:&quot; + initialBroadCastPort);
		MAX_BROADCAST_SIZE = broadcastConnectionIn.getMaximumLength();
		broadcastConnectionOut = (DatagramConnection) Connector.open(&quot;radiogram://broadcast:&quot; + initialBroadCastPort);
		startListenForPartnerResponseThread();
		startLookForBuddyThread();
	}

	public void setBuddyListener(BuddyListener bl) {

		if(null != bl) {
			buddyListener = bl;
		} else {
			buddyListener = new NullBuddyListener(); //allows us to reset the currently loaded BuddyListener
		}

	}

	public void sendMessage(String message) {
		if (null != sendOn) {
			try {
				if (null == sendOnOutputStream) {
					sendOnOutputStream = sendOn.openDataOutputStream();
				}
				sendOnOutputStream.writeUTF(message);
			} catch (IOException ioe) {
				System.out.println(&quot;IOException sending message on partner stream&quot;);
				ioe.printStackTrace();
			}
		} else {
			throw new IllegalStateException(
					&quot;Cannot send message.  No buddy found yet.&quot;);
		}
	}

	private void startLookForBuddyThread() {
		Thread t = new Thread(new Runnable() {
			public void run() {
				lookForBuddy();
			}
		});
		t.start();
	}

	private void lookForBuddy() {
		try {
			while (!foundBuddy) {
				Datagram dg = broadcastConnectionOut.newDatagram(broadcastConnectionOut.getMaximumLength());
				dg.writeUTF(Buddy.NEED_BUDDY + &quot; &quot; + initialBroadCastPort);
				broadcastConnectionOut.send(dg);

				Utils.sleep(1000);
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private void startListenForPartnerResponseThread() {
		Thread t = new Thread(new Runnable() {
			public void run() {
				try {
					while (true) {
						Datagram dg = broadcastConnectionIn.newDatagram(MAX_BROADCAST_SIZE);
						broadcastConnectionIn.receive(dg); // blocking call

						String message = dg.readUTF();

						String otherAddress = dg.getAddress();
						long otherAddressAsNumber = IEEEAddress.toLong(otherAddress);

						if (thisAddressAsNumber != otherAddressAsNumber) {
							handleIncomingBroadcastMessage(dg, message,	otherAddress);
						}
						if (sendOn != null &amp;&amp; listenOn != null) {

							System.out.println(&quot;Buddy status achieved, no longer going to listen to broadcasts&quot;);
							System.out.println(&quot;Partner port to send on: &quot; + sendOn.getLocalPort());
							System.out.println(&quot;Partner port to listen on: &quot; + listenOn.getLocalPort());

							startListenOnPartnerStreamThread();
							break;
						}
					}

				} catch (IOException ioe) {
					System.out.println(&quot;Exception when listening for buddy response&quot;);
					ioe.printStackTrace();
				}
			}
		});
		t.start();

	}

	private void handleIncomingBroadcastMessage(Datagram dg, String message, String otherAddress) throws IOException {
		if (message.startsWith(Buddy.NEED_BUDDY)) {
			if (null == sendOn) {
				int otherPort = Integer.valueOf(separateStrings(message)[1]).intValue();
				Datagram response = offerToBeBuddy(otherPort, otherAddress);

				response.setAddress(dg);
				broadcastConnectionIn.send(response);
			}
		} else if (message.startsWith(Buddy.I_WILL_BE_YOUR_BUDDY)) {
			buddyInviteAccepted(message, otherAddress);
		}
	}

	private void buddyInviteAccepted(String message, String otherAddress)	throws IOException {
		foundBuddy = true;

		portOut = Integer.valueOf(separateStrings(message)[1]).intValue();
		sendOn = (RadiostreamConnection) Connector.open(&quot;radiostream://&quot; + otherAddress + &quot;:&quot; + portOut);

		portIn = portOut - 1;
		listenOn = (RadiostreamConnection) Connector.open(&quot;radiostream://&quot; + otherAddress + &quot;:&quot; + portIn);
	}

	private Datagram offerToBeBuddy(int otherPort, String otherAddress) throws IOException {
		foundBuddy = true;

		portOut = otherPort;
		portIn = portOut + 1;

		System.out.println(&quot;Offering to be a buddy to &quot; + otherAddress + &quot;\nSending on &quot; + portOut + &quot;\nListening on &quot; + portIn);

		sendOn = (RadiostreamConnection) Connector.open(&quot;radiostream://&quot; + otherAddress + &quot;:&quot; + portOut);
		Datagram response = broadcastConnectionIn.newDatagram(MAX_BROADCAST_SIZE);

		response.writeUTF(Buddy.I_WILL_BE_YOUR_BUDDY + &quot; &quot; + portIn);
		listenOn = (RadiostreamConnection) Connector.open(&quot;radiostream://&quot; + otherAddress + &quot;:&quot; + portIn);
		return response;
	}

	private void startListenOnPartnerStreamThread() {
		Thread t = new Thread(new Runnable() {
			public void run() {
				while (true) {
					listenForIncomingMessage();
				}
			}
		});
		t.start();
	}

	private void listenForIncomingMessage() {
		if (null != listenOn) {

			try {
				if (null == listenOnInputStream) {
					listenOnInputStream = listenOn.openDataInputStream();
				}

				String message = listenOnInputStream.readUTF();
				buddyListener.messageRecieved(message);

			} catch (IOException ioe) {
				System.out.println(&quot;IOException recieving message on partner stream&quot;);
				ioe.printStackTrace();
			}
		} else {
			// Maybe we haven't found a partner yet, so don't spin the processor
			Utils.sleep(100);
		}
	}

	private String[] separateStrings(String msg) {
		StringTokenizer stk = new StringTokenizer(msg, &quot; &quot;);
		String[] result = new String[stk.countTokens()];
		for (int i = 0; stk.hasMoreTokens(); i++) {
			result[i] = stk.nextToken();
		}
		return result;
	}
}
</pre>
<p><b>radio.BuddyListener</b> &#8211; Classes wishing to have a buddy must have (or be) one of these and give it to the buddy instance</p>
<pre class="brush: java;">
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package radio;

public interface BuddyListener {
	void messageRecieved(String message);
}
</pre>
<p><b>radio.NullBuddyListener</b> &#8211; It might be that two buddies are connected and one could be chatting to the other which doesn&#8217;t have a <font>BuddyListener</font> attached, in which case this is used instead.</p>
<pre class="brush: java;">
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package radio;

public class NullBuddyListener implements BuddyListener {

	public void messageRecieved(String message) {
		System.out.println(&quot;Warning!  NullBuddyListener being used and messages are getting recieved&quot;);
	}
}
</pre>
<p><b>radio.RadioFun</b> &#8211; This is included for completeness.  It&#8217;s the app that got run when I was testing the Buddy connections.  I don&#8217;t think it makes a lot of sense for any one else to use this class except to see how to talk/listen to the buddy.</p>
<pre class="brush: java;">
/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package radio;

import java.io.IOException;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.util.IEEEAddress;
import com.sun.spot.util.Utils;

public class RadioFun extends MIDlet {

	private Buddy buddy;

	public RadioFun() {
	}

	void start() {
		try {
			buddy = new Buddy(60);
			buddy.setBuddyListener(new BuddyListener() {
				public void messageRecieved(String message) {
					System.out.println(&quot;recieved=[&quot;+message+&quot;]&quot;);
				}
			});
			buddy.lookForPair();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

		IEEEAddress addy = new IEEEAddress(RadioFactory.getRadioPolicyManager().getIEEEAddress());
		String addyStr = addy.asDottedHex();

		while (true) {
			try {
				buddy.sendMessage(&quot;Hello from &quot;+addyStr);
			} catch (IllegalStateException ise) {
				System.out.println(&quot;Failed to send message [&quot;+ise.getMessage()+&quot;]&quot;);
			}

			Utils.sleep(500);
		}
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
	}

	protected void pauseApp() {
	}

	protected void startApp() throws MIDletStateChangeException {
		RadioFun rf = new RadioFun();
		rf.start();
	}
}
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/72/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=72&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/12/18/playing-with-the-sun-spot-radio/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Putting The Pain Into Teamwork</title>
		<link>http://whatimean.wordpress.com/2008/10/30/putting-the-pain-into-teamwork/</link>
		<comments>http://whatimean.wordpress.com/2008/10/30/putting-the-pain-into-teamwork/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 17:23:01 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Team work]]></category>
		<category><![CDATA[best practise]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[quality]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[Java Team Work Software Programming]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=56</guid>
		<description><![CDATA[Introduction

Looking back at code I wrote ages ago often leaves me wondering &#8220;What idiot wrote this junk?&#8221;  Looking back through articles I&#8217;ve written gives me an uncomfortably similar feeling.  Today I&#8217;m thinking specifically about multiple return points, which I announced to be the root of much evil in this post.  What this [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=56&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h2>Introduction</h2>
<p>
Looking back at code I wrote ages ago often leaves me wondering &#8220;What idiot wrote this junk?&#8221;  Looking back through articles I&#8217;ve written gives me an uncomfortably similar feeling.  Today I&#8217;m thinking specifically about multiple return points, which I announced to be the root of much evil in <a href="http://whatimean.wordpress.com/2007/02/08/multiple-return-points-are-bad">this post</a>.  What this post reminds me about most, though, is the <em>Do What Makes Sense</em> principle, something that I&#8217;ve often claimed to subscribe to.
</p>
<h2>How do you plead?</h2>
<p>
I have to confess my guilt before I can continue.  I&#8217;ve recently started writing some methods which have more than one return point (and I&#8217;m not just talking about exceptions here).  But as a kind of mitigation I only use them in very small methods and only sometimes.
</p>
<p>
Actually that&#8217;s not true either.
</p>
<p>
There is a certain kind of method where multiple return points are acceptable, like these;
</p>
<p><code><br />
public Object myMethod() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;if(comeCondition) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return someObject;<br />
&nbsp;&nbsp;&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return someOtherObject;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}<br />
</code></p>
<p>
Or this one;
</p>
<p><code><br />
public Object myOtherMethod() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;switch (something) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 1:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something1;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 2:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something2;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 3:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something3;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 4:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something4;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 5:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something5;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}<br />
</code></p>
<p>
But in these examples the methods are doing very specific things, most plainly, they return something.  No other processing is done.  I would still say <font face="Courier">return</font>s dotted around throughout a method is still a Bad Thing.  But that&#8217;s not what got me thinking.  Whilst trying to justify this use of MRP to myself I started running through the reasons why this code is acceptable, when previously I had said it wasn&#8217;t.  The <font face="Courier">switch</font> method above reminds me of some refactoring work I did on my company&#8217;s product a while back, and it&#8217;s the fallout from that refactoring that I ended thinking about the most.
</p>
<h2>The Situation</h2>
<p>
Here&#8217;s some background.  I work for a company which produces (and uses) it&#8217;s own software product, this product allows the buying and selling of Widgets.  There are many different places that we can buy and sell Widgets from using our software, there is also a piece of third party software which we must tell who has purchased what Widgets, from whom and how many.  The problem comes from the fact that each the objects which represent a user&#8217;s Widget-trading position is different for each Widget Gateway.  Further, the position objects which we must send to the third party software is fixed.  What&#8217;s even worse, is that each Widget Gateway can be further subdivided into more specific kinds of Widget Position Objects.  Again, it&#8217;s even worse than that.
</p>
<p>
The <font face="Courier">AcmeWidgetPositionSubA</font> class and the <font face="Courier">AcmeWidgetPositionSubB</font> class both have the same attributes, but because one is &#8230;SubA and one is &#8230;SubB, when translating this to a <font face="Courier">ThirdPartyWidgetPosition</font> the attributes with the same <em>name</em> in the &#8230;SubA/B classes will be mapped to <em>different</em> attributes in the <font face="Courier">ThirdPartyWidgetPosition</font> class.
</p>
<p>
For example; <font face="Courier">AcmeWidgetPositionSubA.getSpecialCode()</font> needs to be mapped to <font face="Courier">ThirdPartyWidgetPosition.getCode()</font>.  But <font face="Courier">AcmeWidgetPositionSubB.getSpecialCode()</font> needs to be mapped to <font face="Courier">ThirdPartyWidgetPosition.getSystemCode()</font>.
</p>
<p>
This is the scope of the problem and the existing code to do this was lots of lines of if&#8230;then&#8230;elses to get the right things into the write place before the <font face="Courier">ThirdPartyWidgetPosition</font> is sent to the third party software for processing.  Further, there each subtype of Widget Gateway had it&#8217;s own chunk of if&#8230;then&#8230;else code of varying complexity to get the job done specific to itself.  To refactor this code I got rid of all the if&#8230;then&#8230;else functionality and put all the logic into the type system.  By introducing some extra classes that had only overloaded constructors I could remove every occurance of if&#8230;then&#8230;else, create a <font face="Courier">AcmeWidgetPositionSub<i>X</i></font> object, cast it to a <font face="Courier">ThirdPartyWidgetPosition</font> and have everything in the right place, as if by magic.
</p>
<p>
So far so good, lots of complex nested branches get removed, all the unit tests pass, everything works, we all go home happy.  Now fast forward a couple of months.  Someone else is looking at the code and they are struggling to see what goes where and how the branched code has been removed in favour of a clever type hierarchy.  Now, let me first explain that it&#8217;s my opinion that having the logic inside the type system is a better, actually less complex and cleaner implementation approach than if&#8230;then&#8230;else.  It just feels &#8220;more OO&#8221;; even if I can&#8217;t quantify that phrase particularly well.  But to a team member who is more used to seeing and reading if&#8230;then&#8230;else structures it is not cleaner and more obvious.  It&#8217;s something that they need to wrestle with and really <em>read</em> in order to understand it.
</p>
<p>
So if I have slowed down the work of a team member, if I have caused them extra effort to do their own tasks, is my approach still the better one?  Even if the code I wrote was the &#8220;more correct&#8221; implementation; was it the right code to write because of the affect it had on someone else?
</p>
<h2>Style Over Substance</h2>
<p>
A few more of my little foibles are using <font face="Courier">Boolean.TRUE</font> rather than the primative <font face="Courier">true</font>, and putting the literal I am comparing as the first operand of <font face="Courier">equals</font> &#8211; even though I know that the protection this offers me is irrelevant given I spend most of my time writing Java<sub>1</sub>.  I know, because I have been told, that some people find these things more difficult to read than their more usual alternatives.  Personally I don&#8217;t understand why they are more confusing to read.  But given that I can read the code quite happily either way and given that the compiler will change my code to whatever it feels like; should I be tailoring my professional coding style so as the most number of team members are happiest reading it?
</p>
<h2>Drawing The Line</h2>
<p>
The answer, as everything when discussing &#8216;programming best practise&#8217;, is; &#8220;it depends&#8221;.  In the first example with the types vs if&#8230;then&#8230;else, that change should definitely be made.  I can sit down with you and discuss why it is better, what benefits it has, show you how it is easier to extend etc.  And as a consequence of that discussion, the team members who will be reading that code will hopefully start to learn from that example and we&#8217;ll be seeing fewer and fewer nested-branched code.  Designs will become cleaner and gradually the overall quality of the code across the project will get better.
</p>
<p>
But what of more style based differences, or indeed, anything else which you can&#8217;t prove is a tangible benefit?  If they cause pain for other team members or get in the way, then I suggest always defaulting to the lowest common denominator<sub>2</sub>.  That might be structuring code for the least experienced developer &#8211; <em>as long as such structuring does not compromise quality in any way</em>.  Or at least, structuring your code so that it is consistent with the rest of the code base.  It means shoe-horning your coding style into the style used in the rest of the code base to make it easier to read for the whole team &#8211; this is especially true in large legacy codebases.
</p>
<p>
Doing these kinds of silly superficial things in difference to the rest of the code base is something that I am guilty of, and on reflection, something that I should be trying much harder to put a stop to.  Make my code blend more seamlessly into the rest of the code is going to make reading it easier for everyone.  But beware, when there is a real change that should be made, for a real reason with benefits that can be quantified I will still argue for that change &#8211; even if it&#8217;s out of the comfort zone of those around me.  And I fully expect, nay demand, that those around make those same kinds of changes to pull me out of my comfort zone &#8211; because that&#8217;s the only way I&#8217;m going to become a better programmer.
</p>
<p>
There is a lot of talk in various technical blogs about how superstar programmers should be allowed to express themselves in any way, structure their code the way they think it should be done, and basically do whatever they want because (you know) they&#8217;re superstars.  Most of us are probably not superstars and most of the teams we work in are probably not 100% made up of superstars, so I really don&#8217;t find those arguments compelling.  What I do find compelling is trying to increase the average code quality and the skill levels of the average (or lowest) team member, and these things are not measured by where they put their curly brackets or whether they use <font face="Courier">Boolean.FALSE</font> or <font face="Courier">false</font>.  These things are superficial and any non-superficial programmer should be able to get over them.
</p>
<p>
And let&#8217;s not forget; everyone of us is the average-est or the lowest skilled level programmer in the team at something.  And even if your team <i>is</i> made up of Superstars, chances are they are not all going to be the same <i>kind</i> of Superstar.  Think of your favourite classical music composer, rock performer, rap artist, solo violinist, jazz pianist and so on.  Now imagine putting them all in the same band; left to their own devices I really don&#8217;t think any music they produce is going to be bearable, let alone enjoyable &#8211; and this assumes that they&#8217;ll manage to produce anything!  Not unless they all agree to do certain things in the same or similar way and all pull in the same direction<sub>3</sub>.  And I guarantee that each one of them will feel restricted in some way by that.  But what they produce will be well worth the Superstar fees they&#8217;ll be charging!
</p>
<h2>Conclusion</h2>
<p>
It is true that a bit of sand inside an oyster will make a pearl, but a bit of sand inside your shoe is just going to make blisters on your feet.  Removing code complexity and builder and more defined cleaner design is a worthy goal and one worth fighting for.  But doing what is essentially meaningless things for no tangible benefit is not.  As with anything where more than one individual is concerns the rule of give and take must be applied.  Forcing your team members to adopt a distorted concept of Hungarian Notation is pointless.  Similarly, when such a notation has been adopted and is prevelant in a large percentage of the code base, fighting that notation is probably a hiding to nothing.
</p>
<p>
Team cohesion is important.  Every team will be working better if each member is considerate to the others.  By all means bring up the uncomfortable truths and fight to make the design and code better.  But if the benefits of what you&#8217;re fighting for are not worth the battles to win it, then it&#8217;s likely your efforts would be better spent putting for head down and servicing user requests and bug fixes.</p>
<p>1 &#8211; Unless I&#8217;m comparing booleans, of course.<br />
2 &#8211; This is not meant to be a derogatory phrase.<br />
2 &#8211; Singing from the same song-sheet even.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/56/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=56&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/10/30/putting-the-pain-into-teamwork/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>New Baby!</title>
		<link>http://whatimean.wordpress.com/2008/07/26/new-baby/</link>
		<comments>http://whatimean.wordpress.com/2008/07/26/new-baby/#comments</comments>
		<pubDate>Sat, 26 Jul 2008 13:29:51 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=42</guid>
		<description><![CDATA[A personal article this one&#8230;
Rachael gave birth to Esmé Faith this morning (26th July 2008 ) at 4:20 AM BST.  She weighed 7lb 2oz, for those looking for metric measurements please go to Brussels where you will (unlike here) be welcomed.
Mother and baby are doing fine.  Kate (2 years, 2 months old) is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=42&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A personal article this one&#8230;</p>
<p>Rachael gave birth to Esmé Faith this morning (26th July 2008 ) at 4:20 AM BST.  She weighed 7lb 2oz, for those looking for metric measurements please go to Brussels where you will (unlike here) be welcomed.</p>
<p>Mother and baby are doing fine.  Kate (2 years, 2 months old) is running around saying &#8220;You must go to sleep!  Don&#8217;t wake the baby.&#8221;  Followed by bellows of &#8220;SILENCE!&#8221;  I don&#8217;t know where she got that from.</p>
<p>On a technical aspect, I was impressed with the midwifery team, as soon as the baby was built they ran all the unit tests (developed before the baby was, naturally) and could easily indicate a successful build.</p>
<p>A small subset of pictures is below.</p>
<div id="attachment_43" class="wp-caption alignnone" style="width: 310px"><a href="http://whatimean.files.wordpress.com/2008/07/imgp1428.jpg"><img src="http://whatimean.files.wordpress.com/2008/07/imgp1428.jpg?w=300&#038;h=225" alt="About 15 minutes old" width="300" height="225" class="size-medium wp-image-43" /></a><p class="wp-caption-text">About 15 minutes old</p></div><br />
<br />
<div id="attachment_44" class="wp-caption alignnone" style="width: 310px"><a href="http://whatimean.files.wordpress.com/2008/07/imgp1433.jpg"><img src="http://whatimean.files.wordpress.com/2008/07/imgp1433.jpg?w=300&#038;h=225" alt="A few hours old" width="300" height="225" class="size-medium wp-image-44" /></a><p class="wp-caption-text">A few hours old</p></div><br />
<br />
<a href="http://whatimean.files.wordpress.com/2008/07/imgp1444.jpg"><img src="http://whatimean.files.wordpress.com/2008/07/imgp1444.jpg?w=300&#038;h=225" alt="" width="300" height="225" class="alignnone size-medium wp-image-45" /></a><br />
<br />
<div id="attachment_48" class="wp-caption alignnone" style="width: 310px"><a href="http://whatimean.files.wordpress.com/2008/08/p1010529.jpg"><img src="http://whatimean.files.wordpress.com/2008/08/p1010529.jpg?w=300&#038;h=225" alt="All together at home" width="300" height="225" class="size-medium wp-image-48" /></a><p class="wp-caption-text">All together at home</p></div>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/42/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/42/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/42/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=42&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/07/26/new-baby/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>

		<media:content url="http://whatimean.files.wordpress.com/2008/07/imgp1428.jpg?w=300" medium="image">
			<media:title type="html">About 15 minutes old</media:title>
		</media:content>

		<media:content url="http://whatimean.files.wordpress.com/2008/07/imgp1433.jpg?w=300" medium="image">
			<media:title type="html">A few hours old</media:title>
		</media:content>

		<media:content url="http://whatimean.files.wordpress.com/2008/07/imgp1444.jpg?w=300" medium="image" />

		<media:content url="http://whatimean.files.wordpress.com/2008/08/p1010529.jpg?w=300" medium="image">
			<media:title type="html">All together at home</media:title>
		</media:content>
	</item>
		<item>
		<title>Haskel Puzzle Solved</title>
		<link>http://whatimean.wordpress.com/2008/05/18/haskel-puzzle-solved/</link>
		<comments>http://whatimean.wordpress.com/2008/05/18/haskel-puzzle-solved/#comments</comments>
		<pubDate>Sun, 18 May 2008 20:11:39 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=41</guid>
		<description><![CDATA[Disclaimer

Don&#8217;t expect this post to be breaking any barriers.  I&#8217;ve been struggling with to solve an exercise from my Haskell Road book for the past week or so and I finally cracked it.


I&#8217;d be interested to know if anyone has a better way to solve it.  I&#8217;m still very much a Haskell beginner [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=41&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h1>Disclaimer</h1>
<p>
Don&#8217;t expect this post to be breaking any barriers.  I&#8217;ve been struggling with to solve an exercise from my <a href="http://homepages.cwi.nl/~jve/HR/">Haskell Road</a> book for the past week or so and I finally cracked it.
</p>
<p>
I&#8217;d be interested to know if anyone has a better way to solve it.  I&#8217;m still very much a Haskell beginner and haven&#8217;t gotten much past pattern matching, guards and the where clause; so try not to confuse me.
</p>
<h2>The Problem</h2>
<p>
Create a function </p>
<p><code><strong>splitList :: [a] -&gt; [([a],[a])]</strong></code></p>
<p>Which takes a list </p>
<p><code><strong>[1..5]</strong></code></p>
<p>and returns a list;</p>
<p><code><strong>[([1], [2,3,4,5]), ([1,2], [3,4,5]), ([1,2,3], [4,5]), ([1,2,3,4], [5])]</strong></code>
</p>
<h2>My Solution</h2>
<p><code><b>moveHeadToTail :: [a] -&gt; [a] -&gt; [a]<br />
moveHeadToTail (xs) (y:ys)	= xs ++ [y]</p>
<p>splitListAux		:: [a] -&gt; [a] -&gt; [([a],[a])]<br />
splitListAux (o:os) []	= [([o],os)] ++ splitListAux os [o]<br />
splitListAux (o:os) h<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| length (o:os) == 2	= [(head,os)]<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| otherwise		= [(head,os)] ++ splitListAux os head<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;head = moveHeadToTail h (o:os)</p>
<p>splitList		:: [a] -&gt; [([a],[a])]<br />
splitList (x:xs)	= splitListAux (x:xs) []</b></code></p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/41/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/41/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/41/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=41&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/05/18/haskel-puzzle-solved/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Why Can&#8217;t Java Do That?</title>
		<link>http://whatimean.wordpress.com/2008/05/15/why-cant-java-do-that/</link>
		<comments>http://whatimean.wordpress.com/2008/05/15/why-cant-java-do-that/#comments</comments>
		<pubDate>Thu, 15 May 2008 20:56:35 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=40</guid>
		<description><![CDATA[So this year I&#8217;m trying to make in-roads in learning some new languages, in particular Ruby and Haskell.  My problem is now that since I pay my bills by writing Java code every day I&#8217;m left thinking &#8220;That&#8217;s one line in Ruby&#8221; or &#8220;Why can&#8217;t Java do this like Haskell?&#8221;
Without these changes I will [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=40&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>So this year I&#8217;m trying to make in-roads in learning some new languages, in particular Ruby and Haskell.  My problem is now that since I pay my bills by writing Java code every day I&#8217;m left thinking &#8220;That&#8217;s one line in Ruby&#8221; or &#8220;Why can&#8217;t Java do this like Haskell?&#8221;</p>
<p>Without these changes I will spend each day being a little bit more gumpy than is necessary.  This is bad because I vocalise my grumpiness.  (I like to think of it as contributing to the team.)  So if I&#8217;m grumpy, I&#8217;ll make those around me grumpy.  And in turn, they&#8217;ll make the ones around them grumpy.  So without these changes and with a few more hops like that <a href="http://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon">Kevin Bacon</a> will be grumpy.*  So I think that it&#8217;s safe to say that even Kevin Bacon want&#8217;s these changes.  Sun is actually making Keving Bacon grumpy.  And that&#8217;s not fair.</p>
<p>So here&#8217;s a very quick, off-the-top-of-my-head, list of things that I&#8217;d like to see in Java.  I don&#8217;t care if they&#8217;re adopted as fundamental language changes or whether they&#8217;re just syntactic sugar that the compiler removes and replaces.  As long as the changes are made, I&#8217;ll be a happy bunny.</p>
<h2>Validate Method Parameters</h2>
<p>Like a good boy I always check my method parameters before I can use them.  Most of my checks are boring and repetative, they clutter up my super-important-and-complicated business method.  Why can&#8217;t they be moved out to annotations?</p>
<h3>Code Like This&#8230;</h3>
<p><code><b>public String complexMethod(Object someObj, String someStr, int number) {<br />
&nbsp;&nbsp;if(null == someObj) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;throw new IllegalArgumentException("someObj cannot be null");<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;if(null == someStr || 0 == someStr.trim().length()) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;throw new IllegalArgumentException("someStr cannot be null or empty");<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;if(MIN &gt; number || MAX &lt; number) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;throw new IllegalArgumentException("number out of range");<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;// Complex code goes here<br />
}</b></code></p>
<h3>Is Replaced With&#8230;</h3>
<p><code><b>@Check(NOT_NULL, IllegalArgumentException, someObj, "someObj cannot be null")<br />
@Check(NOT_EMPTY, IllegalArgumentException, someStr, "someStr cannot be null or whitespace only")<br />
@Check(IN_RANGE, com.mycompany.BadNumberRangeException, number, MIN, MAX)<br />
public String complexMethod(Object someObj, String someStr, int number) {<br />
&nbsp;&nbsp;// Complex code goes here<br />
}</b></code></p>
<h2>Wrap Methods in Try-Catch</h2>
<p>Many times a day I see code where the entire method is wrapped in a try-catch statement.  Often times the stuff in the catch statement is repeated though the class (or classes).  Another annotation could remove this noise and make the business code look much more plain.</p>
<h3>Code Like This&#8230;</h3>
<p><code><b>public void doDatabaseThing() throws SQLException {<br />
&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// some database thing<br />
&nbsp;&nbsp;} catch (SQLException sqle) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;methodToRun();<br />
&nbsp;&nbsp;}<br />
}</b></code></p>
<h3>Is Replaced With&#8230;</h3>
<p><code><b>@IfThrown(java.sql.SQLException, methodToRun)<br />
public void doDatabaseThing() throws SQLException {<br />
&nbsp;&nbsp;// some database thing<br />
}</b></code></p>
<p>Maybe a better approach is to abolish all checked exceptions, but that&#8217;s another post.</p>
<h2>What was the index, please?</h2>
<p>Java&#8217;s for-each loop is just syntactic sugar for a normal for loop, complete with counter.  Why couldn&#8217;t they introduce a Perl-esque special variable that had the current iterations index in it?  For example;
<p>
<code><b>for(String name : names) {<br />
&nbsp;&nbsp;System.out.println(name + " is at index " + $_);<br />
}</b></code></p>
<h2>Controvertial: Easily implement the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a></h2>
<p>Sometimes you need to wrap objects in other objects.  Fine.  Sometimes you can&#8217;t use a simple &#8220;extends&#8221; and just override the methods you&#8217;re interested.  Annoying.  But what happens when the object you want to wrap has an enormous public interface?  You can argue that this is implying you have a bad object model, and I probably won&#8217;t disagree, but sometimes you just have to play the cards dealt you and that means wrapping something with a big public interface.</p>
<h3>Code Like This&#8230;</h3>
<p><code><b>public class Wrapper {<br />
&nbsp;&nbsp;private Wrapped wrapped = new Wrapped();<br />
&nbsp;&nbsp;public void method1() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;wrapped.method1();<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;public void method2() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;wrapped.method2();<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;public void method3() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;//do something different first...<br />
&nbsp;&nbsp;&nbsp;&nbsp;wrapped.method3();<br />
&nbsp;&nbsp;}<br />
}</b></code></p>
<h3>Is Replaced With&#8230;</h3>
<p><code><b>@Decorates(wrapped)<br />
public class WrapperClass {<br />
&nbsp;&nbsp;private Wrapped wrapped = new Wrapped();<br />
&nbsp;&nbsp;public void method3() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;//do something different first...<br />
&nbsp;&nbsp;&nbsp;&nbsp;wrapped.method3();<br />
&nbsp;&nbsp;}<br />
}</b></code></p>
<p>&#8230;and have the compiler fill in all the boring pass-through methods for me.</p>
<h2>Pattern Matching</h2>
<p>I really like the pattern matching of methods you get in Haskell and I&#8217;m left wondering if Java might benefit from them to.</p>
<h3>Code Like This&#8230;</h3>
<p><code><b>public void doSomething(boolean flag, Object otherArg) {<br />
&nbsp;&nbsp;if (flag) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// some code here<br />
&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// other code here<br />
&nbsp;&nbsp;}<br />
}</b></code></p>
<h3>Is Replaced With&#8230;</h3>
<p><code><b>public void doSomething(Boolean.TRUE, Object otherArg) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// some code here<br />
}<br />
public void doSomething(Boolean.FALSE, Object otherArg) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// other code here<br />
}</b></code></p>
<p>But I really don&#8217;t know if this makes things more simple.</p>
<h3>In Closing&#8230;</h3>
<p>I haven&#8217;t actually done much (read: any) research into how to write my own annotations in Java.  I <em>really</em> don&#8217;t know how to write an annotation that will make the compiler behave differently and inject code into the source.  I&#8217;d be interested to hear if anyone knows where I can do some reading on this.</p>
<p></p>
<p>* Okay, so it&#8217;s not a perfect application of 6-degrees, so what?</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/40/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/40/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/40/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=40&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/05/15/why-cant-java-do-that/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>First Steps In Logical Proofs</title>
		<link>http://whatimean.wordpress.com/2008/04/15/first-steps-in-logical-proofs/</link>
		<comments>http://whatimean.wordpress.com/2008/04/15/first-steps-in-logical-proofs/#comments</comments>
		<pubDate>Tue, 15 Apr 2008 13:55:51 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Maths]]></category>
		<category><![CDATA[Proof]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=39</guid>
		<description><![CDATA[Edit: I&#8217;ve just read this (pdf) and found it really helpful explaining some of the concepts I&#8217;ve been wrestling with
I&#8217;m working my way through The Haskell Road to Logic, Maths and Programming to try and get a better understanding of functional programming and all the things that that entails.
Sadly, I&#8217;m hitting problems.  The programming [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=39&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><P>Edit: I&#8217;ve just <a href="http://homepages.inf.ed.ac.uk/wadler/papers/frege/frege.pdf">read this (pdf)</a> and found it really helpful explaining some of the concepts I&#8217;ve been wrestling with</P></p>
<p><P>I&#8217;m working my way through <a href="http://www.amazon.co.uk/Haskell-Logic-Maths-Programming-Computing/dp/0954300696/ref=sr_11_1?ie=UTF8&amp;qid=1208266045&amp;sr=11-1">The Haskell Road to Logic, Maths and Programming</a> to try and get a better understanding of functional programming and all the things that that entails.</P></p>
<p><P>Sadly, I&#8217;m hitting problems.  The programming problems I&#8217;m okay with, I can run the code and see if the result is was I expect it to be.  But I&#8217;m struggling with the proof-based exercises.  I can contact the authors <a href="http://homepages.cwi.nl/~jve/HR/">here</a> but I don&#8217;t want to get a list of all the answers &#8211; mostly because I&#8217;ll know I&#8217;ll start cheating if I have them!  So I&#8217;m stuck trying to work out if what I&#8217;ve done is correct.</P></p>
<p><P>That&#8217;s where this blog comes in, maybe I&#8217;ll get some comments from people telling me what I&#8217;m doing wrong&#8230;<P></p>
<h2>Exercise: 3.5.1 (Page 83)</h2>
<p><em>Show that from  P &lt;=&gt; Q it follows that (P =&gt; R) &lt;=&gt; (Q =&gt; R)</em><br />
<P><em>Major edit alert!</em></P><br />
<P>After lots of reading and help I&#8217;ve reached a conclusion.  There&#8217;s an easier way to write proofs using actual sentances!  Also, for this first exercise there are two ways to do it, the first which is what I originally tried to say (but got wrong) and a second which Kim-Ee Yeoh helped me reach in the comments.</P></p>
<h3>My Way</h3>
<p>We are given P &lt;=&gt; Q, so we know that this is True.  For this to be True the following two statements must also be True.</p>
<ul>
<li>P =&gt; Q</li>
<li>P &lt;= Q</li>
</ul>
<p>For these two statements to be True, P and Q must also be True.</p>
<p>Because we know that P and Q are True, we can take these as new givens and use the Reduction Rule on both sides of the &lt;=&gt; in the statement we&#8217;re asked to prove.  So;</p>
<ul>
<li>P =&gt; R becomes R (using the Reduction Rule and our knowledge that P is True)</li>
<li>Q =&gt; R becomes R (using the Reduction Rule and our knowledge that Q is True)</li>
</ul>
<p>Now I&#8217;m a bit stuck, now I have to prove R &lt;=&gt; R and the only thing that tells me that this is True is my intuition, which can rarely be trusted.  I can break it into two peices (as above for the oriignal given) and prove R =&gt; R and R &lt;= R, which should leave me concluding that R is True.  Right?</p>
<p></p>
<h3>Kim-Ee Yeoh&#8217;s Way</h3>
<p><strong>Part 1</strong>: Copied from the comments below</p>
<p>Assume Q =&gt; P and P =&gt; R. We want to show Q=&gt;R. It suffices to show that if Q is true, R must also be true. So let’s assume Q is true. Then Q=&gt;P forces P to be true. In turn P=&gt;R forces R to be true. Done.</p>
<p><strong>Part 2</strong>: All my own mess</p>
<p>Assume P =&gt; Q and Q =&gt; R. We want to show P =&gt; R.  It suffices to show that if P is True, R must also be True. So let’s assume P is True. Then P =&gt; Q forces Q to be True. In turn Q =&gt; R forces R to be True. Done.
</p>
<p><strong>Part 3</strong>: Mess continuation, a step to far?</p>
<p>The above two sub-proofs mean we can rewrite the original statement to be proved as True &lt;=&gt; True, which again boils down to True.
</p>
<p>
Now I&#8217;m sure I&#8217;ve got something wrong, because it seems too easy.  Also, writing out these two approaches one after the other makes me think that they are basically the same, is that a correct thinking?
</p>
<p></p>
<h2>Exercise: 3.5.2 (Page 83)</h2>
<p><em>Show that from  P &lt;=&gt; Q it follows that (R =&gt; P) &lt;=&gt; (R =&gt; Q)</em></p>
<p>We are given P &lt;=&gt; Q, so we know that this is True.  For this to be True the following two statements must also be True.</p>
<ul>
<li>P =&gt; Q</li>
<li>P &lt;= Q</li>
</ul>
<p>For these two statements to be True, P and Q must also be True.</p>
<p>Because we know that P and Q are True, we can take these as new givens and use the Reduction Rule on both sides of the &lt;=&gt; in the statement we&#8217;re asked to prove.  So;</p>
<ul>
<li>R =&gt; P becomes R =&gt; T</li>
<li>R =&gt; Q becomes R =&gt; T</li>
</ul>
<p>Looking at the Truth Table for =&gt;, ? =&gt; True is always True, so the original statement we need to prove can be rewritten as True &lt;=&amp;gt True, which again boils down to plain old &#8220;True&#8221;.</p>
<p><P><br />
I guess what I&#8217;m trying to say is, given my lack of confidence in this area, can someone who knows more than me about this stuff help me work out if I&#8217;m doing it right?  A thousand &#8220;Thank You&#8221;s in advance.<br />
</P></p>
<p><P>Edit: I must say a big thank you to Kim-Ee Yeoh for the comments he left, I found them <em>really</em> useful!</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/39/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/39/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/39/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/39/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/39/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=39&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/04/15/first-steps-in-logical-proofs/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Latest Rails &#8216;Gotcha&#8217; Solved</title>
		<link>http://whatimean.wordpress.com/2008/03/01/latest-rails-gotcha-solved/</link>
		<comments>http://whatimean.wordpress.com/2008/03/01/latest-rails-gotcha-solved/#comments</comments>
		<pubDate>Sat, 01 Mar 2008 23:17:47 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby On Rails]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=38</guid>
		<description><![CDATA[So continuing my Ruby on Rails adventure it seems I have hit another problem.  Luckily this one seems quite easy to fix, although it did take me a good old time to find the solution.
Maybe it&#8217;s also obvious to everyone else in the world and it was only me that was stuck, but maybe [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=38&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>So continuing my Ruby on Rails adventure it seems I have hit another problem.  Luckily this one seems quite easy to fix, although it did take me a good old time to find the solution.</p>
<p>Maybe it&#8217;s also obvious to everyone else in the world and it was only me that was stuck, but maybe not.  So I&#8217;m sharing this here to help others who might be interested.</p>
<h2>The Situation</h2>
<p>I have two models, Products and Categories.  Products belong to a Category.  So when searching for all the Products for a given category I have the following ruby code in my controller;</p>
<p><code>def show_category<br />
&nbsp;&nbsp;id = params[:id]<br />
&nbsp;&nbsp;@category = Category.find_by_id(id)<br />
&nbsp;&nbsp;@products = Product.find_by_category_id(id)<br />
end</code></p>
<p>What I&#8217;m expecting is to return a list of Products to my view, all of which belong to a category.</p>
<h2>The Problem</h2>
<p>But instead I was getting the following error;</p>
<p><code>undefined method `each' for #</code></p>
<p>For this view code;</p>
<p><code>&lt;% for product in @products %&gt;</code></p>
<h2>The Solution</h2>
<p>I worked out that this is because for the data I was testing only one product was being returned from the find method.  This was correct behaviour because there was only one product in the data.  But that meant that a single Product object was being returned, <em>not a Collection containing a single Product object</em>.  So change the controller to look like;<br />
<code>def show_category<br />
&nbsp;&nbsp;id = params[:id]<br />
&nbsp;&nbsp;@category = Category.find_by_id(id)<br />
&nbsp;&nbsp;@products = Product.find_<b>all_</b>by_category_id(id)<br />
end</code></p>
<p>And a collection is always returned, even if there is only one Product.  Problem solved.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/38/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/38/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/38/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=38&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/03/01/latest-rails-gotcha-solved/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>SSL For Apache And Rails</title>
		<link>http://whatimean.wordpress.com/2008/02/20/ssl-for-apache-and-rails/</link>
		<comments>http://whatimean.wordpress.com/2008/02/20/ssl-for-apache-and-rails/#comments</comments>
		<pubDate>Wed, 20 Feb 2008 22:52:20 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby On Rails]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=36</guid>
		<description><![CDATA[Introduction

For myriad reasons I&#8217;ve decided to start writing my own website and I&#8217;m doing that using Ruby On Rails.  Unfortunately I hit a snag.  I wanted to secure some parts of the site using SSL whilst leaving others open.  To do this I needed to, among other things, front the rails server [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=36&subd=whatimean&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><h1>Introduction</h1>
<p>
For myriad reasons I&#8217;ve decided to start writing my own website and I&#8217;m doing that using <a href="http://www.rubyonrails.org/">Ruby On Rails</a>.  Unfortunately I hit a snag.  I wanted to secure some parts of the site using SSL whilst leaving others open.  To do this I needed to, among other things, front the rails server (in my case that&#8217;s WEBrick) with Apache and have the later do the proxy pass through magic.
</p>
<p>
I spent a lot of time in search engines reading various different articles trying to work out how to do this, but not matter which instructions I followed I couldn&#8217;t manage to get it to work.  I did eventually find a solution though.  This article is just to detail that solution so others don&#8217;t have to do the same level of research and gnashing of teeth that I did.
</p>
<p>
Before I forget, these instructions work on my reasonably clean Ubuntu Gutsy install running on my Rizeon (actually a Compal IFL90) laptop.  which reminds me&#8230;  If anyone out there has an IFL90 which they&#8217;re having Ubuntu trouble with I recommend <a href="http://lddubeau.com/avaktavyam/linux-on-a-compal-ifl90/">Louis-Dominique&#8217;s site</a> which gave me a lot of good pointers.
</p>
<h3>Assumptions</h3>
<p>
I&#8217;m assuming that you&#8217;ve installed RoR and Apache2 using your preferred method.  These instructions are all about getting them to play nicely together.
</p>
<p></p>
<h2>SSL Certificate: Self Signing</h2>
<p>
Because my application is in development mode I just need a certificate to test with, which is where self-signing comes in.  See the instructions on <a href="http://articles.slicehost.com/2007/11/26/ubuntu-gutsy-generating-a-self-signed-ssl-certificate">this page</a> on how to download and create a self-signed certificate.
</p>
<p></p>
<h2>Apache2: Enabling the mods</h2>
<p>
Now, I didn&#8217;t download anything extra when I used apt-get to install Apache2, so it&#8217;s my belief that it downloaded the list of following mods when Apache was installed.  Therefore, I also believe that all you need to do is enable them.</p>
<p>The following incantations will do the enabling, if you get errors because certain mods are missing from your install then I&#8217;m afraid that you&#8217;re going to have to find out how to install them on your own, sorry.
</p>
<p><code>$ sudo a2enmod ssl<br />
$ sudo a2enmod proxy<br />
$ sudo a2enmod rewrite<br />
$ sudo a2enmod proxy_balancer<br />
$ sudo a2enmod proxy_http<br />
$ sudo a2enmod headers<br />
</code><br />
</p>
<h2>Apache2: Setting up the VirtualHost</h2>
<p>
We need to set up some virtual hosts for Apache to represent our proxied site.  I also disabled the default proxy application.  Here&#8217;s the commands needed, instructions follow.<br />
<code>$ cd /etc/apache2<br />
$ sudo a2dissite default<br />
$ sudo cp sites-available/default sites-available/myapp<br />
$ sudo a2ensite myapp<br />
</code></p>
<p>
Where &#8220;<em>myapp</em>&#8221; is obviously the name of the application I&#8217;m trying to set Apache up as a proxy for.  The &#8220;<em>a2dissite</em>&#8221; command disables the default web application inside Apache, and the &#8220;<em>a2ensite</em>&#8221; command enables our one.  I copied the <strong>sites-available/default</strong> file into <strong>sites-available/myapp</strong> to make sure that the new file describing <em>myapp</em> has the correct permissions etc.  We&#8217;ll be scrubbing the contents of this new file completely in the next step.
</p>
<p>
Still in the terminal and still in the <strong>/etc/apache2</strong> directory we need to modify our <strong>sites-available/myapp</strong> file, which we need to do as route, so obviously using your text editor of choice&#8230;;<br />
<code>$ sudo vi sites-available/myapp<br />
</code></p>
<p>
Below if the contents of my file, feel free to copy it.
</p>
<p><code>&lt;VirtualHost *:80&gt;<br />
&nbsp;&nbsp;ServerName localhost<br />
&nbsp;&nbsp;ProxyPass / http://localhost:3000/<br />
&nbsp;&nbsp;ProxyPassReverse / http://localhost:3000/<br />
&lt;/VirtualHost&gt;<br />
<br />
&lt;VirtualHost *:443&gt;<br />
&nbsp;&nbsp;ServerName localhost<br />
&nbsp;&nbsp;ProxyPass / http://localhost:3000/<br />
&nbsp;&nbsp;ProxyPassReverse / http://localhost:3000/<br />
&nbsp;&nbsp;ProxyPreserveHost On<br />
&nbsp;&nbsp;RequestHeader set X_FORWARDED_PROTO 'https'<br />
<br />
&nbsp;&nbsp;SSLEngine On<br />
&nbsp;&nbsp;SSLProxyEngine On<br />
&nbsp;&nbsp;SSLCertificateFile /etc/ssl/certs/selfsigned.pem<br />
&nbsp;&nbsp;SSLProxyMachineCertificateFile /etc/ssl/certs/selfsigned.pem<br />
&lt;/VirtualHost&gt;</code></p>
<p>
Now I&#8217;m the first to admit that I don&#8217;t 100% understand what the RequestHeaders line is for.  It&#8217;s my understanding that because Rails doesn&#8217;t have a concept of http/https this line overrides some functionality in the link_to code so the correct &#8220;http/https&#8221; is appended to the URL as required.  But as I say, I&#8217;m not totally sure that my understanding is accurate in any way.
</p>
<h2>Apache2: proxy.conf</h2>
<p>
We need to configure the apache proxy behaviour.  To do this we have to modify the file <strong>/etc/apache2/mods-available/proxy.conf</strong> We need to tell Apache where to accept proxy requests from.  Here&#8217;s the snip of my <strong>proxy.conf</strong> file which allows proxy-ing from localhost.<br />
<code>&lt;/Proxy *&gt;<br />
&nbsp;&nbsp;AddDefaultCharset off<br />
&nbsp;&nbsp;Order deny,allow<br />
&nbsp;&nbsp;Deny from all<br />
&nbsp;&nbsp;Allow from localhost<br />
&lt;/Proxy&gt;<br />
</code>
</p>
<p>
We now need to bounce Apache2, so issue the following command;
</p>
<p><code>$ sudo /etc/init.d/apache2 force-reload</code></p>
<p>
You shouldn&#8217;t get any errors when Apache2 restarts.  If you do, either you&#8217;ve not followed the above instructions properly or, more likely, I&#8217;ve forgotten a critical part of the instructions.  If it&#8217;s the latter, please let me know of any problems and I&#8217;ll rack my brains (and chalk my nose) and get the missing pieces put up.
</p>
<h2>Rails: Last Stages</h2>
<p>
Now, as I mentioned earlier, WEBrick doesn&#8217;t understand the concept of SSL but Rails/Ruby needs to know to block requests coming in on HTTP when they should be on HTTPS and to do the appropriate redirects.  We do this using the <em>ssl_requirement</em> package&#8230;
</p>
<p><code>$ cd ~/myapp<br />
$ ruby script/plugin install ssl_requirement<br />
</code></p>
<p>
And now we need to modify our controllers to force this usage.  In my setup I have an AdminController which all my, er, administrative controllers extend.  This means that I just need to apply a layout to my AdminController to get all the admin-stuff looking the same, it also means that I can modify this controller with the SSL stuff and have that &#8216;cascade&#8217; down to the other more specific admin-y things.  here&#8217;s my AdminController&#8230;
</p>
<p><code>class AdminController &lt; ApplicationController<br />
<br />
$nbsp;$nbsp;include SslRequirement<br />
<br />
$nbsp;$nbsp;layout 'admin'<br />
<br />
$nbsp;$nbsp;# all methods that extend AdminController should use SSL<br />
$nbsp;$nbsp;def ssl_required?<br />
$nbsp;$nbsp;$nbsp;$nbsp;true<br />
$nbsp;$nbsp;end<br />
<br />
end<br />
</code></p>
<p>
I&#8217;ve overridden the <em>ssl_required</em> method because I want all methods of my admin controllers to use SSL.  If you want to be a bit more specific on which methods in a controller need SSL I suggest no overriding this but following the example which you&#8217;ll find in <strong>~/myapp/vendor/plugins/ssl_requirement/README</strong>
</p>
<p>
Now start WEBrick in the usual way.  If you then browse to <strong>http://localhost</strong> you should get the default non-ssl rails app you were expecting.  But if you browse to a URL which should be on SSL you&#8217;ll find you get redirected.  So in my case; <strong>http://localhost/admin</strong> redirects me to <strong>https://localhost/admin</strong> and from then on all URLs and clicks that should be done on HTTPS are where as all non-secure stuff is done on regular HTTP.
</p>
<h2>Conclusion</h2>
<p>
I hope that someone finds these instructions helpful.  I&#8217;m by no means an expert, I got here just by piecing together instructions found on other sites.  But if there are any problems let me be the first to say <strike>it works on my computer</strike> please post a comment if these instructions don&#8217;t work and I&#8217;ll do my best to help.
</p>
<h2>References</h2>
<p>
For the sake of completeness and politeness below is a list of all the pages I used in getting my install working.  I&#8217;m sure that you&#8217;ll find some (or all) of the commands I&#8217;ve listed here on these other pages.</p>
<ul>
<li><a href="http://www.urbanpuddle.com/articles/2008/01/09/install-ruby-on-rails-on-ubutu-gutsy-gibbon-apache-version">http://www.urbanpuddle.com/articles/2008/01/09/install-ruby-on-rails-on-ubutu-gutsy-gibbon-apache-version</a></li>
<li><a href="http://rikkus.info/apache2-in-front-of-rails-on-debian.html">http://rikkus.info/apache2-in-front-of-rails-on-debian.html</a></li>
<li><a href="http://craiccomputing.blogspot.com">http://craiccomputing.blogspot.com</a></li>
<li><a href="http://articles.slicehost.com/2007/11/26/ubuntu-gutsy-apache-ssl-and-vhosts">http://articles.slicehost.com/2007/11/26/ubuntu-gutsy-apache-ssl-and-vhosts</a></li>
<li><a href="http://articles.slicehost.com/2007/11/26/ubuntu-gutsy-generating-a-self-signed-ssl-certificate">http://articles.slicehost.com/2007/11/26/ubuntu-gutsy-generating-a-self-signed-ssl-certificate</a></li>
</ul>
<p>
Also, apparently<a href="http://www.slash7.com/articles/2006/6/9/because-let-s-face-it-webrick-sucks">because-let-s-face-it-webrick-sucks</a>.  I personally haven&#8217;t encountered the same problems that the author has, but in case you have the article has some good instructions on how to install an alternative called Mongrel.  I might give that a try later.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/36/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/36/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/36/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/36/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/36/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&blog=650809&post=36&subd=whatimean&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/02/20/ssl-for-apache-and-rails/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
	</channel>
</rss>