<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Interrupted]]></title>
  <link href="http://guilespi.github.com/atom.xml" rel="self"/>
  <link href="http://guilespi.github.com/"/>
  <updated>2015-04-13T10:49:24-03:00</updated>
  <id>http://guilespi.github.com/</id>
  <author>
    <name><![CDATA[Guillermo Winkler]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Verifying state machine behavior using test.check]]></title>
    <link href="http://guilespi.github.com/blog/2015/04/12/verifying-state-machine-behavior-using-test-dot-check/"/>
    <updated>2015-04-12T17:21:00-03:00</updated>
    <id>http://guilespi.github.com/blog/2015/04/12/verifying-state-machine-behavior-using-test-dot-check</id>
    <content type="html"><![CDATA[<p>My <a href="http://guilespi.github.com/blog/2015/04/12/property-based-testing-using-quickcheck/">previous post</a> was an introduction to the motivations and benefits of a <code>property-based</code> testing approach.</p>

<p>I also mentioned the <a href="https://www.youtube.com/watch?v=zi0rHwfiX1Q">John Hughes</a> talk, which is great.</p>

<p>But there&#8217;s a catch.</p>

<p>Until now, we&#8217;ve been considering <code>property-based</code> testing in a <em>functional way</em>, where properties for functions depend only on the function input, assuming no <em>state</em> between function invocations.</p>

<p>But that&#8217;s not always the case, sometimes our function inserts data into some database, sends an email, or sends a message to the car anti-lock braking system.</p>

<p>The examples John mentions in his talk are not straightforward to solve without Erlang&#8217;s QuickCheck, since they&#8217;re verifying <em>state machines</em> behavior.</p>

<p>Since I&#8217;m a Clojurist, I was <a href="https://twitter.com/guilespi/status/566315813268111360">a little confused</a> about why I couldn&#8217;t find a way to do that state machine magic using <code>test.check</code>, so bugging Reid and not reading the fine manual was the evident answer.</p>

<p>Thing is, test.check has this strategy of composing generators, particularly using <code>bind</code> you can generate a value based on a previously generated value by another generator.</p>

<p>For instance, this example shows how to generate a <code>vector</code> and then select an element from it:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">keyword-vector</span> <span class="p">(</span><span class="nf">gen/such-that</span> <span class="nv">not-empty</span> <span class="p">(</span><span class="nf">gen/vector</span> <span class="nv">gen/keyword</span><span class="p">)))</span>
</span><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">vec-and-elem</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">gen/bind</span> <span class="nv">keyword-vector</span>
</span><span class='line'>            <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">v</span><span class="p">]</span> <span class="p">(</span><span class="nf">gen/tuple</span> <span class="p">(</span><span class="nf">gen/elements</span> <span class="nv">v</span><span class="p">)</span> <span class="p">(</span><span class="nf">gen/return</span> <span class="nv">v</span><span class="p">)))))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="nf">gen/sample</span> <span class="nv">vec-and-elem</span> <span class="mi">4</span><span class="p">)</span>
</span><span class='line'><span class="c1">;; =&gt; ([:va [:va :b4]] [:Zu1 [:w :Zu1]] [:2 [:2]] [:27X [:27X :KW]])</span>
</span></code></pre></td></tr></table></div></figure>


<p>But it doesn&#8217;t have a declarative or simple way to model expected system state.</p>

<h2>What is state?</h2>

<p>First thing we should think about is, when we do have state? Opposed to a situation when we&#8217;re testing a <a href="http://en.wikipedia.org/wiki/Referential_transparency_%28computer_science%29">referentially transparent</a> function.</p>

<p>The function <code>sort</code> from the previous post is referentially transparent, since for the same input vector, always return the same sorted output.</p>

<p>But what happens when we have a situation like the one described in the talk about this circular buffer?</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/circularbuffer.png" width="680" height="780" title="'Circular Buffer'" ></p>

<p>If you want to test the behavior of the <code>put</code> and <code>remove</code> API calls, it depends on the <em>state</em> of the system, meaning what elements you already have on your buffer.</p>

<p>The properties <code>put</code> must comply with, depend on the system state.</p>

<p>So you have this slide from John&#8217;s presentation:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/fsmmodel.png" width="680" height="780" title="'API Modelling state'" ></p>

<p>With the strategy proposed by QuickCheck to model this testing problem:</p>

<ul>
<li>API under test is seen as a sequence of commands.</li>
<li>Model the state of the system you expect after each command execution.</li>
<li>Execute the commands and validate the system state is what you expect it to be.</li>
</ul>


<p>So we need to generate a <code>sequence</code> of commands and validate system state, instead of generating input for a single function.</p>

<p>This situation is more common than you may think, even if you&#8217;re doing functional programming state is everywhere, you have state on your databases and you also have state on your UI.</p>

<p>You would never think about <code>deleting an email</code>, and after than <code>sending the email</code>, that&#8217;s an invalid generated sequence of commands(relative to the &#8220;email composing state&#8221;).</p>

<p>This last example is exactly the one described by <a href="https://www.youtube.com/watch?v=HXGpBrmR70U">Ashton Kemerling</a> from Pivotal, they&#8217;re using <code>test.check</code> to randomly generate test scenarios for the UI. And because test.check doesn&#8217;t have the <em>finite state machine modeling thing</em>, they ended up generating impossible or invalid action sequences, and having to discard them as <code>NO-OPs</code> when run.</p>

<h2>FSM Behavior</h2>

<p>The problem with Ashton&#8217;s approach for my situation, was that I had this possibly long sequence of commands or transactions, where each transaction modifies the state of the system, so the last one probable makes no sense at all without some of the <em>in-the-middle</em> ocurring transactions.</p>

<p>The problem is not only discarding invalid sequences, but how to generate something valid <em>at all</em>.</p>

<p>Say you have 3 possible actions:</p>

<ul>
<li>add <code>[id, name]</code></li>
<li>edit <code>[id, name]</code></li>
<li>delete <code>[id]</code></li>
</ul>


<p>If the command sequence you generate is:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">[{</span><span class="ss">:type</span> <span class="ss">:add</span> <span class="ss">:name</span> <span class="s">&quot;John&quot;</span> <span class="ss">:id</span> <span class="mi">1</span><span class="p">}</span>
</span><span class='line'> <span class="p">{</span><span class="ss">:type</span> <span class="ss">:add</span> <span class="ss">:name</span> <span class="s">&quot;Ted&quot;</span> <span class="ss">:id</span> <span class="mi">84</span><span class="p">}</span>
</span><span class='line'> <span class="p">{</span><span class="ss">:type</span> <span class="ss">:delete</span> <span class="ss">:id</span> <span class="mi">1</span><span class="p">}]</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>delete</code> action depends on two things:</p>

<ol>
<li>Someone to be already added (as in the circular buffer described above).</li>
<li>Selecting a valid <code>id</code> for deletion from the ones already added.</li>
</ol>


<p>It looks like something you would do using <code>bind</code>, but there&#8217;s something more, there&#8217;s a <code>state</code> that changes when each transaction is applied, and affects each potential command that may be generated afterwards.</p>

<p>Searching around, I found a document titled <a href="http://www.diva-portal.org/smash/get/diva2:343744/FULLTEXT01.pdf">Verifying Finite State Machine Behavior Using QuickCheck Eqc_fsm</a> by Ida Lindgren and Robin Malmros, it&#8217;s an evaluation from <em>Uppsala Universitet</em> to understand whether QuickCheck is suitable for testing mobile telephone communications with base transceiver stations.</p>

<p>Besides the evaluation itself which is worth reading, there&#8217;s a chapter on Finite State Machines I used as guide to implement something similar with <code>test.check</code>.</p>

<h2>The Command protocol</h2>

<p>There&#8217;s a nice diagram in the paper representing the Erlang&#8217;s finite state machine flow</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/fsmflow.png" width="680" height="780" title="'QuickCheck FSM Flow'" ></p>

<p>We observe a few things:</p>

<ul>
<li>You have a set of possible commands to generate.</li>
<li>Each command has a precondition to check validity against current state.</li>
<li>Each command affects state in some way, generating a new-state.</li>
</ul>


<p>Translating that ideas into Clojure we can model a command protocol</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defprotocol </span><span class="nv">Command</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">precondition</span> <span class="p">[</span><span class="nv">this</span> <span class="nv">state</span><span class="p">]</span> <span class="s">&quot;Returns true if command can be applied in current system state&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">exec</span> <span class="p">[</span><span class="nv">this</span> <span class="nv">state</span> <span class="nv">cmd</span><span class="p">]</span> <span class="s">&quot;Applies generated command to the specified system state, returns new state&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">generate</span> <span class="p">[</span><span class="nv">this</span> <span class="nv">state</span><span class="p">]</span> <span class="s">&quot;Generates command given the current system state, returns command generator&quot;</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>So far, we&#8217;ve assumed nothing about:</p>

<ul>
<li>How state is going to be modeled.</li>
<li>What structure each generated command has.</li>
</ul>


<p><strong>Since we&#8217;re using <code>test.check</code> we need a particular protocol function <code>generate</code> returning the command generator.</strong></p>

<h2>A Command generator</h2>

<p>Having a protocol, lets define our <code>add</code>, <code>edit</code> and <code>delete</code> transactions.</p>

<p>Questions to answer are:</p>

<ol>
<li>What will our model of the world look like?</li>
<li>What&#8217;s the initial and expected states after applying each transaction?</li>
</ol>


<p>Our expected state will be something like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">{</span><span class="ss">:people</span> <span class="p">[{</span><span class="ss">:name</span> <span class="s">&quot;John&quot;</span> <span class="ss">:id</span> <span class="mi">1</span><span class="p">}</span>
</span><span class='line'>          <span class="p">{</span><span class="ss">:name</span> <span class="s">&quot;Ted&quot;</span> <span class="ss">:id</span> <span class="mi">84</span><span class="p">}</span>
</span><span class='line'>          <span class="p">{</span><span class="ss">:name</span> <span class="s">&quot;Tess&quot;</span> <span class="ss">:id</span> <span class="mi">22</span><span class="p">}]}</span>
</span></code></pre></td></tr></table></div></figure>


<p></p>

<p>So our <code>add</code> transaction will be:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">add-cmd</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">reify</span>
</span><span class='line'>    <span class="nv">Command</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">precondition</span> <span class="p">[</span><span class="nv">_</span> <span class="nv">state</span><span class="p">]</span>
</span><span class='line'>      <span class="p">(</span><span class="nb">vector? </span><span class="p">(</span><span class="ss">:people</span> <span class="nv">state</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">(</span><span class="nf">exec</span> <span class="p">[</span><span class="nv">_</span> <span class="nv">state</span> <span class="nv">cmd</span><span class="p">]</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">update-in</span> <span class="nv">state</span> <span class="p">[</span><span class="ss">:people</span><span class="p">]</span> <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">people</span><span class="p">]</span>
</span><span class='line'>                                   <span class="p">(</span><span class="nb">conj </span><span class="nv">people</span>
</span><span class='line'>                                         <span class="p">(</span><span class="nb">dissoc </span><span class="nv">cmd</span> <span class="ss">:type</span><span class="p">)))))</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">generate</span> <span class="p">[</span><span class="nv">_</span> <span class="nv">state</span><span class="p">]</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">gen/fmap</span> <span class="p">(</span><span class="nb">partial zipmap </span><span class="p">[</span><span class="ss">:type</span> <span class="ss">:name</span> <span class="ss">:id</span><span class="p">])</span>
</span><span class='line'>                <span class="p">(</span><span class="nf">gen/tuple</span> <span class="p">(</span><span class="nf">gen/return</span> <span class="ss">:add</span><span class="p">)</span>
</span><span class='line'>                           <span class="p">(</span><span class="nf">gen/not-empty</span> <span class="nv">gen/string-alphanumeric</span><span class="p">)</span>
</span><span class='line'>                           <span class="nv">gen/int</span><span class="p">))))))</span>
</span></code></pre></td></tr></table></div></figure>


<p></p>

<p>The highlights:</p>

<ul>
<li>Our only precondition is to have a vector to <code>conj</code> the transaction into.</li>
<li>The <code>generate</code> function returns a standard <code>test.check</code> generator for the command.</li>
<li>The <code>exec</code> function applies the generated command to the current system state and returns a new state.</li>
</ul>


<p>Now, what&#8217;s interesting is the <code>delete</code> transaction:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">delete-cmd</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">reify</span>
</span><span class='line'>    <span class="nv">Command</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">precondition</span> <span class="p">[</span><span class="nv">_</span> <span class="nv">state</span><span class="p">]</span>
</span><span class='line'>      <span class="p">(</span><span class="nb">seq </span><span class="p">(</span><span class="ss">:people</span> <span class="nv">state</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">(</span><span class="nf">exec</span> <span class="p">[</span><span class="nv">_</span> <span class="nv">state</span> <span class="nv">cmd</span><span class="p">]</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">update-in</span> <span class="nv">state</span> <span class="p">[</span><span class="ss">:people</span><span class="p">]</span> <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">people</span><span class="p">]</span>
</span><span class='line'>                                   <span class="p">(</span><span class="nf">vec</span> <span class="p">(</span><span class="nb">filter </span><span class="o">#</span><span class="p">(</span><span class="nb">not= </span><span class="p">(</span><span class="ss">:id</span> <span class="nv">%</span><span class="p">)</span>
</span><span class='line'>                                                       <span class="p">(</span><span class="ss">:id</span> <span class="nv">cmd</span><span class="p">))</span>
</span><span class='line'>                                                <span class="nv">people</span><span class="p">)))))</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">(</span><span class="nf">generate</span> <span class="p">[</span><span class="nv">_</span> <span class="nv">state</span><span class="p">]</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">gen/fmap</span> <span class="p">(</span><span class="nb">partial zipmap </span><span class="p">[</span><span class="ss">:type</span> <span class="ss">:id</span><span class="p">])</span>
</span><span class='line'>                <span class="p">(</span><span class="nf">gen/tuple</span> <span class="p">(</span><span class="nf">gen/return</span> <span class="ss">:delete</span><span class="p">)</span>
</span><span class='line'>                           <span class="p">(</span><span class="nf">gen/elements</span> <span class="p">(</span><span class="nf">mapv</span> <span class="ss">:id</span> <span class="p">(</span><span class="ss">:people</span> <span class="nv">state</span><span class="p">))))))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note the differences:</p>

<ul>
<li><code>delete</code> can only be executed if the people list actually has <em>someone</em> inside</li>
<li>The generator selects to delete an <code>id</code> from the people in the current state (using <code>gen/elements</code> selector)</li>
<li>Applying the command implies removing the selected person from the next state.</li>
</ul>


<h2>Valid sequence generator</h2>

<p>So how do we generate a sequence of commands giving a command list?</p>

<p>This is a recursive approach, that receives the available commands and the sequence size to generate:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">command-seq</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">state</span> <span class="nv">commands</span> <span class="nv">size</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">gen/bind</span> <span class="p">(</span><span class="nf">gen/one-of</span> <span class="p">(</span><span class="nf">-&gt;&gt;</span> <span class="p">(</span><span class="nb">map second </span><span class="nv">commands</span><span class="p">)</span>
</span><span class='line'>                             <span class="p">(</span><span class="nb">filter </span><span class="o">#</span><span class="p">(</span><span class="nf">precondition</span> <span class="nv">%</span> <span class="nv">state</span><span class="p">))</span>
</span><span class='line'>                             <span class="p">(</span><span class="nb">map </span><span class="o">#</span><span class="p">(</span><span class="nf">generate</span> <span class="nv">%</span> <span class="nv">state</span><span class="p">))))</span>
</span><span class='line'>            <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">cmd</span><span class="p">]</span>
</span><span class='line'>              <span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">zero? </span><span class="nv">size</span><span class="p">)</span>
</span><span class='line'>                <span class="p">(</span><span class="nf">gen/return</span> <span class="p">[</span><span class="nv">cmd</span><span class="p">])</span>
</span><span class='line'>                <span class="p">(</span><span class="nf">gen/fmap</span>
</span><span class='line'>                 <span class="p">(</span><span class="nb">partial concat </span><span class="p">[</span><span class="nv">cmd</span><span class="p">])</span>
</span><span class='line'>                 <span class="p">(</span><span class="nf">command-seq</span> <span class="p">(</span><span class="nf">exec</span> <span class="p">(</span><span class="nb">get </span><span class="nv">commands</span> <span class="p">(</span><span class="ss">:type</span> <span class="nv">cmd</span><span class="p">))</span> <span class="nv">state</span> <span class="nv">cmd</span><span class="p">)</span>
</span><span class='line'>                              <span class="nv">commands</span>
</span><span class='line'>                              <span class="p">(</span><span class="nb">dec </span><span class="nv">size</span><span class="p">)))))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>The important parts being:</p>

<ul>
<li>Selects only one valid command to generate with <code>one-of</code> after filtering preconditions.</li>
<li>If command sequence size is <code>0</code> just finish, otherwise recursively concat the rest of the sequence.</li>
<li>The new state is updated in the step <code>(exec (get commands (:type cmd)) state cmd)</code>, where we need to retrieve the original command object.</li>
</ul>


<p>If you would like to generate random sequence sizes, just bind it with <code>gen/choose</code>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">gen/bind</span> <span class="p">(</span><span class="nf">gen/choose</span> <span class="mi">0</span> <span class="mi">10</span><span class="p">)</span>
</span><span class='line'>          <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">num-elements</span><span class="p">]</span>
</span><span class='line'>            <span class="p">(</span><span class="nf">command-seq</span> <span class="p">{</span><span class="ss">:people</span> <span class="p">[]}</span>
</span><span class='line'>                         <span class="p">{</span><span class="ss">:add-cmd</span> <span class="nv">add-cmd</span>
</span><span class='line'>                          <span class="ss">:delete-cmd</span> <span class="nv">delete-cmd</span><span class="p">}</span>
</span><span class='line'>                         <span class="nv">num-elements</span><span class="p">)))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note the initial state is set to <code>{:people []}</code> for the <code>add</code> command precondition to succeed.</p>

<p>If we generate 3 samples now, it looks good, but there&#8217;s still a problem&#8230;.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(({</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;C&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;2&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;xi&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;p&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;3Q&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;9&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">})</span>
</span><span class='line'> <span class="p">({</span><span class="ss">:id</span> <span class="mi">-1</span>, <span class="ss">:name</span> <span class="s">&quot;H&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">-1</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">1</span>, <span class="ss">:name</span> <span class="s">&quot;q&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;F&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">1</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">})</span>
</span><span class='line'> <span class="p">({</span><span class="ss">:id</span> <span class="mi">-1</span>, <span class="ss">:name</span> <span class="s">&quot;fY&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;a&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">-1</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">2</span>, <span class="ss">:name</span> <span class="s">&quot;u&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">2</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">1</span>, <span class="ss">:name</span> <span class="s">&quot;7&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">-1</span>, <span class="ss">:name</span> <span class="s">&quot;E&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">1</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}</span>
</span><span class='line'>  <span class="p">{</span><span class="ss">:id</span> <span class="mi">-1</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Each <code>add-cmd</code> is repeating the <code>id</code>, since it&#8217;s generating it without checking the current state, let&#8217;s change our <code>add</code> transaction generator</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">generate</span> <span class="p">[</span><span class="nv">_</span> <span class="nv">state</span><span class="p">]</span>
</span><span class='line'>          <span class="p">(</span><span class="nf">gen/fmap</span> <span class="p">(</span><span class="nb">partial zipmap </span><span class="p">[</span><span class="ss">:type</span> <span class="ss">:name</span> <span class="ss">:id</span><span class="p">])</span>
</span><span class='line'>                    <span class="p">(</span><span class="nf">gen/tuple</span> <span class="p">(</span><span class="nf">gen/return</span> <span class="ss">:add-cmd</span><span class="p">)</span>
</span><span class='line'>                               <span class="p">(</span><span class="nf">gen/not-empty</span> <span class="nv">gen/string-alphanumeric</span><span class="p">)</span>
</span><span class='line'>                               <span class="p">(</span><span class="nf">gen/such-that</span> <span class="o">#</span><span class="p">(</span><span class="nb">-&gt; </span><span class="p">(</span><span class="nf">mapv</span> <span class="ss">:id</span> <span class="p">(</span><span class="ss">:people</span> <span class="nv">state</span><span class="p">))</span>
</span><span class='line'>                                                   <span class="p">(</span><span class="nb">contains? </span><span class="nv">%</span><span class="p">)</span>
</span><span class='line'>                                                   <span class="nv">not</span><span class="p">)</span>
</span><span class='line'>                                              <span class="nv">gen/int</span><span class="p">))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now the <code>id</code> field generator checks that the generated <code>int</code> doesn&#8217;t belong to the current ids in the state (we could have returned a <code>uuid</code> or something else, but it wouldn&#8217;t make the case for state-dependent generation)</p>

<p>To complete the example we need:</p>

<ul>
<li>To apply the commands to the system under test.</li>
<li>A way to retrieve the system state.</li>
<li>Comparing the final system state with our final generated expected state.</li>
</ul>


<p>Which is pretty straightforward, so we&#8217;ll talk about shrinking first.</p>

<h2>Shrinking the sequence</h2>

<p>If you were to found a failing command sequence using the code above, you would quickly realize it doesn&#8217;t shrink properly.</p>

<p>Since we&#8217;re generating the sequence composing <code>bind</code>, <code>fmap</code> and <code>concat</code> and not using the internal <code>gen/vector</code> or <code>gen/list</code> generators, the generated sequence doesn&#8217;t know how to shrink itself.</p>

<p>If you read <a href="http://reiddraper.com/writing-simple-check/">Reid&#8217;s account</a> on writing <code>test.check</code>, there&#8217;s a glimpse of the problem we face, shrinking depends on the generated data type. So a generated <code>int</code> knows how to shrink itself, which is different on how a <code>vector</code> shrinks itself.</p>

<p>If you combine existing generators, you get shrinking for free, but since we&#8217;re generating our sequence recursively with <code>concat</code> we&#8217;ve lost the <code>vector</code> type shrinking capability.</p>

<p>And there&#8217;s a good reason it is so, but let&#8217;s first see how shrinking works in <code>test.check</code>.</p>

<h3>Rose Trees</h3>

<p><code>test.check</code> complects the data generation step with the shrinking of that data. So when you generate some value, behind the scenes all the alternative shrinked scenarios are also generated.</p>

<p>Let&#8217;s sample an int vector generator:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">gen/sample</span> <span class="p">(</span><span class="nf">gen/not-empty</span> <span class="p">(</span><span class="nf">gen/vector</span> <span class="nv">gen/int</span><span class="p">))</span> <span class="mi">5</span><span class="p">)</span>
</span><span class='line'><span class="nv">=&gt;</span> <span class="p">([</span><span class="mi">0</span><span class="p">]</span> <span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="p">[</span><span class="mi">-1</span> <span class="mi">1</span><span class="p">]</span> <span class="p">[</span><span class="mi">1</span> <span class="mi">1</span> <span class="mi">-3</span><span class="p">]</span> <span class="p">[</span><span class="mi">2</span> <span class="mi">3</span><span class="p">])</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>sample</code> function is hiding from you the alternatives and showing only the actual generated value.</p>

<p>But, if we call the generator using <code>call-gen</code>, we have a completely different structure:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">gen/call-gen</span> <span class="p">(</span><span class="nf">gen/not-empty</span> <span class="p">(</span><span class="nf">gen/vector</span> <span class="nv">gen/int</span><span class="p">))</span> <span class="p">(</span><span class="nf">gen/random</span><span class="p">)</span> <span class="mi">1</span><span class="p">)</span>
</span><span class='line'><span class="nv">=&gt;</span> <span class="p">[[</span><span class="mi">1</span><span class="p">]</span> <span class="p">([[</span><span class="mi">0</span><span class="p">]</span> <span class="p">()])]</span>
</span></code></pre></td></tr></table></div></figure>


<p>What we have is a <a href="http://en.wikipedia.org/wiki/Rose_tree">rose tree</a>, which is a <code>n-ary</code> tree, where each tree node may have any number of childs.</p>

<p><code>test.check</code> uses a very simple modeling approach for the tree, in the form of <code>[parent childs]</code>.</p>

<p>So this tree</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/rosetree.png" width="340" height="390" title="'Rose Tree'" ></p>

<p>Is represented as</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">[</span><span class="mi">1</span> <span class="p">[[</span><span class="mi">2</span> <span class="p">[]]</span>
</span><span class='line'>    <span class="p">[</span><span class="mi">3</span> <span class="p">[]]]]</span>
</span></code></pre></td></tr></table></div></figure>


<p>Everytime you get a generated value, what you&#8217;re looking at is at the root of the tree obtained with <code>rose/root</code>, which is exactly what <code>gen/sample</code> is doing.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">require</span> <span class="o">&#39;</span><span class="p">[</span><span class="nv">clojure.test.check.rose-tree</span> <span class="ss">:as</span> <span class="nv">rose</span><span class="p">])</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="nf">rose/root</span> <span class="p">(</span><span class="nf">gen/call-gen</span> <span class="p">(</span><span class="nf">gen/not-empty</span> <span class="p">(</span><span class="nf">gen/vector</span> <span class="nv">gen/int</span><span class="p">))</span> <span class="p">(</span><span class="nf">gen/random</span><span class="p">)</span> <span class="mi">1</span><span class="p">))</span>
</span><span class='line'><span class="nv">=&gt;</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>The shrinking tree you would expect for a generated vector is:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/vectorshrinktree.png" width="680" height="780" title="'Vector rose tree'" ></p>

<p>The more deep inside the tree, the more shrunk the value is. So for instance <code>integers</code> shrink up to zero, and <code>vectors</code> randomly remove elements until nothing is left.</p>

<p><strong>If we were to actually look inside the shrunk vector tree, it would also include the shrunked integers, but you get the idea.</strong></p>

<h2>Shrinking a valid command sequence</h2>

<p>I said before our sequence doesn&#8217;t shrink since it&#8217;s generated recursively, so this is how our sequence tree looks like so far.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/singlenodecmdtree.png" width="340" height="390" title="'Single node command tree'" ></p>

<p>But even if we were using the vector shrinker we would end up with something like this:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/invalidcmdtree.png" width="680" height="780" title="'Invalid command tree'" ></p>

<p>Since the vector shrinker doesn&#8217;t really know what a valid command sequence looks like, it will just do a random permutation of commands, ending up with many invalid sequences (like <code>[{:add 1} {:delete 2}]</code>).</p>

<p>We will need a custom shrinker, that shrinks only valid command sequences, with a resulting tree like this one:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/validcmdtree.png" width="680" height="780" title="'Valid command tree'" ></p>

<p>To do that, we will modify our protocol to add a new function <code>postcondition</code>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defprotocol </span><span class="nv">Command</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">precondition</span> <span class="p">[</span><span class="nv">this</span> <span class="nv">state</span><span class="p">]</span> <span class="s">&quot;Returns true if command can be applied in current system state&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">exec</span> <span class="p">[</span><span class="nv">this</span> <span class="nv">state</span> <span class="nv">cmd</span><span class="p">]</span> <span class="s">&quot;Applies generated command to the specified system state, returns new state&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">generate</span> <span class="p">[</span><span class="nv">this</span> <span class="nv">state</span><span class="p">]</span> <span class="s">&quot;Generates command given the current system state, returns command generator&quot;</span><span class="p">))</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">postcondition</span> <span class="p">[</span><span class="nv">this</span> <span class="nv">state</span> <span class="nv">cmd</span><span class="p">]</span> <span class="s">&quot;Returns true if cmd can be applied on specified state&quot;</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p><code>postcondition</code> will be called while shrinking, in order to validate if a shirking sequence is valid for the hipotetical state generated by the previous commands.</p>

<p>Another important function is <code>gen/pure</code>, which allows to return our custom rose tree as generator result.</p>

<p>So this is how our command generator looks like now:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">cmd-seq</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">state</span> <span class="nv">commands</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">gen/bind</span> <span class="p">(</span><span class="nf">gen/choose</span> <span class="mi">0</span> <span class="mi">10</span><span class="p">)</span>
</span><span class='line'>            <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">num-elements</span><span class="p">]</span>
</span><span class='line'>              <span class="p">(</span><span class="nf">gen/bind</span> <span class="p">(</span><span class="nf">cmd-seq-helper</span> <span class="nv">state</span> <span class="nv">commands</span> <span class="nv">num-elements</span><span class="p">)</span>
</span><span class='line'>                        <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">cmd-seq</span><span class="p">]</span>
</span><span class='line'>                          <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">shrinked</span> <span class="p">(</span><span class="nf">shrink-sequence</span> <span class="p">(</span><span class="nf">mapv</span> <span class="nb">first </span><span class="nv">cmd-seq</span><span class="p">)</span>
</span><span class='line'>                                                          <span class="p">(</span><span class="nf">mapv</span> <span class="nb">second </span><span class="nv">cmd-seq</span><span class="p">))]</span>
</span><span class='line'>                            <span class="p">(</span><span class="nf">gen/gen-pure</span> <span class="nv">shrinked</span><span class="p">)))))))</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">cmd-seq-helper</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">state</span> <span class="nv">commands</span> <span class="nv">size</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">gen/bind</span> <span class="p">(</span><span class="nf">gen/one-of</span> <span class="p">(</span><span class="nf">-&gt;&gt;</span> <span class="p">(</span><span class="nb">map second </span><span class="nv">commands</span><span class="p">)</span>
</span><span class='line'>                             <span class="p">(</span><span class="nb">filter </span><span class="o">#</span><span class="p">(</span><span class="nf">precondition</span> <span class="nv">%</span> <span class="nv">state</span><span class="p">))</span>
</span><span class='line'>                             <span class="p">(</span><span class="nb">map </span><span class="o">#</span><span class="p">(</span><span class="nf">generate</span> <span class="nv">%</span> <span class="nv">state</span><span class="p">))))</span>
</span><span class='line'>            <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">cmd</span><span class="p">]</span>
</span><span class='line'>              <span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">zero? </span><span class="nv">size</span><span class="p">)</span>
</span><span class='line'>                <span class="p">(</span><span class="nf">gen/return</span> <span class="p">[[</span><span class="nv">cmd</span> <span class="nv">state</span><span class="p">]])</span>
</span><span class='line'>                <span class="p">(</span><span class="nf">gen/fmap</span>
</span><span class='line'>                 <span class="p">(</span><span class="nb">partial concat </span><span class="p">[[</span><span class="nv">cmd</span> <span class="nv">state</span><span class="p">]])</span>
</span><span class='line'>                 <span class="p">(</span><span class="nf">cmd-seq-helper</span> <span class="p">(</span><span class="nf">exec</span> <span class="p">(</span><span class="nb">get </span><span class="nv">commands</span> <span class="p">(</span><span class="ss">:type</span> <span class="nv">cmd</span><span class="p">))</span> <span class="nv">state</span> <span class="nv">cmd</span><span class="p">)</span>
</span><span class='line'>                                 <span class="p">(</span><span class="nb">map second </span><span class="nv">commands</span><span class="p">)</span>
</span><span class='line'>                                 <span class="p">(</span><span class="nb">dec </span><span class="nv">size</span><span class="p">)))))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>We see two different things here:</p>

<ol>
<li>Generator also returns the state for that particular command.</li>
<li>There&#8217;s a call to <code>shrink-sequence</code> that generates the rose tree given the command sequence and intermediate states.</li>
</ol>


<p>The <code>shrink-sequence</code> function being:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">shrink-sequence</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">cmd-seq</span> <span class="nv">state-seq</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">letfn</span> <span class="p">[(</span><span class="nf">shrink-subseq</span> <span class="p">[</span><span class="nv">s</span><span class="p">]</span>
</span><span class='line'>            <span class="p">(</span><span class="nb">when </span><span class="p">(</span><span class="nb">seq </span><span class="nv">s</span><span class="p">)</span>
</span><span class='line'>              <span class="p">[(</span><span class="nb">map </span><span class="o">#</span><span class="p">(</span><span class="nb">get </span><span class="nv">cmd-seq</span> <span class="nv">%</span><span class="p">)</span> <span class="nv">s</span><span class="p">)</span>
</span><span class='line'>               <span class="p">(</span><span class="nf">-&gt;&gt;</span> <span class="p">(</span><span class="nf">remove-seq</span> <span class="nv">s</span><span class="p">)</span>
</span><span class='line'>                    <span class="p">(</span><span class="nb">filter </span><span class="p">(</span><span class="nb">partial </span><span class="nv">valid-sequence?</span> <span class="nv">state-seq</span> <span class="nv">cmd-seq</span><span class="p">))</span>
</span><span class='line'>                    <span class="p">(</span><span class="nf">mapv</span> <span class="nv">shrink-subseq</span><span class="p">))]))]</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">shrink-subseq</span> <span class="p">(</span><span class="nb">range </span><span class="mi">0</span> <span class="p">(</span><span class="nb">count </span><span class="nv">cmd-seq</span><span class="p">)))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Highlights:</p>

<ul>
<li>Returns a rose tree in the form <code>[parent childs]</code>.</li>
<li><code>remove-seq</code> generates a sequence of subsequences with only one element removed.</li>
<li><code>valid-sequence?</code> uses <code>postcondition</code> to validate the shrinked seq.</li>
<li>Recursively shrinks the shrunk childs until nothing&#8217;s left.</li>
</ul>


<h2>Putting all together</h2>

<p>I&#8217;ve put together a running sample for you to check out <a href="https://github.com/guilespi/fsm-test-check/blob/master/src/fsm_test_check/core.clj">here</a>.</p>

<p>There&#8217;s only one property defined: <em>applying all the generated transactions should return true</em>, but it fails when there are two delete commands present.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">apply-tx</span>
</span><span class='line'>  <span class="s">&quot;Apply transactions fails when there are two delete commands&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">tx-log</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">-&gt;&gt;</span> <span class="nv">tx-log</span>
</span><span class='line'>       <span class="p">(</span><span class="nb">filter </span><span class="o">#</span><span class="p">(</span><span class="nb">= </span><span class="ss">:delete-cmd</span> <span class="p">(</span><span class="ss">:type</span> <span class="nv">%</span><span class="p">)))</span>
</span><span class='line'>       <span class="nv">count</span>
</span><span class='line'>       <span class="p">(</span><span class="nb">&gt; </span><span class="mi">2</span><span class="p">)))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">commands-consistent-apply</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">prop/for-all</span> <span class="p">[</span><span class="nv">tx-log</span> <span class="p">(</span><span class="nf">cmd-seq</span> <span class="p">{</span><span class="ss">:people</span> <span class="p">[]}</span> <span class="p">{</span><span class="ss">:add-cmd</span> <span class="nv">add-cmd</span> <span class="ss">:delete-cmd</span> <span class="nv">delete-cmd</span><span class="p">})]</span>
</span><span class='line'>                <span class="p">(</span><span class="nb">true? </span><span class="p">(</span><span class="nf">apply-tx</span> <span class="nv">tx-log</span><span class="p">))))</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">tc/quick-check</span> <span class="mi">10</span> <span class="nv">commands-consistent-apply</span><span class="p">)</span>
</span><span class='line'><span class="nv">=&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="p">{</span><span class="ss">:result</span> <span class="nv">false</span>, <span class="ss">:seed</span> <span class="mi">1428695347616</span>, <span class="ss">:failing-size</span> <span class="mi">7</span>, <span class="ss">:num-tests</span> <span class="mi">8</span>,
</span><span class='line'> <span class="ss">:fail</span> <span class="p">[({</span><span class="ss">:id</span> <span class="mi">6</span>, <span class="ss">:name</span> <span class="s">&quot;8&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>         <span class="p">{</span><span class="ss">:id</span> <span class="mi">-4</span>, <span class="ss">:name</span> <span class="s">&quot;KvoOq&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>         <span class="p">{</span><span class="ss">:id</span> <span class="mi">-6</span>, <span class="ss">:name</span> <span class="s">&quot;hWn&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>         <span class="p">{</span><span class="ss">:id</span> <span class="mi">6</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}</span>
</span><span class='line'>         <span class="p">{</span><span class="ss">:id</span> <span class="mi">-4</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">})]</span>,
</span><span class='line'> <span class="ss">:shrunk</span> <span class="p">{</span><span class="ss">:total-nodes-visited</span> <span class="mi">55</span>, <span class="ss">:depth</span> <span class="mi">16</span>, <span class="ss">:result</span> <span class="nv">false</span>,
</span><span class='line'>          <span class="ss">:smallest</span> <span class="p">[({</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:name</span> <span class="s">&quot;0&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>                      <span class="p">{</span><span class="ss">:id</span> <span class="mi">-2</span>, <span class="ss">:name</span> <span class="s">&quot;2&quot;</span>, <span class="ss">:type</span> <span class="ss">:add-cmd</span><span class="p">}</span>
</span><span class='line'>                      <span class="p">{</span><span class="ss">:id</span> <span class="mi">0</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">}</span>
</span><span class='line'>                      <span class="p">{</span><span class="ss">:id</span> <span class="mi">-2</span>, <span class="ss">:type</span> <span class="ss">:delete-cmd</span><span class="p">})]}}</span>
</span></code></pre></td></tr></table></div></figure>


<p>If you look closely the failing test case has three <code>add</code> commands, but when shrunk only two needed in order to fail appear.</p>

<p>Have fun!</p>

<p>I&#8217;m <a href="https://twitter.com/guilespi">guilespi</a> on Twitter.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Property-based testing using QuickCheck]]></title>
    <link href="http://guilespi.github.com/blog/2015/04/12/property-based-testing-using-quickcheck/"/>
    <updated>2015-04-12T17:05:00-03:00</updated>
    <id>http://guilespi.github.com/blog/2015/04/12/property-based-testing-using-quickcheck</id>
    <content type="html"><![CDATA[<p>Last year I attended <a href="https://www.youtube.com/playlist?list=PLZdCLR02grLp__wRg5OTavVj4wefg69hM">Clojure/West</a> in San Francisco, and was lucky enough to be at the talk by <a href="http://www.cse.chalmers.se/~rjmh/">John Hughes</a>, called <a href="https://www.youtube.com/watch?v=zi0rHwfiX1Q">Testing the hard stuff and staying sane</a>.</p>

<p>I had been previously exposed to some of the concepts of generative testing, particularly Haskell&#8217;s own QuickCheck, but never took the time to do something with it, this talk by John Hughes really stroke a chord on the usefulness of generative -or property based- testing, and how much effort you can save by knowing when and <em>how</em> to use it.</p>

<p>I&#8217;ve been using Clojure <code>test.check</code> for a while, and since I&#8217;m preparing a <a href="http://testing.uy">conference talk</a> on the subject, I decided to write something about it.</p>

<p>So bear with me, in this two-entry blog post I&#8217;ll try to convince you why down the road, it may save your ass too.</p>

<h2>What generative testing is not</h2>

<p>Probably the reason I&#8217;ve always looked down upon generative testing, was thinking it was just about random/junk data generation, for the too-lazy-to-think-your-own-test-cases kind of attitude.</p>

<p>Well, that&#8217;s <strong>not</strong> what generative testing is about.</p>

<p>You <em>will</em> have data generators for some input domain values, but trying to generate random noise to make the program fail is just <a href="http://en.wikipedia.org/wiki/Fuzz_testing">fuzzy testing</a>, and generative testing is more than that.</p>

<p>How?</p>

<h2>On Types vs. Tests</h2>

<p><a href="http://blog.guillermowinkler.com/blog/2012/11/14/neither-types-nor-tests-will-solve-your-data-coverage-problem/">I&#8217;ve written before</a> about the difficulty of using types to prove your program is correct. Some people will always say you can do it with type systems(and types even more complex than the program under proof), and you can <a href="https://coq.inria.fr/a-short-introduction-to-coq">always use Coq</a>.</p>

<p>But for everyday programming languages and type systems it&#8217;s not that easy, say for instance this <code>Java</code> function (assuming such thing exists).</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kt">int</span> <span class="nf">f1</span><span class="o">(</span><span class="kt">int</span> <span class="n">x</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="mi">1</span><span class="o">/</span><span class="n">x</span><span class="o">;</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can say just by looking at the function, that any integer except zero will succeed.</p>

<p>In this other case:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kt">int</span> <span class="nf">f2</span><span class="o">(</span><span class="n">String</span> <span class="n">x</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="n">x</span><span class="o">.</span><span class="na">length</span><span class="o">();</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The function will succeed except when <code>x</code> is <code>null</code>.</p>

<p>So assuming that&#8217;s expected behavior, you can write some tests to check on those special failure cases.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="nd">@Test</span><span class="o">(</span><span class="n">expected</span><span class="o">=</span><span class="n">ArithmeticException</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span><span class='line'><span class="kd">public</span> <span class="kt">void</span> <span class="nf">testDivideByZero</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">f1</span><span class="o">(</span><span class="kc">null</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="c1">//this is just a unit test</span>
</span><span class='line'><span class="nd">@Test</span>
</span><span class='line'><span class="kd">public</span> <span class="kt">void</span> <span class="nf">testUnity</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">assertEquals</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="n">f1</span><span class="o">(</span><span class="mi">1</span><span class="o">));</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="nd">@Test</span><span class="o">(</span><span class="n">expected</span><span class="o">=</span><span class="n">NullPointerException</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span><span class='line'><span class="kd">public</span> <span class="kt">void</span> <span class="nf">testNullPointerException</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">f2</span><span class="o">(</span><span class="kc">null</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>But for the sake of making and argument, assume you&#8217;re testing <code>openssl</code> and this is the function you have&#8230;</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="kt">int</span> <span class="nf">dtls1_process_heartbeat</span><span class="p">(</span><span class="n">SSL</span> <span class="o">*</span><span class="n">s</span><span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="p">...</span>    
</span><span class='line'>  <span class="cm">/* Read type and payload length first */</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span><span class="mi">1</span> <span class="o">+</span> <span class="mi">2</span> <span class="o">+</span> <span class="mi">16</span> <span class="o">&gt;</span> <span class="n">s</span><span class="o">-&gt;</span><span class="n">s3</span><span class="o">-&gt;</span><span class="n">rrec</span><span class="p">.</span><span class="n">length</span><span class="p">)</span>
</span><span class='line'>      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> <span class="cm">/* silently discard */</span>
</span><span class='line'>  <span class="n">hbtype</span> <span class="o">=</span> <span class="o">*</span><span class="n">p</span><span class="o">++</span><span class="p">;</span>
</span><span class='line'>  <span class="n">n2s</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="n">payload</span><span class="p">);</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span><span class="mi">1</span> <span class="o">+</span> <span class="mi">2</span> <span class="o">+</span> <span class="n">payload</span> <span class="o">+</span> <span class="mi">16</span> <span class="o">&gt;</span> <span class="n">s</span><span class="o">-&gt;</span><span class="n">s3</span><span class="o">-&gt;</span><span class="n">rrec</span><span class="p">.</span><span class="n">length</span><span class="p">)</span>
</span><span class='line'>      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span> <span class="cm">/* silently discard per RFC 6520 sec. 4 */</span>
</span><span class='line'>  <span class="n">pl</span> <span class="o">=</span> <span class="n">p</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span><span class="n">hbtype</span> <span class="o">==</span> <span class="n">TLS1_HB_REQUEST</span><span class="p">)</span>
</span><span class='line'>      <span class="p">{</span>
</span><span class='line'>      <span class="kt">unsigned</span> <span class="kt">char</span> <span class="o">*</span><span class="n">buffer</span><span class="p">,</span> <span class="o">*</span><span class="n">bp</span><span class="p">;</span>
</span><span class='line'>      <span class="kt">unsigned</span> <span class="kt">int</span> <span class="n">write_length</span> <span class="o">=</span> <span class="mi">1</span> <span class="cm">/* heartbeat type */</span> <span class="o">+</span>
</span><span class='line'>                      <span class="mi">2</span> <span class="cm">/* heartbeat length */</span> <span class="o">+</span>
</span><span class='line'>                      <span class="n">payload</span> <span class="o">+</span> <span class="n">padding</span><span class="p">;</span>
</span><span class='line'>      <span class="kt">int</span> <span class="n">r</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>      <span class="k">if</span> <span class="p">(</span><span class="n">write_length</span> <span class="o">&gt;</span> <span class="n">SSL3_RT_MAX_PLAIN_LENGTH</span><span class="p">)</span>
</span><span class='line'>          <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>      <span class="cm">/* Allocate memory for the response, size is 1 byte</span>
</span><span class='line'><span class="cm">      * message type, plus 2 bytes payload length, plus</span>
</span><span class='line'><span class="cm">      * payload, plus padding</span>
</span><span class='line'><span class="cm">      */</span>
</span><span class='line'>      <span class="n">buffer</span> <span class="o">=</span> <span class="n">OPENSSL_malloc</span><span class="p">(</span><span class="n">write_length</span><span class="p">);</span>
</span><span class='line'>      <span class="n">bp</span> <span class="o">=</span> <span class="n">buffer</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>      <span class="cm">/* Enter response type, length and copy payload */</span>
</span><span class='line'>      <span class="o">*</span><span class="n">bp</span><span class="o">++</span> <span class="o">=</span> <span class="n">TLS1_HB_RESPONSE</span><span class="p">;</span>
</span><span class='line'>      <span class="n">s2n</span><span class="p">(</span><span class="n">payload</span><span class="p">,</span> <span class="n">bp</span><span class="p">);</span>
</span><span class='line'>      <span class="n">memcpy</span><span class="p">(</span><span class="n">bp</span><span class="p">,</span> <span class="n">pl</span><span class="p">,</span> <span class="n">payload</span><span class="p">);</span>
</span><span class='line'>      <span class="n">bp</span> <span class="o">+=</span> <span class="n">payload</span><span class="p">;</span>
</span><span class='line'>      <span class="cm">/* Random padding */</span>
</span><span class='line'>      <span class="n">RAND_pseudo_bytes</span><span class="p">(</span><span class="n">bp</span><span class="p">,</span> <span class="n">padding</span><span class="p">);</span>
</span><span class='line'>    <span class="p">...</span>
</span></code></pre></td></tr></table></div></figure>


<p>Unless you&#8217;ve been living under a rock, you should have heard about <a href="http://heartbleed.com/">the heartbleed openssl bug</a>, and it&#8217;s just what you think, the bug was in the heartbeat processing function above, and <a href="http://git.openssl.org/gitweb/?p=openssl.git;a=commitdiff;h=96db902">this is the patch with the fix</a>.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/opensslpatch.png" width="680" height="780" title="'Openssl heartbleed patch'" ></p>

<p>Who was the motherfucker that missed that unit test, huh?</p>

<p>When the function logic is more complex, it&#8217;s exponentially more difficult to define both types and tests that make us feel more confident about pushing our nasty bits of code to a production environment.</p>

<p>And that&#8217;s because the possible states our system or function can be, expand like hell when new variables and conditional branches are added (more on this later).</p>

<h2>Code Coverage vs. Domain Coverage</h2>

<p>Looking at the function above you can see the problem is not on some untested code path, but on some <em>values</em> used on function invocation.</p>

<p>Some people aim for 100% code coverage, according to <a href="http://en.wikipedia.org/wiki/Code_coverage">Wikipedia</a></p>

<p><em>In computer science, code coverage is a measure used to describe the degree to which the source code of a program is tested by a particular test suite. A program with high code coverage has been more thoroughly tested and has a lower chance of containing software bugs than a program with low code coverage.</em></p>

<p>Which is great, but since you can have 100% code coverage of the <code>1/x</code> function, but regarding domain coverage (for which values of <code>x</code> the function works as expected) you have nothing.</p>

<p><strong>Code coverage without domain coverage is just half the picture.</strong></p>

<p>Even unit tests prove <em>almost</em> nothing.</p>

<h2>Tests do not prove correctness</h2>

<p>There&#8217;s a great quote by <a href="http://en.wikiquote.org/wiki/Edsger_W._Dijkstra">Edsger Dijkstra</a> from Notes on Structured Programming that says</p>

<p><em>Program testing can be used to show the presence of bugs, but never to show their absence!</em></p>

<p>Which is to say, no matter how many unit tests you write, you&#8217;re only proving that your program works (or fails) for the set of inputs you have selected when writing your tests.</p>

<p>It doesn&#8217;t say a thing about the generalities or about a general property of the system or function under test.</p>

<h2>What is generative testing?</h2>

<p>So what <em>is</em> generative testing?</p>

<p>In generative testing you describe some properties your system or function must comply with, and the test runner provides randomized data to check if the property holds for that data, that&#8217;s why it&#8217;s also known as <code>property-based</code> testing.</p>

<p>A <code>property</code> is a high-level specification of behavior that should hold for a range of data points.</p>

<p>So a property works somewhat like a <em>domain iterator</em>, bringing a little bit closer types and tests.</p>

<p>Since you&#8217;re defining how the system should behave for a particular <em>domain</em> of values, not when the program is compiled, but when it&#8217;s <strong>run</strong>.</p>

<h2>Why random data generation is important?</h2>

<p>In the StrangeLoop 2014 conference, Joe Armstrong gave a talk called <a href="https://www.youtube.com/watch?v=lKXe3HUG2l4">The mess we&#8217;re in</a>, where he discussed system&#8217;s complexity, go watch it since it&#8217;s real fun.</p>

<p>He says that a <code>C</code> program with only six <code>32 bit</code> integers, has the same number of states that atoms exist on the planet, so testing your program by computing all combinations it&#8217;s going to take a <em>really long</em> time.</p>

<p>And if it&#8217;s almost impossible to find the number of states computationally, imagine trying to find the number of possible failing states <em>manually</em>.</p>

<p>I&#8217;ve been in the position of having to hunt a bug that occurs only once a year in a system processing millions of transactions daily, and it&#8217;s not fun at all. Pray to the logging gods the proper piece of information revealing the culprit is logged, so you don&#8217;t have to wait another year for the bug to show up.</p>

<p>If your software runs inside a car, would you wait for the next deadly crash to analyze that dead-driver log file? Maybe that&#8217;s why <a href="http://www.quviq.com/volvo-quickcheck/">Volvo uses QuickCheck</a> to test embedded systems.</p>

<p>Generative testing helps you put and test your system in so many different states it would be impossible to do manually.</p>

<h2>What&#8217;s in a property</h2>

<p>So, should we throw away all of our type systems and unit tests?</p>

<p>Not so fast, property based testing is not a <strong>replacement</strong> for types nor for unit tests.</p>

<p>Haskell and Scala both have their frameworks for property based testing (QuickCheck and ScalaTest) and are strongly typed languages.</p>

<p>Property based testing helps us define considerations for our programs where type systems do not reach, and where dynamically typed languages have a void.</p>

<p>So what does a property look like?</p>

<p>All concepts so far hold true for any language with a generative testing framework, many re-implementations exist from the <a href="http://en.wikipedia.org/wiki/QuickCheck">original QuickCheck version</a>, from <code>C</code>, <code>C++</code>, <code>Ruby</code>, <code>Clojure</code>, <code>Javascript</code>, <code>Java</code>, <code>Scala</code>, etc. So now I will show you a couple of examples in different languages, just for you to grasp the basic property definition semantics, which is quite similar along the implementations.</p>

<p>These examples are not meant to show how powerful generative testing can be, yet.</p>

<h3>Sorting in Javascript</h3>

<p>Let&#8217;s say you want to test a <code>sort</code> function of yours, and instead of specifying individual test cases for particular arrays of integers, you define a property, which says that after sorting the array, the last element should always be greater than the first one.</p>

<p>This is what the property looks like in Javascript&#8217;s <a href="www.jscheck.org">JSCheck</a></p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">JSC</span><span class="p">.</span><span class="nx">reps</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</span><span class='line'><span class="nx">JSC</span><span class="p">.</span><span class="nx">test</span><span class="p">(</span>
</span><span class='line'>    <span class="s2">&quot;First is lower than last after sort&quot;</span><span class="p">,</span>
</span><span class='line'>    <span class="kd">function</span> <span class="p">(</span><span class="nx">verdict</span><span class="p">,</span> <span class="nx">v</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">sorted</span> <span class="o">=</span> <span class="nx">v</span><span class="p">.</span><span class="nx">sort</span><span class="p">();</span>
</span><span class='line'>        <span class="k">return</span> <span class="nx">verdict</span><span class="p">(</span><span class="nx">sorted</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">&lt;</span> <span class="nx">sorted</span><span class="p">[</span><span class="nx">sorted</span><span class="p">.</span><span class="nx">length</span> <span class="o">-</span> <span class="mi">1</span><span class="p">]);</span>
</span><span class='line'>    <span class="p">},</span>
</span><span class='line'>    <span class="p">[</span>
</span><span class='line'>        <span class="nx">JSC</span><span class="p">.</span><span class="nx">array</span><span class="p">([</span><span class="nx">JSC</span><span class="p">.</span><span class="nx">integer</span><span class="p">()]])</span>
</span><span class='line'>    <span class="p">]</span>
</span><span class='line'><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>You don&#8217;t say which particular arrays, just any array of integers must comply with the property, the framework will generate values for you (in this case 10 repetitions will be run).</p>

<p>This is the result:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">First</span> <span class="nx">is</span> <span class="nx">lower</span> <span class="nx">than</span> <span class="nx">last</span> <span class="nx">after</span> <span class="nx">sort</span><span class="o">:</span> <span class="mi">10</span> <span class="nx">cases</span> <span class="nx">tested</span><span class="p">,</span> <span class="mi">0</span> <span class="nx">pass</span><span class="p">,</span> <span class="mi">10</span> <span class="nx">fail</span>
</span><span class='line'> <span class="nx">FAIL</span> <span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="p">([</span><span class="mi">3</span><span class="p">])</span>
</span><span class='line'> <span class="nx">FAIL</span> <span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="p">([</span><span class="mi">5</span><span class="p">])</span>
</span><span class='line'> <span class="nx">FAIL</span> <span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="p">([</span><span class="mi">7</span><span class="p">])</span>
</span></code></pre></td></tr></table></div></figure>


<p>Did you spot when the property doesn&#8217;t hold?</p>

<h3>Sorting in Clojure</h3>

<p>This is what the same property looks like in Clojure&#8217;s <a href="https://github.com/clojure/test.check">test.check</a>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">prop-sorted-first-less-than-last</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">prop/for-all</span> <span class="p">[</span><span class="nv">v</span> <span class="p">(</span><span class="nf">gen/not-empty</span> <span class="p">(</span><span class="nf">gen/vector</span> <span class="nv">gen/int</span><span class="p">))]</span>
</span><span class='line'>    <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">s</span> <span class="p">(</span><span class="nb">sort </span><span class="nv">v</span><span class="p">)]</span>
</span><span class='line'>      <span class="p">(</span><span class="nb">&lt; </span><span class="p">(</span><span class="nb">first </span><span class="nv">s</span><span class="p">)</span> <span class="p">(</span><span class="nb">last </span><span class="nv">s</span><span class="p">)))))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="nf">tc/quick-check</span> <span class="mi">200</span> <span class="nv">prop-sorted-first-less-than-last</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>With the following result:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'>   <span class="nv">=&gt;</span> <span class="p">{</span><span class="ss">:result</span> <span class="nv">false</span>, <span class="ss">:failing-size</span> <span class="mi">0</span>, <span class="ss">:num-tests</span> <span class="mi">1</span>, <span class="ss">:fail</span> <span class="p">[[</span><span class="mi">3</span><span class="p">]]</span>,
</span><span class='line'>       <span class="ss">:shrunk</span> <span class="p">{</span><span class="ss">:total-nodes-visited</span> <span class="mi">5</span>, <span class="ss">:depth</span> <span class="mi">2</span>, <span class="ss">:result</span> <span class="nv">false</span>,
</span><span class='line'>                <span class="ss">:smallest</span> <span class="p">[[</span><span class="mi">0</span><span class="p">]]}}</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you see, <strong>both fail</strong>, since they doesn&#8217;t hold for single element arrays.</p>

<p>The basic semantic for both languages is the same, you need:</p>

<ul>
<li>A property name (or claim in JSCheck)</li>
<li>Some data generator for your input values</li>
<li>A verdict or testing function who validates the property</li>
</ul>


<blockquote><p>This encourages a higher level approach to testing in the form of abstract invariant functions should satisfy universally.</p><footer><strong>http://book.realworldhaskell.org/read/testing-and-quality-assurance.html</strong></footer></blockquote>


<h2>Shrinking</h2>

<p>One of the best features of QuickCheck is the ability to shrink your failure cases to the minimum failing case (not all the implementations have it by the way).</p>

<p>When generating random data, you may end up with a failing case too big to rationalize (for instance a thousand elements vector), but it doesn&#8217;t necessarily means that all the 1000 elements are needed for the function under test to fail.</p>

<p>When QuickCheck finds a failing case, it tries to shrink the input data to the <em>smallest</em> failing case.</p>

<p>This is a powerful feature if you don&#8217;t want to repeat many unnecessary steps in order to reproduce a problem.</p>

<p>A simple example to illustrate the feature comes from <code>test.check</code> samples.</p>

<p>Here a property must hold for all integer vectors, and it is that no vector should have the element <code>42</code> in it.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">prop-no-42</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">prop/for-all</span> <span class="p">[</span><span class="nv">v</span> <span class="p">(</span><span class="nf">gen/vector</span> <span class="nv">gen/int</span><span class="p">)]</span>
</span><span class='line'>    <span class="p">(</span><span class="nb">not </span><span class="p">(</span><span class="nb">some </span><span class="o">#</span><span class="p">{</span><span class="mi">42</span><span class="p">}</span> <span class="nv">v</span><span class="p">))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>When the tests are run, <code>test.check</code> find a failing case being the vector <code>[10 1 28 40 11 -33 42 -42 39 -13 13 -44 -36 11 27 -42 4 21 -39]</code>, which is <strong>not</strong> the minimum failing case.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">tc/quick-check</span> <span class="mi">100</span> <span class="nv">prop-no-42</span><span class="p">)</span>
</span><span class='line'><span class="c1">;; =&gt; {:result false,</span>
</span><span class='line'>       <span class="ss">:failing-size</span> <span class="mi">45</span>,
</span><span class='line'>       <span class="ss">:num-tests</span> <span class="mi">46</span>,
</span><span class='line'>       <span class="ss">:fail</span> <span class="p">[[</span><span class="mi">10</span> <span class="mi">1</span> <span class="mi">28</span> <span class="mi">40</span> <span class="mi">11</span> <span class="mi">-33</span> <span class="mi">42</span> <span class="mi">-42</span> <span class="mi">39</span> <span class="mi">-13</span> <span class="mi">13</span> <span class="mi">-44</span> <span class="mi">-36</span> <span class="mi">11</span> <span class="mi">27</span> <span class="mi">-42</span> <span class="mi">4</span> <span class="mi">21</span> <span class="mi">-39</span><span class="p">]]</span>,
</span><span class='line'>       <span class="ss">:shrunk</span> <span class="p">{</span><span class="ss">:total-nodes-visited</span> <span class="mi">38</span>,
</span><span class='line'>                <span class="ss">:depth</span> <span class="mi">18</span>,
</span><span class='line'>                <span class="ss">:result</span> <span class="nv">false</span>,
</span><span class='line'>                <span class="ss">:smallest</span> <span class="p">[[</span><span class="mi">42</span><span class="p">]]}}</span>
</span></code></pre></td></tr></table></div></figure>


<p>So it starts shrinking the failing case until it reaches the smallest vector for which the property doesn&#8217;t hold, which is <code>[42]</code>.</p>

<p>Unfortunately <code>JSCheck</code> doesn&#8217;t shrink the failure cases, but <a href="http://jsverify.github.io/">jsverify</a> does, so if you want some shrinking on Javascript give it a try.</p>

<h2>Final thoughts</h2>

<p>Since QuickCheck depends on generators to cover the domain, we need to consider those domains may be infinite or very large, so it may be impossible to find the offending failure cases. None the less, we know that by running long enough or a large enough number of tests, we have better odds of finding a problem.</p>

<p>Regarding the name, <code>property-based</code> testing is a much better name than <code>generative</code> testing, since the later gives the idea that it&#8217;s about generating data, when it&#8217;s truly about function and system properties.</p>

<p>The higher level approach of property definition, coupled with the data generation and shrinking features provided by QuickCheck, really helps the case of having something more closer to <em>proofs</em> about how your system behaves.</p>

<p>In the next post I&#8217;ll write about finite state machine testing using <code>test.check</code> and show more complex examples, stay tuned.</p>

<p>I&#8217;m <a href="https://twitter.com/guilespi">guilespi</a> on Twitter, reach out!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Decompiling Clojure III, Graph all the things]]></title>
    <link href="http://guilespi.github.com/blog/2014/04/27/decompiling-clojure-iii/"/>
    <updated>2014-04-27T23:15:00-03:00</updated>
    <id>http://guilespi.github.com/blog/2014/04/27/decompiling-clojure-iii</id>
    <content type="html"><![CDATA[<p>This is the third entry in the Decompiling Clojure series.</p>

<p><a href="http://blog.guillermowinkler.com/blog/2014/04/13/decompiling-clojure-i/">In the first post</a> I showed what Clojure looks like in bytecode, and in <a href="http://blog.guillermowinkler.com/blog/2014/04/21/decompiling-clojure-ii/">the second post</a> I did a quick review of the Clojure compiler and its code generation strategies.</p>

<p>In this post I&#8217;ll go deeper in the decompiling process.</p>

<h2>What is decompiling?</h2>

<p>Decompilers do not usually reconstruct the original source code, since many information meant to be read by humans (for instance comments)
is lost in the compilation process, where stuff is meant to be read only by machines, <code>JVM</code> bytecode in our case.</p>

<p>So by decompiling I mean going from lower level bytecode, to some higher level code, it doesn&#8217;t even need to be Clojure,
we already know from the last post that Clojure compiler loses all macro information, so special heuristics will be needed when trying to reconstruct them.</p>

<p>For instance, it&#8217;s possible for <code>let</code> and <code>if</code> special forms, to be re-created using code signatures.(Think pattern matching applied to code graphs)</p>

<h2>Decompiling goal</h2>

<p>As I&#8217;ve said in my previous post:</p>

<blockquote><p>What use do I have for a line based debugger with Clojure?</p><footer><strong>guilespi</strong> <cite><a href='http://blog.guillermowinkler.com/blog/2014/04/21/decompiling-clojure-ii/'>blog.guillermowinkler.com/blog/&hellip;</a></cite></footer></blockquote>


<p>My goal when decompiling Clojure is not to re-create the original source code, but to re-create the <code>AST</code> that gave origin to the <code>JVM</code> bytecode I&#8217;m observing.</p>

<p>Since I was creating a debugger that knows about s-expressions, I needed a tree representation from the bytecode that can be properly
synchronized with the Clojure source code I&#8217;m debugging.</p>

<p>So my decompiling goal was just getting a higher level semantic tree from the <code>JVM</code> bytecode.</p>

<h2>Decompiling phases</h2>

<p>Much of the work I&#8217;ve done was using as guide the <a href="http://www.informatik.uni-trier.de/~ley/pers/hd/c/Cifuentes:Cristina#footer">many publications from Cristina Cifuentes</a>, and the great book <a href="http://www.amazon.com/gp/product/0444002162/">Flow Analysis of Computer Programs</a>,
which I got an used copy from Amazon. So all the smart ideas belong to them, all mistakes and nonsense are mine.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/flow-analysis-book.jpg" width="320" height="220" title="Flow Analysis of Computer Programs" alt="Flow Analysis of Computer Programs"></p>

<p>I already said I want a reasonable <code>AST</code> from the bytecode, so decompilation process will be split in phases</p>

<ol>
<li>Wind the stack and build a statement list</li>
<li>Create codeblocks and a graph representing control flow</li>
<li>Detect loops and nested loops</li>
<li>Structure conditionals</li>
</ol>


<p>If you want a decompiler that re-creates source code, you would add a fifth step called <em>Emit source code</em>.</p>

<p>As you smart readers would have probably noticed by now, it has some things in common with the compiling process,
only that we need to get to the <code>AST</code> from compiled bytecode instead of doing it from a source file,
once you have the AST you can emit whatever you want, even <code>Basic</code>.</p>

<h3>1. Wind the stack</h3>

<p>Maybe I should have used a different name for this step, since stack unwinding is usually related with C++ exception handling, and refers to how
objects allocated are destroyed when exiting the function and destroying the frame.</p>

<p>But in the general case, stack unwind refers to what happens with the stack when a function is finished and the current frame needs to be cleared.</p>

<p>And if we <a href="http://www.merriam-webster.com/dictionary/unwind">go to the dictionary</a> - pun intended -</p>

<blockquote><p>to become uncoiled or disentangled</p><footer><strong>Merriam-Webster : Unwind</strong> <cite><a href='http://www.merriam-webster.com/dictionary/unwind'>www.merriam-webster.com/unwind/&hellip;</a></cite></footer></blockquote>


<p>I&#8217;m happy to say we will coil the uncoiled stack into proper statements.</p>

<p>As we saw <a href="http://blog.guillermowinkler.com/blog/2014/04/21/decompiling-clojure-ii/">in the second post of our series</a>, the JVM uses a stack based approach to parameter passing</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>f(a, b, c)
</span><span class='line'>
</span><span class='line'>=&gt; compiles to
</span><span class='line'>
</span><span class='line'>push a
</span><span class='line'>push b
</span><span class='line'>push c
</span><span class='line'>call f
</span></code></pre></td></tr></table></div></figure>


<p>So our first step is about getting the stack back together.</p>

<p>Some statements are going to be quite similar to what the Clojure compiler already recognizes, such as <code>IfExpr</code> representing an if conditional, but many statements at this stage won&#8217;t have a direct mapping in Clojure, for instance the <code>AssignStatement</code> representing an assignment to a variable, does not exist in the Clojure compiler, and higher level constructs such as <code>LetFnExpr</code> or <code>MapExpr</code> won&#8217;t be mapped at this stage of low-level bytecode.</p>

<p>So a reduced list would look like:</p>

<ul>
<li>AssignStatatement</li>
<li>IfStatement</li>
<li>InvokeStatement</li>
<li>ReturnStatement</li>
<li>NewStatement</li>
</ul>


<p>So we&#8217;re dealing with less typed expressions/statements, just a small set of generic control structures.</p>

<p>One important thing when winding the stack is: in many cases statement compose, for instance an <code>InvokeStatement</code> result may be used directly from the stack into a subsequent <code>IfStatement</code>.</p>

<p>Let me show you.</p>

<p>Getting back to our previous example</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">test-if</span>
</span><span class='line'>  <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">= </span><span class="p">(</span><span class="nb">inc </span><span class="mi">1</span><span class="p">)</span> <span class="mi">2</span><span class="p">)</span>
</span><span class='line'>    <span class="mi">8</span>
</span><span class='line'>    <span class="mi">9</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Decompiled as</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">public</span> <span class="nv">java.lang.Object</span> <span class="nv">invoke</span><span class="p">()</span><span class="c1">;</span>
</span><span class='line'>    <span class="nv">Code</span><span class="err">:</span>
</span><span class='line'><span class="nv">==&gt;</span>
</span><span class='line'>       <span class="mi">0</span><span class="err">:</span> <span class="nv">lconst_1</span>
</span><span class='line'>       <span class="mi">1</span><span class="err">:</span> <span class="nv">invokestatic</span>  <span class="o">#</span><span class="mi">63</span>                 <span class="nv">//</span> <span class="nv">Method</span> <span class="nv">clojure/lang/Numbers.inc</span><span class="err">:</span><span class="p">(</span><span class="nf">J</span><span class="p">)</span><span class="nv">J</span>
</span><span class='line'>       <span class="mi">4</span><span class="err">:</span> <span class="nv">ldc2_w</span>        <span class="o">#</span><span class="mi">42</span>                 <span class="nv">//</span> <span class="nb">long </span><span class="mi">2</span><span class="nv">l</span>
</span><span class='line'>       <span class="mi">7</span><span class="err">:</span> <span class="nv">lcmp</span>
</span><span class='line'>       <span class="mi">8</span><span class="err">:</span> <span class="nv">ifne</span>          <span class="mi">18</span>
</span><span class='line'><span class="nv">==&gt;</span>
</span><span class='line'>      <span class="mi">11</span><span class="err">:</span> <span class="nv">getstatic</span>     <span class="o">#</span><span class="mi">49</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__4</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">14</span><span class="err">:</span> <span class="nv">goto</span>          <span class="mi">21</span>
</span><span class='line'>      <span class="mi">17</span><span class="err">:</span> <span class="nv">pop</span>
</span><span class='line'>      <span class="mi">18</span><span class="err">:</span> <span class="nv">getstatic</span>     <span class="o">#</span><span class="mi">53</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__5</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">21</span><span class="err">:</span> <span class="nv">areturn</span>
</span></code></pre></td></tr></table></div></figure>


<p>Lines <code>0</code> and <code>1</code> are responsible for the <code>(inc 1)</code> part of the code, decompiling to <code>clojure.lang.Numbers.inc(1)</code>, which result is directly used in line <code>7</code> which compares with the long value <code>2</code> pushed on line <code>4</code>.</p>

<p>So our first decompiled statement on line <code>0</code> is an <code>IfStatement</code>, which contains the <code>InvokeStatement</code> <em>inside</em>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="mi">0</span><span class="ss">:IF</span> <span class="p">(</span><span class="mi">2</span><span class="nv">!=clojure.lang.Numbers.inc</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="nv">GOTO</span> <span class="mi">11</span> <span class="nv">ELSE</span> <span class="nv">GOTO</span> <span class="mi">18</span>
</span><span class='line'><span class="mi">11</span><span class="ss">:RETURN</span> <span class="mi">9</span>
</span><span class='line'><span class="mi">18</span><span class="ss">:RETURN</span> <span class="mi">8</span>
</span></code></pre></td></tr></table></div></figure>


<p>When this step is finished all the low level concepts will be removed, and high level concepts were re-introduced, such as parameter passing.</p>

<p>But we&#8217;re still stuck with our damn Basic!</p>

<h3>Codeblock Graph</h3>

<p>A Codeblock is a sequence of statements with no branch statements in the middle, meaning execution starts at the first statement, and ends with the last one.</p>

<p>The following is a control flow graph, with code blocks numbered from <code>B1</code> to <code>B15</code>.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/codeblock-graph.png" width="580" height="380" title="Sample Control Flow Graph" alt="Sample Control Flow Graph"></p>

<p>Note we&#8217;re building a <strong>graph</strong> here, not a <strong>tree</strong>.</p>

<p>A tree is a minimally connected graph, having only one path between any two vertices,
when modeling control flow you can have <strong>many</strong> paths between two vertices,
for instance in our example <code>B1-&gt;B2-&gt;B4-&gt;B5</code> and <code>B1-&gt;B5</code>.</p>

<p>This is the first step of the control flow analysis phase,
having identified the basic branching statements from the previous step,
building the graph is straightforward.</p>

<h3>Loop Detection</h3>

<p>Loop detection is one of the most difficult tasks when writing a decompiler.</p>

<p>Main reason is when you&#8217;re reading bytecode or assembly, you&#8217;re not entirely sure about the compiler used to generate that,
you may be trying to decompile bytecode written by hand, which may never map to a <em>known</em> higher level construct.</p>

<p>For instance, there are a few higher level constructs identified with loops, which usually take the following form:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/proper-loops.png" width="380" height="280" title="Proper loops" alt="Proper loops"></p>

<p>But then you may have a graph with the following <em>improper</em> looping structures:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/improper-loops.png" width="380" height="280" title="Improper loops" alt="Improper loops"></p>

<p>Improper loops ranging from multi-entry or multi-exit, something you can find on <code>goto</code> enabled languages, to parallel loops with a common header node, or entwined loops.</p>

<p>In our case, we can assume all bytecode we&#8217;re going to find is always created from a reasonable Clojure compiler,
and we can safely guess <code>goto</code> support won&#8217;t be approved by Rich Hickey any time soon.</p>

<p>So, a loop needs to be defined in terms of the graph representation, which not only determines the extent of the loop but also the nesting of the different loops in the function being decompiled.</p>

<p>The loop detection algorithms I used were taken directly from Cifuentes papers about decompiling, which in turn took the ideas from <a href="http://en.wikipedia.org/wiki/James_F._Allen">James F.Allen</a> and <a href="http://en.wikipedia.org/wiki/John_Cocke">John Cocke</a> of using <a href="http://en.wikipedia.org/wiki/Interval_(graph_theory)">graph interval theory</a> for flow analysis,
 since it satisfies the necessary conditions for loops:</p>

<ul>
<li>One loop per interval</li>
<li>A nesting order is provided by the derived sequence of graphs.</li>
</ul>


<p>Even if we don&#8217;t have improper loops, we need to know which <code>IfStatements</code> correspond to a loop header before assuming it&#8217;s indeed an <code>If</code>.</p>

<p>So, what does a Clojure loop looks like?</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">test-loop</span>
</span><span class='line'>  <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">loop </span><span class="p">[</span><span class="nv">x</span> <span class="mi">10</span><span class="p">]</span>
</span><span class='line'>    <span class="p">(</span><span class="nb">when </span><span class="p">(</span><span class="nb">&gt; </span><span class="nv">x</span> <span class="mi">0</span><span class="p">)</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">recur</span> <span class="p">(</span><span class="nb">dec </span><span class="nv">x</span><span class="p">)))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Our first phase decompiler would see it as:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="mi">0</span><span class="ss">:x</span> <span class="nb">= </span><span class="mi">10</span>
</span><span class='line'><span class="mi">4</span><span class="ss">:IF</span> <span class="p">(</span><span class="mi">0</span><span class="nv">&lt;=x</span><span class="p">)</span> <span class="nv">GOTO</span> <span class="mi">10</span> <span class="nv">ELSE</span> <span class="nv">GOTO</span> <span class="mi">22</span>
</span><span class='line'><span class="mi">10</span><span class="ss">:x</span> <span class="nb">= </span><span class="nv">clojure.lang.Numbers.dec</span><span class="p">(</span><span class="nf">x</span><span class="p">)</span>
</span><span class='line'><span class="mi">15</span><span class="ss">:GOTO</span> <span class="mi">4</span>
</span><span class='line'><span class="mi">22</span><span class="ss">:RETURN</span> <span class="nv">NULL</span>
</span></code></pre></td></tr></table></div></figure>


<p>Well, we had a <code>GOTO</code> after all&#8230; as you see a loop is just an <code>If</code> statement followed by a backlink, in this case solved with a <code>GOTO</code> branching statement.</p>

<p>Now if I leave the debug comments from my decompiler, you&#8217;ll see a couple extra things:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">Loading</span><span class="ss">:debugee.test$test_loop</span>
</span><span class='line'>
</span><span class='line'><span class="nv">Block</span> <span class="nv">Start</span><span class="ss">:0</span>
</span><span class='line'><span class="mi">0</span><span class="ss">:x</span> <span class="nb">= </span><span class="mi">10</span>
</span><span class='line'>
</span><span class='line'><span class="nv">Block</span> <span class="nv">Start</span><span class="ss">:4</span>
</span><span class='line'><span class="mi">4</span><span class="ss">:IF</span> <span class="p">(</span><span class="mi">0</span><span class="nv">&lt;=x</span><span class="p">)</span> <span class="nv">GOTO</span> <span class="mi">10</span> <span class="nv">ELSE</span> <span class="nv">GOTO</span> <span class="mi">22</span>
</span><span class='line'>
</span><span class='line'><span class="nv">Block</span> <span class="nv">Start</span><span class="ss">:10</span>
</span><span class='line'><span class="mi">10</span><span class="ss">:x</span> <span class="nb">= </span><span class="nv">clojure.lang.Numbers.dec</span><span class="p">(</span><span class="nf">x</span><span class="p">)</span>
</span><span class='line'><span class="mi">15</span><span class="ss">:GOTO</span> <span class="mi">4</span>
</span><span class='line'>
</span><span class='line'><span class="nv">Block</span> <span class="nv">Start</span><span class="ss">:22</span>
</span><span class='line'><span class="mi">22</span><span class="ss">:RETURN</span> <span class="nv">NULL</span>
</span><span class='line'>
</span><span class='line'><span class="nv">Found</span> <span class="k">new loop </span><span class="nv">header</span> <span class="nv">at</span><span class="ss">:4</span>
</span><span class='line'><span class="nv">Not</span> <span class="nv">belong</span> <span class="nv">to</span> <span class="nv">loop</span><span class="ss">:22</span>
</span><span class='line'><span class="nv">Loop</span> <span class="nv">closes</span> <span class="nv">on</span><span class="ss">:10</span>
</span></code></pre></td></tr></table></div></figure>


<ul>
<li>Code blocks are identified</li>
<li>Loop belonging nodes are identified</li>
<li>Loop header and latch nodes are also identified</li>
</ul>


<h3>Structuring Conditionals</h3>

<p>Conditionals refer to <code>if</code>, <code>when</code>, <code>case</code> and other conditionals that may be found in code, which are usually 1-way or 2-way conditioned branches,
all of them have a common <em>end</em> node reached by all paths.</p>

<p>Since Clojure <code>when</code> is a macro expanding to an <code>if</code>, it&#8217;s just the 1-way conditional branch, if the <code>if</code> clause has an <code>else</code> part we&#8217;re in the 2-way conditional branch, where the else part is taken before reaching the common follow node.</p>

<p>The more difficult situation arises when trying to structure compound boolean conditions, as you see in the following picture:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/compound-conditionals.png" width="580" height="380" title="Compound conditionals" alt="Compound conditionals"></p>

<p>You should expect different <code>IfStatements</code> one behind the other, all being part of the same higher-level compound conditional which is compiled in a short-circuit fashion,
with two chained if statements.</p>

<p>With Clojure we have an additional problem, for instance the following example:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">test-compound</span>
</span><span class='line'>  <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">and </span><span class="p">(</span><span class="nb">&gt; </span><span class="mi">2</span> <span class="mi">1</span><span class="p">)</span> <span class="p">(</span><span class="nb">= </span><span class="mi">0</span> <span class="mi">0</span><span class="p">))</span>
</span><span class='line'>    <span class="mi">2</span>
</span><span class='line'>    <span class="mi">1</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Decompiles to the following <code>Basic</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="mi">0</span><span class="ss">:and__3941__auto__1754</span> <span class="nb">= </span><span class="nv">clojure.lang.Numbers.gt</span><span class="p">(</span><span class="mi">2</span>, <span class="mi">1</span><span class="p">)</span>
</span><span class='line'><span class="mi">8</span><span class="ss">:IF</span> <span class="nv">and__3941__auto__1754==0</span> <span class="nv">GOTO</span> <span class="mi">12</span> <span class="nv">ELSE</span> <span class="nv">GOTO</span> <span class="mi">21</span>
</span><span class='line'><span class="mi">12</span><span class="ss">:IF</span> <span class="nv">clojure.lang.Util.equiv</span><span class="p">(</span><span class="mi">0</span>, <span class="mi">0</span><span class="p">)</span><span class="nv">==0</span> <span class="nv">GOTO</span> <span class="mi">25</span> <span class="nv">ELSE</span> <span class="nv">GOTO</span> <span class="mi">32</span>
</span><span class='line'><span class="mi">21</span><span class="ss">:IF</span> <span class="nv">and__3941__auto__1754==0</span> <span class="nv">GOTO</span> <span class="mi">25</span> <span class="nv">ELSE</span> <span class="nv">GOTO</span> <span class="mi">32</span>
</span><span class='line'><span class="mi">25</span><span class="ss">:RETURN</span> <span class="mi">2</span>
</span><span class='line'><span class="mi">32</span><span class="ss">:RETURN</span> <span class="mi">1</span>
</span></code></pre></td></tr></table></div></figure>


<p>Wait a minute!!</p>

<p>We should be seeing only two <code>IfStatements</code> there, one for each part of the compound conditional, but there are three, what&#8217;s going on?</p>

<p>As you see on line <code>21</code> the same condition of line <code>8</code> is being tested again, which we already know it&#8217;s false, why someone would do that?</p>

<p>It turns out it has to do with <code>and</code> being implemented as a macro, so if we look what&#8217;s the actual Clojure code being emitted the bytecode makes sense</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">clojure.pprint/pprint</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">macroexpand-all</span> <span class="o">&#39;</span><span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">and </span><span class="p">(</span><span class="nb">&gt; </span><span class="mi">2</span> <span class="mi">1</span><span class="p">)</span> <span class="p">(</span><span class="nb">= </span><span class="mi">0</span> <span class="mi">0</span><span class="p">))</span> <span class="mi">2</span> <span class="mi">1</span><span class="p">)))</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">if</span>
</span><span class='line'>     <span class="p">(</span><span class="nf">let*</span>
</span><span class='line'>       <span class="p">[</span><span class="nv">and__3941__auto__</span> <span class="p">(</span><span class="nb">&gt; </span><span class="mi">2</span> <span class="mi">1</span><span class="p">)]</span>
</span><span class='line'>       <span class="p">(</span><span class="k">if </span><span class="nv">and__3941__auto__</span> <span class="p">(</span><span class="nb">= </span><span class="mi">0</span> <span class="mi">0</span><span class="p">)</span> <span class="nv">and__3941__auto__</span><span class="p">))</span>
</span><span class='line'>     <span class="mi">2</span>
</span><span class='line'>     <span class="mi">1</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>and__3941__auto__</code> variable which is the result of the first condition is being checked twice,
I guess this is the reason the temporary variable exists in the first place,
to avoid computation of the boolean expression twice and just checking for the result of it again.</p>

<p>If case the compiler analyzed the <code>and</code> as part of the <code>if</code> it could have emitted the result directly instead of
using a temporary variable and that nasty double check.</p>

<h2>The Clojure case</h2>

<p>Many of the different strategies explored previously apply if you want to decompile just about anything from bytecode (or machine language).</p>

<p>Since in our case we already know we&#8217;re decompiling Clojure, there are a lot of special cases we know we will <em>never</em> encounter.</p>

<p>Targeting our decompiler to only one language makes things easier, since while we&#8217;re not only supporting only one compiler,
but we know we&#8217;ll never encounter manually generated bytecode,
unless your using an agent or custom loader that has patched the bytecode, of course.</p>

<h2>What&#8217;s next</h2>

<p>In the next post I will show you two things, how to synchronize the decompiled bytecode tree with Clojure source code,
and how to patch the debuggee on runtime to use our s-expression references using <a href="https://commons.apache.org/proper/commons-bcel/">BCEL</a>.</p>

<p>Much of the code to accomplish this was developed while understanding the problem, so it&#8217;s not open sourced yet, I&#8217;m planning to move stuff around and make it public,
but if you want to look at the current mess just ping me, I&#8217;ll send it to you(you&#8217;ll need to un-rust your graph mangling skills tough).</p>

<p>Meanwhile, <a href="http://www.twitter.com/guilespi">I&#8217;m guilespi</a> on Twitter.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Decompiling Clojure II, The Compiler]]></title>
    <link href="http://guilespi.github.com/blog/2014/04/21/decompiling-clojure-ii/"/>
    <updated>2014-04-21T01:03:00-03:00</updated>
    <id>http://guilespi.github.com/blog/2014/04/21/decompiling-clojure-ii</id>
    <content type="html"><![CDATA[<p>This is the second post in the Decompiling Clojure series, <a href="http://blog.guillermowinkler.com/blog/2014/04/13/decompiling-clojure-i/">in the first post</a> I showed what Clojure looks like in bytecode.</p>

<p>For this entry, I&#8217;ll do a compiler overview, the idea is to understand why and how does Clojure looks like that.</p>

<p>For other decompilation scenarios you don&#8217;t usually have the advantage of looking at the compiler internals to guide your decompiling algorithms, so we&#8217;ll take our chance to peek at the compiler now.</p>

<p>We will visit some compiler source code, so be warned, there&#8217;s Java ahead.</p>

<h2>It&#8217;s Java</h2>

<p>Well, yes, the Clojure compiler targeting the JVM is written in Java, <a href="https://github.com/Bronsa/CinC">there is an ongoing effort</a> to have a Clojure-in-Clojure compiler, but the original compiler is nowhere near of being replaced.</p>

<p>The source code <a href="https://github.com/clojure/clojure">is hosted on GitHub</a>, but the development process is <a href="http://dev.clojure.org/display/community/JIRA+workflow">a little bit more convoluted</a>, which means you don&#8217;t just send pull requests for it, <a href="https://groups.google.com/d/msg/clojure/0gwjKtatf-0/dOMECoHPlM4J">it was asked for many times</a> and I don&#8217;t think it&#8217;s about to change, so if you wanna contribute, <a href="http://clojure.org/contributing">just sign the contributors agreement</a> and follow the rules.</p>

<h2>The CinC Alternative</h2>

<p>The Clojure-in-Clojure alternative is not only different because it&#8217;s written in Clojure, but because it&#8217;s built with extensibility and modularization in mind.</p>

<p>In the original Clojure compiler you don&#8217;t have a chance to extend, modify or use, many of the data produced by the compilation process.</p>

<p>For instance the <a href="https://github.com/clojure/core.typed">Typed Clojure</a> project, which adds <a href="http://wphomes.soic.indiana.edu/jsiek/what-is-gradual-typing/">gradual typing</a> to Clojure, <a href="http://dev.clojure.org/display/design/Provide+friendly+interface+to+Clojure's+analyzer,+independently+callable+a+la+carte">needed a friendlier interface</a> to the compiler analyzer phase. It was first developed by Ambrose Bonnair-Sergeant <a href="https://github.com/frenchy64/analyze">as an interface to the Compiler analyzer</a> <del>and then moved to be part of the <a href="https://github.com/clojure/tools.analyzer">CinC analyzer</a></del>.</p>

<p>The CinC alternative is modularized in -at least three- different parts.</p>

<ul>
<li><a href="https://github.com/clojure/tools.analyzer">The analyzer</a>, meant to be shared among all Clojure compilers (as Clojurescript)</li>
<li><a href="https://github.com/clojure/tools.analyzer.jvm">The JVM analyzer</a>, contains specific compiler passes for the JVM (for instance locals clearing is done here)</li>
<li><a href="https://github.com/clojure/tools.emitter.jvm">The bytecode emitter</a>, actually emits JVM bytecode.</li>
</ul>


<p>There&#8217;s <a href="http://www.youtube.com/watch?v=KhRQmT22SSg">a great talk from Timothy Baldridge</a> showing some examples using the CinC analyzer, watch it.</p>

<p><strong>Note</strong> <em>CinC developer <a href="https://github.com/Bronsa">Nicola Mometto</a> <a href="https://twitter.com/Bronsa_/status/458643972555300866">pointed out</a> that the analyzer written by Ambrose and CinC are indeed different projects. Which I should&#8217;ve noticed myself since
the analyzer by Ambrose uses the analyzer from the original Clojure compiler, which is <a href="https://github.com/clojure/jvm.tools.analyzer/blob/master/src/main/clojure/clojure/jvm/tools/analyzer.clj#L843">exposed as a function</a>. Part of my mistake was surely derived from the fact one is called <code>tools.analyzer.jvm</code> and
the other one is called <code>jvm.tools.analyzer</code></em></p>

<h2>Compilation process</h2>

<p>One of supposed advantages of Lisp-like languages is that the concrete syntax is already the abstract syntax. If you&#8217;ve read some of the <a href="http://www.twitter.com/fogus">fogus</a> <a href="http://blog.fogus.me/tag/clj-compilation/">writings about Clojure compilation</a> tough, he has some opinions on that statement:</p>

<blockquote><p>This is junk. Actual ASTs are adorned with a boatload of additional information like local binding information, accessible bindings, arity information, and many other useful tidbits.</p><footer><strong>fogus</strong> <cite><a href='http://blog.fogus.me/2012/04/25/the-clojurescript-compilation-pipeline/'>blog.fogus.me/2012/04/25/&hellip;</a></cite></footer></blockquote>


<p>And he&#8217;s right, but there&#8217;s one more thing, Clojure and Lisp syntax are just serialization formats, mapping to the underlying data structure of the program.</p>

<p>That&#8217;s why Lisp like languages are easier to parse and unparse, or build tools for them, because the program data structure is accesible to the user and not only to the compiler.</p>

<p>Also that&#8217;s the reason why macros in Lisp or Clojure are so different than <a href="http://docs.scala-lang.org/overviews/macros/overview.html">macros in Scala</a>, where the pre-processor handles you an AST that has nothing to do with the Scala language itself.</p>

<p>That&#8217;s the proper definition of <a href="http://en.wikipedia.org/wiki/Homoiconicity">homoiconicity</a> by the way, the syntax is isomorphic with the AST.</p>

<h2>Compiler phases</h2>

<p>In general compilers can be broken up into three pieces</p>

<ol>
<li>Lexer/Parser</li>
<li>Analyzer</li>
<li>Emitter</li>
</ol>


<p>Clojure kind of follows this pattern, so if we&#8217;re compiling a Clojure program the <em>very</em> high level approach to the compilation pipeline would be:</p>

<ol>
<li>Read file</li>
<li>Read s-expression</li>
<li>Expand macros if present</li>
<li>Analyze</li>
<li>Generate JVM bytecode</li>
</ol>


<p>The first three steps are the <em>Reading</em> phase <a href="http://blog.fogus.me/2012/04/25/the-clojurescript-compilation-pipeline/">from the fogus article</a>.</p>

<p>There is one important thing about these steps:</p>

<p>Bytecode has <strong>no information about macros whatsoever</strong>, emitted bytecode corresponds to what you see with <a href="http://clojuredocs.org/clojure_core/clojure.core/macroexpand">macroexpand</a> calls.
Since macros are expanded before analyzing, you shouldn&#8217;t expect to find anything about your macro in the compiled bytecode, nada, niet, gone.</p>

<p>Meaning, we shouldn&#8217;t expect to be able to properly decompile macro&#8217;ed stuff either.</p>

<h2>Compile vs. Eval</h2>

<p>As said on the first post, the <code>class</code> file doesn&#8217;t need to be on disk, and that&#8217;s better understood if we think about <a href="http://clojuredocs.org/clojure_core/1.2.0/clojure.core/eval">eval</a>.</p>

<p>When you type a command in the <code>REPL</code> it needs to be properly translated to bytecode before the JVM is able to execute it, but it doesn&#8217;t mean the compiler will save a <code>class</code> file, then load it, and only then execute it.</p>

<p>It will be done on the fly.</p>

<p>We will consider three entry points for the compiler, <code>compile</code>, <code>load</code> and <code>eval</code>.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/compiler-reader.png" width="580" height="380" title="Compiler entry point" alt="Compiler entry points"></p>

<p>The <code>LispReader</code> is responsible for reading forms from an input stream.</p>

<h3>Compile Entry Point</h3>

<p><code>compile</code> is a static function found in the <code>Compiler.java</code> file, member of the <code>Compiler</code> class, and it does generate a <code>class</code> file on disk for each function in the compiled namespace.</p>

<p>For instance it will get called if you do the following in your REPL</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">compile</span> <span class="ss">&#39;clojure.core.reducers</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Clojure function just wraps over the Java function doing the actual work with the signature</p>

<figure class='code'><figcaption><span>compile</span><a href='https://github.com/clojure/clojure/blob/1.5.x/src/jvm/clojure/lang/Compiler.java#L7162'>Compiler.java </a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">static</span> <span class="n">Object</span> <span class="nf">compile</span><span class="o">(</span><span class="n">Reader</span> <span class="n">rdr</span><span class="o">,</span> <span class="n">String</span> <span class="n">sourcePath</span><span class="o">,</span> <span class="n">String</span> <span class="n">sourceName</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">IOException</span><span class="o">{</span>
</span></code></pre></td></tr></table></div></figure>


<p>Besides all the preamble, <a href="https://github.com/clojure/clojure/blob/1.5.x/src/jvm/clojure/lang/Compiler.java#L7214-L7221">the core of the function</a> is just a loop which reads and calls the <code>compile1</code> function for each form found in the file.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="k">for</span><span class="o">(</span><span class="n">Object</span> <span class="n">r</span> <span class="o">=</span> <span class="n">LispReader</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="n">pushbackReader</span><span class="o">,</span> <span class="kc">false</span><span class="o">,</span> <span class="n">EOF</span><span class="o">,</span> <span class="kc">false</span><span class="o">);</span> <span class="n">r</span> <span class="o">!=</span> <span class="n">EOF</span><span class="o">;</span>
</span><span class='line'>          <span class="n">r</span> <span class="o">=</span> <span class="n">LispReader</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="n">pushbackReader</span><span class="o">,</span> <span class="kc">false</span><span class="o">,</span> <span class="n">EOF</span><span class="o">,</span> <span class="kc">false</span><span class="o">))</span>
</span><span class='line'>  <span class="o">{</span>
</span><span class='line'>       <span class="n">compile1</span><span class="o">(</span><span class="n">gen</span><span class="o">,</span> <span class="n">objx</span><span class="o">,</span> <span class="n">r</span><span class="o">);</span>
</span><span class='line'>  <span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>As we expect, <a href="https://github.com/clojure/clojure/blob/1.5.x/src/jvm/clojure/lang/Compiler.java#L7138-L7154">the compile1 function does macro expansion</a> before analyzing or emitting anything, if <code>form</code> turns out to be a list it recursively calls itself, which is
the <code>then</code> branch of the if test:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">form</span> <span class="o">=</span> <span class="n">macroexpand</span><span class="o">(</span><span class="n">form</span><span class="o">);</span>
</span><span class='line'><span class="k">if</span><span class="o">(</span><span class="n">form</span> <span class="k">instanceof</span> <span class="n">IPersistentCollection</span> <span class="o">&amp;&amp;</span> <span class="n">Util</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span><span class="n">RT</span><span class="o">.</span><span class="na">first</span><span class="o">(</span><span class="n">form</span><span class="o">),</span> <span class="n">DO</span><span class="o">))</span>
</span><span class='line'>  <span class="o">{</span>
</span><span class='line'>  <span class="k">for</span><span class="o">(</span><span class="n">ISeq</span> <span class="n">s</span> <span class="o">=</span> <span class="n">RT</span><span class="o">.</span><span class="na">next</span><span class="o">(</span><span class="n">form</span><span class="o">);</span> <span class="n">s</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">;</span> <span class="n">s</span> <span class="o">=</span> <span class="n">RT</span><span class="o">.</span><span class="na">next</span><span class="o">(</span><span class="n">s</span><span class="o">))</span>
</span><span class='line'>  <span class="o">{</span>
</span><span class='line'>      <span class="n">compile1</span><span class="o">(</span><span class="n">gen</span><span class="o">,</span> <span class="n">objx</span><span class="o">,</span> <span class="n">RT</span><span class="o">.</span><span class="na">first</span><span class="o">(</span><span class="n">s</span><span class="o">));</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="k">else</span>
</span><span class='line'>  <span class="o">{</span>
</span><span class='line'>  <span class="n">Expr</span> <span class="n">expr</span> <span class="o">=</span> <span class="n">analyze</span><span class="o">(</span><span class="n">C</span><span class="o">.</span><span class="na">EVAL</span><span class="o">,</span> <span class="n">form</span><span class="o">);</span>
</span><span class='line'>        <span class="o">....</span>
</span><span class='line'>  <span class="n">expr</span><span class="o">.</span><span class="na">emit</span><span class="o">(</span><span class="n">C</span><span class="o">.</span><span class="na">EXPRESSION</span><span class="o">,</span> <span class="n">objx</span><span class="o">,</span> <span class="n">gen</span><span class="o">);</span>
</span><span class='line'>  <span class="n">expr</span><span class="o">.</span><span class="na">eval</span><span class="o">();</span>
</span><span class='line'>  <span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>analyze</code> function we see on the <code>else</code> branch does the proper <code>s-expr</code> analyzing which emits and evals itself afterwards, more on analyzing ahead.</p>

<h3>Load Entry Point</h3>

<p>The <code>load</code> function gets called any time we do a <code>require</code> for a not pre-compiled namespace.</p>

<figure class='code'><figcaption><span>load</span><a href='https://github.com/clojure/clojure/blob/1.5.x/src/jvm/clojure/lang/Compiler.java#L7032'>link</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">static</span> <span class="n">Object</span> <span class="nf">load</span><span class="o">(</span><span class="n">Reader</span> <span class="n">rdr</span><span class="o">,</span> <span class="n">String</span> <span class="n">sourcePath</span><span class="o">,</span> <span class="n">String</span> <span class="n">sourceName</span><span class="o">)</span> <span class="o">{</span>
</span></code></pre></td></tr></table></div></figure>


<p>For instance, say we do a require for the <code>clojure.core.reducers</code> namespace:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nf">require</span> <span class="o">&#39;</span><span class="p">[</span><span class="nv">clojure.core.reducers</span> <span class="ss">:as</span> <span class="nv">r</span><span class="p">])</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>clj</code> file will be read as a stream in the <code>loadResourceScript</code> function and passed as the first <code>rdr</code> parameter of the <code>load</code> function.</p>

<p>You see the <code>load</code> function has a pretty similar read form and eval loop as the one we saw in the compile function.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="k">for</span><span class="o">(</span><span class="n">Object</span> <span class="n">r</span> <span class="o">=</span> <span class="n">LispReader</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="n">pushbackReader</span><span class="o">,</span> <span class="kc">false</span><span class="o">,</span> <span class="n">EOF</span><span class="o">,</span> <span class="kc">false</span><span class="o">);</span> <span class="n">r</span> <span class="o">!=</span> <span class="n">EOF</span><span class="o">;</span>
</span><span class='line'><span class="n">r</span> <span class="o">=</span> <span class="n">LispReader</span><span class="o">.</span><span class="na">read</span><span class="o">(</span><span class="n">pushbackReader</span><span class="o">,</span> <span class="kc">false</span><span class="o">,</span> <span class="n">EOF</span><span class="o">,</span> <span class="kc">false</span><span class="o">))</span>
</span><span class='line'><span class="o">{</span>
</span><span class='line'>  <span class="n">ret</span> <span class="o">=</span> <span class="n">eval</span><span class="o">(</span><span class="n">r</span><span class="o">,</span><span class="kc">false</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Instead of calling <code>compile1</code> calling <code>eval</code>, which is our next entry point.</p>

<h3>Eval Entry Point</h3>

<p><code>eval</code> is the <code>e</code> in REPL, anything to be dynamically evaluated goes through the <code>eval</code> function.</p>

<p>For instance if you type <code>(+ 1 1)</code> on your REPL that expression will be parsed, analyzed and evaluated starting on the <code>eval</code> function.</p>

<figure class='code'><figcaption><span>eval</span><a href='https://github.com/clojure/clojure/blob/1.5.x/src/jvm/clojure/lang/Compiler.java#L6585'>Compiler.java  </a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">static</span> <span class="n">Object</span> <span class="nf">eval</span><span class="o">(</span><span class="n">Object</span> <span class="n">form</span><span class="o">,</span> <span class="kt">boolean</span> <span class="n">freshLoader</span><span class="o">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you see eval receives a <code>form</code> by parameter, since knows nothing about files nor namespaces.</p>

<p><code>eval</code> is just straightforward analyzing of the form, and there&#8217;s not a emit here. This is the <em>simplified</em> version of the function:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">form</span> <span class="o">=</span> <span class="n">macroexpand</span><span class="o">(</span><span class="n">form</span><span class="o">);</span>
</span><span class='line'><span class="n">Expr</span> <span class="n">expr</span> <span class="o">=</span> <span class="n">analyze</span><span class="o">(</span><span class="n">C</span><span class="o">.</span><span class="na">EVAL</span><span class="o">,</span> <span class="n">form</span><span class="o">);</span>
</span><span class='line'><span class="k">return</span> <span class="n">expr</span><span class="o">.</span><span class="na">eval</span><span class="o">();</span>
</span></code></pre></td></tr></table></div></figure>


<h2>The reader</h2>

<p>Languages with more complicated syntaxes separate the Lexer and Parser into two different pieces, like most Lisps, Clojure combines these two into just a <code>Reader</code>.</p>

<p>The reader is pretty much self contained in <code>LispReader.java</code> and its main responsibility is given a stream, return the properly <em>tokenized</em> s-expressions.</p>

<p>The reader dispatches reading to specialized functions and classes when a particular token is found, for instance <code>(</code> dispatches to <code>ListReader</code> class, digits dispatch to the <code>readNumber</code> function and so on.</p>

<p>Much of the list and vector reading classes(<code>VectorReader</code>, <code>MapReader</code>, <code>ListReader</code>, etc) rely on the more generic <code>readDelimitedList</code> function which receives the particular list separator as parameter.</p>

<figure class='code'><figcaption><span>Reader classes for each special character in LispReader</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;&quot;&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">StringReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;;&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">CommentReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;\&#39;&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">WrappingReader</span><span class="o">(</span><span class="n">QUOTE</span><span class="o">);</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;@&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">WrappingReader</span><span class="o">(</span><span class="n">DEREF</span><span class="o">);</span><span class="c1">//new DerefReader();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;^&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MetaReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;`&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">SyntaxQuoteReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;~&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">UnquoteReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;(&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ListReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;)&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">UnmatchedDelimiterReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;[&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">VectorReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;]&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">UnmatchedDelimiterReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;{&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">MapReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;}&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">UnmatchedDelimiterReader</span><span class="o">();</span>
</span><span class='line'><span class="c1">//   macros[&#39;|&#39;] = new ArgVectorReader();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;\\&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">CharacterReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;%&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArgReader</span><span class="o">();</span>
</span><span class='line'><span class="n">macros</span><span class="o">[</span><span class="sc">&#39;#&#39;</span><span class="o">]</span> <span class="o">=</span> <span class="k">new</span> <span class="n">DispatchReader</span><span class="o">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is important because the reader is responsible for reading line and column number information, and establishing a relationship between tokens read and locations in the file.</p>

<p>One of the main drawbacks of the reader used by the compiler is that much of the line and column number information is lost, that&#8217;s one of the reasons <a href="http://blog.guillermowinkler.com/blog/2014/04/13/decompiling-clojure-i/">we saw in our earlier post</a> that for a 7 line function only one line was properly mapped, interestingly, the line corresponding to the outter s-expression.</p>

<p>We will have to modify this reader if we want proper debugging information for our debugger.</p>

<h2>The analyzer</h2>

<p>The analyzer is the part of the compiler that translates your <code>s-expressions</code> into proper things to be emitted.</p>

<p>We&#8217;re already familiar with the REPL, in the <code>eval</code> function <code>analyze</code> and <code>emit</code> are combined in a single step, but internally there&#8217;s a two step process.</p>

<p>First, our parsed but meaningless code needs to be translated into meaningful expressions.</p>

<p>In the case of the Clojure compiler all expressions implement the <code>Expr</code> interface:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">interface</span> <span class="nc">Expr</span><span class="o">{</span>
</span><span class='line'>  <span class="n">Object</span> <span class="nf">eval</span><span class="o">()</span> <span class="o">;</span>
</span><span class='line'>  <span class="kt">void</span> <span class="nf">emit</span><span class="o">(</span><span class="n">C</span> <span class="n">context</span><span class="o">,</span> <span class="n">ObjExpr</span> <span class="n">objx</span><span class="o">,</span> <span class="n">GeneratorAdapter</span> <span class="n">gen</span><span class="o">);</span>
</span><span class='line'>  <span class="kt">boolean</span> <span class="nf">hasJavaClass</span><span class="o">()</span> <span class="o">;</span>
</span><span class='line'>  <span class="n">Class</span> <span class="nf">getJavaClass</span><span class="o">()</span> <span class="o">;</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Much of the <a href="http://clojure.org/special_forms">Clojure special forms</a> are handled here, <code>IfExpr</code>, <code>LetExpr</code>, <code>LetFnExpr</code>, <code>RecurExpr</code>, <code>FnExpr</code>, <code>DefExpr</code>, <code>CaseExpr</code>, you get the idea.</p>

<p>Those are nested classes inside the Compiler class, and for you visualize how many of those special cases exist inside the compiler, I took this picture for you:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/analyze-expr.png" width="380" height="280" title="Analyzer" alt="Analyzer"></p>

<p>As you would expect for a properly modularized piece of software, each expression knows how to parse itself, eval itself, and emit itself.</p>

<p>The analyze function is a switch on the type of the form to be analyzed, just for you to get a taste:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">private</span> <span class="kd">static</span> <span class="n">Expr</span> <span class="nf">analyze</span><span class="o">(</span><span class="n">C</span> <span class="n">context</span><span class="o">,</span> <span class="n">Object</span> <span class="n">form</span><span class="o">,</span> <span class="n">String</span> <span class="n">name</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'><span class="o">...</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span><span class="o">(</span><span class="n">fclass</span> <span class="o">==</span> <span class="n">Symbol</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span><span class='line'>  <span class="k">return</span> <span class="nf">analyzeSymbol</span><span class="o">((</span><span class="n">Symbol</span><span class="o">)</span> <span class="n">form</span><span class="o">);</span>
</span><span class='line'><span class="k">else</span> <span class="nf">if</span><span class="o">(</span><span class="n">fclass</span> <span class="o">==</span> <span class="n">Keyword</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span><span class='line'>  <span class="k">return</span> <span class="nf">registerKeyword</span><span class="o">((</span><span class="n">Keyword</span><span class="o">)</span> <span class="n">form</span><span class="o">);</span>
</span><span class='line'><span class="k">else</span> <span class="nf">if</span><span class="o">(</span><span class="n">form</span> <span class="k">instanceof</span> <span class="n">Number</span><span class="o">)</span>
</span><span class='line'>  <span class="k">return</span> <span class="n">NumberExpr</span><span class="o">.</span><span class="na">parse</span><span class="o">((</span><span class="n">Number</span><span class="o">)</span> <span class="n">form</span><span class="o">);</span>
</span><span class='line'><span class="k">else</span> <span class="nf">if</span><span class="o">(</span><span class="n">fclass</span> <span class="o">==</span> <span class="n">String</span><span class="o">.</span><span class="na">class</span><span class="o">)</span>
</span><span class='line'>  <span class="k">return</span> <span class="k">new</span> <span class="nf">StringExpr</span><span class="o">(((</span><span class="n">String</span><span class="o">)</span> <span class="n">form</span><span class="o">).</span><span class="na">intern</span><span class="o">());</span>
</span><span class='line'><span class="o">...</span>
</span></code></pre></td></tr></table></div></figure>


<p>And there&#8217;s special handling for the special forms which are keyed by Symbol on the same file.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">IPersistentMap</span> <span class="n">specials</span> <span class="o">=</span> <span class="n">PersistentHashMap</span><span class="o">.</span><span class="na">create</span><span class="o">(</span>
</span><span class='line'>      <span class="n">DEF</span><span class="o">,</span> <span class="k">new</span> <span class="n">DefExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">LOOP</span><span class="o">,</span> <span class="k">new</span> <span class="n">LetExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">RECUR</span><span class="o">,</span> <span class="k">new</span> <span class="n">RecurExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">IF</span><span class="o">,</span> <span class="k">new</span> <span class="n">IfExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">CASE</span><span class="o">,</span> <span class="k">new</span> <span class="n">CaseExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">LET</span><span class="o">,</span> <span class="k">new</span> <span class="n">LetExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">LETFN</span><span class="o">,</span> <span class="k">new</span> <span class="n">LetFnExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">DO</span><span class="o">,</span> <span class="k">new</span> <span class="n">BodyExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">FN</span><span class="o">,</span> <span class="kc">null</span><span class="o">,</span>
</span><span class='line'>      <span class="n">QUOTE</span><span class="o">,</span> <span class="k">new</span> <span class="n">ConstantExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">THE_VAR</span><span class="o">,</span> <span class="k">new</span> <span class="n">TheVarExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">IMPORT</span><span class="o">,</span> <span class="k">new</span> <span class="n">ImportExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">DOT</span><span class="o">,</span> <span class="k">new</span> <span class="n">HostExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">ASSIGN</span><span class="o">,</span> <span class="k">new</span> <span class="n">AssignExpr</span><span class="o">.</span><span class="na">Parser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">DEFTYPE</span><span class="o">,</span> <span class="k">new</span> <span class="n">NewInstanceExpr</span><span class="o">.</span><span class="na">DeftypeParser</span><span class="o">(),</span>
</span><span class='line'>      <span class="n">REIFY</span><span class="o">,</span> <span class="k">new</span> <span class="n">NewInstanceExpr</span><span class="o">.</span><span class="na">ReifyParser</span><span class="o">(),</span>
</span></code></pre></td></tr></table></div></figure>


<p>Analyze <em>will</em> return a parsed <code>Expr</code>, which is now a part of your program represented in the internal data structures of the compiler.</p>

<h2>The bytecode generator</h2>

<p>As said before it uses <a href="http://asm.ow2.org/">ASM</a> so we found the standard code stacking up visitors, annotations, methods, fields, etc.</p>

<p>I won&#8217;t enter here into specific details about ASM API since it&#8217;s properly documented somewhere else.</p>

<p>Only notice that no matter if code is eval&#8217;ed or not, JVM bytecode <em>will</em> be generated.</p>

<h2>What&#8217;s next</h2>

<p>One of the reasons I ended up here when I started working on the debugger was to see if by any means, I could <em>add</em> better line number references to the
current Clojure compiler.</p>

<p>As said before and as we saw here, the Java Clojure Compiler is not exactly built for extensibility.</p>

<p>The option I had left, was to modify the line numbers and other debugging information at runtime, and that&#8217;s what I will show you on the next post.</p>

<p>I will properly synchronize Clojure source code with JVM Bytecode, meaning I will synchronize code trees, that way I will not only add proper line references, but I will know
which bytecode corresponds with which <code>s-expression</code> in your source.</p>

<p>Doing Clojure I usually end up with lines of code looking like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nb">map </span><span class="p">(</span><span class="nb">comp first rest </span><span class="p">(</span><span class="nb">partial filter </span><span class="nv">identity</span><span class="p">))</span> <span class="p">(</span><span class="nf">split-line</span> <span class="nv">line</span> <span class="nv">separator</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>What use do I have for a <em>line base debugger</em> with that code??</p>

<p>I want an <strong>s-expression based debugger</strong>, don&#8217;t you?</p>

<p>One more reason we have to envy <a href="http://racket-lang.org/">Dr Racket</a>, whose debugger already knows about them.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/racket-debug.png" width="580" height="480" title="Racket Debugger" alt="Racket Debugger"></p>

<p>Stay tuned to see it working on the JVM.</p>

<p>Meanwhile, <a href="http://www.twitter.com/guilespi">I&#8217;m guilespi</a> on Twitter.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Decompiling Clojure I]]></title>
    <link href="http://guilespi.github.com/blog/2014/04/13/decompiling-clojure-i/"/>
    <updated>2014-04-13T17:19:00-03:00</updated>
    <id>http://guilespi.github.com/blog/2014/04/13/decompiling-clojure-i</id>
    <content type="html"><![CDATA[<p>This is the first in a series of articles about decompiling Clojure, that is, going from JVM bytecode created by the Clojure compiler, to some kind of higher level language, not necessarily Clojure.</p>

<p>This article was written in the scope of a larger project, building a better Clojure debugger, which I&#8217;ll probably blog about in the future.</p>

<p>These articles are going to build form the ground up, so you may skip forward if you find some of the stuff obvious.</p>

<h1>Clojure targets the JVM</h1>

<p>To be more precise, there is a <a href="https://github.com/clojure/clojure">Clojure compiler targeting the JVM</a>, there&#8217;s also one <a href="https://github.com/clojure/clojurescript">targeting Javascript</a>, one for <a href="https://github.com/richhickey/clojure-clr">the CLR</a> and there are some less known projects <a href="https://github.com/raph-amiard/clojurescript-lua">targeting lua</a> or <a href="https://github.com/schani/clojurec">even C</a>.</p>

<p>But the official <a href="http://clojure.com/">clojure core</a> efforts are mainly on the JVM, which stands for <em>Java Virtual Machine</em>.</p>

<p>That means when you write some clojure code:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">ns </span><span class="nv">hello-world</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="nb">println </span><span class="s">&quot;Hello World&quot;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>You won&#8217;t get a native binary, for instance a x86 <a href="http://msdn.microsoft.com/en-us/magazine/cc301805.aspx">PE</a> or <a href="http://www.skyfree.org/linux/references/ELF_Format.pdf">ELF</a> file, although it&#8217;s entirely possible to write a compiler to do it.</p>

<p>When you target a particular runtime though, you usually get a different set of functions to interact with the host, there&#8217;s a lot of language primitives just to deal with <a href="http://clojure.org/java_interop">Java inter operation</a> which do not
migrate easily to other runtimes or virtual machines.</p>

<h1>The JVM is about Java, or is it?</h1>

<p>This doesn&#8217;t mean that the JVM can <em>only</em> run programs written in Java.</p>

<p>In fact, Clojure doesn&#8217;t use Java as an intermediate language before compiling, the Clojure compiler for the JVM generates <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html">JVM bytecode</a> directly <a href="http://asm.ow2.org/">using the ASM library</a>.</p>

<p>So, what does it mean the JVM is about Java if you can compile directly to bytecode without a mandatory visit to <a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html">the kingdom of nouns</a>?</p>

<p>Besides its name, the JVM was designed by James Gosling in 1992 to support the <a href="http://docs.oracle.com/javase/specs/jvms/se5.0/html/Preface.doc.html">Oak Programming Language</a>, before evolving into its current form.</p>

<p>Its main responsibility is to achieve independence from hardware and operating system, and like a real machine, it has an instruction set and manipulates memory at runtime, and the truth is the JVM knows nothing about the Java Programming Language, it only knows of a particularly binary format, <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html">the class file format</a>, which contains bytecode and other information.</p>

<p>So, any programming language with features that can be expressed in terms of a valid class file, can by hosted on the JVM.</p>

<p>But the truth is that the class file format, maintains a lot of resemblance with concepts appearing in Java, or any other OO programming language as a matter of fact, to name a few:</p>

<ul>
<li>A <code>class</code> file corresponds to a Class</li>
<li>A <code>class</code> file has members</li>
<li>A <code>class</code> file has methods</li>
<li>Methods of the <code>class</code> file can be static or instance methods</li>
<li>There are primitive types and reference types, that can be stored in variables</li>
<li>Exceptions are an instance or subclass of <code>Throwable</code></li>
<li>etc</li>
</ul>


<p>So, we can say the JVM is <strong>not</strong> agnostic regarding the concepts supported by the language, as <a href="http://en.wikipedia.org/wiki/Lisp_Machines">the LISP machines</a> were not agnostic either.</p>

<h1>Clojure compiles to bytecode</h1>

<p>So we have a language like Clojure, with many concepts not easily mapped to the JVM spec, but that it was mapped none the less, how?</p>

<h2>Namespaces do not exist</h2>

<p>Maybe you think Clojure namespaces correspond to a <strong>class</strong>, and each method in the namespace is mapped to a method in the class.</p>

<p>Well, that is not the case.</p>

<p>Namespaces <a href="http://www.infoq.com/presentations/What-Sucks-about-Clojure-and-Why-You-ll-Love-It-Anyway">were criticized before</a> for being tough, and the truth is they&#8217;re used for proper modularity,
but do not map to an entity in the JVM. They&#8217;re equivalent to java packages or modules in other languages.</p>

<h2>Each function is a class</h2>

<p>Each function in your namespace will get compiled to a complete different class. That&#8217;s something you can easily confirm listing the files under <code>target/classes</code> in a leiningen project directory.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">git</span><span class="err">:</span><span class="p">(</span><span class="nf">master</span><span class="p">)</span> <span class="err">✗</span> <span class="nv">ls</span> <span class="nv">target/classes/</span>
</span><span class='line'>
</span><span class='line'><span class="nv">config$fn__292.class</span>
</span><span class='line'><span class="nv">routes__init.class</span>
</span><span class='line'><span class="nv">config$loading__4910__auto__.class</span>
</span><span class='line'><span class="nv">config$read_environment$fn__300.class</span>
</span><span class='line'><span class="nv">config$read_environment.class</span>
</span><span class='line'><span class="nv">config$read_properties$iter__304__308$fn__309$fn__310.class</span>
</span><span class='line'><span class="nv">server</span>
</span><span class='line'><span class="nv">server$_main.class</span>
</span><span class='line'><span class="nv">server$_main$fn__4006.class</span>
</span><span class='line'><span class="nv">server$fn__3939.class</span>
</span></code></pre></td></tr></table></div></figure>


<p>You will find a <code>.class</code> file for each function you have defined, <code>namespace$function.class</code> being the standard syntax.</p>

<h2>Each anonymous function is also a class</h2>

<p>As you saw in the previous listing, there are many functions with numbers like <code>config$fn__292.class</code>.</p>

<p>Those correspond to anonymous functions that get their own class when compiled, so if you have this code:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nb">map </span><span class="o">#</span><span class="p">(</span><span class="nb">+ </span><span class="mi">34</span> <span class="nv">%</span><span class="p">)</span> <span class="p">(</span><span class="nb">range </span><span class="mi">10</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>You should expect a <code>.class</code> file for the anonymous function <code>#(+ 34 %)</code>.</p>

<h2><em>class</em> files don&#8217;t need to be on disk</h2>

<p>Many times you&#8217;ll find the <code>class</code> files on disk, but it doesn&#8217;t have to be that way.</p>

<p>In many circumstances we&#8217;re going to be modifying the <code>class</code> structure on runtime, or creating new <code>class</code> structures to be run, entirely on memory. Even the compiler can <code>eval</code> some code
compiling to memory without creating a <code>class</code> file on disk.</p>

<h1>What does bytecode look like?</h1>

<p>For the first example, I selected a real simple clojure function</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">test-multi-let</span>
</span><span class='line'>  <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">a</span> <span class="mi">1</span>
</span><span class='line'>        <span class="nv">b</span> <span class="mi">2</span>
</span><span class='line'>        <span class="nv">c</span> <span class="mi">3</span>
</span><span class='line'>        <span class="nv">b</span> <span class="mi">4</span><span class="p">]</span>
</span><span class='line'>    <span class="mi">9</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>To explore the bytecode we will use <code>javap</code>, simple, but does the job:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">javap</span> <span class="nv">-c</span> <span class="nv">target/classes/debugee/test</span><span class="sc">\$</span><span class="nv">test_multi_let.class</span>
</span><span class='line'><span class="nv">...</span>
</span><span class='line'><span class="nv">public</span> <span class="nv">static</span> <span class="p">{}</span><span class="c1">;</span>
</span><span class='line'>    <span class="nv">Code</span><span class="err">:</span>
</span><span class='line'>       <span class="mi">0</span><span class="err">:</span> <span class="nv">lconst_1</span>
</span><span class='line'>       <span class="mi">1</span><span class="err">:</span> <span class="nv">invokestatic</span>  <span class="o">#</span><span class="mi">19</span>                 <span class="nv">//</span> <span class="nv">Method</span> <span class="nv">java/lang/Long.valueOf</span><span class="err">:</span><span class="p">(</span><span class="nf">J</span><span class="p">)</span><span class="nv">Ljava/lang/Long</span><span class="c1">;</span>
</span><span class='line'>       <span class="mi">4</span><span class="err">:</span> <span class="nv">putstatic</span>     <span class="o">#</span><span class="mi">21</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__0</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>       <span class="mi">7</span><span class="err">:</span> <span class="nv">ldc2_w</span>        <span class="o">#</span><span class="mi">22</span>                 <span class="nv">//</span> <span class="nb">long </span><span class="mi">2</span><span class="nv">l</span>
</span><span class='line'>      <span class="mi">10</span><span class="err">:</span> <span class="nv">invokestatic</span>  <span class="o">#</span><span class="mi">19</span>                 <span class="nv">//</span> <span class="nv">Method</span> <span class="nv">java/lang/Long.valueOf</span><span class="err">:</span><span class="p">(</span><span class="nf">J</span><span class="p">)</span><span class="nv">Ljava/lang/Long</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">13</span><span class="err">:</span> <span class="nv">putstatic</span>     <span class="o">#</span><span class="mi">25</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__1</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">16</span><span class="err">:</span> <span class="nv">ldc2_w</span>        <span class="o">#</span><span class="mi">26</span>                 <span class="nv">//</span> <span class="nb">long </span><span class="mi">3</span><span class="nv">l</span>
</span><span class='line'>      <span class="mi">19</span><span class="err">:</span> <span class="nv">invokestatic</span>  <span class="o">#</span><span class="mi">19</span>                 <span class="nv">//</span> <span class="nv">Method</span> <span class="nv">java/lang/Long.valueOf</span><span class="err">:</span><span class="p">(</span><span class="nf">J</span><span class="p">)</span><span class="nv">Ljava/lang/Long</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">22</span><span class="err">:</span> <span class="nv">putstatic</span>     <span class="o">#</span><span class="mi">29</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__2</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">25</span><span class="err">:</span> <span class="nv">ldc2_w</span>        <span class="o">#</span><span class="mi">30</span>                 <span class="nv">//</span> <span class="nb">long </span><span class="mi">4</span><span class="nv">l</span>
</span><span class='line'>      <span class="mi">28</span><span class="err">:</span> <span class="nv">invokestatic</span>  <span class="o">#</span><span class="mi">19</span>                 <span class="nv">//</span> <span class="nv">Method</span> <span class="nv">java/lang/Long.valueOf</span><span class="err">:</span><span class="p">(</span><span class="nf">J</span><span class="p">)</span><span class="nv">Ljava/lang/Long</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">31</span><span class="err">:</span> <span class="nv">putstatic</span>     <span class="o">#</span><span class="mi">33</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__3</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">34</span><span class="err">:</span> <span class="nv">ldc2_w</span>        <span class="o">#</span><span class="mi">34</span>                 <span class="nv">//</span> <span class="nb">long </span><span class="mi">9</span><span class="nv">l</span>
</span><span class='line'>      <span class="mi">37</span><span class="err">:</span> <span class="nv">invokestatic</span>  <span class="o">#</span><span class="mi">19</span>                 <span class="nv">//</span> <span class="nv">Method</span> <span class="nv">java/lang/Long.valueOf</span><span class="err">:</span><span class="p">(</span><span class="nf">J</span><span class="p">)</span><span class="nv">Ljava/lang/Long</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">40</span><span class="err">:</span> <span class="nv">putstatic</span>     <span class="o">#</span><span class="mi">37</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__4</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">43</span><span class="err">:</span> <span class="nv">return</span>
</span></code></pre></td></tr></table></div></figure>


<p>I&#8217;ve removed some extra information such as variable tables, we&#8217;re going to be visiting those later.</p>

<p>What you see here are JVM <em>assembly instructions</em>, just a subset of the JVM instruction set, generated by the Clojure compiler when feed with the sample function above.</p>

<p>Before we get into more details, let me show you how that code looks after a basic decompiler pass:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="mi">0</span><span class="ss">:a</span> <span class="nb">= </span><span class="mi">1</span>
</span><span class='line'><span class="mi">2</span><span class="ss">:b</span> <span class="nb">= </span><span class="mi">2</span>
</span><span class='line'><span class="mi">6</span><span class="ss">:c</span> <span class="nb">= </span><span class="mi">3</span>
</span><span class='line'><span class="mi">11</span><span class="ss">:b</span> <span class="nb">= </span><span class="mi">4</span>
</span><span class='line'><span class="mi">16</span><span class="ss">:RETURN</span> <span class="mi">9</span>
</span></code></pre></td></tr></table></div></figure>


<p>Prettier uh?</p>

<p>That is until you decompile this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">test-if</span>
</span><span class='line'>  <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">= </span><span class="p">(</span><span class="nb">inc </span><span class="mi">1</span><span class="p">)</span> <span class="mi">2</span><span class="p">)</span>
</span><span class='line'>    <span class="mi">8</span>
</span><span class='line'>    <span class="mi">9</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>And get this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="mi">0</span><span class="ss">:IF</span> <span class="p">(</span><span class="mi">2</span> <span class="nv">!=</span> <span class="nv">clojure.lang.Numbers.inc</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="nv">GOTO</span> <span class="mi">11</span> <span class="nv">ELSE</span> <span class="nv">GOTO</span> <span class="mi">18</span>
</span><span class='line'><span class="mi">11</span><span class="ss">:RETURN</span> <span class="mi">9</span>
</span><span class='line'><span class="mi">18</span><span class="ss">:RETURN</span> <span class="mi">8</span>
</span></code></pre></td></tr></table></div></figure>


<p>Who was the moron that put a <a href="http://groups.engin.umd.umich.edu/CIS/course.des/cis400/basic/basic.html"><strong>BASIC</strong></a> in my Clojure!</p>

<p>Ain&#8217;t it?</p>

<p>Keep reading&#8230; there&#8217;s more to be seen ahead.</p>

<h1>The operand stack</h1>

<p>I won&#8217;t dwell into many details about each JVM instruction and how that translates to something resembling Clojure, or Basic for that matter, but there&#8217;s one thing worth of mention, and that is the operand stack.</p>

<h2>Frames</h2>

<p>A new Frame is created each time a method is invoked and destroyed when the method completes, whether that information is normal or abrupt (throws an uncaught exception), frames are allocated in the JVM stack and have its own array of local variables and its own operand stack.</p>

<p>If you set a breakpoint on your code, each different entry in your thread callstack, is a frame.</p>

<h2>Stack</h2>

<p>The operand stack is a last-in-first-out (LIFO) stack and its empty when the Frame that contains it is created, and the JVM provides instructions for loading constants or variables into the operand stack, and to put values from the operand stack in variables.</p>

<p>The operand stack is usually used to prepare parameters to be passed to methods and to receive method results, <a href="http://markfaction.wordpress.com/2012/07/15/stack-based-vs-register-based-virtual-machine-architecture-and-the-dalvik-vm/">as opposed to using registers to do it</a>.</p>

<p>So you should expect something along these lines:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">f</span><span class="p">(</span><span class="nf">a</span>, <span class="nv">b</span>, <span class="nv">c</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="nv">=&gt;</span> <span class="nv">compiling</span> <span class="nv">to</span>
</span><span class='line'>
</span><span class='line'><span class="nv">push</span> <span class="nv">a</span>
</span><span class='line'><span class="nv">push</span> <span class="nv">b</span>
</span><span class='line'><span class="nv">push</span> <span class="nv">c</span>
</span><span class='line'><span class="nv">call</span> <span class="nv">f</span>
</span></code></pre></td></tr></table></div></figure>


<p>So looking again at the bytecode of the previous function:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">test-if</span>
</span><span class='line'>  <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">if </span><span class="p">(</span><span class="nb">= </span><span class="p">(</span><span class="nb">inc </span><span class="mi">1</span><span class="p">)</span> <span class="mi">2</span><span class="p">)</span>
</span><span class='line'>    <span class="mi">8</span>
</span><span class='line'>    <span class="mi">9</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">public</span> <span class="nv">java.lang.Object</span> <span class="nv">invoke</span><span class="p">()</span><span class="c1">;</span>
</span><span class='line'>    <span class="nv">Code</span><span class="err">:</span>
</span><span class='line'>       <span class="mi">0</span><span class="err">:</span> <span class="nv">lconst_1</span>
</span><span class='line'>       <span class="mi">1</span><span class="err">:</span> <span class="nv">invokestatic</span>  <span class="o">#</span><span class="mi">63</span>                 <span class="nv">//</span> <span class="nv">Method</span> <span class="nv">clojure/lang/Numbers.inc</span><span class="err">:</span><span class="p">(</span><span class="nf">J</span><span class="p">)</span><span class="nv">J</span>
</span><span class='line'>       <span class="mi">4</span><span class="err">:</span> <span class="nv">ldc2_w</span>        <span class="o">#</span><span class="mi">42</span>                 <span class="nv">//</span> <span class="nb">long </span><span class="mi">2</span><span class="nv">l</span>
</span><span class='line'>       <span class="mi">7</span><span class="err">:</span> <span class="nv">lcmp</span>
</span><span class='line'>       <span class="mi">8</span><span class="err">:</span> <span class="nv">ifne</span>          <span class="mi">18</span>
</span><span class='line'>      <span class="mi">11</span><span class="err">:</span> <span class="nv">getstatic</span>     <span class="o">#</span><span class="mi">49</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__4</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">14</span><span class="err">:</span> <span class="nv">goto</span>          <span class="mi">21</span>
</span><span class='line'>      <span class="mi">17</span><span class="err">:</span> <span class="nv">pop</span>
</span><span class='line'>      <span class="mi">18</span><span class="err">:</span> <span class="nv">getstatic</span>     <span class="o">#</span><span class="mi">53</span>                 <span class="nv">//</span> <span class="nv">Field</span> <span class="nv">const__5</span><span class="ss">:Ljava/lang/Object</span><span class="c1">;</span>
</span><span class='line'>      <span class="mi">21</span><span class="err">:</span> <span class="nv">areturn</span>
</span></code></pre></td></tr></table></div></figure>


<p>We can make ourselves an interpretation about what&#8217;s going on&#8230;</p>

<p><code>lconst_1</code> is pushing the constant value <code>1</code> into the stack, then calling a static method with <code>invokestatic</code>, as you&#8217;ve already guessed that&#8217;s the <code>clojure.lang.Numbers.inc(1)</code> we saw on the <em>basic</em> decompiler earlier.</p>

<p>Then <code>ld2_w</code> loads the value <code>2</code> into the stack and <code>lcmp</code> will compare it against the function result, <code>ifne</code> tests for non equality and jumps to line <code>18</code> if values differ.</p>

<p>One thing to consider here is that each entry on the operand stack can hold a value of any JVM type, and those must be operated in ways appropriate to their types, so many operations have a different operation code according to the type they&#8217;re handling.</p>

<p>So looking at this example from the JVM specification, we see the operations are prefixed with a <code>d</code> since they operate on <code>double</code> values.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">Method</span> <span class="nb">double </span><span class="nv">doubleLocals</span><span class="p">(</span><span class="nf">double</span>,<span class="nv">double</span><span class="p">)</span>
</span><span class='line'><span class="mi">0</span> <span class="nv">dload_1</span> <span class="nv">//</span> <span class="nv">First</span> <span class="nv">argument</span> <span class="nv">in</span> <span class="nv">local</span> <span class="nv">variables</span> <span class="mi">1</span> <span class="nb">and </span><span class="mi">2</span>
</span><span class='line'><span class="mi">1</span> <span class="nv">dload_3</span> <span class="nv">//</span> <span class="nv">Second</span> <span class="nv">argument</span> <span class="nv">in</span> <span class="nv">local</span> <span class="nv">variables</span> <span class="mi">3</span> <span class="nb">and </span><span class="mi">4</span>
</span><span class='line'><span class="mi">2</span> <span class="nv">dadd</span>
</span><span class='line'><span class="mi">3</span> <span class="nv">dreturn</span>
</span></code></pre></td></tr></table></div></figure>


<p>Which as you may have guessed, is adding double values <code>1</code> and <code>3</code>.</p>

<h1>JVM auxiliary information</h1>

<p>The JVM <code>class</code> format has support for some extra information that can be used for debugging purposes, some of which you can get rid from your files if you want.</p>

<p>Among those we find <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.12">the LineNumberTable attribute</a> and the <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.13">the LocalVariableTable attribute</a>, which may be used by debuggers to determine the value of a given local variable during the execution of a method.</p>

<p>According to the jvm spec, the table has the following structure inside the <code>class</code> file format</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">LocalVariableTable_attribute</span> <span class="p">{</span>
</span><span class='line'>       <span class="nv">u2</span> <span class="nv">attribute_name_index</span><span class="c1">;</span>
</span><span class='line'>       <span class="nv">u4</span> <span class="nv">attribute_length</span><span class="c1">;</span>
</span><span class='line'>       <span class="nv">u2</span> <span class="nv">local_variable_table_length</span><span class="c1">;</span>
</span><span class='line'>       <span class="p">{</span>   <span class="nv">u2</span> <span class="nv">start_pc</span><span class="c1">;</span>
</span><span class='line'>           <span class="nv">u2</span> <span class="nv">length</span><span class="c1">;</span>
</span><span class='line'>           <span class="nv">u2</span> <span class="nv">name_index</span><span class="c1">;</span>
</span><span class='line'>           <span class="nv">u2</span> <span class="nv">descriptor_index</span><span class="c1">;</span>
</span><span class='line'>           <span class="nv">u2</span> <span class="nv">index</span><span class="c1">;</span>
</span><span class='line'>       <span class="p">}</span> <span class="nv">local_variable_table</span><span class="p">[</span><span class="nv">local_variable_table_length</span><span class="p">]</span><span class="c1">;</span>
</span><span class='line'>   <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Basically it says which variable starts at which instruction: <code>start_pc</code> and lasts for how long: <code>length</code>.</p>

<p>If we look at that table for our <code>let</code> example:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">test-multi-let</span>
</span><span class='line'>  <span class="p">[]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">a</span> <span class="mi">1</span>
</span><span class='line'>        <span class="nv">b</span> <span class="mi">2</span>
</span><span class='line'>        <span class="nv">c</span> <span class="mi">3</span>
</span><span class='line'>        <span class="nv">b</span> <span class="mi">4</span><span class="p">]</span>
</span><span class='line'>    <span class="mi">9</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>We see how each variable is referenced against program counter(<code>pc</code>) line numbers (do not get confused with source file line numbers).</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">LocalVariableTable</span><span class="err">:</span>
</span><span class='line'>      <span class="nv">Start</span>  <span class="nv">Length</span>  <span class="nv">Slot</span>  <span class="nv">Name</span>   <span class="nv">Signature</span>
</span><span class='line'>             <span class="mi">2</span>      <span class="mi">17</span>     <span class="mi">1</span>     <span class="nv">a</span>   <span class="nv">J</span>
</span><span class='line'>             <span class="mi">6</span>      <span class="mi">13</span>     <span class="mi">3</span>     <span class="nv">b</span>   <span class="nv">J</span>
</span><span class='line'>            <span class="mi">11</span>       <span class="mi">8</span>     <span class="mi">5</span>     <span class="nv">c</span>   <span class="nv">J</span>
</span><span class='line'>            <span class="mi">16</span>       <span class="mi">3</span>     <span class="mi">7</span>     <span class="nv">b</span>   <span class="nv">J</span>
</span><span class='line'>             <span class="mi">0</span>      <span class="mi">19</span>     <span class="mi">0</span>  <span class="nv">this</span>   <span class="nv">Ljava/lang/Object</span><span class="c1">;</span>
</span></code></pre></td></tr></table></div></figure>


<p>One interesting thing though, is the <code>LineNumberTable</code></p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'>  <span class="nv">public</span> <span class="nv">debugee.test$test_multi_let</span><span class="p">()</span><span class="c1">;</span>
</span><span class='line'>    <span class="nv">LineNumberTable</span><span class="err">:</span>
</span><span class='line'>      <span class="nv">line</span> <span class="mi">204</span><span class="err">:</span> <span class="mi">0</span>
</span></code></pre></td></tr></table></div></figure>


<p>Which has only <strong>one</strong> line number reference, even if our function was 7 lines long, obviously that cannot be good for a debugger expecting to step over each line!</p>

<p>Next post I&#8217;ll blog about the Clojure compiler and how it ends up creating that bytecode, before visiting again the decompiling process.</p>

<p>I&#8217;m <a href="http://www.twitter.com/guilespi">guilespi</a> on Twitter, get in touch!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What's so great about Reducers?]]></title>
    <link href="http://guilespi.github.com/blog/2013/12/01/whats-so-great-about-reducers/"/>
    <updated>2013-12-01T13:25:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2013/12/01/whats-so-great-about-reducers</id>
    <content type="html"><![CDATA[<p>This post is about Clojure reducers, but what makes them great are the ideas behind the implementation, which may be portable to other languages.</p>

<p>So if you&#8217;re interested in performance don&#8217;t leave just yet.</p>

<p>One of the primary motivators for the reducers library is <a href="http://vimeo.com/6624203">Guy Steele&#8217;s ICFP &#8216;09</a> talk,
and since I assume you don&#8217;t have one hour to spend verifying I&#8217;m telling you it&#8217;s worth watching,
I&#8217;ll do my best to summarize it here, which is a post you will probably scan in less than 15 seconds.</p>

<p>One of the main points of the talk is that <strong>the way we&#8217;ve been thinking about programming for the last 50 years isn&#8217;t serving us anymore</strong>.</p>

<p>Why?</p>

<p>Because good sequential code is different from good parallel code.</p>

<h1>Parallel vs. Sequential</h1>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>+------------+--------------------------------------+-------------------------------------------------------------+
</span><span class='line'>|            |              Sequential              |                          Parallel                           |
</span><span class='line'>+------------+--------------------------------------+-------------------------------------------------------------+
</span><span class='line'>| Operations | Minimizes total number of operations | Often performs redundant operations to reduce communication |
</span><span class='line'>| Space      | Minimize space usage                 | Extra space to permit temporal decoupling                   |
</span><span class='line'>| Problem    | Linear problem decomposition         | Multiway aggregation of results                             |
</span><span class='line'>+------------+--------------------------------------+-------------------------------------------------------------+</span></code></pre></td></tr></table></div></figure>


<h1>The accumulator loop</h1>

<p>How would you sum all the elements of an array?</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>SUM = 0 
</span><span class='line'>DO I = 1, 1000000
</span><span class='line'>   SUM = SUM + X(I)
</span><span class='line'>END DO</span></code></pre></td></tr></table></div></figure>


<p>That&#8217;s right, the accumulator loop, you initialize the accumulator and update the thingy in each iteration step.</p>

<p>But you&#8217;re complecting how you update your sum with how you iterate your collection, ain&#8217;t it?</p>

<p>There&#8217;s a difference between <em>what</em> you do with <em>how</em> you do it. If you say <code>SUM(X)</code> it doesn&#8217;t make promises on the strategy,
it&#8217;s when you actually implement that SUM that the sequential promise is made.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/sequential_tree.png" width="480" height="580" title="'Sequential Tree'" ></p>

<p>The problem is the computation tree for the sequential strategy, if we remove the looping machinery and leave only the sums,
there&#8217;s a one million steps delay to get to the final result.</p>

<p>So what&#8217;s the tree you would like to see?</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/parallel_tree.png" width="480" height="580" title="'Parallel Tree'" ></p>

<p>And what code you would need to write in order to get that tree? Functional code?</p>

<p>Think again.</p>

<p>Functional code is not the complete answer, since you can write functional code and still have the same problem.</p>

<p>Since linear linked lists are inherently sequential you may be using a reducer and be on the same spot.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="nb">reduce + </span><span class="p">(</span><span class="nb">range </span><span class="mi">1</span> <span class="mi">1000000</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>We need <em>multiway decomposition</em>.</p>

<h1>Divide and conquer</h1>

<p>Rationale behind multiway decomposition is that we need a list representation that allows for binary decomposition of the list.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/tree_list_representation.png" width="480" height="580" title="'List as Tree'" ></p>

<p>You can obviously have many redundant trees representing the same conceptual list, and there&#8217;s value in redundancy since different trees have different properties.</p>

<h1>Summary</h1>

<ul>
<li>Don&#8217;t split a problem between first and rest, split in equal pieces.</li>
<li>Don&#8217;t create a null solution an successively update it, map inputs to singleton solutions and merge tree-wise.</li>
<li>Combining solutions is trickier than incremental updates.</li>
<li>Use sequential techniques near the leaves.</li>
<li>Programs organized for parallelism can be processed in parallel or sequentially.</li>
<li>Get rid of cons.</li>
</ul>


<h1>Clojure Reducers</h1>

<p>So what are Clojure reducers?</p>

<p>In short, it&#8217;s a library providing a new function <code>fold</code>, which is a parallel <code>reduce+combine</code>
that shares the same shape with the old sequence based code, main difference been you get to
provide a <code>combiner</code> function.</p>

<p>Go and read <a href="http://clojure.com/blog/2012/05/08/reducers-a-library-and-model-for-collection-processing.html">this</a> and <a href="http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html">this</a> great posts by Rich Hickey.</p>

<p>Back? Ok&#8230;</p>

<p>As Rich says in his article the accumulator style is not absent but the single initial value
and the serial execution promises of <code>foldl/r</code> have been abandoned.</p>

<p>For what it&#8217;s worth, I&#8217;ve written in Clojure the <strong>Split a string into words</strong> parallel
algorithm suggested by Steele <a href="https://gist.github.com/guilespi/7458410">here</a>, performance sucks compared against
<code>clojure.string/split</code> but it&#8217;s a nice algorithm none the less.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">parallel-words</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">w</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">to-word-list</span>
</span><span class='line'>   <span class="p">(</span><span class="nf">r/fold</span> <span class="mi">100</span>
</span><span class='line'>           <span class="nv">combine-states</span>
</span><span class='line'>           <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">state</span> <span class="nv">char</span><span class="p">]</span>
</span><span class='line'>             <span class="p">(</span><span class="nf">append-state</span> <span class="nv">state</span> <span class="p">(</span><span class="nf">process-char</span> <span class="nv">char</span><span class="p">)))</span>
</span><span class='line'>           <span class="p">(</span><span class="nf">vec</span> <span class="p">(</span><span class="nb">seq </span><span class="nv">w</span><span class="p">)))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>There are a couple interesting things in the code.</p>

<ul>
<li><code>combine-states</code> is the new combiner function, decides how to combine different splits</li>
<li><code>100</code> is the size when to stop splitting and do a sequential processing (calls <code>reduce</code> afterwards). Defaults to <code>512</code>.</li>
<li>The <code>fn</code> is the standard reducing function</li>
<li>The list is transformed into a <code>vector</code> before processing.</li>
</ul>


<p>Last step is just for the sake of experimentation, and has all to do with the underlying structure for vectors.</p>

<p>Both vectors and maps in Clojure are implemented as trees, which as we saw above, is one of the requirements for multiway decomposition.
There&#8217;s a <a href="http://hypirion.com/musings/understanding-persistent-vector-pt-1">great article here</a> about Clojure vectors, but key interest point is that it provides
practically <code>O(1)</code> runtime for <code>subvec</code>, which is how the vector folder <code>foldvec</code> successively splits the input vector before reaching the
sequential processing size.</p>

<p>So if you look at <a href="https://github.com/clojure/clojure/blob/master/src/clj/clojure/core/reducers.clj#L347-L367">the source code</a> only for vectors and maps actual fork/join parallelism happens, and standard reduce is called for linear lists.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'> <span class="nv">clojure.lang.IPersistentVector</span>
</span><span class='line'> <span class="p">(</span><span class="nf">coll-fold</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">v</span> <span class="nv">n</span> <span class="nv">combinef</span> <span class="nv">reducef</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">foldvec</span> <span class="nv">v</span> <span class="nv">n</span> <span class="nv">combinef</span> <span class="nv">reducef</span><span class="p">))</span>
</span><span class='line'>
</span><span class='line'> <span class="nv">Object</span>
</span><span class='line'> <span class="p">(</span><span class="nf">coll-fold</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">coll</span> <span class="nv">n</span> <span class="nv">combinef</span> <span class="nv">reducef</span><span class="p">]</span>
</span><span class='line'>  <span class="c1">;;can&#39;t fold, single reduce</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">reduce </span><span class="nv">reducef</span> <span class="p">(</span><span class="nf">combinef</span><span class="p">)</span> <span class="nv">coll</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>What I like the most about reducers is that reducer functions are curried, so you can compose them together as in:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">def </span><span class="nv">red</span> <span class="p">(</span><span class="nb">comp </span><span class="p">(</span><span class="nf">r/filter</span> <span class="nv">even?</span><span class="p">)</span> <span class="p">(</span><span class="nf">r/map</span> <span class="nv">inc</span><span class="p">)))</span>
</span><span class='line'><span class="p">(</span><span class="nb">reduce + </span><span class="p">(</span><span class="nf">red</span> <span class="p">[</span><span class="mi">1</span> <span class="mi">1</span> <span class="mi">1</span> <span class="mi">2</span><span class="p">]))</span>
</span><span class='line'><span class="c1">;=&gt; 6</span>
</span></code></pre></td></tr></table></div></figure>


<p>It&#8217;s like the utmost example of the <a href="http://www.infoq.com/presentations/Simple-Made-Easy">simple made easy</a> Hickey&#8217;s talk, where decomplecting the system, results in a much simpler but powerful
design at the same time.</p>

<p><em>I&#8217;m <a href="http://www.twitter.com/guilespi">guilespi</a> at Twitter</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Zipkin distributed tracing using Clojure]]></title>
    <link href="http://guilespi.github.com/blog/2013/11/28/zipkin-distributed-tracing-using-clojure/"/>
    <updated>2013-11-28T13:05:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2013/11/28/zipkin-distributed-tracing-using-clojure</id>
    <content type="html"><![CDATA[<p>When you have a system with many moving parts it&#8217;s usually difficult trying to understand which one of those pieces is the culprit,
say for instance your home page is taking 3 seconds to render and you&#8217;re losing customers, what the hell is going on?</p>

<p>Whether you&#8217;re using Memcache, Redis, RabbitMQ or a custom distributed service, if you&#8217;re trying to scale your shit up, you probably have many pieces or boxes involved.</p>

<p>At least that&#8217;s what happens <a href="http://highscalability.com/blog/2013/7/8/the-architecture-twitter-uses-to-deal-with-150m-active-users.html">at Twitter</a>, so they&#8217;ve come up with <a href="http://twitter.github.io/zipkin/">a solution called Zipkin</a> to trace distributed operations,
that is, an operation that is potentially solved using many different nodes.</p>

<p><em>Twitter Architecture</em>
<img class="center" src="http://guilespi.github.com/images/blog/twitter_arch.png" width="680" height="780" title="'Twitter Architecture'" ></p>

<p>Having dealt with distributed logging in the past, reconstructing a distributed operation from logs,
it&#8217;s like trying to build a giant jigsaw puzzle in the middle of a Tornado.</p>

<p>The standard strategy is to propagate some <code>operation id</code> and use it anywhere you want
to track what happened, and that is the essence of what Zipkin does, but in a structured kind of way.</p>

<h1>Zipkin</h1>

<p>Zipkin was modelled after <a href="http://research.google.com/pubs/pub36356.html">Google Dapper</a> paper on distributed tracing and basically gives you two things:</p>

<ul>
<li>Trace Collection</li>
<li>Trace Querying</li>
</ul>


<p><em>Zipkin Architecture</em>
<img class="center" src="http://guilespi.github.com/images/blog/zipkin_arch.png" width="680" height="780" title="'Zipkin Architecture'" ></p>

<p>The architecture looks complex but it ain&#8217;t that much, since you can avoid using <code>Scribe</code>, <code>Cassandra</code>, <code>Zookeeper</code>
and pretty much everything related to scaling the tracing platform itself.</p>

<p>Since the trace collector <em>speaks</em> the Scribe protocol you can trace directly to the collector, and you can also use
local disk storage for tracing and avoid a distributed database like Cassandra, it&#8217;s an easy way
to get your feet wet without having to setup a cluster to peek a few traces.</p>

<h1>Tracing</h1>

<p>There are a couple entities involved in Zipkin tracing which you should know before moving forward:</p>

<p><strong>Trace</strong></p>

<p>A trace is a particular operation which may occur in many different nodes and be composed on many different Spans.</p>

<p><strong>Span</strong></p>

<p>A span represents a sub-operation for the Trace, it can be a different service or a different stage in the operation process.
Also, spans have a hierarchy, so a span can be a child of another span.</p>

<p><strong>Annotation</strong></p>

<p>The annotation is how you tag your Spans to actually know what happened, there are two type of spans:</p>

<ul>
<li>Timestamp</li>
<li>Binary</li>
</ul>


<p>Timestamp spans are used for tracing time related stuff, and Binary annotations are used to tag your operation with a particular context,
which is useful for filtering later.</p>

<p>For instance you can have a new <em>Trace</em> for each home page request, which decomposes in the <em>Memcache Span</em>
the <em>Postgres Span</em> and the <em>Computation Span</em>, each of those
with their particular <em>Start Annotation</em> and <em>Finish Annotation</em>.</p>

<h1>API</h1>

<p>Zipkin is programmed in Scala and uses thrift, since it&#8217;s assumed you&#8217;re going to have distributed operations,
the <em>official client</em> is <a href="http://twitter.github.io/finagle/">Finagle</a>, which is kind of a RPC system for the JVM, but at least for me, it&#8217;s quite ugly.</p>

<p>Main reason is that it makes you feel that if you want to use Zipkin you must use a <em>Distributed Framework</em>, which is not at all necessary.
For a moment I almost felt like <a href="http://en.wikipedia.org/wiki/Common_Object_Request_Broker_Architecture">Corba</a> and <a href="http://en.wikipedia.org/wiki/Distributed_Component_Object_Model">DCOM</a> were coming back from the grave trying to lure me into the abyss.</p>

<p>There&#8217;s also libraries for <a href="https://rubygems.org/gems/finagle-thrift">Ruby</a> and <a href="https://github.com/racker/restkin">Python</a> but none of them felt quite right to me,
for Ruby you either use Finagle or you use Thrift, but there&#8217;s no actual Zipkin library,
for Python you have <a href="https://github.com/racker/tryfer">Tryfer</a> which is good and <a href="https://github.com/racker/restkin">Restkin</a> which is a REST API on top of it.</p>

<h1>Clojure</h1>

<p>In the process of understanding what Zipkin can do for you (that means <em>me</em>) I <a href="https://github.com/guilespi/clj-zipkin">hacked a client</a> for
Clojure using <a href="https://github.com/livingsocial/clj-scribe/">clj-scribe</a> and <a href="https://github.com/xsc/thrift-clj">clj-thrift</a> which made the process almost painless.</p>

<p>It comes with a ring handler so you can trace your incoming requests out of the box.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'> <span class="p">(</span><span class="nf">require</span> <span class="o">&#39;</span><span class="p">[</span><span class="nv">clj-zipkin.middleware</span> <span class="ss">:as</span> <span class="nv">m</span><span class="p">])</span>
</span><span class='line'>
</span><span class='line'>   <span class="p">(</span><span class="nf">defroutes</span> <span class="nv">routes</span>
</span><span class='line'>     <span class="p">(</span><span class="nf">GET</span> <span class="s">&quot;/&quot;</span> <span class="p">[]</span> <span class="s">&quot;&lt;h1&gt;Hello World&lt;/h1&gt;&quot;</span><span class="p">)</span>
</span><span class='line'>     <span class="p">(</span><span class="nf">route/not-found</span> <span class="s">&quot;&lt;h1&gt;Page not found&lt;/h1&gt;&quot;</span><span class="p">))</span>
</span><span class='line'>
</span><span class='line'>   <span class="p">(</span><span class="k">def </span><span class="nv">app</span>
</span><span class='line'>       <span class="p">(</span><span class="nb">-&gt; </span><span class="nv">routes</span>
</span><span class='line'>       <span class="p">(</span><span class="nf">m/request-tracer</span> <span class="p">{</span><span class="ss">:scribe</span> <span class="p">{</span><span class="ss">:host</span> <span class="s">&quot;localhost&quot;</span> <span class="ss">:port</span> <span class="mi">9410</span><span class="p">}</span>
</span><span class='line'>                          <span class="ss">:service</span> <span class="s">&quot;WebServer&quot;</span><span class="p">})))</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Zipkin Web Analyzer</em>
<img class="center" src="http://guilespi.github.com/images/blog/clj-zipkin-sample.png" width="580" height="680" title="'Zipkin Sample'" ></p>

<p>It&#8217;s far from perfect, undocumented and incomplete, but at least it&#8217;s free :)</p>

<p>Give it a try and let me know what you think.</p>

<p><em>I&#8217;m <a href="http://www.twitter.com/guilespi">guilespi</a> at Twitter</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Is StackOverflow a gentlemen's club?]]></title>
    <link href="http://guilespi.github.com/blog/2013/11/04/is-stackoverflow-a-gentlemens-club/"/>
    <updated>2013-11-04T14:53:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2013/11/04/is-stackoverflow-a-gentlemens-club</id>
    <content type="html"><![CDATA[<p>For some time now, tech industry has taken an active role in trying to solve the gender imbalance problem.</p>

<ul>
<li>Organizing <a href="http://railsgirls.com/">conferences</a> for women or by women</li>
<li>Trying to bring more women into math or <a href="http://railsbridge.org/">cs</a></li>
<li>Offering <a href="http://women2.com/etsy-hacker-school-scholarships-support-women-in-technology/">grants and scholarships</a> for <a href="https://www.hackerschool.com/faq">Hacker School</a></li>
<li><a href="http://valleywag.gawker.com/business-insider-ctos-is-your-new-tech-bro-nightmare-1280336916">Public scorn</a> <a href="https://twitter.com/adriarichards/status/313417655879102464/photo/1">for offenders</a> when deserved</li>
<li><a href="http://www.wired.com/underwire/2013/07/convention-harassment-comic-con/">Anti-Harassment</a> policies for conferences</li>
</ul>


<p>There&#8217;s even <a href="http://pages.uoregon.edu/wmnmath/Statistics/index.html">gender studies in mathematics and other sciences</a>.</p>

<p>But even if the issue has been on the table for a while, I&#8217;ve attended a few conferences where I live and the usual attendance looks like this:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/meetup-gender.jpg" width="680" height="780" title="'What a conference looks like'" ></p>

<p>I don&#8217;t think you&#8217;ll find more than 5 women in the picture.</p>

<p>And I can tell you <strong>for sure</strong>, that picture does not represent <em>at all</em> the <em>women in tech</em> in the city.
There may be an imbalance, but women are not by any means, 0,5% of computer science graduates here.</p>

<p>So women are not participating, but why?</p>

<h1>The Data</h1>

<p>Since StackExchange has <a href="http://data.stackexchange.com/">open data</a> you can <a href="http://blog.guillermowinkler.com/blog/2012/10/30/how-long-waiting-for-an-answer-in-stackoverflow/">derive some insights from</a>, I decided to take a look at the problem from a different perspective,
and address the question of the underrepresentation using StackOverflow data.</p>

<p>I started with a few questions in mind:</p>

<ul>
<li>What % of users are women?</li>
<li>What&#8217;s the question/answer rate for men and women?</li>
<li>How the reputation score for men and women compares?</li>
<li>How it compares to ambiguous/unisex names?</li>
<li>Is in fact SO a gentleman&#8217;s club?</li>
</ul>


<p>Since SO has no gender data, gender needs to be inferred from  <em>user names</em>, which is obviously not 100% accurate,
many names are unisex or depend on the country of origin. I decided to use <a href="http://www.heise.de/ct/ftp/07/17/182/">this database and program</a> which
has names from all over the world curated by local people. In many cases you will get a statistical result: <em>mostly male</em>
or <em>mostly female</em>, and that makes sense.</p>

<p><em>Be warned</em> this is not a scientific study nor tries to be, just trying to see some patterns here.</p>

<h1>First Glimpse</h1>

<p>First I wanted to get a glimpse of the general trends, so I did a random draw of 50k users, more than enough for what I need.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="k">Select</span> <span class="o">*</span> <span class="k">From</span> <span class="n">users</span>
</span><span class='line'><span class="k">Order</span> <span class="k">By</span> <span class="n">newid</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p>StackExchange limits the number of rows returned by the online database browser to 50k, so that&#8217;s it.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/random-share.png" width="680" height="780" title="'Random share'" ></p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'>  <span class="o">&gt;</span> <span class="k">table</span><span class="p">(</span><span class="n">users</span><span class="err">$</span><span class="n">gender</span><span class="p">)</span><span class="o">/</span><span class="n">nrow</span><span class="p">(</span><span class="n">users</span><span class="p">)</span>
</span><span class='line'>  <span class="n">anonymous</span>    <span class="n">error</span> <span class="k">in</span> <span class="n">name</span>        <span class="k">is</span> <span class="n">female</span>          <span class="k">is</span> <span class="n">male</span>     <span class="k">is</span> <span class="n">mostly</span> <span class="n">female</span>   <span class="k">is</span> <span class="n">mostly</span> <span class="n">male</span>   <span class="k">is</span> <span class="n">unisex</span> <span class="n">name</span>   <span class="n">name</span> <span class="k">not</span> <span class="k">found</span>
</span><span class='line'>   <span class="mi">0</span><span class="p">.</span><span class="mi">25662</span>       <span class="mi">0</span><span class="p">.</span><span class="mi">00006</span>              <span class="mi">0</span><span class="p">.</span><span class="mi">02910</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">23640</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">00946</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">04654</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">02942</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">39240</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you see there&#8217;s a 27% of confirmed males and only a 4% of confirmed females.  <code>Anonymous</code> users are the usual numerical users like <code>user395607</code>,
and <code>name not found</code> refers to things like <code>ppkt</code>, <code>HeTsH</code>,  <code>holden321</code> and <code>ITGronk</code>, you get the idea.</p>

<p>Then I wanted to see how reputation was distributed among those users, and how that compared against how long the user was using the site.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/random-reputation.png" width="680" height="780" title="'Random reputation'" ></p>

<p>There you go, an image is worth a thousand words, reputation difference among genders is <em>huge</em>, it doesn&#8217;t seem to be related to how long you&#8217;ve been around either.</p>

<h1>Fresh users</h1>

<p>To confirm that, I drew randomly 50k fresh users, who joined the site after <code>2012-10-10</code>, just to see if trends were any different considering only last year data.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="k">Select</span> <span class="o">*</span> <span class="k">From</span> <span class="n">users</span>
</span><span class='line'><span class="k">Where</span> <span class="n">CreationDate</span> <span class="o">&gt;</span> <span class="s1">&#39;2012-10-10&#39;</span>
</span><span class='line'><span class="k">Order</span> <span class="k">By</span> <span class="n">newid</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<p><img class="center" src="http://guilespi.github.com/images/blog/fresh-share.png" width="680" height="780" title="'Fresh share'" ></p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="o">&gt;</span> <span class="k">table</span><span class="p">(</span><span class="n">users</span><span class="err">$</span><span class="n">gender</span><span class="p">)</span><span class="o">/</span><span class="n">nrow</span><span class="p">(</span><span class="n">users</span><span class="p">)</span>
</span><span class='line'>   <span class="n">anonymous</span>    <span class="n">error</span> <span class="k">in</span> <span class="n">name</span>        <span class="k">is</span> <span class="n">female</span>          <span class="k">is</span> <span class="n">male</span>     <span class="k">is</span> <span class="n">mostly</span> <span class="n">female</span>   <span class="k">is</span> <span class="n">mostly</span> <span class="n">male</span>   <span class="k">is</span> <span class="n">unisex</span> <span class="n">name</span>   <span class="n">name</span> <span class="k">not</span> <span class="k">found</span>
</span><span class='line'>     <span class="mi">0</span><span class="p">.</span><span class="mi">35620</span>      <span class="mi">0</span><span class="p">.</span><span class="mi">00002</span>             <span class="mi">0</span><span class="p">.</span><span class="mi">03178</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">20320</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">01014</span>            <span class="mi">0</span><span class="p">.</span><span class="mi">04076</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">02544</span>         <span class="mi">0</span><span class="p">.</span><span class="mi">33246</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here women seem to be a little bit closer, but still a great difference.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/fresh-reputation.png" width="680" height="780" title="'Fresh reputation'" ></p>

<h1>The best of the best</h1>

<p>Then I drew the 50k users with the highest reputation score.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="k">Select</span> <span class="o">*</span> <span class="k">From</span> <span class="n">users</span>
</span><span class='line'><span class="k">Order</span> <span class="k">By</span> <span class="n">Reputation</span> <span class="k">Desc</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we&#8217;re seeing some changes:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/top-share.png" width="680" height="780" title="'Top share'" ></p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="o">&gt;</span> <span class="k">table</span><span class="p">(</span><span class="n">users</span><span class="err">$</span><span class="n">gender</span><span class="p">)</span><span class="o">/</span><span class="n">nrow</span><span class="p">(</span><span class="n">users</span><span class="p">)</span>
</span><span class='line'>   <span class="n">anonymous</span>    <span class="n">error</span> <span class="k">in</span> <span class="n">name</span>        <span class="k">is</span> <span class="n">female</span>          <span class="k">is</span> <span class="n">male</span> <span class="k">is</span> <span class="n">mostly</span> <span class="n">female</span>   <span class="k">is</span> <span class="n">mostly</span> <span class="n">male</span>   <span class="k">is</span> <span class="n">unisex</span> <span class="n">name</span>   <span class="n">name</span> <span class="k">not</span> <span class="k">found</span>
</span><span class='line'>     <span class="mi">0</span><span class="p">.</span><span class="mi">00794</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">00002</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">01064</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">34130</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">00890</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">06656</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">03524</span>          <span class="mi">0</span><span class="p">.</span><span class="mi">52940</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you expect here there&#8217;s almost no <code>anonymous</code> users, in the <em>online community</em> charity has a name attached to it, ain&#8217;t it?</p>

<p>And the reputation trend is still there, something you can readily confirm if you scroll the first pages of the <a href="http://stackoverflow.com/users?tab=Reputation&amp;filter=all">all time user&#8217;s reputation page</a>.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/top-reputation.png" width="680" height="780" title="'Top reputation'" ></p>

<p>But then I charted the reputation <em>distribution</em> against gender and something interesting arises:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/top-distribution-all.png" width="680" height="780" title="'Top distribution all'" ></p>

<p>As you see, there&#8217;s a great deal of outliers there, with 75% of the top 50k users below 4200 points.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='sql'><span class='line'><span class="o">&gt;</span> <span class="n">quantile</span><span class="p">(</span><span class="n">users</span><span class="err">$</span><span class="n">reputation</span><span class="p">)</span>
</span><span class='line'>       <span class="mi">0</span><span class="o">%</span>       <span class="mi">25</span><span class="o">%</span>       <span class="mi">50</span><span class="o">%</span>       <span class="mi">75</span><span class="o">%</span>      <span class="mi">100</span><span class="o">%</span>
</span><span class='line'>  <span class="mi">1024</span><span class="p">.</span><span class="mi">00</span>   <span class="mi">1415</span><span class="p">.</span><span class="mi">00</span>   <span class="mi">2178</span><span class="p">.</span><span class="mi">00</span>   <span class="mi">4214</span><span class="p">.</span><span class="mi">25</span> <span class="mi">618862</span><span class="p">.</span><span class="mi">00</span>
</span></code></pre></td></tr></table></div></figure>


<p>So what happens when we look at the distribution considering the 75% of the users, that are in fact below 4215 points?</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/first-three-quantiles.png" width="680" height="780" title="'First three quantiles'" ></p>

<p>Well <strong>that&#8217;s something!</strong> Now distribution looks pretty much alike.</p>

<p>Seems to me those outliers, that are mostly men, are well beyond everyone else, men or women.</p>

<p>How do <em>you</em> read that data?</p>

<h1>Wrap up</h1>

<p>At 4% females, SO seems to be suffering the same phenomena occurring in the <em>real world</em>, that is, women being underrepresented,
but being SO a strongly moderated virtual community the problem can&#8217;t be related to harassment.
So, there&#8217;s something else going on, is it that SO is designed for male competitiveness,
being the site designed exclusively by males -there were no women on the team AFAIK-?</p>

<p>Isn&#8217;t it the reason you want diversity on your teams to start with? To provide a different perspective on the world, that enables you to reach <em>everyone</em>.</p>

<p>In my opinion, that&#8217;s why women should be part of the <em>creation</em> process, don&#8217;t you think?</p>

<p>None the less, a large group of men are acting as if they already know what women need,
and as patriarchy mandates, providing it, creating programs, making conferences
and burning witches, but not a single soul has asked women what they think, want, or need.</p>

<p>For a change, I&#8217;ve put up <a href="https://docs.google.com/forms/d/1g3FfFKz70HTuFWug609Zkc_5lZzldPkG_ubidjl2oTA/viewform">an anonymous survey online</a> with the purpose of understanding how women who are already in tech,
feel, if you have a female coworker, friend or colleague please share it,
we may even find some interesting insights if we start listening.</p>

<p><em>I&#8217;m <a href="http://www.twitter.com/guilespi">guilespi</a> at Twitter</em></p>

<h1>Survey</h1>

<p>Share the link above or take the survey here:</p>

<iframe src="https://docs.google.com/forms/d/1g3FfFKz70HTuFWug609Zkc_5lZzldPkG_ubidjl2oTA/viewform?embedded=true" width="760" height="500" frameborder="0" marginheight="0" marginwidth="0">Loading&#8230;</iframe>



]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Making wealth by trusting people]]></title>
    <link href="http://guilespi.github.com/blog/2013/07/05/making-wealth-by-trusting-people/"/>
    <updated>2013-07-05T23:20:00-03:00</updated>
    <id>http://guilespi.github.com/blog/2013/07/05/making-wealth-by-trusting-people</id>
    <content type="html"><![CDATA[<p>This week my brother resigned the job he had for quite a few years. There comes a time for all of us when we need new challenges,
and moving is the only way to keep learning and growing.</p>

<p>Today he gave me to read his &#8220;farewell letter&#8221;, his goodbye to co-workers. Far from commonplaces and standard templates,
 it was a really heartfelt goodbye, and what struck a chord with me, it&#8217;s that it was a thank you letter.</p>

<p>Thank you to the ones who gave me the opportunity, thank you to the ones who helped me,
 thank you to the ones who have shared your time with me, and thank you to the ones who made me better.</p>

<p>And I kept thinking, not about being thankful, which is by the way a great thing,
 but about trusting people and making opportunities for others.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/mincer.jpg" width="480" height="580" title="'The people mincer, Pink Floyd'" ></p>

<p>We&#8217;re now living in a mincer, a people eater, with a permanent desire to crash each other,
 fiercely competitive startups, hiring and poaching, making sure every single hire is at the top of her game,
 because failure is not an option, and hey, we <em>need</em> that extra million.</p>

<p>Don&#8217;t we?</p>

<p>What is it that we have at the end of the game?</p>

<p>At least for me, the &#8220;thanks you&#8221; I&#8217;ve had, have made more for me than any money I can make
, knowing that you&#8217;ve helped someone be better, or trusted someone when no one else would do it
, <em>that</em> will stay with you when money is long gone, and it will probably stay when <em>you</em> are gone too.</p>

<p>Hiring only the very best is a safe bet anyone can take, having the talent to see potential takes skill,
 and having the guts to make opportunities and trust people not only takes courage, but it&#8217;s the only human thing to do.</p>

<p>Next time you&#8217;re about to put a cog on the machine, think human, and take the risk.</p>

<p>Rewards are worth it.</p>

<p><em>I&#8217;m <a href="http://www.twitter.com/guilespi">guilespi</a> at Twitter</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Real Life Clojure Application]]></title>
    <link href="http://guilespi.github.com/blog/2013/04/20/real-life-clojure-application/"/>
    <updated>2013-04-20T17:56:00-03:00</updated>
    <id>http://guilespi.github.com/blog/2013/04/20/real-life-clojure-application</id>
    <content type="html"><![CDATA[<p>When a language is going through its maturity process, there&#8217;s always the need for sample code and applications to look at, design patterns,
coding guidelines, best libraries, you name it, you usually get those looking at the source code of others.</p>

<p>That is what really builds community, having a common language, besides the <em>language</em>.</p>

<p>Clojure&#8217;s been going through this phenomenon for the last years, as you see <a href="http://stackoverflow.com/questions/329221/medium-size-clojure-sample-application">in this question</a> from 2008 and <a href="http://stackoverflow.com/questions/3628958/good-clojure-code-examples">this question</a> still being answered in 2012.</p>

<p>This year I made a real life full application in Clojure so I&#8217;ve spent some time deciding on many strategies,
where to put which code, how to test, best libraries to use and what not.</p>

<p>So I decided to put <a href="https://github.com/guilespi/notify-me">the source code</a> online, not only because I think it may help someone,
but hopefully somebody will come up and help me improve what it&#8217;s done in one way or another, it&#8217;s certainly <em>far</em> from perfect.</p>

<p>In case you wonder, it&#8217;s an application for automatic call and sms dispatching.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/notifyme.png" width="480" height="580" title="'Notify Me Blaster Application'" ></p>

<p>Among other things, you&#8217;ll find inside:</p>

<ul>
<li>Web development using <a href="https://github.com/ring-clojure/ring">ring</a>, <a href="https://github.com/weavejester/compojure">compojure</a> and <a href="https://github.com/weavejester/hiccup">hiccup</a>.</li>
<li>Client side <em>almost</em> entirely done in <a href="https://github.com/clojure/clojurescript">clojurescript</a>.</li>
<li>Authentication and authorization using <a href="https://github.com/cemerick/friend">friend</a>.</li>
<li>Database access using both <a href="https://github.com/clojure/java.jdbc">jdbc</a> and <a href="https://github.com/korma/Korma">korma</a>.</li>
<li>Async jobs using <a href="https://github.com/michaelklishin/quartzite">quartz</a> for call and sms dispatching.</li>
<li>Unit tests using <a href="https://github.com/marick/Midje">midje</a>.</li>
<li>Chart drawing using <a href="https://github.com/liebke/incanter">incanter</a>.</li>
<li>Asterisk telephony integration using my own <a href="https://github.com/guilespi/clj-asterisk">clj-asterisk</a> bindings.</li>
<li>Deploy configuration using <a href="https://github.com/pallet">pallet</a> <em>(not yet finished)</em>.</li>
</ul>


<p><em>If you like it say hi! I&#8217;m <a href="http://www.twitter.com/guilespi">guilespi</a></em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[When should you personally decline a job applicant?]]></title>
    <link href="http://guilespi.github.com/blog/2013/02/11/when-should-you-personally-decline-a-job-applicant/"/>
    <updated>2013-02-11T23:55:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2013/02/11/when-should-you-personally-decline-a-job-applicant</id>
    <content type="html"><![CDATA[<p>Everybody hates rejection, and everybody fears rejection(Unless you&#8217;re a salesman, of course).</p>

<p>The idea of someone telling us that we&#8217;re not good, we&#8217;re not a fit, we&#8217;re not loved anymore, it&#8217;s against the human condition <em>need</em> of being liked.</p>

<p>Have you ever been paralyzed before asking out that girl you like? Even knowing you have nothing to lose by doing it?</p>

<p>Interviewing for a job is no different, when someone applies for a position you have opened is dealing with the fear of rejection,
and your responsibility is to acknowledge that fact, and treat people who want to work with you as a human being.</p>

<p>Does it mean you need to personally thank every applicant sending an email with his resume?</p>

<p>Not exactly.</p>

<p><strong> Respect </strong></p>

<p><img class="left" src="http://guilespi.github.com/images/blog/aretha.jpg" width="260" height="460" title="'Aretha, R.E.S.P.E.C.T'" ></p>

<p>You need to show <em>respect</em>, If you will remember only one thing, remember that.</p>

<p>Being in the position of the interviewer doesn&#8217;t make you better, and if the people you&#8217;re hiring is any good,
you should be better showing your brightest side during the process, no one likes to work with assholes.</p>

<p>Having failed myself many times -always with a reasonable excuse, of course- I made some easy rules to follow when interviewing people.</p>

<p><strong> It&#8217;s not about the stage </strong></p>

<p><img class="right" src="http://guilespi.github.com/images/blog/pinkfloydtime.jpg" width="260" height="460" title="'Pink Floyd, TIME'" ></p>

<p>The interviewing process in your company may have many stages, technical interviews and whatnot.</p>

<p>But in my book about respect, there are only two things that matters when interviewing someone:</p>

<ol>
<li>How much time the applicant has spent</li>
<li>Have you ever meet her face to face</li>
</ol>


<p>That&#8217;s all, your respect rules must derive from that.</p>

<p><strong> Dealing with time </strong></p>

<p>What to do when you&#8217;re rejecting someone, according to the time he has spent?</p>

<ul>
<li>He sent an off-the-shelf resume, no personal letter

<ul>
<li>No need to respond</li>
</ul>
</li>
<li>She applied with a personal letter, took the time to understand what your company does, and why she&#8217;s a fit

<ul>
<li>Thank you note, you&#8217;re not exactly what we&#8217;re looking for</li>
</ul>
</li>
<li>He spent 3 hours in a technical interview and failed

<ul>
<li>Note thanking for the time spent, if it explains why the applicant failed, much better. People always want to know the reasons of rejection.</li>
</ul>
</li>
<li>Applicant passed the technical interview, but fails later on the process

<ul>
<li>Same as above</li>
</ul>
</li>
<li>She failed on the later stages, and you have seen her face in an interview

<ul>
<li>You should make a phone call and personally thank for the time spent</li>
</ul>
</li>
</ul>


<p>Easy ain&#8217;t it?</p>

<p>It&#8217;s about other people&#8217;s time, and it&#8217;s about human relationships.</p>

<p>If you don&#8217;t have the balls to reject someone like a human being, you shouldn&#8217;t be interviewing at all.</p>

<p><em>Don&#8217;t reject me, and <a href="http://www.twitter.com/guilespi">follow me on Twitter</a> :)</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Can you make a native app using Phonegap?]]></title>
    <link href="http://guilespi.github.com/blog/2013/02/10/can-you-make-a-native-app-using-phonegap/"/>
    <updated>2013-02-10T21:02:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2013/02/10/can-you-make-a-native-app-using-phonegap</id>
    <content type="html"><![CDATA[<p>I&#8217;ve been looking at Phonegap since it started, long before <a href="http://news.cnet.com/8301-30685_3-20114857-264/adobe-buys-phonegap-typekit-for-better-web-tools/">Adobe bought it</a> in a desperate attempt to destroy it.</p>

<p>Up until now, I never got the chance to make something with it, but always had the doubt how good or bad the applications you could create were.</p>

<p>Last week I had an opportunity to take a look under the hood, and made the source code available <a href="https://github.com/guilespi/phonegap-ios-plugins">on GitHub</a>.</p>

<p>The big question was, can you make native apps using Phonegap?</p>

<p><strong> What you mean by native? </strong></p>

<p>According to <a href="http://stackoverflow.com/questions/4656475/iphone-native-application-vs-web-application">this guy</a> in order to make native IOS applications you need to program in Objective-C.</p>

<p>I say that&#8217;s misleading.</p>

<p>Native applications are applications that run on the phone and provide a <code>native experience</code>, for which I understand at least the following treats:</p>

<ul>
<li>Can access all of the device API, address book, camera, etc.</li>
<li>Access to local storage</li>
<li>Zero latency feedback</li>
<li>Interoperability with other phone applications</li>
<li>UX should respect the device culture and guidelines
,
If you have those, why should you care about the language the app is written in?</li>
</ul>


<p><strong> The wrong reason to use Phonegap </strong></p>

<p>At first sight you may think that the main reason to use Phonegap is program once, run everywhere.</p>

<p>Wrong.</p>

<p>In order to provide a native experience you will need to design the UX of your app for every platform you&#8217;re targeting, so at least the UX/UI code will be different.</p>

<p>Obviously you <em>can</em> use the same UI for all the platforms, but unless the purpose of your app is to alienate your users I wouldn&#8217;t try it.</p>

<p>Software should behave as the user expects it to behave, you would not create new affordances for the sake of creativity, don&#8217;t do it for the sake of saving money,
because it ain&#8217;t cheaper in the long run.</p>

<p>So, no matter what you&#8217;re thinking about doing, save some time to read the UX/UI guidelines for each mobile platform you&#8217;re targeting.</p>

<p>The great <a href="http://www.infoq.com/presentations/Product-Engineering">Mike Lee</a> would tell you that you even need a different team for each of those platforms.</p>

<p><strong> WTF is Phonegap? </strong></p>

<p>You know the tagline <em>&#8220;easily create apps using web technology you love&#8221;</em>, does it mean the only thing you need to know is HTML and Javascript?</p>

<p>Of course not.</p>

<p>Phonegap is an extensible framework for creating web applications, with the following properties:</p>

<ul>
<li>The framework exposes an API to access the device different components

<ul>
<li>Accelerometer</li>
<li>Camera</li>
<li>Compass</li>
<li>Contacts</li>
<li>Etc.</li>
</ul>
</li>
<li>The API is the same for the different supported platforms

<ul>
<li>IOS 4.2+</li>
<li>Android 2.1+</li>
<li>Blackberry OS6+</li>
</ul>
</li>
<li>You must code your program using HTML and Javascript.</li>
</ul>


<p>You can think of it as a native host that lets you write your application in Javascript, abstracting the native layer components behind a uniform API. That&#8217;s all.</p>

<p>So you&#8217;ll end up creating your app inside XCode, dealing with code signing nightmares and taking a lot of walks inside the Apple walled gardens.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/phonegapide.png" width="680" height="780" title="'Phonegap Application Inside XCODE'" ></p>

<p>And you <em>will</em> need to learn the Phonegap API.</p>

<p><strong> It doesn&#8217;t have to be 100% HTML </strong></p>

<p>The first reaction is to think that since Phonegap uses a webview you will have to create your application using only HTML, but it&#8217;s not the case.</p>

<p>Phonegap supports <a href="https://github.com/phonegap/phonegap-plugins">plugins</a>, which is a mechanism for exposing different native features not already exposed in Phonegap API.
So you can create more native plugins and expose them to javascript, where javascript works as the <em>glue</em> that blends
together the native controls but not necessarily is used to create all the UI.</p>

<p>The most common example is the TabBar and NavigationBar in IOS, plugins for those already exist, and lets you design a more native experience than the one
you would get using only HTML.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/phonegapplugins.png" width="280" height="480" title="'Phonegap TabBar and NavigationBar Plugins'" ></p>

<p>Notice the <code>Back</code> button in there, it&#8217;s just a custom button with the back text. If you want to create an arrow like back button you&#8217;ll need to go
down the <a href="http://stackoverflow.com/questions/227078/creating-a-left-arrow-button-like-uinavigationbars-back-style-on-a-uitoolba">same path</a> as if you were doing Objective-C IOS development.</p>

<p><strong> Mobile Frameworks </strong></p>

<p>There are many mobile frameworks available <a href="http://www.markus-falk.com/mobile-frameworks-comparison-chart/">out there to be compared</a>.</p>

<p>Among the most well known are <a href="http://jquerymobile.com/">jQuery Mobile</a> and <a href="http://www.sencha.com/products/touch/">Sencha Touch</a>. JQM development being more <em>web like</em>, something to consider if your team is already
comfortable with HTML, Sencha generates its own DOM based on Javascript objects 100% programatically.</p>

<p>I haven&#8217;t dig deep enough in order to write a complete evaluation, you may found some interesting ones <a href="http://altabel.wordpress.com/2012/12/14/mobile-web-app-frameworks-review-sencha-touch-vs-jquery-mobile/">here</a>, <a href="http://www.collabera.com/blog/default/2012/12/12/1355310199068.html">here</a> and <a href="http://blog.roveb.com/post/17259708005/our-experience-with-jquery-mobile-and-sencha-touch">here</a>.</p>

<p>Almost everybody agrees in one important point:</p>

<p>JQM is sluggish and transitions doesn&#8217;t feel native enough, something I easily verified testing the app in my IPad I, even the <code>slider</code> was sluggish.</p>

<p><strong> Using Phonegap Plugins </strong></p>

<p>Plugins are usually composed of two parts:</p>

<ul>
<li>The native bridge between Objective-C and Javascript</li>
<li>The Javascript exposing the plugin</li>
</ul>


<p>Usually you&#8217;ll need to copy the <code>m</code> and <code>h</code> plugin files to the <code>Plugins</code> directory of your project, you will also need to declare the plugins
being used in the <code>config.xml</code> project file.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'> <span class="nt">&lt;plugins&gt;</span>
</span><span class='line'>   ...
</span><span class='line'>  <span class="nt">&lt;plugin</span> <span class="na">name=</span><span class="s">&quot;TabBar&quot;</span> <span class="na">value=</span><span class="s">&quot;TabBar&quot;</span><span class="nt">/&gt;</span>
</span><span class='line'>  <span class="nt">&lt;plugin</span> <span class="na">name=</span><span class="s">&quot;NavigationBar&quot;</span> <span class="na">value=</span><span class="s">&quot;NavigationBar&quot;</span><span class="nt">/&gt;</span>
</span><span class='line'>  ...
</span><span class='line'> <span class="nt">&lt;/plugins&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>And then include the Javascript files in your <code>index.html</code>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'> <span class="o">&lt;</span><span class="nx">script</span> <span class="nx">type</span><span class="o">=</span><span class="s2">&quot;text/javascript&quot;</span> <span class="nx">src</span><span class="o">=</span><span class="s2">&quot;js/TabBar.js&quot;</span><span class="o">&gt;&lt;</span><span class="err">/script&gt;</span>
</span><span class='line'> <span class="o">&lt;</span><span class="nx">script</span> <span class="nx">type</span><span class="o">=</span><span class="s2">&quot;text/javascript&quot;</span> <span class="nx">src</span><span class="o">=</span><span class="s2">&quot;js/NavigationBar.js&quot;</span><span class="o">&gt;&lt;</span><span class="err">/script&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Using the native plugins from your applications is straightforward, you initialize, create, setup and show the buttons you want.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">navigationBar</span><span class="p">.</span><span class="nx">init</span><span class="p">();</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">tabBar</span><span class="p">.</span><span class="nx">init</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">navigationBar</span><span class="p">.</span><span class="nx">create</span><span class="p">();</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">tabBar</span><span class="p">.</span><span class="nx">create</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">navigationBar</span><span class="p">.</span><span class="nx">setTitle</span><span class="p">(</span><span class="s2">&quot;Navigation Bar&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">navigationBar</span><span class="p">.</span><span class="nx">showLeftButton</span><span class="p">()</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">navigationBar</span><span class="p">.</span><span class="nx">showRightButton</span><span class="p">()</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">navigationBar</span><span class="p">.</span><span class="nx">setupLeftButton</span><span class="p">(</span><span class="s2">&quot;Back&quot;</span><span class="p">,</span>
</span><span class='line'>                                        <span class="s2">&quot;&quot;</span><span class="p">,</span>
</span><span class='line'>                                        <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>                                          <span class="nx">$</span><span class="p">(</span><span class="nb">window</span><span class="p">).</span><span class="nx">unbind</span><span class="p">(</span><span class="s2">&quot;scrollstop&quot;</span><span class="p">);</span>
</span><span class='line'>                                          <span class="nx">history</span><span class="p">.</span><span class="nx">back</span><span class="p">();</span>
</span><span class='line'>                                          <span class="k">return</span> <span class="kc">false</span><span class="p">;</span>
</span><span class='line'>                                        <span class="p">});</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">navigationBar</span><span class="p">.</span><span class="nx">setupRightButton</span><span class="p">(</span>
</span><span class='line'>                                         <span class="s2">&quot;Alert&quot;</span><span class="p">,</span>
</span><span class='line'>                                         <span class="s2">&quot;barButton:Bookmarks&quot;</span><span class="p">,</span>
</span><span class='line'>                                         <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>                                          <span class="nx">alert</span><span class="p">(</span><span class="s2">&quot;right nav button tapped&quot;</span><span class="p">)</span>
</span><span class='line'>                                         <span class="p">});</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">navigationBar</span><span class="p">.</span><span class="nx">show</span><span class="p">()</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">tabBar</span><span class="p">.</span><span class="nx">createItem</span><span class="p">(</span><span class="s2">&quot;contacts&quot;</span><span class="p">,</span> <span class="s2">&quot;&quot;</span><span class="p">,</span> <span class="s2">&quot;tabButton:Contacts&quot;</span><span class="p">,</span> <span class="p">{</span><span class="nx">onSelect</span><span class="o">:</span> <span class="nx">app</span><span class="p">.</span><span class="nx">loadNews</span><span class="p">});</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">tabBar</span><span class="p">.</span><span class="nx">createItem</span><span class="p">(</span><span class="s2">&quot;recents&quot;</span><span class="p">,</span> <span class="s2">&quot;&quot;</span><span class="p">,</span> <span class="s2">&quot;tabButton:Recents&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">tabBar</span><span class="p">.</span><span class="nx">createItem</span><span class="p">(</span><span class="s2">&quot;another&quot;</span><span class="p">,</span> <span class="s2">&quot;Branches&quot;</span><span class="p">,</span> <span class="s2">&quot;www/images/map-marker.png&quot;</span><span class="p">,</span>
</span><span class='line'>                                        <span class="p">{</span>
</span><span class='line'>                                          <span class="nx">onSelect</span><span class="o">:</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>                                                            <span class="nx">app</span><span class="p">.</span><span class="nx">loadMap</span><span class="p">();</span>
</span><span class='line'>                                                        <span class="p">}});</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">tabBar</span><span class="p">.</span><span class="nx">show</span><span class="p">()</span>
</span><span class='line'>  <span class="nx">plugins</span><span class="p">.</span><span class="nx">tabBar</span><span class="p">.</span><span class="nx">showItems</span><span class="p">(</span><span class="s2">&quot;contacts&quot;</span><span class="p">,</span> <span class="s2">&quot;recents&quot;</span><span class="p">,</span> <span class="s2">&quot;another&quot;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Using this strategy lets you extend your app for a more native experience exposing to javascript even custom controls you may design.
This way you can have some members of your team focused on the native code of the app and exposing the building blocks to the web developers <em>assembling</em> the pieces.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/phonegapplugincomparison.png" width="280" height="480" title="'Phonegap TabBar comparison against HTML'" ></p>

<p>As you see in the last image, the TabBar is shown in the native version and the HTML version side-by-side. The HTML version was created using jQuery Mobile.</p>

<p><strong> Debugging is hell </strong></p>

<p>Well maybe it&#8217;s not hell, but it&#8217;s not a pleasant experience either.</p>

<p>If you include the following line in your html using your own id:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="o">&lt;</span><span class="nx">script</span> <span class="nx">src</span><span class="o">=</span><span class="s2">&quot;http://debug.phonegap.com/target/target-script-min.js#guilespi&quot;</span><span class="o">&gt;&lt;</span><span class="err">/script&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>You&#8217;ll have easy access to debug your app using <a href="http://people.apache.org/~pmuellr/weinre/docs/latest/">weinre</a> without the need to set it up, at least it&#8217;s good for HTML inspection.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/weinredebug.png" width="680" height="780" title="'Weinre Debugging inside Chrome'" ></p>

<p>If you want to debug javascript, you&#8217;ll certainly end up using <code>alert</code> and <code>console.log</code>, even <a href="http://phonegap.com/2011/05/18/debugging-phonegap-javascript/">the guys at Phonegap</a> are recommending the poor&#8217;s man debugger.</p>

<p>Be ready to waste some of the time you gained by choosing Javascript doing print based debugging.</p>

<p><strong>Update</strong>
<em>Raymond Camden pointed out in the comments that <a href="http://www.raymondcamden.com/index.cfm/2013/1/21/Did-you-know--Safari-Remote-Debugging-and-PhoneGap">a better approach to debugging exists</a>, specially with Safari and IOS6</em></p>

<p><strong> Conclusion </strong></p>

<p>Tools are picked for the team, so that&#8217;s what you should think about when choosing or not to pursue the Phonegap path. If you already have members on your team
who are great at web development, Phonegap may be an option, certainly it&#8217;s fast for prototyping and seems to be a great asset for product discovery and validation.</p>

<p>If charging for your app is among your goals, I wouldn&#8217;t pick Phonegap or any other framework that uses the webview renderer as the main application.
Also, for most tasks the Javascript VM would be alright, but if you have inner loops cpu intensive, such as in game development, using Phonegap it&#8217;s not really an option.</p>

<p>Reviewing the main points considered to categorize a mobile application as native, web frameworks will provide you a sub-par experience regarding feedback,
latency and usability. Using the Phonegap plugins to avoid it will only go so far before the cost being so high you&#8217;ll better be programming in Java or Objective-C anyway.</p>

<p>If you still have doubts, <a href="https://github.com/guilespi/phonegap-ios-plugins">fork the code</a> and give yourself a try.</p>

<p><em>And don&#8217;t forget to follow me on <a href="http://www.twitter.com/guilespi">twitter</a></em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Build yourself a dialer with Clojure and Asterisk]]></title>
    <link href="http://guilespi.github.com/blog/2013/01/29/build-yourself-a-dialer-with-clojure-and-asterisk/"/>
    <updated>2013-01-29T17:05:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2013/01/29/build-yourself-a-dialer-with-clojure-and-asterisk</id>
    <content type="html"><![CDATA[<p>There are some really <a href="http://www.twilio.com">nice</a> <a href="http://plivo.com/">alternatives</a> out there if you want your application to be able to make a call or send a SMS.</p>

<p>But the truth is sometimes you don&#8217;t want to rely on <code>the cloud</code> for your latency-sensitive communications, you already have communications infrastructure
you want to reuse, or you have such a volume of calls to make that it&#8217;s cheaper for you to roll your own solution.</p>

<p>So I will show you a DIY guide to roll your own dialer using Clojure and <a href="http://www.asterisk.org/">Asterisk</a>, the self proclaimed PBX &amp; Telephony Toolkit.</p>

<p><strong> What is a Dialer </strong></p>

<p>If you ever received a spam call from someone trying to sell you something, it was probably made by an automated dialer.
The purpose is to reach the most possible people in the least time, optimizing resources.</p>

<p>Sometimes it&#8217;s someone selling Viagra, but hopefully it&#8217;s used for higher purposes such as massive notification of upcoming emergencies.</p>

<p><strong> Integrating with Asterisk </strong></p>

<p>Asterisk has a lot if integration alternatives, custom dial-plans, AGI scripting, outgoing call spooling, or you can write your own low-level C module,
each strategy serves its purpose.</p>

<p>For this scenario I&#8217;ve decided to show you an integration with Asterisk using the <a href="http://www.voip-info.org/wiki/view/Asterisk+manager+API">Asterisk Manager API</a>,
which allows for remote command execution and event-handling.</p>

<p>I&#8217;ve written a binding for Clojure called <a href="https://github.com/guilespi/clj-asterisk">clj-asterisk</a> to sit on top of the low-level text based protocol.</p>

<p><strong> Making a Call </strong></p>

<p>The <code>clj-asterisk</code> binding map against the Asterisk API is straightforward, so checking against the <a href="http://www.voip-info.org/wiki/view/Asterisk+Manager+API+Action+Originate">Originate Action</a> which is the
one we need to create an outgoing call.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>Action: Originate
</span><span class='line'>Channel: SIP/101test
</span><span class='line'>Context: default
</span><span class='line'>Exten: 8135551212
</span><span class='line'>Priority: 1
</span><span class='line'>Callerid: 3125551212
</span><span class='line'>Timeout: 30000
</span><span class='line'>Variable: var1=23|var2=24|var3=25
</span><span class='line'>ActionID: ABC45678901234567890</span></code></pre></td></tr></table></div></figure>


<p>The corresponding <code>clj-asterisk</code> invocation is:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">ns </span><span class="nv">call.test</span>
</span><span class='line'>  <span class="p">(</span><span class="ss">:require</span> <span class="p">[</span><span class="nv">clj-asterisk.manager</span> <span class="ss">:as</span> <span class="nv">manager</span><span class="p">]</span>
</span><span class='line'>               <span class="p">[</span><span class="nv">clj-asterisk.events</span> <span class="ss">:as</span> <span class="nv">events</span><span class="p">]))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="nf">manager/action</span> <span class="ss">:Originate</span> <span class="p">{</span><span class="ss">:Channel</span> <span class="s">&quot;SIP/101test&quot;</span>
</span><span class='line'>                            <span class="ss">:Context</span> <span class="s">&quot;default&quot;</span>
</span><span class='line'>                            <span class="ss">:Exten</span> <span class="mi">8135551212</span>
</span><span class='line'>                            <span class="ss">:Priority</span> <span class="mi">1</span>
</span><span class='line'>                            <span class="ss">:Timeout</span> <span class="mi">30000</span>
</span><span class='line'>                            <span class="ss">:CallerID</span> <span class="mi">3125551212</span>
</span><span class='line'>                            <span class="ss">:Variables</span> <span class="p">[</span><span class="nv">var1=23</span>
</span><span class='line'>                                        <span class="nv">var2=24</span>
</span><span class='line'>                                        <span class="nv">var3=25</span><span class="p">]})</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>ActionID</code> attribute is not specified since it&#8217;s internally handled by the <code>clj-asterisk</code> library in order to track async responses from Asterisk.</p>

<p><strong> Receiving events </strong></p>

<p>For most telephony related actions blocking is not desirable, since most of the time the PBX is handling a conversation and waiting for
something to happen, using a blocking scheme is far from the best. You need a strategy to wait for events that tell you when something
you may be interested in, happens.</p>

<p>In this case we will be interested in the <code>Hangup</code> event in order to know when the call has ended, so the dialing port is free,
so we can issue a new call. If you&#8217;re interested in the complete list of events, <a href="http://www.voip-info.org/wiki/view/asterisk+manager+events">it&#8217;s available on the Asterisk Wiki</a></p>

<p>To receive an event using <code>clj-asterisk</code> you only need to declare the method with the event name you need to handle:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">ns </span><span class="nv">call.test</span>
</span><span class='line'>  <span class="p">(</span><span class="ss">:require</span> <span class="p">[</span><span class="nv">clj-asterisk.manager</span> <span class="ss">:as</span> <span class="nv">manager</span><span class="p">]</span>
</span><span class='line'>            <span class="p">[</span><span class="nv">clj-asterisk.events</span> <span class="ss">:as</span> <span class="nv">events</span><span class="p">]))</span>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defmethod </span><span class="nv">events/handle-event</span> <span class="s">&quot;Hangup&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">event</span> <span class="nv">context</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">println </span><span class="nv">event</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>The method passes as parameter the received event and the connection context where the event happened.</p>

<p><strong> The Main Loop </strong></p>

<p>In order to have a proper dialer you will need a main-loop, which life-fulfillment-purpose is:</p>

<ul>
<li>Decide on which contacts are to be called</li>
<li>How many ports are free so how many I can dial now</li>
<li>Handle retrying and error rules</li>
<li>Dispatching the calls</li>
</ul>


<p>I&#8217;m assuming you have some data storage to retrieve the contacts to be dialed and will share those details in a later post,
I will focus now only in the dialing strategy.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">process</span>
</span><span class='line'>  <span class="s">&quot;Loops until all contacts for a notification are reached or finally</span>
</span><span class='line'><span class="s">   cancelled&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">notification</span> <span class="nv">context</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">total-ports</span> <span class="p">(</span><span class="nf">get-available-ports</span> <span class="nv">notification</span><span class="p">)</span>
</span><span class='line'>        <span class="nv">contact-list</span> <span class="p">(</span><span class="nf">model/expand-rcpt</span> <span class="nv">notification</span><span class="p">)]</span>
</span><span class='line'>    <span class="p">(</span><span class="k">loop </span><span class="p">[</span><span class="nv">remaining</span> <span class="nv">contact-list</span> <span class="nv">pending-contacts</span> <span class="p">[]]</span>
</span><span class='line'>      <span class="p">(</span><span class="nb">or </span><span class="p">(</span><span class="nb">seq </span><span class="nv">remaining</span><span class="p">)</span>
</span><span class='line'>           <span class="p">(</span><span class="nb">seq </span><span class="nv">pending-contacts</span><span class="p">))</span>
</span><span class='line'>             <span class="p">(</span><span class="nf">do</span>
</span><span class='line'>               <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">pending</span> <span class="p">(</span><span class="nb">filter </span><span class="p">(</span><span class="nb">comp not </span><span class="nv">realized?</span><span class="p">)</span> <span class="nv">pending-contacts</span><span class="p">)</span>
</span><span class='line'>                     <span class="nv">finished</span> <span class="p">(</span><span class="nb">filter </span><span class="nv">realized?</span> <span class="nv">pending-contacts</span><span class="p">)</span>
</span><span class='line'>                     <span class="nv">failed</span> <span class="p">(</span><span class="nf">filter</span>
</span><span class='line'>                             <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">r</span><span class="p">]</span> <span class="p">(</span><span class="nb">not </span><span class="p">(</span><span class="nb">contains? </span><span class="o">#</span><span class="p">{</span><span class="s">&quot;CONNECTED&quot;</span> <span class="s">&quot;CANCELLED&quot;</span><span class="p">}</span> <span class="p">(</span><span class="ss">:status</span> <span class="err">@</span><span class="nv">r</span><span class="p">))))</span>
</span><span class='line'>                             <span class="nv">finished</span><span class="p">)</span>
</span><span class='line'>                     <span class="nv">free-ports</span> <span class="p">(</span><span class="nb">- </span><span class="nv">total-ports</span> <span class="p">(</span><span class="nb">count </span><span class="nv">pending</span><span class="p">))</span>
</span><span class='line'>                     <span class="nv">contacts</span> <span class="p">(</span><span class="nb">take </span><span class="nv">free-ports</span> <span class="nv">remaining</span><span class="p">)</span>
</span><span class='line'>                     <span class="nv">dialing</span> <span class="p">(</span><span class="nf">dispatch-calls</span> <span class="nv">context</span> <span class="nv">notification</span> <span class="nv">contacts</span><span class="p">)]</span>
</span><span class='line'>                 <span class="p">(</span><span class="nb">println </span><span class="p">(</span><span class="nf">format</span> <span class="s">&quot;Pending %s Finished %s Failed %s Free Ports %s Dispatched %s&quot;</span>
</span><span class='line'>                                  <span class="p">(</span><span class="nb">count </span><span class="nv">pending</span><span class="p">)</span> <span class="p">(</span><span class="nb">count </span><span class="nv">finished</span><span class="p">)</span> <span class="p">(</span><span class="nb">count </span><span class="nv">failed</span><span class="p">)</span> <span class="nv">free-ports</span>
</span><span class='line'>                                  <span class="p">(</span><span class="nb">count </span><span class="nv">dialing</span><span class="p">)))</span>
</span><span class='line'>                 <span class="p">(</span><span class="nf">Thread/sleep</span> <span class="mi">100</span><span class="p">)</span>
</span><span class='line'>                 <span class="p">(</span><span class="nf">recur</span> <span class="p">(</span><span class="nb">concat </span><span class="p">(</span><span class="nb">drop </span><span class="nv">free-ports</span> <span class="nv">remaining</span><span class="p">)</span> <span class="p">(</span><span class="nb">map </span><span class="ss">:contact</span> <span class="nv">failed</span><span class="p">))</span>
</span><span class='line'>                        <span class="p">(</span><span class="nb">concat </span><span class="nv">pending</span> <span class="nv">dialing</span><span class="p">)))))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Lets go piece by piece&#8230;</p>

<p>You wanna know how many ports are available to dial, for instance you may have only 10 outgoing lines to be used.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">total-ports</span> <span class="p">(</span><span class="nf">get-available-ports</span> <span class="nv">notification</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>You wanna know the recipients to be reached.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">contact-list</span> <span class="p">(</span><span class="nf">model/expand-rcpt</span> <span class="nv">notification</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then you wanna know the status of the contacts you&#8217;re already dialing and waiting for an answer or for the call to finish.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="k">let </span><span class="p">[</span><span class="nv">pending</span> <span class="p">(</span><span class="nb">filter </span><span class="p">(</span><span class="nb">comp not </span><span class="nv">realized?</span><span class="p">)</span> <span class="nv">pending-contacts</span><span class="p">)</span>
</span><span class='line'>     <span class="nv">finished</span> <span class="p">(</span><span class="nb">filter </span><span class="nv">realized?</span> <span class="nv">pending-contacts</span><span class="p">)</span>
</span><span class='line'>     <span class="nv">failed</span> <span class="p">(</span><span class="nf">filter</span>
</span><span class='line'>                  <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">r</span><span class="p">]</span> <span class="p">(</span><span class="nb">not </span><span class="p">(</span><span class="nb">contains? </span><span class="o">#</span><span class="p">{</span><span class="s">&quot;CONNECTED&quot;</span> <span class="s">&quot;CANCELLED&quot;</span><span class="p">}</span> <span class="p">(</span><span class="ss">:status</span> <span class="err">@</span><span class="nv">r</span><span class="p">))))</span>
</span><span class='line'>                  <span class="nv">finished</span><span class="p">)</span>
</span><span class='line'>     <span class="nv">free-ports</span> <span class="p">(</span><span class="nb">- </span><span class="nv">total-ports</span> <span class="p">(</span><span class="nb">count </span><span class="nv">pending</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here pending-contacts is a list of <a href="http://clojuredocs.org/clojure_core/clojure.core/future">futures</a>, the contacts being currently dialed. Since we don&#8217;t wanna block waiting for the answer the <code>realized?</code>
function is used in order to count how many of them are finished and filter them. If the finish status is not <code>CONNECTED</code> or <code>CANCELLED</code>
we assume the contact has failed and we need to issue a retry for those, typically the <code>BUSY</code> and <code>NO ANSWER</code> statuses.</p>

<p>Then, given the total available ports minus the already being dialed contacts, a new batch of contacts is dialed</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="nv">contacts</span> <span class="p">(</span><span class="nb">take </span><span class="nv">free-ports</span> <span class="nv">remaining</span><span class="p">)</span>
</span><span class='line'><span class="nv">dialing</span> <span class="p">(</span><span class="nf">dispatch-calls</span> <span class="nv">context</span> <span class="nv">notification</span> <span class="nv">contacts</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <code>dispatch-calls</code> function is pretty straightforward, it just async calls each contact of the list.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">dispatch-calls</span>
</span><span class='line'>  <span class="s">&quot;Returns the list of futures of each call thread (one p/contact)&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">context</span> <span class="nv">notification</span> <span class="nv">contacts</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">map </span><span class="o">#</span><span class="p">(</span><span class="nf">future</span> <span class="p">(</span><span class="nf">call</span> <span class="nv">context</span> <span class="nv">notification</span> <span class="nv">%</span><span class="p">))</span> <span class="nv">contacts</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Finally the call function issues the request against the Asterisk PBX and saves the result for further tracking or analytics.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">call</span>
</span><span class='line'>  <span class="s">&quot;Call a contact and wait till the call ends.</span>
</span><span class='line'><span class="s">   Function returns the hangup event or nil if timedout&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">context</span> <span class="nv">notification</span> <span class="nv">contact</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">manager/with-connection</span> <span class="nv">context</span>
</span><span class='line'>    <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">trunk</span> <span class="p">(</span><span class="nf">model/get-trunk</span> <span class="nv">notification</span><span class="p">)</span>
</span><span class='line'>          <span class="nv">call-id</span> <span class="p">(</span><span class="nf">.toString</span> <span class="p">(</span><span class="nf">java.util.UUID/randomUUID</span><span class="p">))</span>
</span><span class='line'>          <span class="nv">prom</span> <span class="p">(</span><span class="nf">manager/set-user-data!</span> <span class="nv">call-id</span> <span class="p">(</span><span class="nf">promise</span><span class="p">))</span>
</span><span class='line'>          <span class="nv">response</span> <span class="p">(</span><span class="nf">manager/action</span> <span class="ss">:Originate</span>
</span><span class='line'>                                   <span class="p">{</span><span class="ss">:Channel</span> <span class="p">(</span><span class="nf">format</span> <span class="s">&quot;%s/%s/%s&quot;</span>
</span><span class='line'>                                                     <span class="p">(</span><span class="ss">:technology</span> <span class="nv">trunk</span><span class="p">)</span>
</span><span class='line'>                                                     <span class="p">(</span><span class="ss">:number</span> <span class="nv">trunk</span><span class="p">)</span>
</span><span class='line'>                                                     <span class="p">(</span><span class="ss">:address</span> <span class="nv">contact</span><span class="p">))</span>
</span><span class='line'>                                    <span class="ss">:Context</span> <span class="p">(</span><span class="ss">:context</span> <span class="nv">trunk</span><span class="p">)</span>
</span><span class='line'>                                    <span class="ss">:Exten</span> <span class="p">(</span><span class="ss">:extension</span> <span class="nv">trunk</span><span class="p">)</span>
</span><span class='line'>                                    <span class="ss">:Priority</span> <span class="p">(</span><span class="ss">:priority</span> <span class="nv">trunk</span><span class="p">)</span>
</span><span class='line'>                                    <span class="ss">:Timeout</span> <span class="mi">60000</span>
</span><span class='line'>                                    <span class="ss">:CallerID</span> <span class="p">(</span><span class="ss">:callerid</span> <span class="nv">trunk</span><span class="p">)</span>
</span><span class='line'>                                    <span class="ss">:Variables</span> <span class="p">[(</span><span class="nf">format</span> <span class="s">&quot;MESSAGE=%s&quot;</span> <span class="p">(</span><span class="ss">:message</span> <span class="nv">notification</span><span class="p">))</span>
</span><span class='line'>                                                <span class="p">(</span><span class="nf">format</span> <span class="s">&quot;CALLID=%s&quot;</span> <span class="nv">call-id</span><span class="p">)]})]</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">model/save-result</span> <span class="nv">notification</span>
</span><span class='line'>                         <span class="nv">contact</span>
</span><span class='line'>                         <span class="p">(</span><span class="nb">deref </span><span class="nv">prom</span> <span class="mi">200000</span> <span class="p">{</span><span class="ss">:error</span> <span class="err">:</span><span class="ss">:timeout</span><span class="p">})))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>The tricky part here is that it&#8217;s impossible to know before-hand the call-id Asterisk is going to use for our newly created call,
so we need a way to <em>mark</em> our call and relate to it later when an event is received, we do that using the call variable <code>CALLID</code>
which is a <code>guid</code> created for each new call.</p>

<p>Our call creating function will wait on a <code>promise</code> until the call ends, something we will <code>deliver</code> in the Hangup event as shown here:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="c1">;; Signal the end of the call to the waiting promise in order to</span>
</span><span class='line'><span class="c1">;; release the channel</span>
</span><span class='line'><span class="p">(</span><span class="kd">defmethod </span><span class="nv">events/handle-event</span> <span class="s">&quot;Hangup&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">event</span> <span class="nv">context</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">println </span><span class="nv">event</span><span class="p">)</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">manager/with-connection</span> <span class="nv">context</span>
</span><span class='line'>    <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">unique-id</span> <span class="p">(</span><span class="ss">:Uniqueid</span> <span class="nv">event</span><span class="p">)</span>
</span><span class='line'>          <span class="nv">call-id</span> <span class="p">(</span><span class="nf">manager/get-user-data</span> <span class="nv">unique-id</span><span class="p">)</span>
</span><span class='line'>          <span class="nv">prom</span> <span class="p">(</span><span class="nf">manager/get-user-data</span> <span class="nv">call-id</span><span class="p">)]</span>
</span><span class='line'>      <span class="p">(</span><span class="nb">println </span><span class="p">(</span><span class="nf">format</span> <span class="s">&quot;Hanging up call %s with unique id %s&quot;</span> <span class="nv">call-id</span> <span class="nv">unique-id</span><span class="p">))</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">deliver</span> <span class="nv">prom</span> <span class="nv">event</span><span class="p">)</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">manager/remove-user-data!</span> <span class="nv">call-id</span><span class="p">)</span> <span class="c1">;;FIX: this should be done</span>
</span><span class='line'>      <span class="c1">;;on the waiting side or promise may get lost</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">manager/remove-user-data!</span> <span class="nv">unique-id</span><span class="p">))))</span>
</span><span class='line'>
</span><span class='line'><span class="c1">;; When CALLID is set, relate it to the call unique-id</span>
</span><span class='line'><span class="c1">;; to be used later in hangup detection</span>
</span><span class='line'><span class="c1">;;</span>
</span><span class='line'><span class="c1">;; The context has the following info inside:</span>
</span><span class='line'><span class="c1">;;   callid =&gt; promise</span>
</span><span class='line'><span class="c1">;;   Uniqueid =&gt; callid</span>
</span><span class='line'><span class="c1">;;</span>
</span><span class='line'><span class="c1">;; so it&#39;s possible to deliver a response to someone waiting</span>
</span><span class='line'><span class="c1">;; on the callid promise</span>
</span><span class='line'><span class="p">(</span><span class="kd">defmethod </span><span class="nv">events/handle-event</span> <span class="s">&quot;VarSet&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">event</span> <span class="nv">context</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">when </span><span class="p">(</span><span class="nb">= </span><span class="p">(</span><span class="ss">:Variable</span> <span class="nv">event</span><span class="p">)</span> <span class="s">&quot;CALLID&quot;</span><span class="p">)</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">manager/with-connection</span> <span class="nv">context</span>
</span><span class='line'>      <span class="p">(</span><span class="nb">println </span><span class="p">(</span><span class="nf">format</span> <span class="s">&quot;Setting data %s match %s&quot;</span> <span class="p">(</span><span class="ss">:Uniqueid</span> <span class="nv">event</span><span class="p">)</span> <span class="p">(</span><span class="ss">:Value</span> <span class="nv">event</span><span class="p">)))</span>
</span><span class='line'>      <span class="p">(</span><span class="nf">manager/set-user-data!</span> <span class="p">(</span><span class="ss">:Uniqueid</span> <span class="nv">event</span><span class="p">)</span> <span class="p">(</span><span class="ss">:Value</span> <span class="nv">event</span><span class="p">)))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>It seems more convoluted than what it actually is, when the <code>CALLID</code> variable is set we receive an event that allows the mapping between call-id and
Asterisk UniqueId to be done. Then when the <code>Hangup</code> occurs we can find the promise to be delivered and let the <code>call</code> function happily end.</p>

<p>Keep tuned for part II, when I will publish the data model and the complete running Dialer.</p>

<p><a href="https://gist.github.com/4666926">Here</a> is the gist with the code of the current post.</p>

<p><em>While you wait, you can follow me on <a href="http://www.twitter.com/guilespi">Twitter</a>!</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Coxcomb Charts with Raphael.js]]></title>
    <link href="http://guilespi.github.com/blog/2012/11/25/coxcomb-charts-with-raphael-dot-js/"/>
    <updated>2012-11-25T18:21:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2012/11/25/coxcomb-charts-with-raphael-dot-js</id>
    <content type="html"><![CDATA[<p>The coxcomb chart was first used by Florence Nightingale to persuade Queen Victoria about improving
conditions in the military hospitals during the Crimean War.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/coxcomb-nightingale.jpg" width="480" height="680" title="'Nightingale coxcomb'" ></p>

<p>As you see it serves the same purpose as a traditional barchart, but displays the information in
a coxcomb flower pattern.</p>

<p>I couldn&#8217;t find something already done that suited my needs, so I made one my self.</p>

<p>It&#8217;s slightly modified from the original design, since it doesn&#8217;t display the bars stacked but side by side, I think it&#8217;s better
to display superposed labels that way.</p>

<p><strong>Death and Mortality</strong></p>

<script type="text/javascript" src="https://raw.github.com/guilespi/resume-of-sorts/master/scripts/jquery-1.7.2.min.js"></script>


<script type="text/javascript" src="https://raw.github.com/guilespi/resume-of-sorts/master/scripts/raphael-min.js"></script>


<script type="text/javascript" src="https://raw.github.com/guilespi/coxcomb-chart/master/src/coxcomb.js"></script>


<div id="deaths"></div>


<script type="text/javascript">
  var deaths = {
     data : { 
         jan : {
            disease : 50,
            wounds : 20
         },
         feb : {
            disease : 60,
            wounds : 35
         },
         mar : {
            disease : 80,
            wounds : 50
         },
         apr : {
            disease : 70,
            wounds : 20
         },
         may : {
            disease : 30,
            wounds : 60
         },
         jun : {
            disease : 75,
            wounds : 22
         },
         jul : {
            disease : 66,
            wounds : 65
         },
         aug : {
            disease : 30,
            wounds : 14
         },
         sep : {
            disease : 50,
            wounds : 14
         },
         oct : {
            disease : 24,
            wounds : 32
         },
         nov : {
            disease : 30,
            wounds : 44
         },
         dec : {
            disease : 50,
            wounds : 5
         },
     },
     colors : {
        category : "#2B2B2B",
        opacity : 0.8,
        fontColor: "#fff",
        bySeries : {
            disease  : {
              color : "#E9E581",
              opacity : 0.8,
              fontColor: "#000",
            },
            wounds : {
              color: "#DE1B1B",
              opacity: 0.7,
              fontColor: "#fff"
            }
        }
      } 
    }; 
    var paperWidth = 600;
    var paperHeight = paperWidth * 0.8;
    var lastSelection;
    var properties = {
        categorySize : 0.20,
        categoryFontSize: paperWidth > 500 ? 10 : 6,
        seriesFontSize: paperWidth > 500 ? 10 : 6,
        onClick: function(polygon, text) {
            if (lastSelection) {
                lastSelection.remove();
            }
            lastSelection = polygon.glow();
        },
        stroke: "#fff"
    };
    Raphael("deaths", paperWidth, paperHeight)
            .coxCombChart(paperWidth / 2,paperHeight / 2, paperHeight / 2, deaths, properties);
</script>


<p>Feeding data into the chart is straightforward</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='javascript'><span class='line'><span class="nx">deaths</span> <span class="o">=</span> <span class="p">{</span>
</span><span class='line'>   <span class="nx">data</span> <span class="o">:</span> <span class="p">{</span>
</span><span class='line'>       <span class="nx">jan</span> <span class="o">:</span> <span class="p">{</span>
</span><span class='line'>          <span class="nx">disease</span> <span class="o">:</span> <span class="mi">180</span><span class="p">,</span>
</span><span class='line'>          <span class="nx">wounds</span> <span class="o">:</span> <span class="mi">20</span>
</span><span class='line'>       <span class="p">},</span>
</span><span class='line'>       <span class="nx">feb</span> <span class="o">:</span> <span class="p">{</span>
</span><span class='line'>          <span class="nx">disease</span> <span class="o">:</span> <span class="mi">140</span><span class="p">,</span>
</span><span class='line'>          <span class="nx">wounds</span> <span class="o">:</span> <span class="mi">35</span>
</span><span class='line'>       <span class="p">},</span>
</span><span class='line'>       <span class="nx">mar</span> <span class="o">:</span> <span class="p">{</span>
</span><span class='line'>          <span class="nx">disease</span> <span class="o">:</span> <span class="mi">80</span><span class="p">,</span>
</span><span class='line'>          <span class="nx">wounds</span> <span class="o">:</span> <span class="mi">50</span>
</span><span class='line'>       <span class="p">},</span>
</span><span class='line'>       <span class="nx">may</span> <span class="o">:</span> <span class="p">{</span>
</span><span class='line'>          <span class="nx">disease</span> <span class="o">:</span> <span class="mi">40</span><span class="p">,</span>
</span><span class='line'>          <span class="nx">wounds</span> <span class="o">:</span> <span class="mi">40</span>
</span><span class='line'>       <span class="p">},</span>
</span><span class='line'>       <span class="p">...</span>
</span><span class='line'>    <span class="nx">colors</span> <span class="o">:</span> <span class="p">{</span>
</span><span class='line'>        <span class="p">...</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="nx">Raphael</span><span class="p">(</span><span class="s2">&quot;deaths&quot;</span><span class="p">,</span> <span class="nx">width</span><span class="p">,</span> <span class="nx">height</span><span class="p">).</span>
</span><span class='line'>    <span class="nx">coxCombChart</span><span class="p">(</span><span class="nx">width</span> <span class="o">/</span> <span class="mi">2</span><span class="p">,</span> <span class="nx">height</span> <span class="o">/</span> <span class="mi">2</span><span class="p">,</span> <span class="nx">height</span> <span class="o">/</span> <span class="mi">2</span><span class="p">,</span> <span class="nx">deaths</span><span class="p">,</span> <span class="nx">properties</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>I&#8217;ve used it to show some skills in a <a href="http://resume.guillermowinkler.com">resume-of-sorts</a> if you wanna see a color strategy by category and not by series.</p>

<p><strong>Lie Factor Warning</strong></p>

<p>The received values are normalized and the maximum value takes the complete radius of the coxcomb. Be warned,
each value is normalized and only the radius is affected, not the complete area of the disc sector.
This may introduce visualization problems as the ones pointed by <a href="http://www.amazon.com/Visual-Display-Quantitative-Information/dp/0961392142">Edward Tufte</a>, with x10 lie factors or more, as in the following known case with a 9.4
lie factor.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/barreltufte.jpg" width="280" height="480" title="'Lie factor 9.4, Edward Tufte, The Visual Display of Quantitative Information'" ></p>

<p>I may fix it if someone founds this useful, the area for the formulas are on <a href="http://understandinguncertainty.org/node/214">this website</a>. The source code is <a href="https://github.com/guilespi/coxcomb-chart">on github</a>.</p>

<p><em>Follow me on <a href="http://www.twitter.com/guilespi">Twitter</a></em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Neither types nor tests will solve your data coverage problem]]></title>
    <link href="http://guilespi.github.com/blog/2012/11/14/neither-types-nor-tests-will-solve-your-data-coverage-problem/"/>
    <updated>2012-11-14T22:24:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2012/11/14/neither-types-nor-tests-will-solve-your-data-coverage-problem</id>
    <content type="html"><![CDATA[<p>I just watched the Strangeloop talk titled <a href="http://www.infoq.com/presentations/Types-Tests">Types vs. Tests: An Epic Battle</a> from Amanda Laucher and Paul Snively.
As Amanda says it&#8217;s a discussion many of us have had in the past, I used to talk about it with <a href="http://www.twitter.com/fedesilva">fedesilva</a>,
hardcore Scala advocate, you know what I mean?</p>

<p>For me, I think types and tests are two sides of the same coin, because neither strategy
for proving correctness is computable.</p>

<p>Bear with me.</p>

<p>The purpose of having types or having tests, it&#8217;s to prove your program to be correct before <a href="http://blog.guillermowinkler.com/blog/2012/11/07/whats-a-bug-worth/">your bugs reach your customers</a>,
one strategy tries to prove it <em>at compile time</em> and the other <em>after compile time</em>. But what it really means your program to be <em>correct</em>?</p>

<p>Let&#8217;s go for ride on <a href="http://en.wikipedia.org/wiki/Computability_theory">Computability Theory</a>.</p>

<p><strong>Functions and programs</strong></p>

<p>According to the definition a function <code>f</code> is computable if a program <code>P</code> exists which can calculate the function given unlimited amounts of time and storage.</p>

<pre><code>f:N→N is computable ↔ ∃ a program P which computes the function.
</code></pre>

<p>Also we must define when a program <code>P</code> converges for input <code>n</code>.</p>

<pre><code>Program P with input n converges if ∃ m ∈ N / &lt;Q,n&gt; = m , it's written &lt;Q,n&gt;↓
</code></pre>

<p>In computer theory there are well known functions to be non computable, two of them are:</p>

<pre><code>Θ(n) = 1  if &lt;Ix(n), n&gt;↓
       0  if &lt;Ix(n), n&gt;↑
</code></pre>

<p>Which says that the function <code>Θ</code> is equal to 1 if the program of index <code>n</code> converges on input <code>n</code> and 0 if the program of index <code>n</code> diverges on input <code>n</code>.</p>

<p>There&#8217;s another very famous function which has been proved to be non computable.</p>

<pre><code>stop(p, n) = 1 if &lt;Ix(p), n&gt;↓
             0 if &lt;Ix(p), n&gt;↑
</code></pre>

<p>Which pretty much says that given a description of an arbitrary computer program, decide whether the program finishes running or continues to run forever.
As you may have guessed, it&#8217;s the well known <a href="http://en.wikipedia.org/wiki/Halting_problem">Halting Problem</a>, and it&#8217;s <em>not</em> computable.</p>

<p><strong>How the Halting Problem relates to types and tests</strong></p>

<p>Let&#8217;s assume our program <code>P</code> we&#8217;re trying to prove correct, computes the function <code>f:N→N</code>. We can define our program that proves correctness, a program <code>T</code>
that computes the function</p>

<pre><code>ft:N→{0,1} 
</code></pre>

<p>Which is to say, for every input of the domain, our program <code>T</code> decides if the program converges or not. It&#8217;s starting to sound familiar ain&#8217;t it?</p>

<p>Let&#8217;s assume such a program <code>T</code> exists to prove correctness, and we have a macro <code>MT</code> to find such a program given <code>P</code>. We could write the following program <code>Q</code></p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>PROGRAM(x0, x1)
</span><span class='line'>x3=MT(x0)
</span><span class='line'>x4=EVAL_PROG(x3, x1)
</span><span class='line'>RESULT(x4)</span></code></pre></td></tr></table></div></figure>


<p>What <code>Q</code> does it&#8217;s having received a program <code>x0</code> and an input <code>x1</code>, first finds the <code>T</code> decider program for the program <code>x0</code>, and then evaluates the program
with the input <code>x1</code>.</p>

<p>So what do we have here?</p>

<pre><code>Q(p, n) = 1 ↔ ft(n) = 1 ↔ &lt;P, n&gt; ↓
</code></pre>

<p>So we have written a program which computes the <code>stop</code> function, which is absurd. It means we cannot have a program that decides on the computability of
a program.</p>

<p><strong>Show me the code</strong></p>

<p>In practice, it means that if you have this program</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="kt">int</span> <span class="nf">f</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">while</span> <span class="p">(</span><span class="n">x</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>     <span class="n">x</span><span class="o">--</span><span class="p">;</span>
</span><span class='line'>   <span class="p">}</span>
</span><span class='line'>   <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This program doesn&#8217;t stop for <code>x &lt; 0</code>, and according to theory, there&#8217;s no program you can write to find out about it.</p>

<p>There are also a few other funny cases regarding the domain of your functions, such as</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='c'><span class='line'><span class="kt">int</span> <span class="nf">f</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">return</span> <span class="mi">1</span> <span class="o">/</span> <span class="p">(</span><span class="n">x</span> <span class="o">-</span> <span class="mi">3</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This function fails miserably if <code>x = 3</code>. Just think about it when your functions have a more complex domain.</p>

<p><strong>How to improve your tests for correctness</strong></p>

<p>Most people I see are worried about having 100% <em>code coverage</em>, but it&#8217;s not that usual to see people worried about <em>data coverage</em>.</p>

<p>As seen in the previous example if you forget to test for <code>x = 3</code> you may have 100% code coverage but your program will blow up anyway.</p>

<p>Regarding types, I know <a href="http://en.wikipedia.org/wiki/Dependent_type">Dependent Types</a> exists, but it&#8217;s the other side of the same coin, you have to provide a constructive
proof that the type is <em>inhabited</em>. So if you don&#8217;t define your type considering the special cases of your function domain, no one is coming
up to save your ass.</p>

<p>But when thinking about correctness you should be thinking about your function domain.</p>

<p><strong>Conclusion</strong></p>

<p>Both tests and types are useful ways to validate your program is correct, but not perfect. Even the discussion is meaningless, because it&#8217;s just a matter
of taste whether you like to specify your correctness rules in types or tests, but it&#8217;s something you will keep doing as far as I can tell.</p>

<p>As Rich Hickey <a href="https://twitter.com/richhickey/status/116490495500357633">said</a>, both tests and types are like guard rails, and you must know the cliff is there in order to decide building them.</p>

<p><strong>Update:</strong>
Many people wrote to me as if I&#8217;m saying you can&#8217;t prove a program to be correct, that was not what I&#8217;ve tried to say.
It was that you can&#8217;t have a system that can prove programs to be correct without specifying the rules yourself.
That is, it was a case against <code>Q</code> not against <code>T</code>.</p>

<p><em>And hey! you follow me on <a href="http://www.twitter.com/guilespi">twitter</a>!</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What's a bug worth, a case for continuous integration]]></title>
    <link href="http://guilespi.github.com/blog/2012/11/07/whats-a-bug-worth/"/>
    <updated>2012-11-07T19:48:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2012/11/07/whats-a-bug-worth</id>
    <content type="html"><![CDATA[<p>It&#8217;s almost amazing that being the year 2012, on the break of Mayan Apocalypse, and there&#8217;s still some people pushing code out the door without stopping for a minute to think how much a bug costs.</p>

<p>I&#8217;ll save you the thinking, it&#8217;s costing you customers.</p>

<p>See the following chart I&#8217;ve crafted for you(emphasis on <em>crafted</em>), please hit the <code>play</code> button.</p>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/static/modules/gviz/1.0/chart.js"> {"dataSourceUrl":"https://docs.google.com/spreadsheet/tq?key=0AgXlknkCPjl9dFpMT0pjRlNFZ1p4TkFDRWljY1AwYXc&transpose=0&headers=1&range=A1%3AF10&gid=0&pub=1","options":{"titleTextStyle":{"fontSize":16},"vAxes":[{"useFormatFromData":true,"title":"Left vertical axis title","minValue":null,"viewWindowMode":"pretty","viewWindow":{"min":null,"max":null},"maxValue":null},{"useFormatFromData":true,"minValue":null,"viewWindowMode":"pretty","viewWindow":{"min":null,"max":null},"maxValue":null}],"booleanRole":"certainty","title":"Chart title","height":321,"animation":{"duration":500},"width":667,"hAxis":{"useFormatFromData":true,"title":"Horizontal axis title","minValue":null,"viewWindowMode":"pretty","viewWindow":{"min":null,"max":null},"maxValue":null}},"state":{},"view":{},"chartType":"MotionChart","chartName":"Chart 1"} </script>




<br>


<br>


<p>There&#8217;s an obvious relationship between the cost of fixing a bug and how much customers your company can effectively take.</p>

<p>It has an easy explanation, if you have only one customer and your solution has a bug, what do you do?
You call her, you explain the bug, you go to her office, you hack a fix, you drink some coffee, and you move on.
Maybe if you have one big fat customer based on a personal relationship, you can live with that.</p>

<p>I hope it&#8217;s clear for you this delivery process does not scale, is it?</p>

<p>When you have hundreds or thousands of customers you can&#8217;t clone yourself and explain to everyone why your product is failing,
you won&#8217;t drink a hundred coffees to build rapport and talk your way out of the mess.</p>

<p>I think there&#8217;s still two big misconceptions about this relationship between your bugs and your customers,
and it may affect how you decide on your development and delivery process.</p>

<p><strong>Bug fixing cost and quality are not the same thing</strong></p>

<p>It&#8217;s widely known, I hope, that the earlier you find a bug, the cheaper it is to fix it. <a href="http://blip.tv/clojure/hammock-driven-development-4475586">This guy</a> even fixes his bugs in the hammock, before writing any code.
Take a look at the chart of the relative cost of fixing defects, <a href="http://www.riceconsulting.com/public_pdf/STBC-WM.pdf">this is the source</a></p>

<p><img class="center" src="http://guilespi.github.com/images/blog/costofbugfixing.jpg" width="480" height="580" title="'Whats a bug worth'" ></p>

<p>Obviously you should be investing in good Engineering, peer reviewing even your documents and designs, and testing your components early an often.
(Quality is not about testing either, but that&#8217;s material for another rant). What&#8217;s not so clear, is given that some bugs <em>will always</em> reach your customers,
how do you reduce the cost of fixing your on-the-wild bugs?</p>

<p>You should do everything in your reach to produce quality products, because it&#8217;s cheaper in the long run.
But what will make or break your ability to grow your customer base, is how fast and cheap you move when a bug is found.
Your maintenance cost, if you want.</p>

<p><strong>Bug fixing cost is like performance in the browser</strong></p>

<p>You should watch <a href="http://www.infoq.com/presentations/Performance-V8-Dart">this talk</a> from the last Strangeloop, besides being great, Lars Bak makes a great point about performance in the browser,
when a new level of performance was reached on the Javascript VM, all new kinds of applications started to pop up taking advantage of that performance.</p>

<p>It&#8217;s <em>not</em> the other way around.</p>

<p><a href="http://en.wikipedia.org/wiki/Correlation_does_not_imply_causation">Correlation does not imply causation</a>, until it does, just be sure to understand what causes what.</p>

<p>Speed in the browser did not improve because Gmail was running too slow, first speed improved, then we have Gmail.</p>

<p>It&#8217;s the same with your customers.</p>

<p>If you wait till having lots of customers to start thinking about improving your maintenance costs, you will never have them.
Having low support and maintenance costs will make you find a way to acquire more customers, just because you can.</p>

<p><strong>What to do?</strong></p>

<p>This is not by any means a complete nor bulletproof list, but some strategies I&#8217;ve found from personal experience that help.</p>

<p><strong>You do <a href="https://speakerdeck.com/sebastianmoreno/continuous-improvement-o-como-poner-los-robots-de-tu-lado">continuous integration and deployment</a></strong></p>

<p>Have you ever been involved in a delivery process having to test thousands of test cases, run dozens of performance and stress tests,
do it in multiple platforms, all of it, just because you patched 3 lines of code, and you must be absolutely sure everything is still working as intended?</p>

<p>I have, and it&#8217;s not fun</p>

<p>It&#8217;s not fun for your customer either, because you end up batching even your hot-fixes, and they&#8217;re not so hot anymore.
And your customer has to wait, and you will eventually lose your customer.</p>

<p>Continuous integration is not about some geeks with shiny tools, it&#8217;s about customers.</p>

<p><strong>You develop with operations in mind</strong></p>

<p>There&#8217;s a <a href="http://www.youtube.com/watch?v=LAP1zaXUvAE">great talk by Theo Schlossnagle</a> about what it means to have a career in web operations, walking the path, and becoming a craftsman, you must watch it, seriously, because it&#8217;s <em>that</em> good.</p>

<p>One of the remarkable points is that you must build systems that are observable. Developers cannot separate themselves from the fact that software has to operate,
actually run. And developers shouldn&#8217;t be trying to reproduce a bug in a controlled environment in order to understand if there&#8217;s really a bug.
You should be able to diagnose the problem in the running system, so it must be observable. How much elements in that queue? is it stalled? you must know, now.</p>

<p>And you don&#8217;t build observable systems if you start thinking about it after you&#8217;ve shipped, using an entirely different team(hello DevOps).</p>

<p>Software with operations in mind is like software with security in mind, or quality in mind, it&#8217;s a state of being, and it&#8217;s about your development process.</p>

<p><strong>You use the right tools</strong></p>

<p>How long does it take you to <em>see</em> that a function is returning the wrong value?
How long does it take you to find the 3 lines of log that point you to the exact spot the problem is?
How long does it take you to analyze a crash dump and get to the cause of the crash?</p>

<p>Being able to debug and diagnose a problem fast, is almost as important as being able to fix it fast, and deploying the fix fast.</p>

<p>This is an area where I personally think there&#8217;s a lot of room for improvement regarding the tools we daily use,
but you should know <a href="http://dtrace.org/blogs/">DTrace</a> exists and how to use it, idealistically.</p>

<p><strong>Conclusion</strong></p>

<p>If you&#8217;re hacking your brains out and life&#8217;s good, all the power to you. I like that too.</p>

<p>But if you&#8217;re really thinking about scaling your business, you should be taking a look at your bug fixing and maintenance costs, now.</p>

<p>There&#8217;s also a <a href="http://www.amazon.com/Art-Scalability-Architecture-Organizations-Enterprise/dp/0137030428">great book</a> about scaling companies, you should read that one too.</p>

<p><em>And don&#8217;t forget to follow me on <a href="http://www.twitter.com/guilespi">twitter</a></em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[On firing yourself]]></title>
    <link href="http://guilespi.github.com/blog/2012/11/07/on-firing-yourself/"/>
    <updated>2012-11-07T16:31:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2012/11/07/on-firing-yourself</id>
    <content type="html"><![CDATA[<p>When you&#8217;ve been leading a team for a while, you kinda get used to get them together and break some news, whether it&#8217;s good or bad. People also get used to listening, and if you&#8217;ve done well, trusting you.</p>

<p>But there&#8217;s some news you will never be ready to break, it&#8217;s the day you must say you&#8217;re stepping down.</p>

<p>I know I wasn&#8217;t.</p>

<p>It was one of the more difficult and saddest moments I&#8217;ve ever had to go through, I&#8217;m still finding hard to even write about it.</p>

<p>Beyond all reasons, there&#8217;s only one thing I really want to say to Ewe, Niko, Burguer, Seba, Fernickk, Nacho, Juan, Cany, Paola, El Ruso Alexis, Fede, Canario, Lolo &amp; Diego.</p>

<p>Thank you, it was an amazing ride.</p>

<p>You&#8217;re gonna be missed</p>

<p>El Cabeza</p>

<p><em>At least you should follow me on <a href="http://www.twitter.com/guilespi">twitter</a>!</em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How long waiting for an answer in StackOverflow]]></title>
    <link href="http://guilespi.github.com/blog/2012/10/30/how-long-waiting-for-an-answer-in-stackoverflow/"/>
    <updated>2012-10-30T23:52:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2012/10/30/how-long-waiting-for-an-answer-in-stackoverflow</id>
    <content type="html"><![CDATA[<p>I&#8217;m not a <a href="http://www.stackoverflow.com">StackOverflow</a> active contributor, something I recently decided should start to change.</p>

<p>I think it&#8217;s amazing the <code>speed</code> an answer is given for any asked question, like <em>freaking</em> fast. If you are using Google Reader to peek new questions filtered by tag, when you see a question, almost for sure it&#8217;s already answered.</p>

<p>Fortunately all StackExchange data is <a href="http://media10.simplex.tv/content/xtendx/stu/stackoverflow/">open</a>, so we can see exactly <em>how</em> fast is that. I used the online <a href="http://data.stackexchange.com/faq">data browser</a>, more than enough for the task.</p>

<p>I decided to consider only the questions having an accepted answer, since questions with many bogus answers should not be treated as having an answer at all.</p>

<p><strong>tl;dr</strong></p>

<p>The average answer time seems to be dependent on a mix of the maturity of the language and how many people is using it.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/averageanswerbylanguage5.png" width="550" height="650" title="'How long waiting for an answer by language, easy questions'" ></p>

<p>Hey, Haskell has pretty good answer times, at least considering its <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html">33th</a> position in the <a href="http://en.wikipedia.org/wiki/TIOBE_index">TIOBE Index</a>.</p>

<p><strong>Not all questions are the same</strong></p>

<p>Of course not all questions are the same, this is from the first query I ran.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/averageanswerbylanguageunfiltered.png" width="550" height="650" title="'How long waiting for an answer by language, all questions'" ></p>

<p>This is an unfiltered query using all the questions from year 2012, you see the average answer time is much higher than the previous chart, around 1000 minutes, looking at the data:</p>

<pre><code>Language    Ans. Time         Stdev
c               934       7630.98957971267
c++            1036       7258.13498426685
clojure        1078       7485.94721484444
haskell        1199       9059.91937846459
php            1210       8588.58929278208
lua            1386       6569.08356022594
c#             1452       8875.00837073432
scala          1472      10707.9191188056
javascript     1490       9756.64151519177
java           1755      10541.6111024572
ruby           2124      11850.4353701107
</code></pre>

<p>The standard deviation is huge, we have a lot of questions that took ages to get answered, making the average answer time meaningless.</p>

<p>So I decided to take out questions with an answer time greater than 24 hours, as 92% of the questions have an approved answer in less than 5 hours.
(<a href="https://gist.github.com/3984320">here</a> you can see the query used to get this table)</p>

<pre><code>DifficultyGroup    Total     Average              StandardDev
Easy                47099        27           44.7263057563449 
Medium                344       691          339.312936469053
Hard                 1926      3769         2004.75027395979
Hell                 1623     66865        96822.8840748525
</code></pre>

<p>It started to look like something:</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/averageanswerbylanguage24.png" width="550" height="650" title="'How long waiting for an answer by language, less than 24 hours'" >
<a href="https://gist.github.com/3984333">This</a> is the query.</p>

<p>You see there, PHP running at front with 68 minutes average accepted answer time, either it&#8217;s too easy or there&#8217;re too many of them.</p>

<p>If you wanna see how the distribution goes when considering accepted answers in less than 5 hours, is the first picture of the page, the trend is also there.</p>

<p><strong>What about the time?</strong></p>

<p>Something unexpected, average answer time is almost unaffected by the time of the day the question was asked.
The only thing I see here is that Ruby programmers are being killed by the lunch break and c++ programmers slowly fade out with the day, ain&#8217;t it?</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/averageanswerhourbyhour.png" width="550" height="650" title="'How long waiting for an answer by time of day, ruby and c++'" ></p>

<p><a href="https://gist.github.com/3984329">This</a> is the query.</p>

<p>There goes my idea of catching unanswered questions at night. It would be interesting to see how many cross-timezone answering is happening.</p>

<p><strong>Conclusion</strong></p>

<p>It should work better running a regression against the complete dataset using more features than only programming language and time of day
 to automatically guess which questions have more chance of have a long life unanswered. Maybe next time.</p>

<p><em>Follow me on <a href="http://www.twitter.com/guilespi">Twitter</a></em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Computational Investment QSTK Framework from Python to Clojure]]></title>
    <link href="http://guilespi.github.com/blog/2012/10/29/computational-investment-qstk-framework-from-python-to-clojure/"/>
    <updated>2012-10-29T01:07:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2012/10/29/computational-investment-qstk-framework-from-python-to-clojure</id>
    <content type="html"><![CDATA[<p>Last week started the course on <a href="https://class.coursera.org/compinvesting1-2012-001/class/index">Computational Investing</a> from Coursera and I&#8217;ve been taking a look.</p>

<p>What caught my attention is the libraries used for portfolio construction and management, <a href="http://wiki.quantsoftware.org/index.php?title=QuantSoftware_ToolKit">QSTK</a>, an opensource python framework, based on numpy, scipy, matplotlib, pandas, etc.</p>

<p>Looking at the <a href="http://wiki.quantsoftware.org/index.php?title=QSTK_Tutorial_1">first tutorial</a>&#8217;s <a href="https://gist.github.com/3971007">source code</a>, saw it as an opportunity to migrate the tutorials and libraries to Clojure and get to play a little with <a href="http://incanter.org/">Incanter</a>.</p>

<p>I&#8217;m going to highlight what I&#8217;ve found interesting when migrating the tutorials. I&#8217;m assuming you have QSTK installed and the QS environment variable is set, since the code depends on that for data reading.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="k">def </span><span class="o">^</span><span class="p">{</span><span class="ss">:dynamic</span> <span class="nv">true</span><span class="p">}</span> <span class="nv">*QS*</span> <span class="p">(</span><span class="nb">get </span><span class="p">(</span><span class="nf">System/getenv</span><span class="p">)</span> <span class="s">&quot;QS&quot;</span><span class="p">))</span>
</span></code></pre></td></tr></table></div></figure>


<p><strong>NYSE operation dates</strong></p>

<p>As part of the initialization process the tutorial calls a function <a href="http://www.quantsoftware.org/Docs/html/QSTK.qstkutil.dateutil-pysrc.html#getNYSEdays">getNYSEDays</a>, which retrieves all the days there was trading at the NYSE. Migration is straightforward using incanter&#8217;s read-dataset to read file into memory and then filter the required range.</p>

<div><script src='https://gist.github.com/3970987.js'></script>
<noscript><pre><code>(defn get-NYSE-days
  &quot;Create a set of timestamps between startday and endday
  that correspond to the days there was trading at the NYSE&quot;
  [start-date end-date time-of-day]
  (let [dates-file (str *QS* &quot;/qstkutil/NYSE_dates.txt&quot;)
        NYSE-dates (incanter.io/read-dataset dates-file)
        fmt (formatter &quot;MM/dd/yyyy&quot;)
        dates (incanter.core/$map #(parse fmt %) :col0 NYSE-dates)]
    (set (filter (fn [d] (within? (interval start-date end-date) d))
           (map #(plus % time-of-day) dates)))))
</code></pre></noscript></div>


<p>Pay attention to the <code>time-of-day</code> set at 16 hours, <a href="http://en.wikipedia.org/wiki/List_of_market_opening_times">the time NYSE closes</a>, we&#8217;ll see it again in unexpected places.</p>

<p><strong>Data Access</strong></p>

<p>QSTK provides a helper class called <a href="http://www.quantsoftware.org/Docs/html/QSTK.qstkutil.DataAccess.DataAccess-class.html">DataAccess</a> used for reading and caching stock prices.</p>

<p>As you see here there&#8217;s some data reading happening, we&#8217;re gonna take a look at these functions since we&#8217;ll need to write them from scratch.</p>

<figure class='code'><figcaption><span>Data initialization in python tutorial </span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='python'><span class='line'><span class="n">dataobj</span> <span class="o">=</span> <span class="n">da</span><span class="o">.</span><span class="n">DataAccess</span><span class="p">(</span><span class="s">&#39;Yahoo&#39;</span><span class="p">)</span>
</span><span class='line'><span class="n">voldata</span> <span class="o">=</span> <span class="n">dataobj</span><span class="o">.</span><span class="n">get_data</span><span class="p">(</span><span class="n">timestamps</span><span class="p">,</span> <span class="n">symbols</span><span class="p">,</span> <span class="s">&quot;volume&quot;</span><span class="p">,</span><span class="n">verbose</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</span><span class='line'><span class="n">close</span> <span class="o">=</span> <span class="n">dataobj</span><span class="o">.</span><span class="n">get_data</span><span class="p">(</span><span class="n">timestamps</span><span class="p">,</span> <span class="n">symbols</span><span class="p">,</span> <span class="s">&quot;close&quot;</span><span class="p">,</span><span class="n">verbose</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</span><span class='line'><span class="n">actualclose</span> <span class="o">=</span> <span class="n">dataobj</span><span class="o">.</span><span class="n">get_data</span><span class="p">(</span><span class="n">timestamps</span><span class="p">,</span> <span class="n">symbols</span><span class="p">,</span> <span class="s">&quot;actual_close&quot;</span><span class="p">,</span><span class="n">verbose</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>We&#8217;re going to separate this in two functions, first reading symbol data from disk using again read-dataset and creating a hash-map indexed by symbol name.</p>

<figure class='code'><figcaption><span>Creating a symbols hash-map of incanter datasets</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='Clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">read-symbols-data</span>
</span><span class='line'>  <span class="s">&quot;Returns a hashmap of symbols/incanter datasets read from QS data directory&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">source-in</span> <span class="nv">symbols</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">data-dir</span> <span class="p">(</span><span class="nb">str </span><span class="nv">*QS*</span> <span class="s">&quot;/QSData/&quot;</span> <span class="nv">source-in</span> <span class="s">&quot;/&quot;</span><span class="p">)]</span>
</span><span class='line'>    <span class="p">(</span><span class="nb">reduce </span><span class="o">#</span><span class="p">(</span><span class="nb">assoc </span><span class="nv">%1</span> <span class="nv">%2</span> <span class="p">(</span><span class="nf">incanter.io/read-dataset</span> <span class="p">(</span><span class="nb">str </span><span class="nv">data-dir</span> <span class="nv">%2</span> <span class="s">&quot;.csv&quot;</span><span class="p">)</span> <span class="ss">:header</span> <span class="nv">true</span><span class="p">))</span> <span class="p">{}</span> <span class="nv">symbols</span><span class="p">)))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then if you take a look at <code>voldata</code> in a python repl, you can see pretty much what it&#8217;s doing</p>

<pre><code>                       AAPL       GLD     GOOG        $SPX       XOM
 2012-05-01 16:00:00  21821400   7414800  2002300  2706893315  13816900
 2012-05-02 16:00:00  15263900   5632300  1611500  2634854740  11108700
 2012-05-03 16:00:00  13948200  13172000  1868000  2673299265   9998600
</code></pre>

<p>It&#8217;s grabbing the specified column <code>volume</code> or <code>close</code> from each symbol dataset, and it&#8217;s creating a new table with the resulting column renamed as the symbol.</p>

<p>All the get_data magic happens inside <a href="http://www.quantsoftware.org/Docs/html/QSTK.qstkutil.DataAccess-pysrc.html#DataAccess.get_data_hardread">get_data_hardread</a>, it&#8217;s an ugly piece of code making a lot of assumptions about column names, and even about market closing time. I guess you can only use this library for markets closing at 16 hours local time.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='python'><span class='line'><span class="n">timemonth</span> <span class="o">=</span> <span class="nb">int</span><span class="p">((</span><span class="n">timebase</span><span class="o">-</span><span class="n">timeyear</span><span class="o">*</span><span class="mi">10000</span><span class="p">)</span><span class="o">/</span><span class="mi">100</span><span class="p">)</span>
</span><span class='line'><span class="n">timeday</span> <span class="o">=</span> <span class="nb">int</span><span class="p">((</span><span class="n">timebase</span><span class="o">-</span><span class="n">timeyear</span><span class="o">*</span><span class="mi">10000</span><span class="o">-</span><span class="n">timemonth</span><span class="o">*</span><span class="mi">100</span><span class="p">))</span>
</span><span class='line'><span class="n">timehour</span> <span class="o">=</span> <span class="mi">16</span>
</span></code></pre></td></tr></table></div></figure>


<p>I&#8217;ve translated that into these two functions:</p>

<div><script src='https://gist.github.com/3971076.js'></script>
<noscript><pre><code>(defn select-value
  &quot;Given a dataset indexed by date, returns the value corresponding to a specified column
  if existent for a specific date&quot;
  [ds column date]
  (let [row (ds {:Date date})]
    (when-not (nil? row) (incanter.core/$ 0 column row))))

(defn get-data
  &quot;Given a list of `symbols`, its data and a list of specific `timestamps`, builds a matrix(sequence)
  with each column corresponding to a stock and the value extracted using `column` 
  :Date        AAPL    GOOG    WFC
  2012-02-01   54.1    33.1    25.0
  2012-02-02   56.3    33.4    22.9&quot;
  [timestamps symbols column symbols-data time-of-day]
  (let [grouped-data (reduce (fn [m, s] (assoc m (s 0) (incanter.core/$group-by :Date (s 1)))) {} symbols-data)]
    (for [t timestamps]
      (let [unparsed-date (unparse (formatters :year-month-day) t)]
        (reduce #(merge %1 {(%2 0) (select-value (%2 1) column unparsed-date)}) {:Date (to-long t)} grouped-data)))))</code></pre></noscript></div>


<p>In this case Clojure shines, the <a href="https://gist.github.com/3971102">original function</a> is almost 300 lines of code. I&#8217;m missing a couple of checks but it&#8217;s not bad for a rookie, I think.</p>

<p>The helper function <code>select-value</code> is there in order to avoid an exception when trying to find stock data for a non existent date. Also the function returns <code>:Date</code> as a double since it&#8217;s easier to handle later for charting.</p>

<p><strong>Charting</strong></p>

<p>Charting with Incanter is straightforward, there a subtle difference with python since you need to add each series one by one. So what python is doing here charting multiple series at once</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='python'><span class='line'><span class="n">newtimestamps</span> <span class="o">=</span> <span class="n">close</span><span class="o">.</span><span class="n">index</span>
</span><span class='line'><span class="n">pricedat</span> <span class="o">=</span> <span class="n">close</span><span class="o">.</span><span class="n">values</span> <span class="c"># pull the 2D ndarray out of the pandas object</span>
</span><span class='line'><span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">newtimestamps</span><span class="p">,</span><span class="n">pricedat</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>We need a little function to solve it with Incanter. Each iteration gets reduced into the next with all the series accumulated in one chart.</p>

<figure class='code'><figcaption><span>creates multiple time-series at once</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">multi-series-chart</span>
</span><span class='line'>  <span class="s">&quot;Creates a xy-chart with multiple series extracted from column data</span>
</span><span class='line'><span class="s">  as specified by series parameter&quot;</span>
</span><span class='line'>  <span class="p">[{</span><span class="ss">:keys</span> <span class="p">[</span><span class="nv">series</span> <span class="nv">title</span> <span class="nv">x-label</span> <span class="nv">y-label</span> <span class="nv">data</span><span class="p">]}]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">chart</span> <span class="p">(</span><span class="nf">incanter.charts/time-series-plot</span> <span class="ss">:Date</span> <span class="p">(</span><span class="nb">first </span><span class="nv">series</span><span class="p">)</span>
</span><span class='line'>                                                 <span class="ss">:x-label</span> <span class="nv">x-label</span>
</span><span class='line'>                                                 <span class="ss">:y-label</span> <span class="nv">y-label</span>
</span><span class='line'>                                                 <span class="ss">:title</span> <span class="nv">title</span>
</span><span class='line'>                                                 <span class="ss">:series-label</span> <span class="p">(</span><span class="nb">first </span><span class="nv">series</span><span class="p">)</span>
</span><span class='line'>                                                 <span class="ss">:legend</span> <span class="nv">true</span>
</span><span class='line'>                                                 <span class="ss">:data</span> <span class="nv">data</span><span class="p">)]</span>
</span><span class='line'>  <span class="p">(</span><span class="nb">reduce </span><span class="o">#</span><span class="p">(</span><span class="nf">incanter.charts/add-lines</span> <span class="nv">%1</span> <span class="ss">:Date</span> <span class="nv">%2</span> <span class="ss">:series-label</span> <span class="nv">%2</span> <span class="ss">:data</span> <span class="nv">data</span><span class="p">)</span> <span class="nv">chart</span> <span class="p">(</span><span class="nb">rest </span><span class="nv">series</span><span class="p">))))</span>
</span></code></pre></td></tr></table></div></figure>


<p><strong>Data Mangling</strong></p>

<p>Incanter has <em>a lot</em> of built-in functions and helpers to operate on your data, unfortunately I couldn&#8217;t use one of the many options for operating
on a matrix, or even <code>$=</code>, since the data we&#8217;re processing has many <code>nil</code> values inside the dataset for dates the stock didn&#8217;t trade which raises an exception when
treated as a number, which is what to-matrix does, tries to create an array of Doubles.</p>

<p>There&#8217;s one more downside and it&#8217;s we need to keep the <code>:Date</code> column as-is when operating on the dataset, so we need to remove it, operate, and add it later again, what happens to be a beautiful one-liner in python</p>

<figure class='code'><figcaption><span>This attempts a naive normalization dividing each row by the first one. </span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='python'><span class='line'> <span class="n">normdat</span> <span class="o">=</span> <span class="n">pricedat</span><span class="o">/</span><span class="n">pricedat</span><span class="p">[</span><span class="mi">0</span><span class="p">,:]</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>Or the daily return function. </span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='python'><span class='line'><span class="n">dailyrets</span> <span class="o">=</span> <span class="p">(</span><span class="n">pricedat</span><span class="p">[</span><span class="mi">1</span><span class="p">:,:]</span><span class="o">/</span><span class="n">pricedat</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">,:])</span> <span class="o">-</span> <span class="mi">1</span>
</span></code></pre></td></tr></table></div></figure>


<p>I ended up writing from scratch the iteration and function applying code.</p>

<div><script src='https://gist.github.com/3971236.js'></script>
<noscript><pre><code>
(defmacro apply-filtered
  &quot;Given two sequences, apply a function to each pair of elements when condition is met
  anaphoras n and m exists for each indexed element

  e.g. (apply-filtered / [1 2 3] [1 0 3] when (&gt; m 0)) =&gt; (1 nil 1)
  &quot;
  [op a b &amp; condition]
  `(for [x# (range (count ~a))]
    (let [n# (nth ~a x#)
          m# (nth ~b x#)]
      (when (~(second condition) n# m#)
        (~op n# m#)))))

(defmacro apply-rows
  &quot;Apply an operation to each row of the dataset excluding :Date column
   A start row and a condition must be given

  .e.g Divide each row by vector [1 0 3] starting from 0 validating divide by zero
    (apply-rows ds (/ [1 2 3]) 0 (fn [n m] (&gt; m 0))&quot;
  [data operation start cond]
  `(let [raw-data# (incanter.core/$ :all [:not :Date] ~data)
        raw-cols# (incanter.core/col-names raw-data#)
        dates# (incanter.core/$ :all :Date ~data)] 
       (incanter.core/col-names
        (incanter.core/conj-cols
         (for [~&#39;i (range ~start (incanter.core/nrow raw-data#))]
           (apply-filtered
                      ~(first operation)
                      (vec (incanter.core/$ ~&#39;i [:not :Date] raw-data#))
                      ~(second operation)
                      :when ~cond))
         dates#) (conj raw-cols# :Date))))
</code></pre></noscript></div>


<p>Maybe there&#8217;s an easier way but I couldn&#8217;t think of it, if you know a better way please drop me a line!</p>

<p>Now normalization and daily-returns are at least manageable.</p>

<figure class='code'><figcaption><span>Normalization and Daily Returns</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='clojure'><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">normalize</span>
</span><span class='line'>  <span class="s">&quot;Divide each row in a dataset by the first row&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">ds</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="k">let </span><span class="p">[</span><span class="nv">first-row</span> <span class="p">(</span><span class="nf">vec</span> <span class="p">(</span><span class="nf">incanter.core/$</span> <span class="mi">0</span> <span class="p">[</span><span class="ss">:not</span> <span class="ss">:Date</span><span class="p">]</span> <span class="nv">ds</span><span class="p">))]</span>
</span><span class='line'>    <span class="p">(</span><span class="nf">apply-rows</span> <span class="nv">ds</span> <span class="p">(</span><span class="nb">/ </span><span class="nv">first-row</span><span class="p">)</span> <span class="mi">0</span> <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">n</span> <span class="nv">m</span><span class="p">]</span> <span class="p">(</span><span class="nb">and </span><span class="p">(</span><span class="nb">not-any? nil? </span><span class="p">[</span><span class="nv">n</span> <span class="nv">m</span><span class="p">])</span> <span class="p">(</span><span class="nb">&gt; </span><span class="nv">m</span> <span class="mi">0</span><span class="p">))))))</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">defn </span><span class="nv">daily-rets</span>
</span><span class='line'>  <span class="s">&quot;Daily returns&quot;</span>
</span><span class='line'>  <span class="p">[</span><span class="nv">data</span><span class="p">]</span>
</span><span class='line'>  <span class="p">(</span><span class="nf">apply-rows</span> <span class="nv">data</span>
</span><span class='line'>            <span class="p">((</span><span class="k">fn </span><span class="p">[</span><span class="nv">n</span> <span class="nv">m</span><span class="p">]</span> <span class="p">(</span><span class="nb">- </span><span class="p">(</span><span class="nb">/ </span><span class="nv">n</span> <span class="nv">m</span><span class="p">)</span> <span class="mi">1</span><span class="p">))</span> <span class="p">(</span><span class="nf">vec</span> <span class="p">(</span><span class="nf">incanter.core/$</span> <span class="p">(</span><span class="nb">- </span><span class="nv">i</span> <span class="mi">1</span><span class="p">)</span> <span class="p">[</span><span class="ss">:not</span> <span class="ss">:Date</span><span class="p">]</span> <span class="nv">data</span><span class="p">)))</span>
</span><span class='line'>            <span class="mi">1</span>
</span><span class='line'>            <span class="p">(</span><span class="k">fn </span><span class="p">[</span><span class="nv">n</span> <span class="nv">m</span><span class="p">]</span> <span class="p">(</span><span class="nb">and </span><span class="p">(</span><span class="nb">not-any? nil? </span><span class="p">[</span><span class="nv">n</span> <span class="nv">m</span><span class="p">])</span> <span class="p">(</span><span class="nb">&gt; </span><span class="nv">m</span> <span class="mi">0</span><span class="p">)))))</span>
</span></code></pre></td></tr></table></div></figure>


<p>Having the helper functions done, running of the tutorial is almost declarative.</p>

<div><script src='https://gist.github.com/3971246.js'></script>
<noscript><pre><code>(defn run
  []
  (let [symbols [&quot;AAPL&quot;,&quot;GLD&quot;,&quot;GOOG&quot;,&quot;$SPX&quot;,&quot;XOM&quot;]
        start-day (date-time 2012 1 1)
        end-day (date-time 2012 12 31)
        time-of-day (hours 16)
        timestamps (get-NYSE-days start-day end-day time-of-day)
        symbols-data (read-symbols-data &quot;Yahoo&quot; symbols)
        adj-close-data (incanter.core/to-dataset
                        (get-data timestamps symbols (keyword &quot;Adj Close&quot;) symbols-data time-of-day))]
    (do
      ;;first chart of the tutorial
      (incanter.core/view (multi-series-chart {:series symbols
                                               :x-label &quot;Date&quot;
                                               :y-label &quot;Adjusted Close&quot;
                                               :title &quot;Adjusted close data&quot;
                                               :data adj-close-data}))
      ;;second chart of the tutorial
      (incanter.core/view (multi-series-chart {:series symbols
                                               :x-label &quot;Date&quot;
                                               :y-label &quot;Adjusted Close&quot;
                                               :title &quot;Normalized close data&quot;
                                               :data (normalize adj-close-data)}))
      ;;daily returns
      (incanter.core/view (multi-series-chart {:series symbols
                                               :x-label &quot;Date&quot;
                                               :y-label &quot;Return&quot;
                                               :title &quot;Daily Returns&quot;
                                               :data (daily-rets adj-close-data)}))
      ;;quotes comparison with scatter plot
      (incanter.core/view (incanter.charts/scatter-plot
                           &quot;AAPL&quot; &quot;GOOG&quot;
                           :x-label &quot;AAPL&quot;
                           :y-label &quot;GOOG&quot;
                           :legend true
                           :data (normalize adj-close-data)
                           )))))</code></pre></noscript></div>


<p>If you wanna take a look at the whole thing together here&#8217;s the <a href="https://gist.github.com/3971253">gist</a>, I may create a repo later.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/chartincanter.png" width="380" height="480" title="'Incanter charting finance data'" ></p>

<p>Please remember NumPy is way much faster than Clojure since it links <a href="http://www.netlib.org/lapack/">BLAS/Lapack</a> libraries.</p>

<p><em>Follow me on <a href="http://www.twitter.com/guilespi">twitter</a></em></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[You don't redistribute a distribution]]></title>
    <link href="http://guilespi.github.com/blog/2012/10/21/you-dont-redistribute-a-distribution/"/>
    <updated>2012-10-21T14:54:00-02:00</updated>
    <id>http://guilespi.github.com/blog/2012/10/21/you-dont-redistribute-a-distribution</id>
    <content type="html"><![CDATA[<p>I&#8217;ve written a post for <a href="http://www.cabezapropia.com/">cabeza propia</a> on <a href="http://www.cabezapropia.com/el-primer-problema-sobre-la-distribucion-de-la-riqueza/">distribution of wealth</a>. If you read spanish, take a look.</p>

<p>The main point is there&#8217;s a semantic misunderstanding of what distribution of wealth is, confusing a statistical <a href="http://en.wikipedia.org/wiki/Frequency_distribution">frequency distribution</a> of income, with the transitive verb <code>distribute</code>.
As if the current distribution of wealth is the result of someone who decided to distribute it unfairly.</p>

<p>I pretty much agree on <a href="http://www.paulgraham.com/wealth.html">Paul Graham&#8217;s take</a> on wealth creation, and think our focus should be on individuals being able to create more value for society and for themselves.</p>

<p><img class="center" src="http://guilespi.github.com/images/blog/sharingpie.jpg" width="450" height="550" title="'Wealth as a finite pie to be distributed'" ></p>

<p>The semantic confusion may be just part of the reason we&#8217;re having the wrong conversation, about distributing, instead of being about affecting the distribution by creating.</p>
]]></content>
  </entry>
  
</feed>
