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

<channel>
	<title>Mark W. Shead &#187; Programming</title>
	<atom:link href="http://blog.markwshead.com/category/technology/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.markwshead.com</link>
	<description>Mark's thoughts on being Mark Shead and other random subjects</description>
	<lastBuildDate>Mon, 02 Jan 2012 16:04:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Simple Made Easy &#8211; Rich Hickey</title>
		<link>http://blog.markwshead.com/1069/simple-made-easy-rich-hickey/</link>
		<comments>http://blog.markwshead.com/1069/simple-made-easy-rich-hickey/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 22:12:59 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=1069</guid>
		<description><![CDATA[Notes from Rich Hickey&#8217;s talk on simplicity at Strangeloop 2011. The video is now available here. Word origins: Simple  = sim &#8211; plex = one braid Easy = adjacent = lie near Simple: Simple means having one of something, one braid, one fold, one role, one concept, one task, one dimension. Simple can involve many [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Notes from Rich Hickey&#8217;s talk on simplicity at Strangeloop 2011.</p>
<p><strong>The video is now available <a href="http://www.infoq.com/presentations/Simple-Made-Easy">here</a>.</strong></p>
<p><strong>Word origins:</strong></p>
<ul>
<li>Simple  = sim &#8211; plex = one braid</li>
<li>Easy = adjacent = lie near</li>
</ul>
<div><strong>Simple:</strong></div>
<div>
<ul>
<li>Simple means having one of something, one braid, one fold, one role, one concept, one task, one dimension.</li>
<li>Simple can involve many things, but not having interleaving.</li>
<li>Simple is an objective notion.</li>
</ul>
</div>
<div><strong>Easy:</strong></div>
<ul>
<li>Near, at hand.</li>
<li>Near to our understanding&#8211;being familiar.</li>
<li>Near to our capabilities. We don&#8217;t like to talk about this because it tramples on our egos.</li>
<li>We are far to interested in things being <strong>easy. </strong>This is to our detriment.</li>
<li>Easy is relative (unlike &#8220;simple&#8221;). Music and German are hard from some and easy for others.</li>
</ul>
<div><strong>Construct vs Artifact</strong></div>
<div>
<ul>
<li>We become to infatuated with things being easy  instead of being simple.</li>
<li>Long term use is a better indication of simplicity and helps keep use from focusing on things being easy.</li>
</ul>
<p>We can only hope to make reliable those things we can understand. There is a limit to how much we can keep in our mind at the same time. Intertwined things have to be considered together and this taxes our brains. Fewer &#8220;braids&#8221; means less complexity and less complexity means we can hold it in our minds better.</p>
<p>To change software requires analysis and decisions. You must be able to reason about your program to be able to reliably change it.</p>
<blockquote><p>We say, &#8220;I can make a change because I have tests.&#8221; Who does that? Who drives their car around banging into the guard rails!?</p></blockquote>
<p>Easy things make us feel like we are fast.</p>
<blockquote><p>What type of runner can run full speed from the very start of the race? Thats right. Someone who runs very short distances. But as programmers, we are smarter than that. We just fire the starter pistol again every 100 yards.  I don&#8217;t know why runners haven&#8217;t figured that out.</p></blockquote>
<p>Ignoring complexity will slow you down if you aren&#8217;t just doing a very small project.<br />
There are many constructs that are easy to use, but are very complex.</p>
<p><strong>Benefits of Simplicity:</strong></p>
<ul>
<li>Ease of understanding</li>
<li>Ease of change</li>
<li>Easier debugging</li>
<li>Flexibility</li>
<li>More independence for change.</li>
</ul>
<p><strong>Making Things Easy:</strong></p>
<ul>
<li>Making it &#8220;at hand&#8221; by bringing it into our environment&#8211;installing it.</li>
<li>Become familiar with it by learning it.</li>
<li>There is a mental barrier. We can&#8217;t really get much smaller.</li>
</ul>
<p>We are all very limited compared to the complexity we create. The difference between a really smart programmer and an average programmer is minimal&#8211;no one can really understand all of the complexity we can create.  A juggler can juggle 3 balls. A really good juggler can juggle 9. No juggler can juggle 90 or 900.</p>
<blockquote><p>Everyone has seen parenthesis, but they haven&#8217;t seen it on THAT SIDE of the method. Thats crazy!</p></blockquote>
<p>Parenthesis are overloaded in lisp. They do several different things so they are complex. By removing this complexity the ease problem is back in the domain of what we can change.</p>
<p>Everyone is happy to grab benefits of new tools, but no one takes the time to see if there are any trade offs.</p>
<ul>
<li>Complect = braid together.</li>
<li>Compose = place together.</li>
</ul>
<p>We can write modules that are completely complected. What are your modules allowed to &#8220;think&#8221; about. Just partitioning doesn&#8217;t give you simplicity.</p>
<p>Having state is never simple because it complects value and time. It is easy, familiar, at hand, etc. The only way to get rid of state is to put it in a box that gives you a functional interface where you always get the same output with the same input.</p>
<p>Simplicity is a choice. It is your fault if you don&#8217;t have a simple system.</p>
</div>
<h4>People Found This When Looking For:</h4><ul><li>simple made easy rich hickey (40)</li><li>simple made easy (30)</li><li>rich hickey simple made easy (17)</li><li>rich hickey strangeloop (13)</li><li>rich hickey strange loop (13)</li><li>simple made easy hickey (11)</li><li>download simple made easy rich hickey (11)</li><li>strangeloop rich hickey (10)</li><li>rich hickey simplicity (8)</li><li>hickey simple made easy (6)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/1069/simple-made-easy-rich-hickey/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tapestry and testng.xml</title>
		<link>http://blog.markwshead.com/1007/tapestry-and-testng-xml/</link>
		<comments>http://blog.markwshead.com/1007/tapestry-and-testng-xml/#comments</comments>
		<pubDate>Sun, 07 Aug 2011 04:06:49 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Tapestry]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=1007</guid>
		<description><![CDATA[You can use a testng.xml file to help control the tests and browser used by Selenium in Tapestry.  However, you have to tell Maven to look for the testng.xml file or it will ignore it.  You do this by putting the following in your pom.xml -&#62; build -&#62; plugins: People Found This When Looking For:testng [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>You can use a testng.xml file to help control the tests and browser used by Selenium in Tapestry.  However, you have to tell Maven to look for the testng.xml file or it will ignore it.  You do this by putting the following in your pom.xml -&gt; build -&gt; plugins:</p>
<pre class="brush: xml; title: ; notranslate">
			&lt;plugin&gt;
				&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
				&lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
				&lt;version&gt;2.6&lt;/version&gt;
				&lt;configuration&gt;
					&lt;suiteXmlFiles&gt;
						&lt;suiteXmlFile&gt;src/test/conf/testng.xml&lt;/suiteXmlFile&gt;
					&lt;/suiteXmlFiles&gt;
				&lt;/configuration&gt;
			&lt;/plugin&gt;
</pre>
<h4>People Found This When Looking For:</h4><ul><li>testng xml (23)</li><li>testng xml example (5)</li><li>testng xml file (3)</li><li>tapestry testng (3)</li><li>testng xml sample (2)</li><li>testng version tapestry pom (1)</li><li>testng testng xml (1)</li><li>what is tapestry? (1)</li><li>TestNG testng = new TestNG(); xml (1)</li><li>testng tapestry (1)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/1007/tapestry-and-testng-xml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lucene MoreLikeThis Example Code</title>
		<link>http://blog.markwshead.com/966/lucene-morelikethis-example-code/</link>
		<comments>http://blog.markwshead.com/966/lucene-morelikethis-example-code/#comments</comments>
		<pubDate>Thu, 26 May 2011 23:10:09 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=966</guid>
		<description><![CDATA[I was recently working on a simple application where the user will enter famous quotations.  Obviously we want to avoid duplicates so I needed a way to check for quotations that were substantially similar before a new quote was added to the database. The idea was to show the top 5 most similar quotes before letting the [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I was recently working on a simple application where the user will enter <a href="http://www.noteaquote.com/">famous quotations</a>.  Obviously we want to avoid duplicates so I needed a way to check for quotations that were substantially similar before a new quote was added to the database.</p>
<p>The idea was to show the top 5 most similar quotes before letting the user save the new quotation to the db. I used Lucene for this which allowed me to punt on the more difficult task of figuring out if two quotes were similar or not. I left that up to Lucene and only had to worry about how to get my information in and out of Lucene in a usable manner.</p>
<p>Below is the interesting method that uses Lucene to build an index of all the quotes in the system and then returns the five quotes that are most similar to the new quote text.  Obviously creating a new index each time a quote is added isn&#8217;t particularly efficient, but makes it easier to demonstrate how it works and processor efficiency isn&#8217;t much of an issue with this particular task.</p>
<pre class="brush: java; title: ; notranslate">
    public List&lt;Quote&gt; getSimilarQuotes() throws CorruptIndexException, IOException {

        String quoteText = quote.getText();
        logger.info(&quot;creating RAMDirectory&quot;);
        RAMDirectory idx = new RAMDirectory();
        IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_31, new StandardAnalyzer(Version.LUCENE_31));
        IndexWriter writer = new IndexWriter(idx, indexWriterConfig);

        List&lt;Quote&gt; quotes =  session.createCriteria(Quote.class).list();

        //Create a Lucene document for each quote and add them to the
        //RAMDirectory Index.  We include the db id so we can retrive the
        //similar quotes before returning them to the client.
        for (Quote quote : quotes) {
            Document doc = new Document();
            doc.add(new Field(&quot;contents&quot;, quote.getText(),Field.Store.YES, Field.Index.ANALYZED));
            doc.add(new Field(&quot;id&quot;, quote.getId().toString() ,Field.Store.YES, Field.Index.ANALYZED));
            writer.addDocument(doc);
        }

        //We are done writing documents to the index at this point
        writer.close();

        //Open the index
        IndexReader ir = IndexReader.open(idx);
        logger.info(&quot;ir has &quot; + ir.numDocs() + &quot; docs in it&quot;);
        IndexSearcher is = new IndexSearcher(idx, true);

        MoreLikeThis mlt = new MoreLikeThis(ir);

 		//lower some settings to MoreLikeThis will work with very short
        //quotations
        mlt.setMinTermFreq(1);
        mlt.setMinDocFreq(1);

		//We need a Reader to create the Query so we'll create one
        //using the string quoteText.
        Reader reader = new StringReader(quoteText);

        //Create the query that we can then use to search the index
        Query query = mlt.like( reader);

        //Search the index using the query and get the top 5 results
        TopDocs topDocs = is.search(query,5);
        logger.info(&quot;found &quot; + topDocs.totalHits + &quot; topDocs&quot;);

        //Create an array to hold the quotes we are going to
        //pass back to the client
        List&lt;Quote&gt; foundQuotes = new ArrayList&lt;Quote&gt;();
        for ( ScoreDoc scoreDoc : topDocs.scoreDocs ) {
            //This retrieves the actual Document from the index using
            //the document number. (scoreDoc.doc is an int that is the
            //doc's id
            Document doc = is.doc( scoreDoc.doc );

            //Get the id that we previously stored in the document from
            //hibernate and parse it back to a long.
            String idField =  doc.get(&quot;id&quot;);
            long id = Long.parseLong(idField);

            //retrieve the quote from Hibernate so we can pass
            //back an Array of actual Quote objects.
            Quote thisQuote = (Quote)session.get(Quote.class, id);

            //Add the quote to the array we'll pass back to the client
            foundQuotes.add(thisQuote);
        }

        return foundQuotes;
    }
</pre>
<h4>People Found This When Looking For:</h4><ul><li>lucene indexwriterconfig (168)</li><li>lucene example (150)</li><li>lucene morelikethis (109)</li><li>IndexWriterConfig example (90)</li><li>IndexWriterConfig (51)</li><li>morelikethis lucene (38)</li><li>lucene indexwriterconfig example (34)</li><li>lucene more like this (33)</li><li>lucene examples (31)</li><li>lucene morelikethis example (30)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/966/lucene-morelikethis-example-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Tapestry 5 &#8211; 10 Minute Demo of Apache Tapestry</title>
		<link>http://blog.markwshead.com/900/tapestry-5-10-minute-demo/</link>
		<comments>http://blog.markwshead.com/900/tapestry-5-10-minute-demo/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 04:07:18 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tapestry]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=900</guid>
		<description><![CDATA[This is a demonstration of about 10 minutes of programming in Tapestry 5 creating a sample application. The app is pretty basic and just lets you add URLs to a list and then vote on them-similar to the idea behind Digg or Reddit. I didn&#8217;t really explain things in great detail so it is more of a [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>This is a demonstration of about 10 minutes of programming in Tapestry 5 creating a sample application. The app is pretty basic and just lets you add URLs to a list and then vote on them-similar to the idea behind Digg or Reddit. I didn&#8217;t really explain things in great detail so it is more of a demonstration of some of the things you can do than it is a step by step tutorial.<br />
<span id="more-900"></span><br />
<iframe width="853" height="510" src="http://www.youtube.com/embed/-vzCfzJ7ETA" frameborder="0" allowfullscreen></iframe><br />
General steps in making the application:</p>
<ul>
<li>Create a Quickstart application from the Maven archetype.</li>
<li>Add the dependencies and configs for Hibernate.</li>
<li>Create an Item entity to store our url, title, and number of votes.</li>
<li>Use a BeanEditForm and onSuccess method to create Items.</li>
<li>Use a Loop to show the items in the database</li>
<li>Use an ActionLink and onActionFromVote method to count the votes</li>
<li>Add onValidate method to do validate the URLs.</li>
<li>Stick the loop in a Zone and update it with the ActionLink</li>
</ul>
<p>The app uses the Quickstart archetype from 5.3 so it uses the new green theme.</p>
<h3>Errata</h3>
<ul>
<li>I used @Component on the BeanEditForm, but I should have used @InjectComponent.  As you can see in the comments, Howard isn&#8217;t really sure why this worked. So use @InjectComponent instead.</li>
<li>The zone should have gone around the ul elements instead of within it.  The zone renders as a div and we shouldn&#8217;t have a div inside of the open/close ul.</li>
</ul>
<h4>People Found This When Looking For:</h4><ul><li>tapestry 5 (75)</li><li>apache tapestry (26)</li><li>tapestry demo (19)</li><li>tapestry tutorial (16)</li><li>tapestry 5 demo (14)</li><li>tapestry 10 minute (10)</li><li>apache tapestry tutorial (9)</li><li>tapestry 5 example (8)</li><li>tapestry hibernate (8)</li><li>tapestry5 demo (7)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/900/tapestry-5-10-minute-demo/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>State Machines &#8211; Basics of Computer Science</title>
		<link>http://blog.markwshead.com/869/state-machines-computer-science/</link>
		<comments>http://blog.markwshead.com/869/state-machines-computer-science/#comments</comments>
		<pubDate>Sat, 12 Feb 2011 18:02:53 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=869</guid>
		<description><![CDATA[Computer science is what enables programming, but it is possible to do a lot of programming without understanding the computer science concepts underlying the process of computation. This isn&#8217;t always a bad thing.  When we program we work at a much higher level of abstraction.  When we drive a car, we only concern ourselves with [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Computer science is what enables programming, but it is possible to do a lot of programming without understanding the computer science concepts underlying the process of computation. This isn&#8217;t always a bad thing.  When we program we work at a much higher level of abstraction.  When we drive a car, we only concern ourselves with two or three pedals, a gearshift and a steering wheel.  You can safely operate a car without having any clear idea of how it works. However, if you want to operate a car at the very limits of its capabilities, you need to know a lot more about automobiles than just the three pedals, gearshift and steering wheel.</p>
<p>The same is true of programming.  Much mundane everyday work that can be accomplished with little or no understanding of computer science. You don&#8217;t need to understand computational theory to build a &#8220;contact us&#8221; form in PHP.  However, if you plan to write code that requires serious computation, you are going to need to understand a bit more about how computation works under the hood.</p>
<p>The purpose of this article is to provide some fundamental background for computation. If there is interest I may follow up with some more advanced topics, but right now I want to look at the logic behind one of the simplest abstract computational devices&#8211;a finite state machine.</p>
<h3>Finite State Machine</h3>
<p>A finite state machine is a mathematical abstraction used to design algorithms. In simple terms, a state machine will read a series of inputs.  When it reads an input it will switch to a different state.  Each state specifies which state to switch for a given input.  This sounds complicated but it is really quite simple.</p>
<p>Imagine a device that reads a long piece of paper.  For every inch of paper there is a single letter printed on it&#8211;either the letter a or the letter b.</p>
<p><img class="aligncenter size-full wp-image-870" title="finite-state-machine-tape" src="http://blog.markwshead.com/wp-content/uploads/2011/02/finite-state-machine-tape.png" alt="" width="463" height="94" />As the state machine reads each letter it changes state.  Here is a very simple state machine.</p>
<p><img class="aligncenter size-full wp-image-871" title="simple-state-machine" src="http://blog.markwshead.com/wp-content/uploads/2011/02/simple-state-machine.png" alt="" width="304" height="183" />The circles are &#8220;states&#8221; that the machine can be in.  The arrows are the transitions.  So if you are in state <em>s</em> and read an <em>a</em> you&#8217;ll transition to state <em>q</em>.  If you read a <em>b</em>, you&#8217;ll stay in state <em>s</em>.</p>
<p>So if we start on s and read the paper tape above from left to right, we will read the <em>a</em> and move to state <em>q</em>.  Then we&#8217;ll read a <em>b</em> and move back. Another <em>b</em> will keep us on s followed by an <em>a</em> which moves us back to the <em>q</em> state. Simple enough, but whats the point?</p>
<p>Well it turns out that you can run a tape through the state machine and once it is done tell something about the sequence of letters by examining the state you end up on.  In our simple state machine above, if we end on <em>s</em>, the tape ends with the letter <em>b</em>, if we end on <em>q</em>, the tape ends with the letter <em>a</em>.</p>
<p>This may sound pointless, but there are an awful lot of problems that can be solved with this type of approach. A very simple example would be to determine if a page of HTML contains these tags in this order:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
	&lt;head&gt;
	&lt;/head&gt;
	&lt;body&gt;
	&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The state machine can move to state that shows it has read the html tag, loop until it gets to the head tag, loop until it gets to the head close tag, etc. If it successfully makes it to the final state, then you have those particular tags in the right order.</p>
<p>Finite state machines can also be used to represent the mechanics of a parking meter, pop machine, automated gas pump and all kinds of other things.</p>
<h3><strong>Deterministic Finite State Machine</strong></h3>
<p>The state machines we&#8217;ve looked at so far are all deterministic state machines.  From any state there is only one transition for any allowed input.  In other words there aren&#8217;t two paths leading out of a state when you read the letter <em>a</em>. At first this sounds silly to even make this distinction.</p>
<p>What good is a set of decisions if the same input can result in moving to more than one state?  You can&#8217;t tell a computer, if x==true then execute doSomethingBig or execute doSomethingSmall, can you?</p>
<p>Well you kind of can with a state machine. The output of a state machine is its final state.  It goes through all its processing and then the final state is read and <strong>then</strong> an action is taken. A state machine doesn&#8217;t <strong>do</strong> anything as it moves from state to state.  It processes and then when it gets to the end, the state is read and something external triggers the desired action (dispenses a soda can, etc.).  This is an important concept when it comes to non-deterministic finite state machines.</p>
<h3>Non-deterministic Finite State Machine</h3>
<p>Non-deterministic finite state machines are finite state machines where a given input from a particular state can lead to more than one different state.  For example, lets say we want to build a finite state machine that can recognize strings of letters that start with a and are then followed by zero or more occurrences of the letter b or zero or more occurrences of the letter c terminated by the next letter of the alphabet. Valid strings would be:</p>
<ul>
<li>abbbbbbbbbc</li>
<li>abbbc</li>
<li>acccd</li>
<li>acccccd</li>
<li>ac (zero occurrences of b)</li>
<li>ad (zero occurrences of c)</li>
</ul>
<p>So it will recognize the letter <em>a</em> followed by zero or more of the same letter of <em>b</em> or <em>c</em> followed by the next letter of the alphabet. A very simple way to represent this is with a state machine that looks like the one below, where a final state of <em>t</em> means that the string was accepted and matches the pattern.</p>
<p><img class="aligncenter size-full wp-image-876" title="non-deterministic-finite-state-machine" src="http://blog.markwshead.com/wp-content/uploads/2011/02/non-deterministic-finite-state-machine.png" alt="" width="417" height="360" />Do you see the problem?  From starting point s, we don&#8217;t know which path to take.  If we read the letter <em>a</em>, we don&#8217;t know whether to go to the state <em>q</em> or <em>r. </em>There are a few ways to solve this problem.  One is by back tracking.  You simply take all the possible paths and ignore or back out of the ones where you get stuck.</p>
<p>This is basically how most of the chess playing computers work.  They look at all the possibilities and all the possibilities of those possibilities and choose the path that gives them the greatest number of advantages over their opponent.</p>
<p>The other option is to convert the non-deterministic machine into a deterministic machine. One of the interesting attributes of a non-deterministic machine is that there exists an algorithm to turn any non-deterministic machine into a deterministic one.  However, it is often much more complicated.  Fortunately for us, the example above is only slightly more complicated. In fact this one is simple enough we can transform it into a deterministic machine in our head without the aid of a formal algorithm.</p>
<p>The machine below is a deterministic version of the non-deterministic machine above.  In the machine below, a final state of <em>t</em> or <em>v </em>is reached by any string that is accepted by the machine.</p>
<p><img class="aligncenter size-full wp-image-892" title="deterministic-conversion" src="http://blog.markwshead.com/wp-content/uploads/2011/02/deterministic-conversion2.png" alt="" width="337" height="405" /></p>
<p>The non-deterministic model has four states and six transitions.  The deterministic model has 6 states, 10 transitions and two possible final states. That isn&#8217;t that much more, but the complexity usually grows exponentially and a moderately sized non-deterministic machine can produce an absolutely huge deterministic machine.</p>
<h3>Regular Expression</h3>
<p>If you have done any type of programming, you&#8217;ve probably encountered regular expressions.  Regular expressions and finite state machines are functionally equivalent.  Anything you can accept or match with a regular expression can be accepted or matched with a state machine. For example the pattern above could be matched with:</p>
<p>a(b*c|c*d)</p>
<p>Regular expressions and finite state machines also have the same limitations.  In particular they both can only match or accept patterns that can be handled with finite memory.  So what type of patterns can&#8217;t they match?  Lets say you want to only match strings of a and b, where there are a number of a&#8217;s followed by an equal number of b&#8217;s. Or n a&#8217;s followed by n b&#8217;s where n is some number. Examples would be:</p>
<ul>
<li>ab</li>
<li>aabb</li>
<li>aaaaaabbbbbb</li>
<li>aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbb</li>
</ul>
<p>At first this looks like an easy job for a finite state machine. The problem is that you&#8217;ll quickly run out of states or you&#8217;ll have to assume an infinite number of states&#8211;at which point it is no longer a finite state machine. Lets say you create a finite state machine that can accept up to 20 a&#8217;s followed by 20 b&#8217;s.  That works fine until you get a string of 21 a&#8217;s followed by 21 b&#8217;s at which point you either need to rewrite your machine to handle a longer string. For any string you can recognize, there is one just a little bit longer that your machine can&#8217;t recognize because it runs out of memory.</p>
<p>This is known as the Pumping Lemma which basically says, if your pattern has a section that can be repeated like the one above then the pattern is not regular.  In other words you can&#8217;t use a regular expression or finite state machine to recognize all the strings that <em>do</em> match the pattern.</p>
<p>If you look carefully, you&#8217;ll notice that this type of pattern where every a has a matching b, looks very similar to HTML where within any pair of tags you may have any number of other matching pairs of tags. So while you may be able to use a regular expression or finite state machine to recognize if a page of HTML has the html, head and body elements in the correct order, you can&#8217;t use a regular expression to tell if an entire HTML page is valid or not because HTML is not a regular pattern.</p>
<h3>Turing Machines</h3>
<p>So how do you recognize non-regular patterns?  There is a theoretical device that is similar to a state machine called a Turing Machine.  It is similar to a finite state machine that it has a paper strip that it reads, but a Turing Machine can erase and write on the paper tape. Explaining a Turing Machine will take more space that we have here, but there are a few important points relevant to our discussion of finite state machines and regular expressions.</p>
<p>Turing Machines are computationally complete and anything that can be computed can be computed on a Turing Machine. Since a Turing Machine can write as well as read from the paper tape, it is not limited to a finite number of states. The paper tape can be assumed to be infinite in length.  Obviously actual computers don&#8217;t have an infinite amount of memory, but they contain enough memory that you don&#8217;t hit the limit for the type of problems they process.</p>
<p>Turing Machines give us an imaginary mechanical device that lets us visualize and understand how the computational process works. It is particularly useful in understanding the limits of computation. If there is interest I&#8217;ll do another article on Turing Machines in the future.</p>
<h3>Why does this matter?</h3>
<p>So whats the point?  How is this going to help you create that next PHP form?  Regardless of their limitations state machines are a very central concept to computing.  In particular the recognition that for any non-deterministic state machine you can design, there exists a deterministic state machine that does the same thing.  This is a very key point because it means you can design your algorithm in which ever way is the easiest to think about.  Once you have a proper algorithm, you can convert it into whatever form is most efficient.</p>
<p>The understanding that finite state machines and regular expressions are functionally equivalent opens up some incredibly interesting uses for regular expression engines&#8211;particularly when it comes to creating business rules that can be changed without recompiling a system.</p>
<p>A foundation in computer science allows you to take a problem X that you don&#8217;t know how to solve and reason, &#8220;I don&#8217;t know how to solve X, but I do know how to solve Y and I know how to convert a solution for Y into a solution for X.  Therefore I now known how to solve X.&#8221;</p>
<h4>People Found This When Looking For:</h4><ul><li>state machine (2777)</li><li>finite state machine (333)</li><li>state machines (202)</li><li>statemachines (131)</li><li>basics of computer science (115)</li><li>finite state machines (102)</li><li>fundamentals of computer science (100)</li><li>fundamentals of computer (66)</li><li>computer science basics (56)</li><li>what is a state machine (45)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/869/state-machines-computer-science/feed/</wfw:commentRss>
		<slash:comments>62</slash:comments>
		</item>
		<item>
		<title>How to Charge for Programming</title>
		<link>http://blog.markwshead.com/866/how-to-charge-for-programming/</link>
		<comments>http://blog.markwshead.com/866/how-to-charge-for-programming/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 16:25:28 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=866</guid>
		<description><![CDATA[Charging for programming can be a bit tricky.  Clients obviously would prefer a solid quote. However, any experienced programmer knows that what the client wants is going to change as the software takes shape. Furthermore, any non-trivial program is going to involve some unknown problems that the programmer may be able to solve quickly, but [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Charging for programming can be a bit tricky.  Clients obviously would prefer a solid quote. However, any experienced programmer knows that what the client wants is going to change as the software takes shape. Furthermore, any non-trivial program is going to involve some unknown problems that the programmer may be able to solve quickly, but might take a long time. It isn&#8217;t easy to estimate how long it will take to find an algorithm that does X in Y seconds.</p>
<p>In order to feel safe giving a firm quote, a programmer is going to have to pad the numbers quite a bit to deal with unknowns, client changes, etc.  Of course this might push the price up to the point where the client decides it isn&#8217;t worth it.</p>
<p>An experienced client is going to have already experienced a project where they paid lots of money just working off of an estimate only to end up with software that doesn&#8217;t work and a code base that no one else is willing to touch. They can either keep sinking money into the project or just write off the whole thing as a failure.</p>
<p>So how can you compromise between what the client and the programmer both need?</p>
<h3>1. Small bites</h3>
<p>If you can determine the smallest amount of functionality for the software to be useful to the client, do that as an independent project first.  Instead of trying to quote for an entire year long programming job, pick the part that solves the most number of issues with the least amount of work and try to have something delivered in 2 to 4 weeks or less.</p>
<p>The client likes this approach because you are delivering solutions to problems instead of just a program. If they can get their biggest problems solved early on with the least amount of expense, so much the better. They may want you to do x, y an z, but if x gives them 90% of the benefits, you should definitely do that as a project and then let them decide if they want to proceed with y and z.</p>
<p>What you learn in completing the first project will make your estimate of the next project much more accurate. The chances of you getting anywhere near an accurate estimate when estimating x, y and z all together are very low.  The chances of you being able to accurately estimate y after having completed x are much greater.</p>
<p>You as the programmer face a lot less risk with a 2 to 4 week project as long as the requirements are defined and the scope is clear to both parties.  Keep in mind you need to clearly articulate not only what the software will do, but also what it will <strong>not</strong> do. Make sure the client knows what is being left out and what will be part of future projects should they choose to proceed.</p>
<h3>2. Range estimate with upper limit</h3>
<p>The client doesn&#8217;t want to pay twice as much just because you won&#8217;t know how long the project will take until you are half way done.  If you give a single quote that factors in the risk, they may feel they are being taken advantage of.  On the other hand, you don&#8217;t want to give a low bid only to find you drastically underestimated how difficult it would be to solve particular problems, interface with their existing system, etc.</p>
<p>Giving an estimate such as $5,000 to $10,000 with a cap of $10,000 is often a fair way to handle the needs of both sides. The greater the unknown risks, the wider the gap between the first and second number.  Basically the second number is the amount you&#8217;d want if you were giving a hard quote.  It should factor in all the risks of dealing with unknowns, the chance that the customer will change their mind a lot, etc.  The first number should be a reasonable estimate if everything goes ok with only a few minor problems.</p>
<p>The client will need to commit to paying up to the higher number.  If the project is worth it to them at $5,000, but not at $10,000 then you need to reduce the scope until the value and your upper limit match.</p>
<h3>3. Charging for programming time</h3>
<p>Some people like charging a low rate, but charging for every minute they spend on the project. They operate with the idea that, &#8220;If I&#8217;m doing something I wouldn&#8217;t be doing on my own, the clock is running.&#8221; This seems reasonable from the programmer&#8217;s standpoint.  However, imagine you are personally hiring a graphic designer to create some designs in HTML 5. The designer is good, but has mainly done work in HTML 4.  As a result they are going to be spending at least some of their time learning exactly how to use HTML 5. Do you want to be paying for their learning curve? Probably not.</p>
<p>Chances are very high that not all of your time on a programming project are going to be spent actually coding.  You&#8217;ll probably spend time doing the following:</p>
<ul>
<li>Reading the documentation for your framework</li>
<li>Looking for open source libraries that will do what you need</li>
<li>Looking through mailing lists archives to see how other people solved similar problems.</li>
<li>etc.</li>
</ul>
<p>These all might sound like reasonable things to charge for, but they are investments in making you a better programmer. My preference is to charge a much higher rate as an expert, but not bill for learning anything new.</p>
<p>I use a time tracking tool (Mylyn and TaskTop) that measures how long I spend working on a particular issue in my IDE.  That way I&#8217;m only measuring the time spend coding and not any of the time I spend doing research. The tool I use, times out after three minutes.  So if I just need to jump over to lookup the specifics of an API call, all the time is counted.  However, if I head off on a 30 minute search for a better open source expression language to embed in my program, it isn&#8217;t.</p>
<p>There are three consequences of this type of billing:</p>
<ul>
<li>The hourly rate I charge is much higher than some of my peers.</li>
<li>20 to 30 billable programming hours is a full week.</li>
<li>My estimates are much more accurate because I&#8217;m only estimating actual coding time.</li>
</ul>
<h3>4. Getting paid</h3>
<p>With known and trusted clients, I bill at the end of the month for any work performed during that month.  With unknown clients, I prefer that they pay ahead of time.  When my work depletes their deposit, they need to deposit some more money.</p>
<h3>5. Partnerships</h3>
<p>The world is full of people with no programming skills who are trying to invent the next Facebook and feel that the only thing holding them back is the fact that they can&#8217;t afford a programmer willing to work for a percentage of the company. You want to avoid people like that.  Ideas are cheap and generally you don&#8217;t want to ever partner with someone who is wanting you to bring the man hours and they will bring the &#8220;ideas&#8221;.</p>
<p>However, there are people that have something significant to offer that you can&#8217;t get easily on your own.  In particular this comes in the form of marketing and existing customers. The hard part of making money from selling software isn&#8217;t writing the software&#8211;it is getting noticed.  Partnerships with people who can help your product get noticed can be valuable.</p>
<p>You want to avoid partnerships where you front all the risk though. Your partner needs to have some type of incentive to use their connections, mailing list, clout or whatever to promote the product once it is ready to go.  One easy way to do this is to split the development cost.  You approach things the same way you do with a client, but you and your partner are both responsible for half the bill.  If you are operating as a sole proprietor, then you simply don&#8217;t pay your half of the bill.  If you have a corporation you may pay your half personally.</p>
<p>This type of arrangement means you both have something invested.  You have your time and they have their money&#8211;albiet a lot less money than they would have if they were to have tried to do it on their own.</p>
<p>If you deliver the software, but your partner turns out to be incapable of actually marketing it, you still have half of what you&#8217;d normally bill.</p>
<p><em>Partnerships are tricky and you need to be very clear and very careful how you set things up, so make sure you do your homework.  The main point here is to not overlook partnerships when the partner has something genuine to offer&#8211;and very rarely is that going to be their idea.</em></p>
<h4>People Found This When Looking For:</h4><ul><li>how to charge for software development (20)</li><li>how to charge for programming (15)</li><li>what to charge for programming (12)</li><li>programming - how to calculate time for project to complete (11)</li><li>how to bill for software projects (9)</li><li>how much to charge for programming (8)</li><li>charging for software development (6)</li><li>how to charge for software (6)</li><li>how to charge software (5)</li><li>How to charge for programming work (5)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/866/how-to-charge-for-programming/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Tapestry Facebook Share Component</title>
		<link>http://blog.markwshead.com/845/tapestry-facebook-share-component/</link>
		<comments>http://blog.markwshead.com/845/tapestry-facebook-share-component/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 23:23:26 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Tapestry]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=845</guid>
		<description><![CDATA[I am working on a project where we need to be able to do a Facebook share on a particular page for an event from multiple places within a web application. Putting this functionality into a Tapestry component makes it easy to call it from where ever it is needed and the code makes for [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I am working on a project where we need to be able to do a Facebook share on a particular page for an event from multiple places within a web application.  Putting this functionality into a Tapestry component makes it easy to call it from where ever it is needed and the code makes for a nice concise example of how components work in Tapestry.</p>
<p>In Tapestry components consist of two parts.  The first part is the .tml file and the second is the .java file. In general the .tml file is concerned with how things render out in HTML and the .java file is concerned with the programatic side of things and retrieving the data.  </p>
<p>The end result is going to be a tag that we can use in other .tml files that will look like this:</p>
<pre class="brush: xml; title: ; notranslate">&lt;t:facebookshare event=&quot;myEvent&quot;/&gt;</pre>
<p>First lets look at the .tml file.  This file is saved under:<br />
<code>/src/main/resources/com/example/myapp/components/FacebookShare.tml</code></p>
<pre class="brush: xml; title: ; notranslate">
&lt;t:container xmlns:t=&quot;http://tapestry.apache.org/schema/tapestry_5_1_0.xsd&quot; &gt;
&lt;a href=&quot;#&quot; onclick=&quot;window.open('http://www.facebook.com/sharer.php?u=${facebookShareURL}&amp;amp;display=popup','fbshare','menubar=0,location=0,resizable=1,width=700,height=350')&quot;&gt;
	Please share this event on Facebook
&lt;/a&gt;&lt;br/&gt;
&lt;/t:container&gt;
</pre>
<p>The ${facebookShareURL} is what will call getFacebookShareUrl() on the java class in order to fill out the component with the data it needs.  In this case it will be an encoded URL.</p>
<p>The .java component file is saved in:<br />
<code>/src/main/java/com/example/myapp/components/FacebookShare.java</code></p>
<pre class="brush: java; title: ; notranslate">
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.persistence.Transient;

import net.xeric.register.entities.Event;

import org.apache.tapestry5.Link;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;

public abstract class FacebookCommon {

    @Inject
    private PageRenderLinkSource linkSource;

    @Parameter(required=true)
    @Property
    private Event event;

    public String getFacebookShareURL() {
        Link link = linkSource.createPageRenderLinkWithContext(&quot;EventInfo&quot;, event);
        String linkURL = &quot;&quot;;
        try {
            linkURL =  URLEncoder.encode(link.toAbsoluteURI(),&quot;UTF-8&quot;);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return linkURL;
    }
}
</pre>
<p>I have a page called EventInfo that shows all the information about a particular event.  So this component takes an event as a parameter and then constructs the link to share on the EventInfo page.</p>
<p>This is how we tell Tapestry that we have a required parameter that needs to be bound to an event:</p>
<pre class="brush: java; first-line: 19; title: ; notranslate">
    @Parameter(required=true)
    @Property
    private Event event;
</pre>
<p>That means that when we use the component like this:</p>
<pre class="brush: xml; title: ; notranslate">&lt;t:facebookshare event=&quot;myEvent&quot;/&gt;</pre>
<p>Tapestry is going to expect the parameter event to be bound to an event object.</p>
<p>Line 42 has the code that constructs our link back to the EventInfo page using the context of the event that we&#8217;ve passed in as a parameter to the component.</p>
<pre class="brush: java; first-line: 42; title: ; notranslate">
        Link link = linkSource.createPageRenderLinkWithContext(&quot;EventInfo&quot;, event);
        String linkURL = &quot;&quot;;
        try {
            linkURL =  URLEncoder.encode(link.toAbsoluteURI(),&quot;UTF-8&quot;);
</pre>
<p>The rest of the getFacebookShareURL method simply encodes the URL as a string and returns it. This is the value that replaces the ${facebookShareUrl} in the template when the component is rendered.</p>
<h4>People Found This When Looking For:</h4><ul><li>facebook sharer (57)</li><li>facebook sharer php parameters (6)</li><li>facebook tapestry (5)</li><li>tapestry facebook (5)</li><li>facebook share components (3)</li><li>share component (3)</li><li>sharer facebook (3)</li><li>tapestry component (3)</li><li>tapestry createPageRenderLinkWithContext (3)</li><li>tapestry components (3)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/845/tapestry-facebook-share-component/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get the URL of a Page in Tapestry 5</title>
		<link>http://blog.markwshead.com/825/get-the-url-of-page-in-tapestry-5/</link>
		<comments>http://blog.markwshead.com/825/get-the-url-of-page-in-tapestry-5/#comments</comments>
		<pubDate>Tue, 21 Dec 2010 02:23:29 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Tapestry]]></category>
		<category><![CDATA[tapestry]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=825</guid>
		<description><![CDATA[Sometimes your program will need to get the full URL of a page to send in an email, share on Facebook or run through a URL shortener to send to Twitter. You can do this by injecting the HTTPRequest and the building a string representation of the URL manually, but this is a lot more [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>Sometimes your program will need to get the full URL of a page to send in an email, share on Facebook or run through a URL shortener to send to  Twitter. You can do this by injecting the HTTPRequest and the building a string representation of the URL manually, but this is a lot more work that it needs to be.  Here is a simple way to do it using Tapestry&#8217;s PageRenderLinkSource and a Link object.</p>
<pre class="brush: java; title: ; notranslate">
@Inject
PageRenderLinkSource linkSource

/**
 * Return a string with the full URL of MyPage with a
 * context of 5.
 */
public String getPageURL() {
	Link link = linkSource.createPageRenderLinkWithContext(&quot;MyPage&quot;, 5);
	return link.toAbsoluteURI();
}
</pre>
<p>I&#8217;ve hard coded the value 5 as the context&#8211;you&#8217;d normally set that based on whatever you are wanting to share. This method will return a link to MyPage with a context of 5, so it will probably look something like: <code>http://www.myserver.com/MyPage/5</code>.  One of the nice things about this solution is that it will automatically handle things if your application needs to use a URL like: <code>http://www.myserver.com/myapp/MyPage/5</code></p>
<h4>People Found This When Looking For:</h4><ul><li>tapestry get url (24)</li><li>tapestry url (22)</li><li>tapestry get page url (13)</li><li>tapestry5 get url (12)</li><li>tapestry page url (11)</li><li>tapestry5 url (11)</li><li>tapestry get current url (8)</li><li>tapestry get current page (8)</li><li>tapestry current url (7)</li><li>tapestry5 get Context (6)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/825/get-the-url-of-page-in-tapestry-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Thinks There Are 13 Months</title>
		<link>http://blog.markwshead.com/821/java-thinks-there-are-13-months/</link>
		<comments>http://blog.markwshead.com/821/java-thinks-there-are-13-months/#comments</comments>
		<pubDate>Sat, 18 Dec 2010 19:13:23 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=821</guid>
		<description><![CDATA[I was working on a component for credit card processing where I needed to get the months of the year. Trying to plan ahead, I decided to use the DateFormatSymbols so it could easily handle localization if it ever needed to be used in a different language. It wasn&#8217;t doing what I expected and I [...]]]></description>
			<content:encoded><![CDATA[<p></p><p>I was working on a component for credit card processing where I needed to get the months of the year.  Trying to plan ahead, I decided to use the DateFormatSymbols so it could easily handle localization if it ever needed to be used in a different language.</p>
<p>It wasn&#8217;t doing what I expected and I finally found the problem with the following code:</p>
<pre class="brush: java; title: ; notranslate">
DateFormatSymbols symbols = new DateFormatSymbols();
String[] months = symbols.getMonths();
int numOfMonths = months.length
System.out.println(numOfMonths);
</pre>
<p>The output is 13. If you list all of the strings in the <code>months</code> array, you&#8217;ll find the first 12 are what you&#8217;d expect, but there is a 13th blank month at the end.</p>
<p>It turns out that there are some lunar based calendars that have to add a &#8220;leap month&#8221; every so many years.  This month is called Undecimber and comes after December. However, I&#8217;m not clear why Java is giving me a blank month.  If the given locale only has 12 months, what is the value of giving back a 13 item array and just leaving one blank?</p>
<h4>People Found This When Looking For:</h4><ul><li>are there 13 months (5)</li><li>java 13 month (3)</li><li>java 13 months (3)</li><li>java 13th month (3)</li><li>there are 13 months (3)</li><li>DateFormatSymbols 13 months (3)</li><li>java month 13 (2)</li><li>Is there 13 months (2)</li><li>java months 13 (2)</li><li>WAS THERE 13 MONTH (2)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/821/java-thinks-there-are-13-months/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Adding Context to Links in Tapestry</title>
		<link>http://blog.markwshead.com/814/adding-context-to-links-in-tapestry/</link>
		<comments>http://blog.markwshead.com/814/adding-context-to-links-in-tapestry/#comments</comments>
		<pubDate>Sat, 18 Dec 2010 05:07:50 +0000</pubDate>
		<dc:creator>Mark Shead</dc:creator>
				<category><![CDATA[Tapestry]]></category>

		<guid isPermaLink="false">http://blog.markwshead.com/?p=814</guid>
		<description><![CDATA[Introduction Tapestry looks at the URL and assumes that anything after the page name is the context that is being passed to the page. So a URL like: http://www.site.com/MyPage/5 Is going to expect that the number 5 is the context needed on MyPage.  You can have multiple contexts passed to a page like this: http://www.site.com/MyPage/5/foo [...]]]></description>
			<content:encoded><![CDATA[<p></p><h3>Introduction</h3>
<p>Tapestry looks at the URL and assumes that anything after the page name is the context that is being passed to the page. So a URL like:</p>
<p><code>http://www.site.com/MyPage/5</code></p>
<p>Is going to expect that the number 5 is the context needed on MyPage.  You can have multiple contexts passed to a page like this:</p>
<p><code>http://www.site.com/MyPage/5/foo</code></p>
<p>This will pass two contexts to the page.  Depending on what the page is expecting to receive in the context, these values may be uses as they are or they might be coerced into something else.  For example, the five might represent the ID of some object that will be retrieved from the Hibernate.</p>
<p>In the case of a single context value being passed, MyPage can get the value into a page property by doing something like this:</p>
<pre class="brush: java; title: ; notranslate">
@PageActivationContext
@Property
private int myNumber;
</pre>
<p>The PageActivationContext annotation tells Tapestry to put the value on the URL that comes after the page into that variable.  With Hibernate involved you can do something like this:</p>
<pre class="brush: java; title: ; notranslate">
@PageActivationContext
@Property
private Person aPerson;
</pre>
<p>Tapestry will tell Hibernate to get the person object with an id of 5 and assign it to the variable aPerson.</p>
<p>If the page has multiple context values being passed, they are handled through the onActivate method:</p>
<pre class="brush: java; title: ; notranslate">
public void onActivate(int myNumber, String myString) {
//set appropriate page properties
}
</pre>
<h3>PageLink</h3>
<p>Thats a little background.  The main thing I wanted to look at in this post is how to get links that pass in these context values in the first place.</p>
<p>This snippet shows a pagelink that will give us something of the form:<br />
<code>http://www.site.com/MyPage/5</code><br />
Assuming that the person.id is 5.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;t:pagelink page=&quot;MyPage&quot; context=&quot;person.id&quot;&gt;${person.name}&lt;/t:pagelink&gt;
</pre>
<p>If we need to pass multiple context values it can be done like this.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;t:pagelink page=&quot;MyPage&quot; context=&quot;[person.id,order.id]&quot;&gt;view order&lt;/t:pagelink&gt;
</pre>
<p>If person.id is 5 and order.id is 22 this link will produce:<br />
<code>http://www.site.com/MyPage/5/22</code></p>
<h3>Returning Page and Context from a Method</h3>
<p>Tapestry lets us return values in Java that specify the next page to load. This is commonly seen in the <code>onSuccess</code> method which can look like this:</p>
<pre class="brush: java; title: ; notranslate">

    public Object onSuccess() {
       //Do what needs to be done
       return &quot;MyPage&quot;;
    }
</pre>
<p>At first it looks like we can simply append the values like:</p>
<pre class="brush: java; title: ; notranslate">

    public Object onSuccess() {
       //Do what needs to be done
       return &quot;MyPage/&quot; + person.id + &quot;/&quot; + order.id;
    }
</pre>
<p>But this does not work because Tapestry can&#8217;t find the page &#8220;MyPage/5/22&#8243;.  It only knows about &#8220;MyPage&#8221;. To add a context you will need to inject the pageRenderLinkSource and use it to build the context.</p>
<pre class="brush: java; title: ; notranslate">
    @Inject
    private PageRenderLinkSource pageRenderLS;

    public Object onSuccess() {
       //Do what needs to be done
       return pageRenderLS.createPageRenderLinkWithContext(&quot;MyPage&quot;, person.id);
    }
</pre>
<p>You can add additional context values to the parameters as well.</p>
<pre class="brush: java; title: ; notranslate">
    @Inject
    private PageRenderLinkSource pageRenderLS;

    public Object onSuccess() {
       //Do what needs to be done
       return pageRenderLS.createPageRenderLinkWithContext(&quot;MyPage&quot;, person.id, order.id);
    }
</pre>
<h4>People Found This When Looking For:</h4><ul><li>tapestry context (82)</li><li>tapestry pagelink context (22)</li><li>tapestry pagelink (21)</li><li>context tapestry (18)</li><li>tapestry Link (14)</li><li>tapestry get context (12)</li><li>tapestry link context (11)</li><li>tapestry 5 pagelink (8)</li><li>tapestry context: (6)</li><li>tapestry5 pagelink context (5)</li></ul>]]></content:encoded>
			<wfw:commentRss>http://blog.markwshead.com/814/adding-context-to-links-in-tapestry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

