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

  
  <title><![CDATA[Programming DIY]]></title>
  <link href="http://demin.ws/atom.xml" rel="self"/>
  <link href="http://demin.ws/"/>
  <updated>2013-01-29T22:00:00Z</updated>
  <id>http://demin.ws/</id>
  <author>
    <name><![CDATA[Alexander Demin]]></name>
    <email><![CDATA[alexander@demin.ws]]></email>
  </author>

  
  <entry>
    <title type="html"><![CDATA[Tricky details about putenv()]]></title>
    <link href="http://demin.ws/blog/english/2013/01/29/tricky-details-about-putenv/"/>
    <updated>2013-01-29T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2013/01/29/tricky-details-about-putenv/</id>
    <content type="html"><![CDATA[<p>Previously I already talked about a class to deal with the
OS environment variables. The purpose of that class was to store data of the
variables passed into the <code>putenv()</code> function.</p>

<p>We rolled out this class into QA, which works on various platforms (AIX,
HP-UX, Solaris, Linux and Windows). Everything seemed to be okay, unit tests
passed and the production code didn&rsquo;t crash. Alas, QA machines controlled by
Hudson/Jenkins are usually overloaded, and quite often it causes very
unexpected issues. After a week we discovered that sometimes the code crashed
on AIX when calling <code>std::system()</code>. Even more, it crashed inside this
function, that was for sure. In most cases any &ldquo;strange&rdquo; or &ldquo;magical&rdquo; behaviour
is related to memory problems. <a href="http://pic.dhe.ibm.com/infocenter/aix/v6r1/index.jsp?topic=%2Fcom.ibm.aix.cmds%2Fdoc%2Faixcmds5%2Ftruss.htm">truss</a>, injected into command lines passed
to <code>system()</code>, showed that some environment variables in the child process
had corrupted values.</p>

<p>We began investigating the new class, <code>EnvironmentVariablesManager</code>. Below
is its simplified version but still containing a tricky bug. You may try
finding the issue by yourself first, and then read further down.</p>

<p>The simple <code>main()</code> function below easily reproduces the issue.</p>

<pre class="hl">
<span class="hl ppc">#include &lt;vector&gt;</span>
<span class="hl ppc">#include &lt;map&gt;</span>
<span class="hl ppc">#include &lt;string&gt;</span>

<span class="hl ppc">#include &lt;unistd.h&gt;</span>

<span class="hl kwc">class</span> EnvironmentVariablesManager <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwc">typedef</span> std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">char</span><span class="hl opt">&gt;</span> VariableContainer<span class="hl opt">;</span>
  <span class="hl kwc">typedef</span> std<span class="hl opt">::</span>map<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>string<span class="hl opt">,</span> VariableContainer<span class="hl opt">&gt;</span> Variables<span class="hl opt">;</span>
  <span class="hl kwb">void</span> <span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span>
    VariableContainer pair<span class="hl opt">;</span>
    <span class="hl kwd">PairToContainer</span><span class="hl opt">(</span>name<span class="hl opt">,</span> value<span class="hl opt">, &amp;</span>pair<span class="hl opt">);</span>
    <span class="hl kwb">const</span> std<span class="hl opt">::</span>pair<span class="hl opt">&lt;</span>Variables<span class="hl opt">::</span>iterator<span class="hl opt">,</span> <span class="hl kwb">bool</span><span class="hl opt">&gt;</span> inserted <span class="hl opt">=</span>
      vars_<span class="hl opt">.</span><span class="hl kwd">insert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">make_pair</span><span class="hl opt">(</span>name<span class="hl opt">,</span> pair<span class="hl opt">));</span>
    <span class="hl kwa">if</span> <span class="hl opt">(!</span>inserted<span class="hl opt">.</span>second<span class="hl opt">)</span>
      inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second <span class="hl opt">=</span> pair<span class="hl opt">;</span>
    <span class="hl kwd">putenv</span><span class="hl opt">(&amp;</span>inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">]);</span>
  <span class="hl opt">}</span>

 <span class="hl kwc">private</span><span class="hl opt">:</span>
  <span class="hl kwb">void</span> <span class="hl kwd">PairToContainer</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> value<span class="hl opt">,</span>
                       VariableContainer<span class="hl opt">*</span> pair<span class="hl opt">)</span> <span class="hl kwb">const</span> <span class="hl opt">{</span>
    pair<span class="hl opt">-&gt;</span><span class="hl kwd">clear</span><span class="hl opt">();</span>
    std<span class="hl opt">::</span><span class="hl kwd">copy</span><span class="hl opt">(</span>name<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> name<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> std<span class="hl opt">::</span><span class="hl kwd">back_inserter</span><span class="hl opt">(*</span>pair<span class="hl opt">));</span>
    pair<span class="hl opt">-&gt;</span><span class="hl kwd">push_back</span><span class="hl opt">(</span><span class="hl str">'='</span><span class="hl opt">);</span>
    std<span class="hl opt">::</span><span class="hl kwd">copy</span><span class="hl opt">(</span>value<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> value<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> std<span class="hl opt">::</span><span class="hl kwd">back_inserter</span><span class="hl opt">(*</span>pair<span class="hl opt">));</span>
    pair<span class="hl opt">-&gt;</span><span class="hl kwd">push_back</span><span class="hl opt">(</span><span class="hl str">'\0'</span><span class="hl opt">);</span>
  <span class="hl opt">}</span>
  Variables vars_<span class="hl opt">;</span>
<span class="hl opt">};</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  EnvironmentVariablesManager env<span class="hl opt">;</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;DB2_HOME&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;a&quot;</span><span class="hl opt">);</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;DB2_HOME&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;12345678&quot;</span><span class="hl opt">);</span>
<span class="hl opt">}</span>
</pre>

<p>Valgrind complains on this code saying that <code>putenv</code> tries reading some memory
after freeing (this trace is from OSX).</p>

<pre><code>clang++ -o putenv_check putenv_test.cpp &amp;&amp; valgrind ./putenv_check
==1046== Memcheck, a memory error detector
==1046== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==1046== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==1046== Command: ./putenv_check
==1046==
--1046-- ./putenv_check:
--1046-- dSYM directory is missing; consider using --dsymutil=yes
==1046== Invalid read of size 1
==1046==    at 0x2A8A3B: __findenv (in /usr/lib/system/libsystem_c.dylib)
==1046==    by 0x232C62: __setenv (in /usr/lib/system/libsystem_c.dylib)
==1046==    by 0x216A7E: putenv (in /usr/lib/system/libsystem_c.dylib)
==1046==    by 0x100001999: EnvironmentVariablesManager::put(std::string const&amp;, std::string const&amp;) (in ./putenv_check)
==1046==    by 0x1000015DE: main (in ./putenv_check)
==1046==  Address 0x100012560 is 0 bytes inside a block of size 11 free'd
==1046==    at 0x563A: free (in /usr/local/Cellar/valgrind/3.8.1/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==1046==    by 0x10000208C: __gnu_cxx::new_allocator&lt;char&gt;::deallocate(char*, unsigned long) (in ./putenv_check)
==1046==    by 0x10000201D: std::_Vector_base&lt;char, std::allocator&lt;char&gt; &gt;::_M_deallocate(char*, unsigned long) (in ./putenv_check)
==1046==    by 0x100002483: std::vector&lt;char, std::allocator&lt;char&gt; &gt;::operator=(std::vector&lt;char, std::allocator&lt;char&gt; &gt; const&amp;) (in ./putenv_check)
==1046==    by 0x1000018A8: EnvironmentVariablesManager::put(std::string const&amp;, std::string const&amp;) (in ./putenv_check)
==1046==    by 0x1000015DE: main (in ./putenv_check)
==1046==
==1046==
==1046== HEAP SUMMARY:
==1046==     in use at exit: 2,425 bytes in 34 blocks
==1046==   total heap usage: 58 allocs, 24 frees, 2,824 bytes allocated
==1046==
==1046== LEAK SUMMARY:
==1046==    definitely lost: 18 bytes in 1 blocks
==1046==    indirectly lost: 0 bytes in 0 blocks
==1046==      possibly lost: 0 bytes in 0 blocks
==1046==    still reachable: 2,407 bytes in 33 blocks
==1046==         suppressed: 0 bytes in 0 blocks
==1046== Rerun with --leak-check=full to see details of leaked memory
==1046==
==1046== For counts of detected and suppressed errors, rerun with: -v
==1046== ERROR SUMMARY: 9 errors from 1 contexts (suppressed: 1 from 1)
</code></pre>

<p>To me it was not that obvious what was wrong. For example, if to remove the
second call <code>env.put(&quot;DB2_HOME&quot;, &quot;12345678&quot;)</code>, the issue disappeared
(valgrind didn&rsquo;t complain any more). So, we started to suspect the following
lines of code:</p>

<pre class="hl">
    <span class="hl kwa">if</span> <span class="hl opt">(!</span>inserted<span class="hl opt">.</span>second<span class="hl opt">)</span>
      inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second <span class="hl opt">=</span> pair<span class="hl opt">;</span>
    <span class="hl kwd">putenv</span><span class="hl opt">(&amp;</span>inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">]);</span>
</pre>

<p>If to change the code little bit (if fact, doing exactly the same operation
but in a slightly different way):</p>

<pre class="hl">
    <span class="hl kwa">if</span> <span class="hl opt">(!</span>inserted<span class="hl opt">.</span>second<span class="hl opt">)</span>
      inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second<span class="hl opt">.</span><span class="hl kwd">assign</span><span class="hl opt">(</span>pair<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> pair<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">());</span>
</pre>

<p>the error report changes:</p>

<pre><code>--1087-- ./putenv_check:
--1087-- dSYM directory is missing; consider using --dsymutil=yes
==1087== Invalid read of size 1
==1087==    at 0x2A8A3B: __findenv (in /usr/lib/system/libsystem_c.dylib)
==1087==    by 0x232C62: __setenv (in /usr/lib/system/libsystem_c.dylib)
==1087==    by 0x216A7E: putenv (in /usr/lib/system/libsystem_c.dylib)
==1087==    by 0x1000016A9: EnvironmentVariablesManager::put(std::string const&amp;, std::string const&amp;) (in ./putenv_check)
==1087==    by 0x10000129E: main (in ./putenv_check)
==1087==  Address 0x100013560 is 0 bytes inside a block of size 11 free'd
==1087==    at 0x563A: free (in /usr/local/Cellar/valgrind/3.8.1/lib/valgrind/vgpreload_memcheck-amd64-darwin.so)
==1087==    by 0x100001D9C: __gnu_cxx::new_allocator&lt;char&gt;::deallocate(char*, unsigned long) (in ./putenv_check)
==1087==    by 0x100001D2D: std::_Vector_base&lt;char, std::allocator&lt;char&gt; &gt;::_M_deallocate(char*, unsigned long) (in ./putenv_check)
==1087==    by 0x1000022E9: void std::vector&lt;char, std::allocator&lt;char&gt; &gt;::_M_assign_aux&lt;__gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt; &gt;(__gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt;, __gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt;, std::forward_iterator_tag) (in ./putenv_check)
==1087==    by 0x1000021C4: void std::vector&lt;char, std::allocator&lt;char&gt; &gt;::_M_assign_dispatch&lt;__gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt; &gt;(__gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt;, __gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt;, std::__false_type) (in ./putenv_check)
==1087==    by 0x1000020A4: void std::vector&lt;char, std::allocator&lt;char&gt; &gt;::assign&lt;__gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt; &gt;(__gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt;, __gnu_cxx::__normal_iterator&lt;char*, std::vector&lt;char, std::allocator&lt;char&gt; &gt; &gt;) (in ./putenv_check)
==1087==    by 0x1000015BF: EnvironmentVariablesManager::put(std::string const&amp;, std::string const&amp;) (in ./putenv_check)
==1087==    by 0x10000129E: main (in ./putenv_check)
</code></pre>

<p>Now it is more or less clear what is going on. But let&rsquo;s consider a much more
simple example first, purely in C:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;unistd.h&gt;</span>
<span class="hl ppc">#include &lt;stdlib.h&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwb">char</span> <span class="hl opt">*</span>v1<span class="hl opt">, *</span>v2<span class="hl opt">;</span>
  v1 <span class="hl opt">=</span> <span class="hl kwd">malloc</span><span class="hl opt">(</span><span class="hl num">10</span><span class="hl opt">);</span>
  <span class="hl kwd">strcpy</span><span class="hl opt">(</span>v1<span class="hl opt">,</span> <span class="hl str">&quot;x=123&quot;</span><span class="hl opt">);</span>
  <span class="hl kwd">putenv</span><span class="hl opt">(</span>v1<span class="hl opt">);</span>
  <span class="hl kwd">free</span><span class="hl opt">(</span>v1<span class="hl opt">);</span>

  v2 <span class="hl opt">=</span> <span class="hl kwd">malloc</span><span class="hl opt">(</span><span class="hl num">10</span><span class="hl opt">);</span>
  <span class="hl kwd">strcpy</span><span class="hl opt">(</span>v2<span class="hl opt">,</span> <span class="hl str">&quot;x=123&quot;</span><span class="hl opt">);</span>
  <span class="hl kwd">putenv</span><span class="hl opt">(</span>v2<span class="hl opt">);</span>
  <span class="hl kwd">free</span><span class="hl opt">(</span>v2<span class="hl opt">);</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>valgrind also reports about this code (this trace is from Linux):</p>

<pre><code>==523== Memcheck, a memory error detector
==523== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
==523== Using Valgrind-3.6.0 and LibVEX; rerun with -h for copyright info
==523== Command: ./putenv_test
==523==
==523== Invalid read of size 1
==523==    at 0x4A07CF9: __GI_strncmp (mc_replace_strmem.c:400)
==523==    by 0x3E1C235649: __add_to_environ (in /lib64/libc-2.12.so)
==523==    by 0x3E1C2353CD: putenv (in /lib64/libc-2.12.so)
==523==    by 0x4A0952D: putenv (mc_replace_strmem.c:1165)
==523==    by 0x400607: main (in /storage2/home3/ademin/test/env/t)
==523==  Address 0x4c28040 is 0 bytes inside a block of size 10 free'd
==523==    at 0x4A0595D: free (vg_replace_malloc.c:366)
==523==    by 0x4005D7: main (in /storage2/home3/ademin/test/env/t)
==523==
==523== Invalid read of size 1
==523==    at 0x4A07D14: __GI_strncmp (mc_replace_strmem.c:400)
==523==    by 0x3E1C235649: __add_to_environ (in /lib64/libc-2.12.so)
==523==    by 0x3E1C2353CD: putenv (in /lib64/libc-2.12.so)
==523==    by 0x4A0952D: putenv (mc_replace_strmem.c:1165)
==523==    by 0x400607: main (in /storage2/home3/ademin/test/env/t)
==523==  Address 0x4c28040 is 0 bytes inside a block of size 10 free'd
==523==    at 0x4A0595D: free (vg_replace_malloc.c:366)
==523==    by 0x4005D7: main (in /storage2/home3/ademin/test/env/t)
==523==
==523== Invalid read of size 1
==523==    at 0x3E1C235652: __add_to_environ (in /lib64/libc-2.12.so)
==523==    by 0x3E1C2353CD: putenv (in /lib64/libc-2.12.so)
==523==    by 0x4A0952D: putenv (mc_replace_strmem.c:1165)
==523==    by 0x400607: main (in /storage2/home3/ademin/test/env/t)
==523==  Address 0x4c28041 is 1 bytes inside a block of size 10 free'd
==523==    at 0x4A0595D: free (vg_replace_malloc.c:366)
==523==    by 0x4005D7: main (in /storage2/home3/ademin/test/env/t)
==523==
==523==
==523== HEAP SUMMARY:
==523==     in use at exit: 0 bytes in 0 blocks
==523==   total heap usage: 3 allocs, 3 frees, 492 bytes allocated
==523==
==523== All heap blocks were freed -- no leaks are possible
==523==
==523== For counts of detected and suppressed errors, rerun with: -v
==523== ERROR SUMMARY: 3 errors from 3 contexts (suppressed: 6 from 6)
</code></pre>

<p>But if to remove the first <code>free(v1);</code> or move it further down <strong>after</strong> the
second <code>putenv</code>, the valgrind report becomes clean, nothing bad happens.</p>

<h2>The conclusion</h2>

<p>The <code>putenv</code> function requires that at the moment of setting the new value of
a variable the previous value must still exist and be in valid memory
(literally it cannot be freed or moved to another location).</p>

<p>For some reason <code>putenv</code> tries reading the previous value when setting the new
one.</p>

<p>Now go back to C++. If the original code:</p>

<pre class="hl">
    <span class="hl kwa">if</span> <span class="hl opt">(!</span>inserted<span class="hl opt">.</span>second<span class="hl opt">)</span>
      inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second <span class="hl opt">=</span> pair<span class="hl opt">;</span>
</pre>

<p>is replaced to:</p>

<pre class="hl">
    <span class="hl kwa">if</span> <span class="hl opt">(!</span>inserted<span class="hl opt">.</span>second<span class="hl opt">)</span>
      inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second<span class="hl opt">.</span><span class="hl kwd">swap</span><span class="hl opt">(</span>pair<span class="hl opt">);</span>
</pre>

<p>the issue disappears (valgrind doesn&rsquo;t find anything suspecious anymore).</p>

<p>Why? The first code destroys (frees, reallocates) the existing value when
copying the value of <code>pair</code> into the map. That is why the subsequent call to
<code>putenv</code> tries reading a freed memory location.</p>

<p>The second code doing <code>swap</code> only moves the ownership of the data controlled
by <code>pair</code> to the element of the map, and in turn the data owned by the
element of the map (the existing value) is moved into the <code>pair</code> variable.
The <code>pair</code> variable goes out of scope and frees its data only at the end
of the function, clearly after calling <code>putenv</code>, so by postponing freeing
memory of existing value we allow <code>putenv</code> to read it without any problems.</p>

<p>This is it! End of story.</p>

<p>Frankly, this is the most complicated bug in C++ memory management I came
across recently.</p>

<p>Be aware.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[snprintf() on different platforms]]></title>
    <link href="http://demin.ws/blog/english/2013/01/28/use-snprintf-on-different-platforms/"/>
    <updated>2013-01-28T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2013/01/28/use-snprintf-on-different-platforms/</id>
    <content type="html"><![CDATA[<p>The <code>snprintf()</code> is considered to be &ldquo;good&rdquo; for formatting in C in terms of
the buffer overrun problem. But similarly to other functions supporting the
maximum buffer size there is a tricky moment &ndash; dealing with the trailing
zero character if the buffer isn&rsquo;t big enough.</p>

<p>I wanted some clarity in this question, so I wrote the following test
program:</p>

<pre><code>#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#ifdef WINDOWS
#define snprintf _snprintf
#endif
void test(const int capacity) {
  char buf[1024];
  int n;
  strcpy(buf, &quot;abcdefghijk&quot;);
  n = snprintf(buf, capacity, &quot;%d&quot;, 123);
  printf(&quot;capacity=%d, n=%d, buf=[%s] (length %d)\n&quot;,
         capacity, n, buf, (int)strlen(buf));
}

int main() {
  test(0);
  test(1);
  test(2);
  test(3);
  test(4);
  test(5);
  return 0;
}
</code></pre>

<p>The program tests how <code>snprintf()</code> deals with the buffer when there is no
room for the full result, and whether it adds the trailing <code>\0</code> in this case.</p>

<p>I&rsquo;ll be testing on different systems and compilers.</p>

<h2>Solaris SunOS 5.10 SPARC, Sun C 5.8</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>Solaris SunOS 5.10 SPARC, Sun C 5.12</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>Solaris SunOS 5.10 Intel x86, Sun C 5.12</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>Solaris SunOS 5.11 Intel x86, Sun C 5.12</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>Linux 2.6.18 x64, gcc 4.1.2</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>Linux 2.6.32 x64, gcc 4.4.6</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>HP-UX B.11.31 Itanium 64, HP C/aC++ B3910B A.06.22</h2>

<pre><code>capacity=0, n=0, buf=[abcdefghijk] (length 11)
capacity=1, n=-1, buf=[] (length 0)
capacity=2, n=-1, buf=[1] (length 1)
capacity=3, n=-1, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>AIX 5.3 (PowerPC), IBM XL C/C++ 8.0.0.20</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>AIX 6.1 (PowerPC), IBM XL C/C++ 9.0.0.0</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>AIX 6.1 (PowerPC), IBM XL C/C++ 9.0.0.15</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>AIX 7.1 (PowerPC), IBM XL C/C++ 11.1.0.0</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>Windows 7, Visual Studio 12 (17.00.50727.1), x86</h2>

<pre><code>capacity=0, n=-1, buf=[abcdefghijk] (length 11)
capacity=1, n=-1, buf=[1bcdefghijk] (length 11)
capacity=2, n=-1, buf=[12cdefghijk] (length 11)
capacity=3, n=3, buf=[123defghijk] (length 11)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>Windows 7, Visual Studio 12 (17.00.50727.1), x64</h2>

<pre><code>capacity=0, n=-1, buf=[abcdefghijk] (length 11)
capacity=1, n=-1, buf=[1bcdefghijk] (length 11)
capacity=2, n=-1, buf=[12cdefghijk] (length 11)
capacity=3, n=3, buf=[123defghijk] (length 11)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>OSX 10.7.5, Apple clang 4.1</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h2>OSX 10.7.5, Apple gcc/llmv 4.2.1</h2>

<pre><code>capacity=0, n=3, buf=[abcdefghijk] (length 11)
capacity=1, n=3, buf=[] (length 0)
capacity=2, n=3, buf=[1] (length 1)
capacity=3, n=3, buf=[12] (length 2)
capacity=4, n=3, buf=[123] (length 3)
capacity=5, n=3, buf=[123] (length 3)
</code></pre>

<h1>The conclusion</h1>

<p>On all UNIX systems (SunOS, Linux, AIX, OSX), except HP-UX, the buffer is not
touched if it is capacity is 0. Also, the trailing <code>\0</code> is counted in the
length of the output (if the buffer size is 1 it can fit only one character,
and this character is the trailing zero). Finally, the function returns the
length of data which would be written if the buffer has enough room. This
length can be used to allocate another, big enough buffer and call the function
once again.</p>

<p>Alas, on HP-UX, if the buffer cannot fit the result, the function returns -1.
In this case it is not clear how to figure out the required length of the
buffer. By the dichotomy method?</p>

<p>On Windows the situation is even worse. First, the function returns -1 similar
to HP-UX if the buffer is not big enough. Second, it does not count the trailing
zero in the length of its output, which means it does not append the trailing
zero at all in the situation of the small buffer. Though, Microsoft does not
recommend using <code>snprintf()</code> at all as a non-thread safe function, and
recommends <code>_snprintf_s()</code> instead.</p>

<p>It is obvious now why there are so many &ldquo;a portable snprintf&rdquo; implementations
in the internet.</p>

<h1>Bonus</h1>

<p>In my particular case I would be happy using <a href="http://linux.die.net/man/3/asprintf">asprintf</a> as an easy to use
alternative, but this function is not standard, and, for instance, HP-UX
does not support it.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An environment variables manager class]]></title>
    <link href="http://demin.ws/blog/english/2013/01/12/environment-variables-manager/"/>
    <updated>2013-01-12T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2013/01/12/environment-variables-manager/</id>
    <content type="html"><![CDATA[<p>I haven&rsquo;t publish code quite a long time. Let&rsquo;s get back to the roots.</p>

<p>The <code>putenv()</code> function has a quite unpleasant property. It doesn&rsquo;t take a
copy of its argument using it directly by pointer. Moreover, the argument
is a non-const pointer. So, it is impossible to pass automatic or
temporary objects, and even passing constant strings (which are persistent
by default) we need to cast them to non-const ones, which is not quite right.
All of this encourages such nonsense like <code>malloc</code> or <code>strdup</code>.</p>

<p>So, there is a class below called <code>EnvironmentVariablesManager</code>. This is a
simple wrapper around <code>putenv()</code> and <code>getenv()</code> proving persistent storage
for the values passed to <code>putenv()</code> (in the form of &ldquo;name=value&rdquo;) .</p>

<p>The class is designed to work on Linux, AIX, HP-UX, Solaris and Windows.</p>

<p>EnvironmentVariablesManager.h file:</p>

<pre class="hl">
<span class="hl ppc">#ifndef ENVIRONMENT_VARIABLE_MANAGER_H</span>
<span class="hl ppc">#define ENVIRONMENT_VARIABLE_MANAGER_H</span>

<span class="hl ppc">#include &lt;string&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>
<span class="hl ppc">#include &lt;map&gt;</span>

<span class="hl kwc">class</span> EnvironmentVariablesManager <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwc">typedef</span> std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">char</span><span class="hl opt">&gt;</span> VariableContainer<span class="hl opt">;</span>
  <span class="hl kwc">typedef</span> std<span class="hl opt">::</span>map<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>string<span class="hl opt">,</span> VariableContainer<span class="hl opt">&gt;</span> Variables<span class="hl opt">;</span>

  <span class="hl kwd">EnvironmentVariablesManager</span><span class="hl opt">() {}</span>

  <span class="hl kwb">void</span> <span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> value<span class="hl opt">);</span>
  std<span class="hl opt">::</span>string <span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">)</span> <span class="hl kwb">const</span><span class="hl opt">;</span>
  <span class="hl kwb">void</span> <span class="hl kwd">del</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">);</span>

  <span class="hl kwb">static void</span> <span class="hl kwd">PutOSVariable</span><span class="hl opt">(</span><span class="hl kwb">char</span><span class="hl opt">*</span> value<span class="hl opt">);</span>
  <span class="hl kwb">static</span> std<span class="hl opt">::</span>string <span class="hl kwd">GetOSVariable</span><span class="hl opt">(</span><span class="hl kwb">const char</span><span class="hl opt">*</span> name<span class="hl opt">);</span>
  <span class="hl kwb">static bool</span> <span class="hl kwd">IsOSVariableSet</span><span class="hl opt">(</span><span class="hl kwb">const char</span><span class="hl opt">*</span> name<span class="hl opt">);</span>

 <span class="hl kwc">private</span><span class="hl opt">:</span>
  VariableContainer <span class="hl kwd">PairToContainer</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">,</span>
                                    <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> value<span class="hl opt">)</span> <span class="hl kwb">const</span><span class="hl opt">;</span>
  Variables vars_<span class="hl opt">;</span>

  <span class="hl slc">// This class is not copiable.</span>
  <span class="hl kwd">EnvironmentVariablesManager</span><span class="hl opt">(</span><span class="hl kwb">const</span> EnvironmentVariablesManager<span class="hl opt">&amp;);</span>
  <span class="hl kwb">void</span> <span class="hl kwc">operator</span><span class="hl opt">=(</span><span class="hl kwb">const</span> EnvironmentVariablesManager<span class="hl opt">&amp;);</span>
<span class="hl opt">};</span>

<span class="hl ppc">#endif</span>
</pre>

<p>EnvironmentVariablesManager.cpp file:</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;EnvironmentVariablesManager.h&quot;</span><span class="hl ppc"></span>

<span class="hl ppc">#ifdef WINDOWS</span>
<span class="hl ppc">#include &lt;windows.h&gt;</span>
<span class="hl ppc">#else</span>
<span class="hl ppc">#include &lt;unistd.h&gt;</span>
<span class="hl ppc">#endif</span>

<span class="hl ppc">#include &lt;vector&gt;</span>
<span class="hl ppc">#include &lt;map&gt;</span>
<span class="hl ppc">#include &lt;string&gt;</span>
<span class="hl ppc">#include &lt;iterator&gt;</span>
<span class="hl ppc">#include &lt;algorithm&gt;</span>

<span class="hl ppc">#include &lt;cassert&gt;</span>

<span class="hl kwb">void</span> EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">,</span>
                                      <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span>
  <span class="hl kwb">const</span> VariableContainer pair <span class="hl opt">=</span> <span class="hl kwd">PairToContainer</span><span class="hl opt">(</span>name<span class="hl opt">,</span> value<span class="hl opt">);</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>pair<span class="hl opt">&lt;</span>Variables<span class="hl opt">::</span>iterator<span class="hl opt">,</span> <span class="hl kwb">bool</span><span class="hl opt">&gt;</span> inserted <span class="hl opt">=</span>
    vars_<span class="hl opt">.</span><span class="hl kwd">insert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">make_pair</span><span class="hl opt">(</span>name<span class="hl opt">,</span> pair<span class="hl opt">));</span>
  <span class="hl kwa">if</span> <span class="hl opt">(!</span>inserted<span class="hl opt">.</span>second<span class="hl opt">)</span>
    inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second <span class="hl opt">=</span> pair<span class="hl opt">;</span>
  <span class="hl kwb">char</span><span class="hl opt">*</span> data <span class="hl opt">= &amp;(</span>inserted<span class="hl opt">.</span>first<span class="hl opt">-&gt;</span>second<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">]);</span>
  <span class="hl kwd">PutOSVariable</span><span class="hl opt">(</span>data<span class="hl opt">);</span>
<span class="hl opt">}</span>

std<span class="hl opt">::</span>string EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">)</span> <span class="hl kwb">const</span> <span class="hl opt">{</span>
  <span class="hl kwa">return</span> <span class="hl kwd">GetOSVariable</span><span class="hl opt">(</span>name<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">());</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">del</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">) {</span>
  <span class="hl kwd">put</span><span class="hl opt">(</span>name<span class="hl opt">,</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">PutOSVariable</span><span class="hl opt">(</span><span class="hl kwb">char</span><span class="hl opt">*</span> value<span class="hl opt">) {</span>
  <span class="hl opt">::</span><span class="hl kwd">putenv</span><span class="hl opt">(</span>value<span class="hl opt">);</span>
<span class="hl opt">}</span>

std<span class="hl opt">::</span>string EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">GetOSVariable</span><span class="hl opt">(</span><span class="hl kwb">const char</span><span class="hl opt">*</span> name<span class="hl opt">) {</span>
<span class="hl ppc">#ifdef WINDOWS</span>
  <span class="hl kwb">size_t</span> sz <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span><span class="hl kwd">getenv_s</span><span class="hl opt">(&amp;</span>sz<span class="hl opt">,</span> NULL<span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">,</span> name<span class="hl opt">) ==</span> <span class="hl num">0</span><span class="hl opt">);</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>sz <span class="hl opt">==</span> <span class="hl num">0</span><span class="hl opt">)</span> <span class="hl kwa">return</span> std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">char</span><span class="hl opt">&gt;</span> <span class="hl kwd">value</span><span class="hl opt">(</span>sz <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span><span class="hl kwd">getenv_s</span><span class="hl opt">(&amp;</span>sz<span class="hl opt">, &amp;</span>value<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">],</span> sz<span class="hl opt">,</span> name<span class="hl opt">) ==</span> <span class="hl num">0</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(&amp;</span>value<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">],</span> sz <span class="hl opt">-</span> <span class="hl num">1</span><span class="hl opt">);</span>
<span class="hl ppc">#else</span>
  <span class="hl kwb">const char</span><span class="hl opt">*</span> <span class="hl kwb">const</span> value <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">getenv</span><span class="hl opt">(</span>name<span class="hl opt">);</span>
  <span class="hl kwa">return</span> value ? value <span class="hl opt">:</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">;</span>
<span class="hl ppc">#endif</span>
<span class="hl opt">}</span>

<span class="hl kwb">bool</span> EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">IsOSVariableSet</span><span class="hl opt">(</span><span class="hl kwb">const char</span><span class="hl opt">*</span> name<span class="hl opt">) {</span>
<span class="hl ppc">#ifdef WINDOWS</span>
  <span class="hl kwb">size_t</span> sz <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span><span class="hl kwd">getenv_s</span><span class="hl opt">(&amp;</span>sz<span class="hl opt">,</span> NULL<span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">,</span> name<span class="hl opt">) ==</span> <span class="hl num">0</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> sz <span class="hl opt">&gt;</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl ppc">#else</span>
  <span class="hl kwb">const char</span><span class="hl opt">*</span> value <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">getenv</span><span class="hl opt">(</span>name<span class="hl opt">);</span>
  <span class="hl kwa">return</span> value <span class="hl opt">!=</span> NULL <span class="hl opt">&amp;&amp; *</span>value <span class="hl opt">!=</span> <span class="hl str">'\0'</span><span class="hl opt">;</span>
<span class="hl ppc">#endif</span>
<span class="hl opt">}</span>

EnvironmentVariablesManager<span class="hl opt">::</span>VariableContainer 
EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">PairToContainer</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">,</span>
                                             <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> value<span class="hl opt">)</span> <span class="hl kwb">const</span> <span class="hl opt">{</span>
  VariableContainer pair<span class="hl opt">;</span>                                            
  std<span class="hl opt">::</span><span class="hl kwd">copy</span><span class="hl opt">(</span>name<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> name<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> std<span class="hl opt">::</span><span class="hl kwd">back_inserter</span><span class="hl opt">(</span>pair<span class="hl opt">));</span>
  pair<span class="hl opt">.</span><span class="hl kwd">push_back</span><span class="hl opt">(</span><span class="hl str">'='</span><span class="hl opt">);</span>
  std<span class="hl opt">::</span><span class="hl kwd">copy</span><span class="hl opt">(</span>value<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> value<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> std<span class="hl opt">::</span><span class="hl kwd">back_inserter</span><span class="hl opt">(</span>pair<span class="hl opt">));</span>
  pair<span class="hl opt">.</span><span class="hl kwd">push_back</span><span class="hl opt">(</span><span class="hl str">'\0'</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> pair<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Unit-tests using <code>std::assert</code>.</p>

<p>EnvironmentVariablesManager_unittest.cpp file:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;string&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>
<span class="hl ppc">#include &lt;cstdlib&gt;</span>
<span class="hl ppc">#include &lt;cstring&gt;</span>
<span class="hl ppc">#include &lt;cassert&gt;</span>

<span class="hl ppc">#ifdef WINDOWS</span>
<span class="hl ppc">#include &lt;windows.h&gt;</span>
<span class="hl ppc">#else</span>
<span class="hl ppc">#include &lt;stdlib.h&gt;</span>
<span class="hl ppc">#include &lt;stdio.h&gt;</span>
<span class="hl ppc">#include &lt;unistd.h&gt;</span>
<span class="hl ppc">#endif</span>

<span class="hl ppc">#include</span> <span class="hl pps">&quot;EnvironmentVariablesManager.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwb">void</span> <span class="hl kwd">Test_EnvironmentVariablesManager_get_put</span><span class="hl opt">() {</span>
  EnvironmentVariablesManager env<span class="hl opt">;</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span><span class="hl str">&quot;&quot;</span><span class="hl opt">) ==</span> env<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl str">&quot;_a_unique_variable_&quot;</span><span class="hl opt">));</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;_a_unique_variable_&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;b&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span><span class="hl str">&quot;b&quot;</span><span class="hl opt">) ==</span> env<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl str">&quot;_a_unique_variable_&quot;</span><span class="hl opt">));</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;_a_unique_variable_&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;abc&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span><span class="hl str">&quot;abc&quot;</span><span class="hl opt">) ==</span> env<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl str">&quot;_a_unique_variable_&quot;</span><span class="hl opt">));</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;_a_unique_variable_&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span><span class="hl str">&quot;&quot;</span><span class="hl opt">) ==</span> env<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl str">&quot;_a_unique_variable_&quot;</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

<span class="hl kwa">namespace</span> <span class="hl opt">{</span>
std<span class="hl opt">::</span>string <span class="hl kwd">ReadEnvironmentVariableViaShell</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">) {</span>
<span class="hl ppc">#ifdef WINDOWS</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string shell <span class="hl opt">=</span>
    EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">GetOSVariable</span><span class="hl opt">(</span><span class="hl str">&quot;ComSpec&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(!</span>shell<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string cmd <span class="hl opt">=</span> shell <span class="hl opt">+</span> <span class="hl str">&quot; /c echo %&quot;</span> <span class="hl opt">+</span> name <span class="hl opt">+</span> <span class="hl str">&quot;%&quot;</span><span class="hl opt">;</span>
  <span class="hl kwb">FILE</span><span class="hl opt">*</span> <span class="hl kwb">const</span> f <span class="hl opt">=</span> <span class="hl kwd">_popen</span><span class="hl opt">(</span>cmd<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">(),</span> <span class="hl str">&quot;rb&quot;</span><span class="hl opt">);</span>
<span class="hl ppc">#else</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string cmd <span class="hl opt">=</span> <span class="hl str">&quot;echo $&quot;</span> <span class="hl opt">+</span> name<span class="hl opt">;</span>
  <span class="hl kwb">FILE</span><span class="hl opt">*</span> <span class="hl kwb">const</span> f <span class="hl opt">=</span> <span class="hl kwd">popen</span><span class="hl opt">(</span>cmd<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">(),</span> <span class="hl str">&quot;r&quot;</span><span class="hl opt">);</span>
<span class="hl ppc">#endif</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>f <span class="hl opt">!=</span> NULL<span class="hl opt">);</span>
  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">char</span><span class="hl opt">&gt;</span> <span class="hl kwd">line</span><span class="hl opt">(</span><span class="hl num">1024</span><span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">);</span>
  <span class="hl kwb">size_t</span> read <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">while</span> <span class="hl opt">(!::</span><span class="hl kwd">feof</span><span class="hl opt">(</span>f<span class="hl opt">) &amp;&amp;</span> read <span class="hl opt">&lt;</span> line<span class="hl opt">.</span><span class="hl kwd">size</span><span class="hl opt">()) {</span>
    <span class="hl kwb">const size_t</span> sz <span class="hl opt">= ::</span><span class="hl kwd">fread</span><span class="hl opt">(&amp;</span>line<span class="hl opt">[</span>read<span class="hl opt">],</span> <span class="hl num">1</span><span class="hl opt">,</span> line<span class="hl opt">.</span><span class="hl kwd">size</span><span class="hl opt">() -</span> read<span class="hl opt">,</span> f<span class="hl opt">);</span>
    read <span class="hl opt">+=</span> sz<span class="hl opt">;</span>
  <span class="hl opt">}</span>
<span class="hl ppc">#ifdef WINDOWS</span>
  <span class="hl opt">::</span><span class="hl kwd">_pclose</span><span class="hl opt">(</span>f<span class="hl opt">);</span>
<span class="hl ppc">#else</span>
  <span class="hl opt">::</span><span class="hl kwd">pclose</span><span class="hl opt">(</span>f<span class="hl opt">);</span>
<span class="hl ppc">#endif</span>
  line<span class="hl opt">.</span><span class="hl kwd">resize</span><span class="hl opt">(</span>read<span class="hl opt">);</span>
  std<span class="hl opt">::</span>string <span class="hl kwd">trimmed</span><span class="hl opt">(</span>read<span class="hl opt">,</span> <span class="hl str">'\0'</span><span class="hl opt">);</span>
  std<span class="hl opt">::</span><span class="hl kwd">copy</span><span class="hl opt">(</span>line<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> line<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> trimmed<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">());</span>
  <span class="hl kwa">return</span> trimmed<span class="hl opt">.</span><span class="hl kwd">substr</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> trimmed<span class="hl opt">.</span><span class="hl kwd">find_last_not_of</span><span class="hl opt">(</span><span class="hl str">&quot;</span><span class="hl esc">\r\n</span><span class="hl str">&quot;</span><span class="hl opt">) +</span> <span class="hl num">1</span><span class="hl opt">);</span>
<span class="hl opt">}</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">Test_EnvironmentVariablesManager_put_is_propagated_to_child_process</span><span class="hl opt">() {</span>
  EnvironmentVariablesManager env<span class="hl opt">;</span>
<span class="hl ppc">#ifdef WINDOWS</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string empty <span class="hl opt">=</span> <span class="hl str">&quot;%__unique_%&quot;</span><span class="hl opt">;</span>
<span class="hl ppc">#else</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string empty <span class="hl opt">=</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">;</span>
<span class="hl ppc">#endif</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>empty <span class="hl opt">==</span> <span class="hl kwd">ReadEnvironmentVariableViaShell</span><span class="hl opt">(</span><span class="hl str">&quot;__unique_&quot;</span><span class="hl opt">));</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;__unique_&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;b&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span><span class="hl str">&quot;b&quot;</span><span class="hl opt">) ==</span> <span class="hl kwd">ReadEnvironmentVariableViaShell</span><span class="hl opt">(</span><span class="hl str">&quot;__unique_&quot;</span><span class="hl opt">));</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;__unique_&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>empty <span class="hl opt">==</span> <span class="hl kwd">ReadEnvironmentVariableViaShell</span><span class="hl opt">(</span><span class="hl str">&quot;__unique_&quot;</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">Test_EnvironmentVariablesManager_must_take_a_copy</span><span class="hl opt">() {</span>
  EnvironmentVariablesManager env<span class="hl opt">;</span>
  <span class="hl kwb">char</span> var<span class="hl opt">[] =</span> <span class="hl str">&quot;12345678&quot;</span><span class="hl opt">;</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;var&quot;</span><span class="hl opt">,</span> var<span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>env<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl str">&quot;var&quot;</span><span class="hl opt">) ==</span> std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span><span class="hl str">&quot;12345678&quot;</span><span class="hl opt">));</span>
  std<span class="hl opt">::</span><span class="hl kwd">strcpy</span><span class="hl opt">(</span>var<span class="hl opt">,</span> <span class="hl str">&quot;abc&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>env<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl str">&quot;var&quot;</span><span class="hl opt">) ==</span> std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span><span class="hl str">&quot;12345678&quot;</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">Test_EnvironmentVariablesManager_del</span><span class="hl opt">() {</span>
  EnvironmentVariablesManager env<span class="hl opt">;</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;variable_to_delete&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;123&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span><span class="hl str">&quot;123&quot;</span><span class="hl opt">) ==</span> env<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl str">&quot;variable_to_delete&quot;</span><span class="hl opt">));</span>
  env<span class="hl opt">.</span><span class="hl kwd">del</span><span class="hl opt">(</span><span class="hl str">&quot;variable_to_delete&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>env<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl str">&quot;variable_to_delete&quot;</span><span class="hl opt">).</span><span class="hl kwd">empty</span><span class="hl opt">() ==</span> <span class="hl kwa">true</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">Test_EnvironmentVariablesManager_IsOSVariableSet_set_and_unset</span><span class="hl opt">() {</span>
  EnvironmentVariablesManager env<span class="hl opt">;</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;value&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">IsOSVariableSet</span><span class="hl opt">(</span><span class="hl str">&quot;a&quot;</span><span class="hl opt">) ==</span> <span class="hl kwa">true</span><span class="hl opt">);</span>
  env<span class="hl opt">.</span><span class="hl kwd">put</span><span class="hl opt">(</span><span class="hl str">&quot;a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">IsOSVariableSet</span><span class="hl opt">(</span><span class="hl str">&quot;a&quot;</span><span class="hl opt">) ==</span> <span class="hl kwa">false</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">Test_EnvironmentVariablesManager_GetOSVariable</span><span class="hl opt">() {</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string unique_name <span class="hl opt">=</span> <span class="hl str">&quot;EnvironmentVariablesManager_GetOSVariable&quot;</span><span class="hl opt">;</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">GetOSVariable</span><span class="hl opt">(</span>unique_name<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">())</span>
                                                    <span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string unique_name_pair <span class="hl opt">=</span> unique_name <span class="hl opt">+</span> <span class="hl str">&quot;=12345678&quot;</span><span class="hl opt">;</span>
  <span class="hl kwb">char</span> var<span class="hl opt">[</span><span class="hl num">1024</span><span class="hl opt">];</span>
  unique_name_pair<span class="hl opt">.</span><span class="hl kwd">copy</span><span class="hl opt">(</span>var<span class="hl opt">,</span> <span class="hl kwa">sizeof</span><span class="hl opt">(</span>var<span class="hl opt">));</span>
  var<span class="hl opt">[</span>unique_name_pair<span class="hl opt">.</span><span class="hl kwd">length</span><span class="hl opt">()] =</span> <span class="hl str">'\0'</span><span class="hl opt">;</span>
  <span class="hl opt">::</span><span class="hl kwd">putenv</span><span class="hl opt">(</span>var<span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">GetOSVariable</span><span class="hl opt">(</span>unique_name<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">())</span>
                                                    <span class="hl opt">==</span> <span class="hl str">&quot;12345678&quot;</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">Test_EnvironmentVariablesManager_PutOSVariable</span><span class="hl opt">() {</span>
  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string unique_name <span class="hl opt">=</span> <span class="hl str">&quot;EnvironmentVariablesManager_PutOSVariable&quot;</span><span class="hl opt">;</span>
  <span class="hl kwb">const char</span><span class="hl opt">*</span> before <span class="hl opt">= ::</span><span class="hl kwd">getenv</span><span class="hl opt">(</span>unique_name<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">());</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>before <span class="hl opt">!=</span> NULL<span class="hl opt">)</span>
    <span class="hl kwa">assert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span>before<span class="hl opt">).</span><span class="hl kwd">empty</span><span class="hl opt">());</span>

  <span class="hl kwb">const</span> std<span class="hl opt">::</span>string unique_name_pair <span class="hl opt">=</span> unique_name <span class="hl opt">+</span> <span class="hl str">&quot;=12345678&quot;</span><span class="hl opt">;</span>
  <span class="hl kwb">char</span> var<span class="hl opt">[</span><span class="hl num">1024</span><span class="hl opt">];</span>
  unique_name_pair<span class="hl opt">.</span><span class="hl kwd">copy</span><span class="hl opt">(</span>var<span class="hl opt">,</span> <span class="hl kwa">sizeof</span><span class="hl opt">(</span>var<span class="hl opt">));</span>
  var<span class="hl opt">[</span>unique_name_pair<span class="hl opt">.</span><span class="hl kwd">length</span><span class="hl opt">()] =</span> <span class="hl str">'\0'</span><span class="hl opt">;</span>

  EnvironmentVariablesManager<span class="hl opt">::</span><span class="hl kwd">PutOSVariable</span><span class="hl opt">(</span>var<span class="hl opt">);</span>
  <span class="hl kwb">const char</span><span class="hl opt">*</span> after <span class="hl opt">= ::</span><span class="hl kwd">getenv</span><span class="hl opt">(</span>unique_name<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">());</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>after <span class="hl opt">!=</span> NULL<span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span>after<span class="hl opt">) ==</span> <span class="hl str">&quot;12345678&quot;</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">run_tests</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">const char</span><span class="hl opt">*</span> <span class="hl kwb">const</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwd">Test_EnvironmentVariablesManager_GetOSVariable</span><span class="hl opt">();</span>
  <span class="hl kwd">Test_EnvironmentVariablesManager_PutOSVariable</span><span class="hl opt">();</span>
  <span class="hl kwd">Test_EnvironmentVariablesManager_get_put</span><span class="hl opt">();</span>
  <span class="hl kwd">Test_EnvironmentVariablesManager_put_is_propagated_to_child_process</span><span class="hl opt">();</span>
  <span class="hl kwd">Test_EnvironmentVariablesManager_must_take_a_copy</span><span class="hl opt">();</span>
  <span class="hl kwd">Test_EnvironmentVariablesManager_del</span><span class="hl opt">();</span>
  <span class="hl kwd">Test_EnvironmentVariablesManager_IsOSVariableSet_set_and_unset</span><span class="hl opt">();</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">const char</span><span class="hl opt">*</span> <span class="hl kwb">const</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwd">run_tests</span><span class="hl opt">(</span>argc<span class="hl opt">,</span> argv<span class="hl opt">);</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;All tests pass.&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Overall, nothing really intricate but quite handy.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The OMNI-395 payment terminal inside]]></title>
    <link href="http://demin.ws/blog/english/2013/01/04/omni395/"/>
    <updated>2013-01-04T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2013/01/04/omni395/</id>
    <content type="html"><![CDATA[<p>First time I encountered specialized mini- and micro- computers was at the beginning
of 2000 when I got a job in the plastic card processing department of a bank.
I started developing software for Point Of Sale (POS) terminals.
POS is a standalone mini-computer, usually with a screen, keyboard,
magnetic stripe reader, and often a printer, plus nowadays with a chip and
pin reader.</p>

<p>My first POS was VeriFone OMNI-395. It was based on Zilog Z180, up to 1M
non-volatile memory (for transaction logs, for instance), a Hayes compatible
modem (up to 2400BPS), 12 volts RS232 ports for a PIN pad, a serial printer
and other devices (alas, not all RS232 ports had all standard line causing
inventing a handmade wheel for the flow control.), and an LCD-screen with
loadable fonts.</p>

<p><img src="http://demin.ws/blog/english/2013/01/04/omni395/IMG_1621.JPG" alt="" />
</p>

<p>The architecture was pretty interesting. The user code was executed inside
a VM running on top of native Z180 code. It allowed dealing with larger
amounts of memory which Z180 can address directly, and implementing dynamically
loadable user modules (R-modules). Unfortunately it affected overall
performance, and, for example, even table-driven CRC16 on 5-10KB of data
took a few seconds. Also, the stack size in the C language was quite limited,
and sometimes it was worth implementing, for example, the &ldquo;sprintf&rdquo; function
manually to avoid random crashes due to stack overflows.</p>

<p><img src="http://demin.ws/blog/english/2013/01/04/omni395/IMG_1622.JPG" alt="" />
</p>

<p>But, frankly speaking, comparing to terminal from other vendors back those
days (Injenico, Nurit, etc.) where you had to deal with using raw memory
blocks, switching pages manually, etc., VeriFone (TXO) provided almost
standard C library. In TXO C you dealt with persistent files, serial ports, LCD
and other peripherals with read/write/ioctl functions.</p>

<p>The TXO C compiler supported support also loadable modules (R-modules).
Such modules can be loaded on the fly from the user code (similar to overlays
or CHAIN in the classic BASIC).</p>

<p>A few days ago The Frost Father presented me an old good OMNI-395. Do you
want to see it inside? Indeed!</p>

<p>Turn it on, and, (surprise!) it still runs my firmware.</p>

<p><img src="http://demin.ws/blog/english/2013/01/04/omni395/IMG_1623.JPG" alt="" />
</p>

<p>Inside.</p>

<p><img src="http://demin.ws/blog/english/2013/01/04/omni395/IMG_1624.JPG" alt="" />
</p>

<p>The top board, under the keypad, and the bottom one, with connectors.</p>

<p><img src="http://demin.ws/blog/english/2013/01/04/omni395/IMG_1635.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2013/01/04/omni395/IMG_1636.JPG" alt="" />
</p>

<p>If I find the compiler and loader I&rsquo;ll try to write a little demo.</p>

<p>Alas, there is no official documentation about OMNI-395 hardware, but the
programmer manuals only cover the standard library and the VM a little bit.</p>

<p>Of course, OMNI-395 can be used as a generic controller. It can communicate via
the standard RS232, plus DTR/RTS can be digital output and CTS/DSR &ndash; inputs.</p>

<p>Ideally, it is possible to disassemble the ROM (only 64K of Z180 code), and
then reverse engineer the architecture. It will allow programming OMNI-395
directly in Z180 assembly.</p>

<h1>P.S.</h1>

<p>Despite of changing the hardware platform a few times after OMNI-395, VeriFone
also provides very good backward compatibility in the programmer&rsquo;s API. So,
porting to newer models is quite simple. After OMNI-395 I ported our POS
software to OMNI-3350, 3750, VX510, VX610.</p>

<p>An finally, by the <a href="https://twitter.com/search?q=%23cardpayments&amp;src=hash">#cardpayments</a> tag at Twitter I post pictures of POS,
PIN pads, ATM and other plastic card payment machines I come across. Please,
join.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A Serial VGA adapter]]></title>
    <link href="http://demin.ws/blog/english/2012/12/26/serial-vga/"/>
    <updated>2012-12-26T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/12/26/serial-vga/</id>
    <content type="html"><![CDATA[<p>I have tested a quite interesting breakout board &ndash; <a href="http://www.hobbytronics.co.uk/serial-vga">Serial VGA</a>. It
allows to organize multi-windows textual output via RS-232 (TTL) on a VGA
monitor.</p>

<p><img src="http://demin.ws/blog/english/2012/12/26/serial-vga/IMG_1284.jpg" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/26/serial-vga/IMG_1284.jpg" alt="" />
</p>

<p>The maximum window size is 100x50 with 64 colours. It supports up to 9
windows simultaneously. Each window is controlled independently via
special escape (<code>^[</code>) sequences.</p>

<p><img src="http://demin.ws/blog/english/2012/12/26/serial-vga/serial-vga-5.jpg" alt="" />
</p>

<p>In general &ndash; very useful for small projects on microcontrollers if you don&rsquo;t
bother doing VGA output by yourself (RS-232 output can be implemented even
manually if your microcontroller doesn&rsquo;t support it for some reason). I also
tested Serial VGA with Raspberry Pi. The only recommendation is to support the
CTS signal line on baud rates faster than 9600. Otherwise the device can loose
some characters.</p>

<p><a href="http://demin.ws/blog/english/2012/12/26/serial-vga/SerialVGA-1.0.pdf">The Serial VGA datasheet</a>.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[My collection of Intel 8080 microprocessors]]></title>
    <link href="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/"/>
    <updated>2012-12-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/12/24/my-i8080-collection/</id>
    <content type="html"><![CDATA[<p>I started programming twenty year ago coding in machine codes for Intel 8080.
This microprocessor was my lucky pass to the fascinating world of bits and
bytes. Years later developing various emulators of i8080 and tackling with
undocumented and partially documented features of this processor I decided to
collect real chips from different manufacturers and examine them using the
<a href="http://www.idb.me.uk/sunhillow/8080.html">8080 CPU Exerciser</a>.</p>

<p>At the moment I have 20 processors (from Intel, AMD, National Semiconductor,
NEC, Samsung, Texas Instruments, and also manufactured in the Soviet Union and
Czechoslovakia). Amongst chips having a year on the label the earliest is
dated back to 1974 and the latest is 1980. All CPUs except one are fully
functional. I tested them on my <a href="http://demin.ws/blog/russian/2012/10/07/rk86-sram/">Радио-86РК</a>.</p>

<p>Testing revealed that all processors are identical according to the CPU
Exerciser except clones from AMD. The AMD processors, AM8080 and AM9080A,
behave differently performing the bitwise AND operation (ANA and ANI
instruction). The original Intel CPUs and non-AMD clones set the AC
(half-carry) flag to the value of the 3rd bit (A3) from the bitwise OR between
the accumulator and the argument of ANA or ANI. The AMD clones always zero the
AC flag in the ANA and ANI instructions. I don&rsquo;t know why the original Intel
CPU calculates the AC flag in such a weird way.</p>

<h1>My i8080 chips</h1>

<p><em>The double click on the pictures flips the top and the bottom views</em>.</p>

<h2>AMD</h2>

<p>Interestingly, AMD i8080-compatible chips were reverse-engineered from
schematics literally stolen from Intel. So, the Intel vs AMD war began from
8080.</p>

<h3>8080A, 1977</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/AM8080A-8507DMA-1977-AMD-PHILIPPINES-top.jpg" alt="" />
</p>

<h3>AM9080, 1977</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/AM9080ACC-D8080A-8015HP-1977-AMD-top.jpg" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/AM9080ADCB-D8080AB-8102WP-1977-AMD-top.jpg" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/AM9080APC-P8080A-790EP-1977-AMD-top.jpg" alt="" />
</p>

<h2>National Semiconductor</h2>

<h3>INS8080AN</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/INS8080AN-P8080A-1927-P4798-CB-FAULTY-top.jpg" alt="" />
</p>

<p><em>This chip is faulty.</em></p>

<h3>INS8080AN</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/INS8080AN-P8080A-B8436-4798D-3062-top.jpg" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/INS8080AN-P8080A-B8436A-4798D-3133-top.jpg" alt="" />
</p>

<h2>Intel</h2>

<h3>1974</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/INTEL-P8080A-S2701-3626D-INTEL-74-MALAYSIA-7943-top.jpg" alt="" />
</p>

<h3>1977</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/INTEL-P8080A-2-L1307000-1977-8134-PHILIPPINES-top.jpg" alt="" />
</p>

<h3>1979</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/INTEL-P8080A-1-U3120121-INTEL-79-8311DT-PHILIPPINES-top.jpg" alt="" />
</p>

<h3>1980</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/INTEL-P8080A-L4480180E-INTEL-1980-top.jpg" alt="" />
</p>

<h2>Russia</h2>

<h3>KR580IK80A (КР580ИК80A)</h3>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/KR580IK80A-8608-top.jpg" alt="" />
</p>

<h3>KR580VM80A (КР580ВМ80A)</h3>

<p>There is the original mini-datasheet in Russian:
<a href="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/KR580VM80A-passport-1.jpg">page 1</a> and <a href="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/KR580VM80A-passport-2.jpg">page 2</a>.</p>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/KR580VM80-8941-top.jpg" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/KR580VM80A-911-615-top.jpg" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/KR580VM80A-9102-top.jpg" alt="" />
</p>

<h2>NEC</h2>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/NEC-JAPAN-D8080AFC-1-X05020-020-top.jpg" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/NEC-JAPAN-D8080AFC-P77236-top.jpg" alt="" />
</p>

<h2>Samsung</h2>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/SAB-8080-A-P-8036-top.jpg" alt="" />
</p>

<h2>Telsa (Czechoslovakia)</h2>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/TESLAU4M-MHB8080A-top.jpg" alt="" />
</p>

<h2>Texas Instruments</h2>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/TMS8080ANL-BP7718-H8080A-SINGAPORE-top.jpg" alt="" />
</p>

<hr />

<p>This is how I took pictures of all these chips in a quite technological way
using one iPhone and two Raspberry Pi:</p>

<p><img src="http://demin.ws/blog/english/2012/12/24/my-i8080-collection/taking-pictures-using-iphone-and-rpi.jpg" alt="" />
</p>

<script>
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; ++i) {
  var img = images[i];
  img.ondblclick = function() {
    var url = this.src;
    if (url.indexOf("-top") != -1)
      this.src = url.replace("-top", "-bottom");
    else
      this.src = url.replace("-bottom", "-top");
  }
}
</script>

<h2>P.S.</h2>

<p>I hope the collection will grow. I still have only one chip in white
ceramic packaging (KR580VM80). If you know i8080 clones from other
manufacturers, which are not listed here, I&rsquo;d appreciate if you let me know.</p>

<p>If you would like to donate any i8080 chip I&rsquo;ll be happy putting a reference
to you next to the image of the chip.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The fascinating apps I am happy to pay for]]></title>
    <link href="http://demin.ws/blog/english/2012/12/22/the-fascinating-apps-i-am-happy-to-pay-for/"/>
    <updated>2012-12-22T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/12/22/the-fascinating-apps-i-am-happy-to-pay-for/</id>
    <content type="html"><![CDATA[<p>Being a software developer sometimes plays against you as a regular user. When
you understand the software development &ldquo;kitchen&rdquo; from inside you become very
biased evaluating prices for software. Why $35? Why £120? Why 1800RUB? &ldquo;I
bloody know that it cannot cost that figure!!!&ldquo;. Obviously, the question is
a bit more complex than that visible tiny tip of the iceberg, even for the
experienced eye of the software developer.</p>

<p>And you know what, after joining the &ldquo;dark side&rdquo; army of Apple users,
particularly with Macbook Air, I become much more tolerant paying for
software. And the main reason is, you guess?, the <strong>easiness</strong> of a purchase.
With AppStore you just &ldquo;click-click&rdquo;, and an application jumps into your
Applications in a few seconds. Purchasing directly on web sites is usually
simple and smooth as well, especially if you pay using PayPal or Google
Wallet.</p>

<p>Moving even further, I listed some apps which I am <em>happy</em> to pay for.</p>

<ul>
<li><a href="http://mackeeper.zeobit.com/">MacKeeper</a>. In my view this is the number one
app for OSX.</li>
<li><a href="http://bjango.com/mac/istatmenus/">iStat</a>. This is the &ldquo;must have&rdquo; number
two.</li>
<li><a href="http://www.sublimetext.com/">Sublime</a>. You are a programmer and looking for
a text editor? This is the option you won&rsquo;t regret about.</li>
<li><a href="http://www.hopperapp.com/">Hopper Disassembler</a>. By nature I&rsquo;m a lower
level hacker, so this is the tool I need. I had fallen in love with this
app because of the unprecedented feature/price ratio comparing to IDA, its
&ldquo;big brother&rdquo;.</li>
</ul>

<p>Now a couple of apps which I also pay for but only because there are no
adequate alternatives. I&rsquo;m more or less happy with functionality but I don&rsquo;t
like their pricing (in short &ndash; too much in my view).</p>

<ul>
<li><a href="http://www.parallels.com/">Parallels</a>. Of course, I use VirtualBox
as well, but Parallels is so bloody good on OSX.</li>
<li><a href="http://www.orfo.ru/">ORFO</a>. I&rsquo;m Russian and always will, so I need a
spell and grammar checker integrated into the OS, and ORFO does it pretty
well.</li>
</ul>

<p>However, there is an app, which I&rsquo;m not willing to pay. Its price is
ridiculous. This is the Microsoft Office. Fortunately, the company
I work for provided me a license for this product, so I can work with
working documents on Mac. When it gets stopped I&rsquo;ll switch to the Apple
alternatives (Pages, Numbers and Keynotes).</p>

<p>And finally, there is an app called <a href="http://radare.org/y/">Radare</a>. It is free
and opensource, and I donated some amount to support this great project (I
hope not last time).</p>

<h2>P.S.</h2>

<p>Of course, there are tons of other free apps (iTerm, 7z, muCommander, Skype,
VirtualBox, GitHub, DOSBox, KeePassX, etc.), which I also use but this is a different story.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The console Snake game]]></title>
    <link href="http://demin.ws/blog/english/2012/12/10/snake-game/"/>
    <updated>2012-12-10T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/12/10/snake-game/</id>
    <content type="html"><![CDATA[<p>This code is not mine, I grabbed it from <a href="http://itblogs.org/c-konsolnaya-zmejka/">itblogs</a>. I cleaned up the code
a little bit, removed switching the console background color and added code
for Linux/OSX.</p>

<p>Agreed, the game is trivial, but I just liked it. Also, I tried <a href="http://ascii.io/">ascii.io</a>
recording an asciicast, so you can evaluate gameplay - <a href="http://ascii.io/a/1715">http://ascii.io/a/1715</a>.</p>

<p><a href="https://github.com/begoon/stuff/tree/master/games/snake/c++">The source</a> is available at GitHub&rsquo;е, but you can simply grab it below.</p>

<pre class="hl">
<span class="hl slc">// Originally taken from http://itblogs.org/c-konsolnaya-zmejka/.</span>

<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;cstdio&gt;</span>
<span class="hl ppc">#include &lt;cstdlib&gt;</span>
<span class="hl ppc">#include &lt;ctime&gt;</span>
<span class="hl ppc">#ifdef WINDOWS</span>
<span class="hl ppc">#include &lt;windows.h&gt;</span>
<span class="hl ppc">#include &lt;conio.h&gt;</span>
<span class="hl ppc">#else</span>
<span class="hl ppc">#include &lt;unistd.h&gt;</span>
<span class="hl ppc">#include &lt;termios.h&gt;</span>
<span class="hl ppc">#include &lt;sys/select.h&gt;</span>

<span class="hl ppc">#define STDIN_FILENO 0</span>
<span class="hl ppc">#define NB_DISABLE 0</span>
<span class="hl ppc">#define NB_ENABLE 1</span>

<span class="hl ppc">#define Sleep(x) usleep(x*1000)</span>

<span class="hl kwb">int</span> <span class="hl kwd">kbhit</span><span class="hl opt">() {</span>
  <span class="hl kwb">struct</span> timeval tv<span class="hl opt">;</span>
  fd_set fds<span class="hl opt">;</span>
  tv<span class="hl opt">.</span>tv_sec <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  tv<span class="hl opt">.</span>tv_usec <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwd">FD_ZERO</span><span class="hl opt">(&amp;</span>fds<span class="hl opt">);</span>
  <span class="hl kwd">FD_SET</span><span class="hl opt">(</span>STDIN_FILENO<span class="hl opt">, &amp;</span>fds<span class="hl opt">);</span>
  <span class="hl kwd">select</span><span class="hl opt">(</span>STDIN_FILENO<span class="hl opt">+</span><span class="hl num">1</span><span class="hl opt">, &amp;</span>fds<span class="hl opt">,</span> NULL<span class="hl opt">,</span> NULL<span class="hl opt">, &amp;</span>tv<span class="hl opt">);</span>
  <span class="hl kwa">return</span> <span class="hl kwd">FD_ISSET</span><span class="hl opt">(</span>STDIN_FILENO<span class="hl opt">, &amp;</span>fds<span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">nonblock</span><span class="hl opt">(</span><span class="hl kwb">int</span> state<span class="hl opt">) {</span>
  <span class="hl kwb">struct</span> termios ttystate<span class="hl opt">;</span>

  <span class="hl slc">// Get the terminal state.</span>
  <span class="hl kwd">tcgetattr</span><span class="hl opt">(</span>STDIN_FILENO<span class="hl opt">, &amp;</span>ttystate<span class="hl opt">);</span>

  <span class="hl kwa">if</span> <span class="hl opt">(</span>state <span class="hl opt">==</span> NB_ENABLE<span class="hl opt">) {</span>
    <span class="hl slc">// Turn off canonical mode.</span>
    ttystate<span class="hl opt">.</span>c_lflag <span class="hl opt">&amp;= ~</span>ICANON<span class="hl opt">;</span>
    <span class="hl slc">// Minimum of number input read.</span>
    ttystate<span class="hl opt">.</span>c_cc<span class="hl opt">[</span>VMIN<span class="hl opt">] =</span> <span class="hl num">1</span><span class="hl opt">;</span>
  <span class="hl opt">}</span> <span class="hl kwa">else if</span> <span class="hl opt">(</span>state <span class="hl opt">==</span> NB_DISABLE<span class="hl opt">) {</span>
    <span class="hl slc">// Turn on canonical mode.</span>
    ttystate<span class="hl opt">.</span>c_lflag <span class="hl opt">|=</span> ICANON<span class="hl opt">;</span>
  <span class="hl opt">}</span>
  <span class="hl slc">// Set the terminal attributes.</span>
  <span class="hl kwd">tcsetattr</span><span class="hl opt">(</span>STDIN_FILENO<span class="hl opt">,</span> TCSANOW<span class="hl opt">, &amp;</span>ttystate<span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">getch</span><span class="hl opt">() {</span>
  <span class="hl kwa">return</span> <span class="hl kwd">fgetc</span><span class="hl opt">(</span>stdin<span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl ppc">#endif</span>

<span class="hl kwb">int</span> snake_size<span class="hl opt">,</span> change_x<span class="hl opt">,</span> change_y<span class="hl opt">,</span> coordinates_x<span class="hl opt">[</span><span class="hl num">1000</span><span class="hl opt">],</span> coordinates_y<span class="hl opt">[</span><span class="hl num">1000</span><span class="hl opt">];</span>
<span class="hl kwb">int</span> food_x <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">,</span> food_y <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">;</span>

<span class="hl kwb">char</span> symbol<span class="hl opt">,</span> a<span class="hl opt">[</span><span class="hl num">1000</span><span class="hl opt">][</span><span class="hl num">1000</span><span class="hl opt">];</span>

<span class="hl kwb">const int</span> N <span class="hl opt">=</span> <span class="hl num">13</span><span class="hl opt">,</span> M <span class="hl opt">=</span> <span class="hl num">17</span><span class="hl opt">,</span> INTERVAL <span class="hl opt">=</span> <span class="hl num">200</span><span class="hl opt">;</span>

<span class="hl kwb">void</span> <span class="hl kwd">change_direction</span><span class="hl opt">() {</span>
  symbol <span class="hl opt">=</span> <span class="hl kwd">getch</span><span class="hl opt">();</span>
  <span class="hl kwa">switch</span> <span class="hl opt">(</span>symbol<span class="hl opt">) {</span>
    <span class="hl kwa">case</span> <span class="hl str">'w'</span><span class="hl opt">:</span> <span class="hl kwa">if</span> <span class="hl opt">(</span>change_x <span class="hl opt">!=</span> <span class="hl num">1</span> <span class="hl opt">||</span> change_y <span class="hl opt">!=</span> <span class="hl num">0</span><span class="hl opt">) {</span>
                change_x <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">;</span> change_y <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
              <span class="hl opt">}</span>
              <span class="hl kwa">break</span><span class="hl opt">;</span>
    <span class="hl kwa">case</span> <span class="hl str">'a'</span><span class="hl opt">:</span> <span class="hl kwa">if</span> <span class="hl opt">(</span>change_x <span class="hl opt">!=</span> <span class="hl num">0</span> <span class="hl opt">||</span> change_y <span class="hl opt">!=</span> <span class="hl num">1</span><span class="hl opt">) {</span>
                change_x <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> change_y <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">;</span>
              <span class="hl opt">}</span>
              <span class="hl kwa">break</span><span class="hl opt">;</span>
    <span class="hl kwa">case</span> <span class="hl str">'s'</span><span class="hl opt">:</span> <span class="hl kwa">if</span> <span class="hl opt">(</span>change_x <span class="hl opt">!= -</span><span class="hl num">1</span> <span class="hl opt">||</span> change_y <span class="hl opt">!=</span> <span class="hl num">0</span><span class="hl opt">) {</span>
                change_x <span class="hl opt">=</span> <span class="hl num">1</span><span class="hl opt">;</span> change_y <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
              <span class="hl opt">}</span>
              <span class="hl kwa">break</span><span class="hl opt">;</span>
    <span class="hl kwa">case</span> <span class="hl str">'d'</span><span class="hl opt">:</span> <span class="hl kwa">if</span> <span class="hl opt">(</span>change_x <span class="hl opt">!=</span> <span class="hl num">0</span> <span class="hl opt">||</span> change_y <span class="hl opt">!= -</span><span class="hl num">1</span><span class="hl opt">) {</span>
                change_x <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> change_y <span class="hl opt">=</span> <span class="hl num">1</span><span class="hl opt">;</span>
              <span class="hl opt">}</span>
              <span class="hl kwa">break</span><span class="hl opt">;</span>
<span class="hl ppc">#ifndef WINDOWS</span>
    <span class="hl kwa">case</span> <span class="hl str">'q'</span><span class="hl opt">:</span> <span class="hl kwd">nonblock</span><span class="hl opt">(</span>NB_DISABLE<span class="hl opt">);</span> std<span class="hl opt">::</span><span class="hl kwd">exit</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">);</span>
<span class="hl ppc">#endif</span>
    <span class="hl kwa">default</span><span class="hl opt">:</span> <span class="hl kwa">break</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">show_table</span><span class="hl opt">() {</span>
<span class="hl ppc">#ifdef WINDOWS</span>
  <span class="hl kwd">system</span><span class="hl opt">(</span><span class="hl str">&quot;cls&quot;</span><span class="hl opt">);</span>
<span class="hl ppc">#else</span>
  <span class="hl kwd">system</span><span class="hl opt">(</span><span class="hl str">&quot;clear&quot;</span><span class="hl opt">);</span>
<span class="hl ppc">#endif</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;=</span> N <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> j <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> j <span class="hl opt">&lt;=</span> M <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">; ++</span>j<span class="hl opt">)</span>
      std<span class="hl opt">::</span>cout
        <span class="hl opt">&lt;&lt; (</span>i <span class="hl opt">==</span> <span class="hl num">0</span> <span class="hl opt">||</span> j <span class="hl opt">==</span> <span class="hl num">0</span> <span class="hl opt">||</span> i <span class="hl opt">==</span> N <span class="hl opt">+</span> <span class="hl num">1</span> <span class="hl opt">||</span> j <span class="hl opt">==</span> M <span class="hl opt">+</span> <span class="hl num">1</span> ?
           <span class="hl str">'#'</span> <span class="hl opt">:</span> a<span class="hl opt">[</span>i<span class="hl opt">][</span>j<span class="hl opt">])</span>
        <span class="hl opt">&lt;&lt; (</span>j <span class="hl opt">&lt;=</span> M ? <span class="hl str">&quot;&quot;</span> <span class="hl opt">:</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">clear_snake_on_table</span><span class="hl opt">() {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">1</span><span class="hl opt">;</span> i <span class="hl opt">&lt;=</span> snake_size<span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    a<span class="hl opt">[</span>coordinates_x<span class="hl opt">[</span>i<span class="hl opt">]][</span>coordinates_y<span class="hl opt">[</span>i<span class="hl opt">]] =</span> <span class="hl str">' '</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">show_snake_on_table</span><span class="hl opt">() {</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>change_x <span class="hl opt">==</span> <span class="hl num">1</span> <span class="hl opt">&amp;&amp;</span> change_y <span class="hl opt">==</span> <span class="hl num">0</span><span class="hl opt">)</span>
    a<span class="hl opt">[</span>coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]][</span>coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]] =</span> <span class="hl str">'v'</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>change_x <span class="hl opt">== -</span><span class="hl num">1</span> <span class="hl opt">&amp;&amp;</span> change_y <span class="hl opt">==</span> <span class="hl num">0</span><span class="hl opt">)</span>
    a<span class="hl opt">[</span>coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]][</span>coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]] =</span> <span class="hl str">'^'</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>change_x <span class="hl opt">==</span> <span class="hl num">0</span> <span class="hl opt">&amp;&amp;</span> change_y <span class="hl opt">==</span> <span class="hl num">1</span><span class="hl opt">)</span>
    a<span class="hl opt">[</span>coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]][</span>coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]] =</span> <span class="hl str">'&gt;'</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>change_x <span class="hl opt">==</span> <span class="hl num">0</span> <span class="hl opt">&amp;&amp;</span> change_y <span class="hl opt">== -</span><span class="hl num">1</span><span class="hl opt">)</span>
    a<span class="hl opt">[</span>coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]][</span>coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]] =</span> <span class="hl str">'&lt;'</span><span class="hl opt">;</span>

  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;=</span> snake_size<span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    a<span class="hl opt">[</span>coordinates_x<span class="hl opt">[</span>i<span class="hl opt">]][</span>coordinates_y<span class="hl opt">[</span>i<span class="hl opt">]] =</span> <span class="hl str">'&#64;'</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">bool</span> <span class="hl kwd">game_over</span><span class="hl opt">() {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;=</span> snake_size<span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] ==</span> coordinates_x<span class="hl opt">[</span>i<span class="hl opt">] &amp;&amp;</span>
        coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] ==</span> coordinates_y<span class="hl opt">[</span>i<span class="hl opt">])</span>
      <span class="hl kwa">return true</span><span class="hl opt">;</span>
  <span class="hl kwa">return false</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">check_coordinates</span><span class="hl opt">() {</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] &gt;</span> N<span class="hl opt">)</span> coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] =</span> <span class="hl num">1</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] &lt;</span> <span class="hl num">1</span><span class="hl opt">)</span> coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] =</span> N<span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] &gt;</span> M<span class="hl opt">)</span> coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] =</span> <span class="hl num">1</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] &lt;</span> <span class="hl num">1</span><span class="hl opt">)</span> coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] =</span> M<span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">next_step</span><span class="hl opt">() {</span>
  <span class="hl kwd">clear_snake_on_table</span><span class="hl opt">();</span>

  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> snake_size<span class="hl opt">;</span> i <span class="hl opt">&gt;=</span> <span class="hl num">2</span><span class="hl opt">; --</span>i<span class="hl opt">) {</span>
    coordinates_x<span class="hl opt">[</span>i<span class="hl opt">] =</span> coordinates_x<span class="hl opt">[</span>i <span class="hl opt">-</span> <span class="hl num">1</span><span class="hl opt">];</span>
    coordinates_y<span class="hl opt">[</span>i<span class="hl opt">] =</span> coordinates_y<span class="hl opt">[</span>i <span class="hl opt">-</span> <span class="hl num">1</span><span class="hl opt">];</span>
  <span class="hl opt">}</span>

  coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] +=</span> change_x<span class="hl opt">;</span>
  coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] +=</span> change_y<span class="hl opt">;</span>

  <span class="hl kwd">check_coordinates</span><span class="hl opt">();</span>

  <span class="hl kwa">if</span> <span class="hl opt">(</span>coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] ==</span> food_x <span class="hl opt">&amp;&amp;</span> coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] ==</span> food_y<span class="hl opt">) {</span>
    snake_size<span class="hl opt">++;</span>
    food_x <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">;</span>
    food_y <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>

  <span class="hl kwd">show_snake_on_table</span><span class="hl opt">();</span>

  <span class="hl kwa">if</span> <span class="hl opt">(</span><span class="hl kwd">game_over</span><span class="hl opt">()) {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;You're looser!</span> <span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
<span class="hl ppc">#ifdef WINDOWS</span>
    <span class="hl kwd">system</span><span class="hl opt">(</span><span class="hl str">&quot;pause&quot;</span><span class="hl opt">);</span>
<span class="hl ppc">#endif</span>
    std<span class="hl opt">::</span><span class="hl kwd">exit</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">);</span>
  <span class="hl opt">}</span>
<span class="hl opt">}</span>

<span class="hl kwb">bool</span> <span class="hl kwd">food_check</span><span class="hl opt">() {</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>food_x <span class="hl opt">== -</span><span class="hl num">1</span> <span class="hl opt">&amp;&amp;</span> food_y <span class="hl opt">== -</span><span class="hl num">1</span><span class="hl opt">)</span> <span class="hl kwa">return false</span><span class="hl opt">;</span>
  <span class="hl kwa">return true</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">place_food</span><span class="hl opt">() {</span>
  std<span class="hl opt">::</span><span class="hl kwd">srand</span><span class="hl opt">(</span>std<span class="hl opt">::</span><span class="hl kwd">time</span><span class="hl opt">(</span>NULL<span class="hl opt">));</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">1</span><span class="hl opt">;</span> i <span class="hl opt">&lt;=</span> <span class="hl num">9</span><span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl kwb">int</span> x <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">rand</span><span class="hl opt">(),</span> y <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">rand</span><span class="hl opt">();</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>x <span class="hl opt">&lt;</span> <span class="hl num">0</span><span class="hl opt">)</span> x <span class="hl opt">*= -</span><span class="hl num">1</span><span class="hl opt">;</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>y <span class="hl opt">&lt;</span> <span class="hl num">0</span><span class="hl opt">)</span> y <span class="hl opt">*= -</span><span class="hl num">1</span><span class="hl opt">;</span>
    x <span class="hl opt">%= (</span>N <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">);</span>
    y <span class="hl opt">%= (</span>M <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">);</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>x <span class="hl opt">==</span> <span class="hl num">0</span><span class="hl opt">) ++</span>x<span class="hl opt">;</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>y <span class="hl opt">==</span> <span class="hl num">0</span><span class="hl opt">) ++</span>y<span class="hl opt">;</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>a<span class="hl opt">[</span>x<span class="hl opt">][</span>y<span class="hl opt">] !=</span> <span class="hl str">'&#64;'</span> <span class="hl opt">&amp;&amp;</span> a<span class="hl opt">[</span>x<span class="hl opt">][</span>y<span class="hl opt">] !=</span> <span class="hl str">'v'</span> <span class="hl opt">&amp;&amp;</span> a<span class="hl opt">[</span>x<span class="hl opt">][</span>y<span class="hl opt">] !=</span> <span class="hl str">'^'</span> <span class="hl opt">&amp;&amp;</span>
        a<span class="hl opt">[</span>x<span class="hl opt">][</span>y<span class="hl opt">] !=</span> <span class="hl str">'&lt;'</span> <span class="hl opt">&amp;&amp;</span> a<span class="hl opt">[</span>x<span class="hl opt">][</span>y<span class="hl opt">] !=</span> <span class="hl str">'&gt;'</span><span class="hl opt">) {</span>
      food_x <span class="hl opt">=</span> x<span class="hl opt">;</span>
      food_y <span class="hl opt">=</span> y<span class="hl opt">;</span>
      a<span class="hl opt">[</span>x<span class="hl opt">][</span>y<span class="hl opt">] =</span> <span class="hl str">'+'</span><span class="hl opt">;</span>
      <span class="hl kwa">return</span><span class="hl opt">;</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">standart_settings</span><span class="hl opt">() {</span>
  snake_size <span class="hl opt">=</span> <span class="hl num">2</span><span class="hl opt">;</span>

  coordinates_x<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] =</span> <span class="hl num">1</span><span class="hl opt">;</span>
  coordinates_y<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">] =</span> <span class="hl num">2</span><span class="hl opt">;</span>
  coordinates_x<span class="hl opt">[</span><span class="hl num">2</span><span class="hl opt">] =</span> <span class="hl num">1</span><span class="hl opt">;</span>
  coordinates_y<span class="hl opt">[</span><span class="hl num">2</span><span class="hl opt">] =</span> <span class="hl num">1</span><span class="hl opt">;</span>

  change_x <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  change_y <span class="hl opt">=</span> <span class="hl num">1</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwd">standart_settings</span><span class="hl opt">();</span>

<span class="hl ppc">#ifndef WINDOWS</span>
  std<span class="hl opt">::</span><span class="hl kwd">memset</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">' '</span><span class="hl opt">,</span> <span class="hl kwa">sizeof</span><span class="hl opt">(</span>a<span class="hl opt">));</span>
  <span class="hl kwd">nonblock</span><span class="hl opt">(</span>NB_ENABLE<span class="hl opt">);</span>
<span class="hl ppc">#endif</span>

  <span class="hl kwa">while</span> <span class="hl opt">(</span><span class="hl kwa">true</span><span class="hl opt">) {</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span><span class="hl kwd">kbhit</span><span class="hl opt">() !=</span> <span class="hl num">0</span><span class="hl opt">)</span>
     <span class="hl kwd">change_direction</span><span class="hl opt">();</span>

    <span class="hl kwd">next_step</span><span class="hl opt">();</span>

    <span class="hl kwa">if</span> <span class="hl opt">(!</span><span class="hl kwd">food_check</span><span class="hl opt">())</span>
      <span class="hl kwd">place_food</span><span class="hl opt">();</span>

    <span class="hl kwd">show_table</span><span class="hl opt">();</span>

    <span class="hl kwd">Sleep</span><span class="hl opt">(</span>INTERVAL<span class="hl opt">);</span>
  <span class="hl opt">}</span>
<span class="hl opt">}</span>
</pre>

<h2>P.S.</h2>

<p>By the way, if you have similar cool console stuff, please share.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Colour Maximite microcomputer]]></title>
    <link href="http://demin.ws/blog/english/2012/12/04/colour-maximite/"/>
    <updated>2012-12-04T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/12/04/colour-maximite/</id>
    <content type="html"><![CDATA[<p>At the moment, the <a href="http://geoffg.net/maximite.html">Maximite</a> project is my favorite one among modern
homebrew microcomputers. Having assembled its previous,
<a href="http://demin.ws/blog/english/2012/01/19/maximite-kit/">black-and-white version</a>,
I run <a href="http://demin.ws/blog/english/2012/05/11/retrobsd-on-maximite/">RetroBSD</a> on it, and even ported my emulator of the classic
8-bit microcomputer from the eightieth called <a href="http://www.youtube.com/watch?v=JGuYyuCkJR8">Radio-86RK</a>. To me, the
main advantage of Maximite is its completeness as a project. In fact,
design of Maximite is quite simple because PIC32, the heart of this
microcomputer, does almost everything. But the Maximite project is not
only a bare idea or schematic, it includes the board, the case, and, of
course, software &ndash; MMBasic. This is an advanced dialect of BASIC giving
access to all features of Maximite, all its peripherals.
In <a href="http://demin.ws/blog/english/2012/08/07/interview-with-geoff-graham/">the interview</a> the author of Maximite,
Geoff Graham, tells how he was almost forced to get this project to such
complete stage.</p>

<p>Recently Geoff has released a new, updated colour version modification
having a few extra features along with the colour (new and improved
features are marked with the asterisk):</p>

<ul>
<li>PS/2 keyboard</li>
<li>VGA output with eight colours (480x432 or 240x216) (*)</li>
<li>monochrome Composite Video output</li>
<li>synthesised music and sound effects (*)</li>
<li>battery backed real time clock (*)</li>
<li>20 external I/O lines on the back panel</li>
<li>Arduino compatible connector (*)</li>
<li>SD card for storing programs and files (up to 32GB)</li>
<li>USB connectivity as a terminal or for file transfer</li>
<li>protocols including Serial, I2C, SPI and 1-wire</li>
<li>dual-channel PWM analog output (*)</li>
<li>firmware upgrades via USB</li>
<li>special commands for animated games</li>
</ul>

<p>MMBasic allows to take full advantage of all these features. It is even
possible implementing the PIC32 timer interrupt routines directly in BASIC.</p>

<p>As previously I have ordered the new Maximite Kit from
<a href="http://www.altronics.com.au/index.asp?area=item&amp;id=K9555">Altronics</a>.</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1221.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1223.JPG" alt="" />
</p>

<p>There are no on-surface planar elements which makes the life of soldering
laymans like me much easier. There is only one planar capacitor (C10) for
some reason. It is quite small, so proper soldering it took me some time
to avoid shortening on the board.</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1224.JPG" alt="" />
</p>

<p>All done.</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1266.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1268.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1269.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1275.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1276.JPG" alt="" />
</p>

<p>The Original and Colour Maximite.</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1270.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1277.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1278.JPG" alt="" />
</p>

<p>In general, the kit from Altronics is very high quality. Recommended.</p>

<p>This is what MMBasic allows a user to do with colours.</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1289.JPG" alt="" />
</p>

<p>Well, no colours though, but just classics.</p>

<p><img src="http://demin.ws/blog/english/2012/12/04/colour-maximite/IMG_1287.JPG" alt="" />
</p>

<p>As the author explains, generating colours requires the 100-pin version
of PIC32 with three SPI channels. Obviously, it also requires three times much
work processing the colour information. Because the crystal still works on the
same frequency as previously, 80MHz, the colour Maximite works a bit slower
than its black-and-white predecessor. But along with the firmware providing
colours, there is a black-and-white version of MMBasic for the new Maximite
having all new features except the colour video, so it works with the same
speed as the original Maximite.</p>

<p>Well, as previously I have a lot of fun using Maximite, and strongly
recommend it if you are up building a nice powerful microcomputer in a few
hours.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Creating a live progress bar using Splunk]]></title>
    <link href="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/"/>
    <updated>2012-11-25T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/</id>
    <content type="html"><![CDATA[<p>Splunk is a tool for managing and analysing logs. In short, Splunk does the following: there is a Splunk server which stores, indexes and allows analysing log files, and there are client machines (application servers) generating logs and shipping them to the Splunk server. In turn, the Splunk server can be configured as a cluster of physical machines. Logs stored inside Splunk are split amongst these machines, and also Splunk uses MapReduce for querying. There are plenty of ways to deliver logs to the Splunk server (or cluster):</p>

<ul>
<li>a special log forwarder (from Splunk) which can efficiently send log updates to the server</li>
<li>as regular files via NFS or SMB</li>
<li>SNMP</li>
<li>directly over TCP/IP (for example, instead of creating log files in the first place)</li>
</ul>

<p>On Windows Splunk can take information from Windows Events, Performance Counters or Registry.</p>

<p>For Splunk logs are textual files split into lines. When indexing logs Splunk parses log lines into fields, for example, in the &ldquo;name=value&rdquo; format (which is also configurable though). Then using a special query language called SPL it allows manipulating with these fields: sorting, aggregation, computed fields, creating views and tables, external dictionary lookups (for instance, to RDBMS), and, of course, creating various graphic representations of data. Even though normally SPL operates with individual log lines, it supports multi-line queries, which can be useful, for example, to extract transactions or any other activities generating multiple log records.</p>

<p>As Splunk creators state, all logs kept and indexed by Splunk despite of their age are equally available for querying. There is no concept of archiving. Of course, machines running Splunk should correspond to the volume of logs being processed.</p>

<p>Also Splunk states itself as &ldquo;Google for logs&rdquo;, but let&rsquo;s leave it without comments.</p>

<p>The UI of Splunk is web. It allows creating dashboards, which in turn can be presented as a Splunk app. Splunk has its own app store, where most of apps are free though. There are apps already developed, for example, for UNIX syslog, Apache logs, Microsoft Exchange, etc.</p>

<p><a href="http://www.splunk.com/">Splunk</a> software is freely available on the official website. The licensing model is based on volumes of logs processed daily. Under some small threshold Splunk is free. This threshold is surely enough for evaluation.</p>

<p>I would recommend a book called <a href="http://www.splunk.com/goto/book">Exploring Splunk</a> for those who want quickly dig into Splunk and figure out its main features. This book provides very solid overview of SPL and other concepts how Splunk works.</p>

<p>In this article I would like to show a real example of using Splunk. This exercise can be repeated in half an hour. The only prerequisite is to download and install Splunk on your operating system. Then just follow my instructions.</p>

<p>The example is a bit unusual though. Traditionally, logs are used for post factum analysis. But nothing really prevents from picking up updates on the fly and building &ldquo;live&rdquo; indicators based on logs. Agreed, my example may look a bit artificial, but I want to show how quickly to feed data into Splunk and formalize it, and finally create a dynamic UI with it.</p>

<p>Let&rsquo;s begin with a simple script in Ruby. It generates log records containing a number representing its completion (from 0 to 100%).</p>

<pre class="hl">
    <span class="hl kwa">require</span> <span class="hl str">'date'</span>

    duration <span class="hl opt">=</span> <span class="hl num">60</span><span class="hl opt">*</span><span class="hl num">1</span>
    update_period <span class="hl opt">=</span> <span class="hl num">0.5</span>
    i <span class="hl opt">=</span> <span class="hl num">0</span>
    <span class="hl kwa">while</span> i <span class="hl opt">&lt;=</span> duration <span class="hl kwa">do</span>
      progress <span class="hl opt">=</span> i <span class="hl opt">*</span> <span class="hl num">100.0</span> <span class="hl opt">/</span> duration
      msg <span class="hl opt">=</span> <span class="hl str">&quot;%s progress=%05.2f\n&quot;</span> <span class="hl opt">% [</span>DateTime<span class="hl opt">.</span>now<span class="hl opt">,</span> progress<span class="hl opt">]</span>
      puts msg
      <span class="hl kwd">open</span><span class="hl opt">(</span><span class="hl str">&quot;logs/my.log&quot;</span><span class="hl opt">,</span> <span class="hl str">'a'</span>) <span class="hl esc">{ |f| f &lt;&lt; msg }</span>
      i <span class="hl opt">=</span> i <span class="hl opt">+</span> update_period
      sleep update_period
    <span class="hl kwa">end</span>
</pre>

<p>The log records may look like:</p>

<pre><code>2012-11-23T15:58:54+00:00 progress=45.00
2012-11-23T15:58:55+00:00 progress=45.83
2012-11-23T15:58:55+00:00 progress=46.67
2012-11-23T15:58:56+00:00 progress=47.50
2012-11-23T15:58:56+00:00 progress=48.33
2012-11-23T15:58:57+00:00 progress=49.17
2012-11-23T15:58:57+00:00 progress=50.00
</code></pre>

<p>We will develop a dashboard in Splunk, which displays the percentage in the form of a cool indicator taking updates from logs.</p>

<p>For simplicity we run everything on a single machine, and Splunk will be taking log updates directly from a file.</p>

<p>So, you have already installed Splunk, and if you open &ldquo;http://localhost:8080&rdquo; in your browser you should be able to login as the &ldquo;admin&rdquo; user.</p>

<p>Then in menu follow to: &ldquo;Manager -&gt; Data Inputs -&gt; Add data -&gt; A file or directory or files&rdquo;. Here we specify the file and directory name with the logs (in our case just a single file).</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/01-adding-log.png" alt="" />
</p>

<p>Confirm creating a source of logs (source type). As I said, logs can be delivered to Splunk in various ways. Each way can be named and addressed as a source type.</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/02-data-source-creation.png" alt="" />
</p>

<p>The log has been added. We see that Splunk has picked up the file and already parsed its lines into fields. Out of the box Splunk understands many date and time formats, but it is configurable.</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/03-data-source-check.png" alt="" />
</p>

<p>Now we give a name to our source type - &ldquo;test_logging&rdquo; and save the settings.</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/04-data-source-name.png" alt="" />
</p>

<p>Now we get back to the main page and type in our first SPL query in the search bar (in red):</p>

<pre><code>sourcetype=&quot;test_logging&quot; | table progress as float
</code></pre>

<p>It says: take logs from the &ldquo;test_logging&rdquo; data source, create a table with one column called &ldquo;progress&rdquo; taking values from the corresponding field, set the type of &ldquo;progress&rdquo; to float. At the bottom (in blue) we see the result of the query (own log already has some data). SPL uses the concept of UNIX pipes (|) feeding output from one command to the next one.</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/05-radial-gauge-query.png" alt="" />
</p>

<p>So, we have the table. Now let&rsquo;s create a widget. Due to simplicity of our data (one single field) we can represent it as a speedometer gauge. Click on &ldquo;Formatting options&rdquo; (in blue) and set the chart type to &ldquo;radial gauge&rdquo; (in red). And here is our cool widget:</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/06-radial-gauge-widget.png" alt="" />
</p>

<p>The first widget is ready. Now let&rsquo;s create an alternative one looking differently. It will also represent the value of the progress but in the form of a horizontal bar moving from left to right. This is the query:</p>

<pre><code>sourcetype=&quot;test_logging&quot; | table _time progress | head 1
</code></pre>

<p>It says: using data from the &ldquo;test_logging&rdquo; source type create a table with two fields, &ldquo;_time&rdquo; and &ldquo;progress&rdquo;, and then take only the first line from it. Default sorting is descending by &ldquo;_time&rdquo;. At the bottom (in green) we see the result of the query.</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/07-bar-chart-query.png" alt="" />
</p>

<p>Now click on &ldquo;Formatting options&rdquo;, choose &ldquo;bar&rdquo; (in green), set the interval for the Y-axis from 0 to 100. For some reason, the X-axis is vertical here (this axis will represent &ldquo;_time&rdquo;), and the Y-axis is horizontal (this one will show &ldquo;progress&rdquo;). Because our query on the previous picture already shown &ldquo;100&rdquo;, the widget is fully filled.</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/08-chart-type-bar.png" alt="" />
</p>

<p>Describing the first widget I deliberately skipped how to save the query. We will do it now. We click on &ldquo;Create&rdquo; and then &ldquo;Dashboard panel&hellip;&rdquo; (in red) and save the settings. We name the first widget as &ldquo;Speedometer&rdquo; and the second - &ldquo;Progress bar&rdquo;.</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/09-create-dashboard-button.png" alt="" />
</p>

<p>Along with saving the first widget we will be asked to create a new panel, a dashboard. Let&rsquo;s call it &ldquo;Test logging&rdquo;. When saving the second widget we will add it to the already created one.</p>

<p>Finally, we click on &ldquo;Dashboards &amp; View&rdquo;, select your dashboard and it will be shown like:</p>

<p><img src="http://demin.ws/blog/english/2012/11/25/progress-indicator-using-splunk/10-dashboard-layout.png" alt="" />
</p>

<p>There is no data here, so the panels are empty. We see the name of the dashboard (in red), the names of the widgets (in yellow) and two &ldquo;Edit&rdquo; buttons (in blue) allowing updating queries and visual representation on the fly. Before starting our Ruby script, we need to click on the both &ldquo;Edit&rdquo; buttons and set the time interval from &ldquo;rt-1s&rdquo; to &ldquo;rt&rdquo;. Such interval means getting updates each second.</p>

<p>Now let&rsquo;s click on &ldquo;On&rdquo; and kick off the script!</p>

<p>A little video how it works:</p>

<iframe width="480" height="360" src="http://www.youtube.com/embed/wPh7dm5brWg" frameborder="0" allowfullscreen></iframe>

<p>That&rsquo;s it.</p>

<p>The example, as I said, is very simple, but I hope it gives you as least initial understanding of Splunk.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Pocket Mini Computer on Parallax Propeller microcontroller]]></title>
    <link href="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/"/>
    <updated>2012-11-22T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/</id>
    <content type="html"><![CDATA[<p>The microcontroller from Parallax called <a href="http://www.parallax.com/propeller/">Propeller</a> comparing to PIC or
AVR occupies quite an unusual niche. The first two can be called as general
purpose architectures. But the creators of Propeller used another approach.</p>

<p>Main distinctive features of Propeller:</p>

<ul>
<li>8 independent cores (cogs) working in parallel. Any resource sharing
(memory or I/O) is handled by hardware and isn&rsquo;t under programmer&rsquo;s
control. This guaranties predictable latency. Each cog (core) has its own
private 4KB RAM, plus an ability to generate the TV or VGA video signal.</li>
<li>There is no concept of interrupts in any form. Instead you run concurrent
tasks on different cogs.</li>
<li>Two main programming languages available: a high level one called Spin,
and the assembly language. Spin simplifies concurrent and multi-core
programming, and its interpreter is build-in to the crystal.</li>
<li>No almost a concept of programming or flashing the crystal. The higher
half of the address space (32KB) is ROM and contains the Spin interpreter
and other system tables. The lower half is RAM and it is volatile. It needs
to be loaded on each reset. In real applications an external EEPROM memory
chip is connected and Propeller copies 32KB from that EEPROM (via I2C) to
RAM.</li>
<li>Propeller is declared as 32-bit because it supports 32-bit operations,
but the address space is 16-bit (64KB).</li>
</ul>

<p>The Spin language was designed to make concurrent and multi-core programming
easier. This language is a mixture of procedural and object-oriented
approaches.</p>

<p>Below is an example of code in Spin launching a function to spin on three
cogs. The code is really easy to read and understand.</p>

<pre><code>CON

  _clkmode = xtal1 + pll16x         'Establish speed
  _xinfreq = 5_000_000              '80Mhz

OBJ

  led: &quot;E555_LEDEngine.spin&quot;        'Include LED methods object

VAR

  byte Counter                      'Establish Counter Variable
  long stack[90]                    'Establish working space

PUB Main

  cognew(Twinkle(16,clkfreq/50), @stack[0])    'start Twinkle cog 1
  cognew(Twinkle(19,clkfreq/150), @stack[30])  'start Twinkle cog 2
  cognew(Twinkle(22,clkfreq/100), @stack[60])  'start Twinkle cog 3

PUB Twinkle(PIN,RATE)                  'Method declaration 

  repeat                               'Initiate a master loop

    repeat Counter from 0 to 100       'Repeat loop Counter
      led.LEDBrightness(Counter, PIN)  'Adjust LED brightness 
      waitcnt(RATE + cnt)              'Wait a moment

    repeat Counter from 100 to 0       'Repeat loop Counter
      led.LEDBrightness(Counter,PIN)   'Adjust LED brightness 
      waitcnt(RATE + cnt)              'Wait a moment
</code></pre>

<p>The <code>cognew</code> function kicks off the function <code>Twinkle</code> on three cores
and parameterizes each one with a frequency and stack.</p>

<p>The diagram of the Propeller architecture:</p>

<p><a href="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/propeller-block-large.jpg"><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/propeller-block.jpg" alt="" />
</a></p>

<p>The name &ldquo;Propeller&rdquo; comes from how the Hub controlling resource sharing
switches between cogs. It does round-robin similar to the spinning propeller.</p>

<p>I don&rsquo;t want to go deeper into Propeller in this post because this is
a long story. Instead I put a list of very useful books at the end. They
provide the exhaustive details.</p>

<p>But I&rsquo;d like to share about an interesting project called
&ldquo;<a href="http://propellerpowered.wikispaces.com/Pocket+Mini+Computer">The Pocket Mini Computer</a>&rdquo; based on Propeller (P8X32A). This project
uses the &ldquo;P8X32A QuickStart&rdquo; evaluation board as a base.</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/P8X32A-quick-start.jpg" alt="" />
</p>

<p>The photo from the official website:</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/pocket-mini-computer.jpg" alt="" />
</p>

<p>In fact, the author <a href="http://propellerpowered.com/shop/?page_id=234">offers</a> the evaluation board, plus the extension,
which has VGA, microSD, PS/2, sound and Wii Gameport interfaces. Optionally,
the 32KB SRAM chip can be added.</p>

<p>The point of the project is a BASIC interpreter running on this computer.
It converts it to a micro-computer a-la from 80s. The interpreter is written
in Spin (<a href="https://www.dropbox.com/sh/qwhixzvtlrvp1u1/y-JshwklWj/PropellerBASIC">sources</a> are open). The dialect is quite limited
though: no arrays, real and string variables, one letter variable names etc.
Nevertheless, BASIC provides access to all peripherals including the SD-card.
Plus, it allows running native binaries which can be developed in assembly,
C (Parallax has a GCC version for Propeller) or Spin.</p>

<p>Below there are a few pictures of the kit to understand how it looks like.
As I said, PMC is based on the P8X32A evaluation board, so only the
extension board requires assembly (soldering).</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/IMG_1192.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/IMG_1193.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/IMG_1194.JPG" alt="" />
</p>

<p>Almost everything is in place.</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/IMG_1195.JPG" alt="" />
</p>

<p>The sandwich is ready.</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/IMG_1196.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/IMG_1197.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/IMG_1198.JPG" alt="" />
</p>

<p><img src="http://demin.ws/blog/english/2012/11/22/personal-mini-computer-on-parallax-propeller/IMG_1199.JPG" alt="" />
</p>

<p>A small demo of graphics capabilities.</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/capsFv1njUE" frameborder="0" allowfullscreen></iframe>

<h2>Overall impression</h2>

<h3>Propeller</h3>

<p>It is not easy to call it &ldquo;a general purpose microcontroller&rdquo;. In my
subjective view it fits perfectly into certain applications, like,
for instance, games consoles or mini-vending machines because it can
generate a good quality video signal out of the box. But, on the other hand
there are no built-in PWM, ADC/DAC, flash memory, triggers, interrupts,
and the creators recommend implementing such functionality manually or using
external chips. In the books listed in the end there are plenty examples of
such applications.</p>

<p><strong>Conslusion</strong>: the very interesting and worth considering architecture.</p>

<h3>The PMC kit</h3>

<p>This is a very interesting and entertaining project. Of course, it is
obvious that BASIC is very limited in resources, for instance, RAM.
<a href="http://demin.ws/blog/english/2012/01/19/maximite-kit/">Maximite</a>, for example, based on PIC32, is much more powerful. It can
easily run not only its powerful MMBasic, but, for example, <a href="http://demin.ws/blog/english/2012/05/11/retrobsd-on-maximite/">RetroBSD</a>
or even emulate <a href="http://demin.ws/blog/russian/2012/08/23/radio86-on-maximite/">Radio-86RK</a>.</p>

<p>But, $39 is the great offer for those who want to play with Propeller having
complete hardware.</p>

<h2>Dessert</h2>

<p>Here is a list of books I read (regarding the architecture) and skimmed
(regarding projects). All are recommended.</p>

<hr />

<p>A short, concise and easy book for beginners. It describes many projects
on Propeller. One of the authors is the PMC inventor.</p>

<p><a href="http://www.amazon.co.uk/gp/product/B004X6U6II/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B004X6U6II&amp;linkCode=as2&amp;tag=prodiy-21">Getting Started With the Propeller</a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B004X6U6II" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p><a href="http://www.amazon.co.uk/gp/product/B004X6U6II/ref=as_li_qf_sp_asin_il?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B004X6U6II&amp;linkCode=as2&amp;tag=prodiy-21"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&amp;ASIN=B004X6U6II&amp;Format=_SL160_&amp;ID=AsinImage&amp;MarketPlace=GB&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=prodiy-21" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B004X6U6II" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<hr />

<p>A very solid and easy to read book. It explains in all details the
architecture of Propeller. Though the author doesn&rsquo;t cover programming in
assembly, only in Spin, but he precisely shows how to use properly and
benefit from the original multi-core architecture of Propeller. The first
section covers the internals of Propeller. Following sections contain
various projects (can be skipped on the first reading).</p>

<p><a href="http://www.amazon.co.uk/gp/product/B003TQM9Y2/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B003TQM9Y2&amp;linkCode=as2&amp;tag=prodiy-21">Programming the Propeller with Spin : A Beginner&rsquo;s Guide to Parallel Processing (Tab Electronics)</a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B003TQM9Y2" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p><a href="http://www.amazon.co.uk/gp/product/B003TQM9Y2/ref=as_li_qf_sp_asin_il?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B003TQM9Y2&amp;linkCode=as2&amp;tag=prodiy-21"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&amp;ASIN=B003TQM9Y2&amp;Format=_SL160_&amp;ID=AsinImage&amp;MarketPlace=GB&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=prodiy-21" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B003TQM9Y2" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<hr />

<p>A collections of real applications with Propeller from its creators.</p>

<p><a href="http://www.amazon.co.uk/gp/product/B003BZVIZC/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B003BZVIZC&amp;linkCode=as2&amp;tag=prodiy-21">Programming and Customizing the Multicore Propeller Microcontroller : The Official Guide</a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B003BZVIZC" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p><a href="http://www.amazon.co.uk/gp/product/B003BZVIZC/ref=as_li_qf_sp_asin_il?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B003BZVIZC&amp;linkCode=as2&amp;tag=prodiy-21"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&amp;ASIN=B003BZVIZC&amp;Format=_SL160_&amp;ID=AsinImage&amp;MarketPlace=GB&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=prodiy-21" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B003BZVIZC" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[&#34;Assembly language for the PC&#34; by Peter Norton and John Socha]]></title>
    <link href="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/"/>
    <updated>2012-11-04T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/</id>
    <content type="html"><![CDATA[<p>I keep going reviewing books which influenced on me considerably at the time.
Today it is a book by Peter Norton and John Socha about programming in the
assembly language for the PC.</p>

<p>A small lyrical digression.</p>

<p>Does any know that Peter Norton didn&rsquo;t write the famous Norton Commander?
The Norton Commander had been invented and then maintained by John Socha
up to its &ldquo;canonical&rdquo; version 3. Socha used quite an unusual approach in those
days mixing the assembly language with C when most of &ldquo;true&rdquo; developers
programmed purely in assembly. It allowed developing sophisticated but still
fast and efficient applications much quicker.</p>

<p>Okay, go back to the book. It liked the idea of buying old books almost for
nothing just for the sake of holding them in hands.</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1171.jpg" alt="" />
</p>

<p>Wonderful. They sent me a decommissioned library copy carefully glued by the
sticky tape.</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1172.jpg" alt="" />
</p>

<p>I personally don&rsquo;t like when people write in books or fold page corners, but
this looks very touching &ndash; somebody did drilled this stuff.</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1173.jpg" alt="" />
</p>

<p>Is it still possible NOT to understand how EQU works?</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1174.jpg" alt="" />
</p>

<p>Or DUP?</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1175.jpg" alt="" />
</p>

<p>Or stack?</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1176.jpg" alt="" />
</p>

<p>Or how to intercept interrupts in DOS?</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1178.jpg" alt="" />
</p>

<p>By the way, it turned that I have got the third edition of the book having
a couple of extra chapters about 286 and 386 comparing to its first
edition which I read years ago in Russian.</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1177.jpg" alt="" />
</p>

<p>The bottom line &ndash; this book was and still is fantastic.</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1180.jpg" alt="" />
</p>

<p>Through the book they explain step by step a process of developing a program
called &ldquo;dskpatch&rdquo;, a visual editor allowing viewing and modifying individual
sectors on floppy or hard drives. In the end it turns into an advanced
product split into modules and having dozens of generic routines easily
re-usable in any program. Starting from the very beginning you have to learn
the basics of 8086, then BIOS and DOS functions, the direct access to video
memory and keyboard.</p>

<p>But the main thing is that this book explains how to write really big projects
in assembly. For example, my real opening was that if each subroutine always
preserves the registers which are not to pass parameters and to return the
result the amount of &ldquo;unpredictable side effects&rdquo; drops down substantially.
Of course, today it sounds like information from a nursery level, but even in
the nursery somebody has communicate it.</p>

<p>In the appendix there is the full carefully commented listing of &ldquo;dskptach&rdquo;.</p>

<p>Also, the third edition has a few chapters about mixing the assembler and
high level languages like C and PASCAL. Passing function parameters to and from
the assembler routines is explained in all details. As a bonus, there is a
library with an unambiguous name &ndash; SOCHALIB congaing a lot of very useful
routines for the screen, mouse and the keyboard. It was delightfully impressed
that a routine putting a character on the screen used a pre-calculated
lookup table to compute an address of the screen line base instead of
multiplying Y times 80 directly. I suspect the code of the library resides
somewhere inside the Norton Commander and Norton Utilities, and it explains
why these products worked blazingly fast.</p>

<p><img src="http://demin.ws/blog/english/2012/11/04/norton-assembly-language-book/IMG_1183.jpg" alt="" />
</p>

<p>The conclusion: strongly recommended as an example of the perfect textbook.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Pi Bow - the most funny case for Raspberry Pi]]></title>
    <link href="http://demin.ws/blog/english/2012/10/17/pi-bow/"/>
    <updated>2012-10-17T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/10/17/pi-bow/</id>
    <content type="html"><![CDATA[<p>I <a href="https://twitter.com/begoon">tweeted</a> recently about a cool case for Raspberry Pi called
<a href="http://www.maplin.co.uk/pibow-colour-raspberry-pi-case-652812">Pibow</a> from Maplin. Alas, despite of my moaning about costliness of this device I have bought it.</p>

<p>How cool is that? Let&rsquo;s check it out. It has arrived:</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1130.JPG" alt="" />
</p>

<p>The parts:</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1102.JPG" alt="" />
</p>

<p>Let&rsquo;s begin its &ldquo;by slice&rdquo; composing:</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1113.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1114.JPG" alt="" />
</p>

<p>After the first two slices let&rsquo;s put the RPi (remember that it&rsquo;s design
doesn&rsquo;t have even holes for screws):</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1115.JPG" alt="" />
</p>

<p>Slice by slice:</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1116.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1117.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1118.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1119.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1120.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1121.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1122.JPG" alt="" />
</p>

<p>Now screws and nuts&hellip;</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1123.JPG" alt="" />
</p>

<p>The device is ready!</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1124.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1125.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1126.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1127.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1128.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1129.JPG" alt="" />
</p>

<p>Frankly I just love Raspberry Pi. It is difficult to imagine a better device
for schools and universities for studying computers. Only <a href="http://demin.ws/blog/english/2012/01/19/maximite-kit/">Maximite</a> could
compete if we need a bit more lower level, closer to hardware.</p>

<p>Before my RPi&rsquo;s &ldquo;case&rdquo; from <a href="http://www.skpang.co.uk/catalog/starter-kita-for-raspberry-pi-pi-not-include-p-1070.html">SK Pang</a> looked like this:</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/pi-bow/IMG_1103.JPG" alt="" />
</p>

<p>Incredibly useful device if you need access to GPIO, but as a &ldquo;normal&rdquo; case
Pibow is unbeatable.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to rewrite a project from Pascal to C, or a macro-assembler for Intel 8080]]></title>
    <link href="http://demin.ws/blog/english/2012/10/09/rewrite-of-as/"/>
    <updated>2012-10-09T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/10/09/rewrite-of-as/</id>
    <content type="html"><![CDATA[<p>Let&rsquo;s look at the code:</p>

<pre><code>BEGIN
   if (Hi(Code) == 0)
    BEGIN
     BAsmCode[0] = Lo(Code); CodeLen = 1;
     return True;
    END
   else if (MomCPU &lt;= CPU1802)
    BEGIN
     WrError(1500);
     return False;
    END
   else
    BEGIN
     BAsmCode[0] = Hi(Code); BAsmCode[1] = Lo(Code); CodeLen = 2;
     return True;
    END
END
</code></pre>

<p>(grabbed from <a href="https://github.com/begoon/asl/blob/master/code1802.c#L46">code1802.c</a>).</p>

<p>Frankly, it is not easy to recognize the language. Of course, this is C but
initially it was Pascal, and then the author had converted in to C trying to
minimize the amount of changes.</p>

<p>The project is called &ldquo;<a href="http://john.ccac.rwth-aachen.de:8000/as/">Macro-assembler AS</a>&rdquo;, by Alfred Arnold. I use it
as an Intel 8080 macro-assembler available on Mac, Linux and Windows.
Frankly I haven&rsquo;t seen anything better so far.</p>

<p>As the author <a href="http://john.ccac.rwth-aachen.de:8000/as/as_EN.html#sect_I_1_">explains</a>, the project was started in Turbo Pascal,
but after Borland had abandoned the DOS version but free implementation of the
modern Pascal didn&rsquo;t exist yet, he decided to convert the sources into C
and continue development in C. Despite of overall doubtfulness of such
approach, to me, the author had managed it very well. The project hadn&rsquo;t
die as it usually happens with big projects after rewrite. But though I
have cloned it for myself and started using successfully, I doubt
that I want to contribute because it requires coding in this weird
&ldquo;Pascal on C steroids&rdquo; dialect. Alas, this is inevitable due to that
conversion, otherwise the project may turn into mess. If to surf amongst
<a href="https://github.com/begoon/asl">the sources of AS</a> it is easy to find a lot of tricks like &ldquo;how
to make C to be Pascal&rdquo;.</p>

<p>Nevertheless, all the best to Alfred with his great project. Again, the
project moves forward and becomes better.</p>

<p>By the way, Alfred has a very cool collection of <a href="http://john.ccac.rwth-aachen.de:8000/alf/index.html#collection">old hardware</a> which makes
me feel envy.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[&#34;Introduction to 8080/8085 assembly language programming&#34; by Judi Fernandez and Ruth Ashley]]></title>
    <link href="http://demin.ws/blog/english/2012/10/08/introduction-to-8080-8085-assembly-language-programming/"/>
    <updated>2012-10-08T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/10/08/introduction-to-8080-8085-assembly-language-programming/</id>
    <content type="html"><![CDATA[<p>Just bought on Amazon an old book from the eighties about programming in the
8080-8085 assembly language.</p>

<p><a href="http://www.amazon.co.uk/gp/product/0471080098/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=0471080098&amp;linkCode=as2&amp;tag=prodiy-21">Introduction to 8080-8085 Assembly Language Programming (Self-teaching Guides)</a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=0471080098" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p><img src="http://demin.ws/images/covers/english/introduction-to-8080-8085-assembly-language-programming.jpg" alt="" />
</p>

<p>A reasonable question &ldquo;why&rdquo;? Especially considering that in the last couple
of months I have re-written from scratch two emulators of the Intel 8080
microprocessor, in C and JavaScript. Do I still have any questions about
8080 assembly? No.</p>

<p>Frankly, I just heard about this book as a perfect example of the
assembly textbook. Something similar to the famous Maurer&rsquo;s book on
programming on 6502 assembly for Apple computers. I believe the digitized
copies are available because the book was published years ago back in 1981,
but I had come across a very cheap hardcopy (~6 pounds including delivery) at
Amazon, second-hand, of course.</p>

<p>Have no idea why but when holding such old books in hands I feel some
unexplainable excitement from all these hand-made annotations, old-fashion
fonts for code and punch card forms.</p>

<p><img src="http://demin.ws/images/blog/book/introduction-to-8080-8085-assmebly-language-programming/IMG_1069.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/book/introduction-to-8080-8085-assmebly-language-programming/IMG_1070.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/book/introduction-to-8080-8085-assmebly-language-programming/IMG_1071.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/book/introduction-to-8080-8085-assmebly-language-programming/IMG_1072.JPG" alt="" />
</p>

<p>And in fact the book is great. If, just in some weird and unusual case you
decide to learn the 8080 assembly language, but you have never heard about
8080 and the assembly language in general, this book is the perfect option.</p>

<p>It begins from the very beginning &ndash; dealing with binary, decimal and
hexadecimal calculations; then it follows through groups of instructions
with many examples &ndash; array indexing, multiplication and division,
BCD representation, the concept of stack and so on. Each chapter is concluded
with exercises.</p>

<p>The very good book. Recommended.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Getting code statistics]]></title>
    <link href="http://demin.ws/blog/english/2012/10/01/git-diff/"/>
    <updated>2012-10-01T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/10/01/git-diff/</id>
    <content type="html"><![CDATA[<p>Problem: Get code statistics &ndash; a number of added and deleted lines of code,
for instance, across annual releases. Git does straightaway
via <a href="http://www.kernel.org/pub/software/scm/git/docs/git-diff.html">git diff</a>.</p>

<pre><code>git diff --shortstat rel-2010 rel-2011
</code></pre>

<p>It prints something like this:</p>

<pre><code>12 files changed, 2462 insertions(+), 488 deletions(-)
</code></pre>

<p>If your project isn&rsquo;t in git, you can quickly import the branches you want
to analyse in a temporary git repo.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to destroy a banking card properly]]></title>
    <link href="http://demin.ws/blog/english/2012/09/29/how-to-destroy-banking-card-properly/"/>
    <updated>2012-09-29T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/29/how-to-destroy-banking-card-properly/</id>
    <content type="html"><![CDATA[<p><img src="http://demin.ws/images/blog/how-to-destroy-banking-card.jpg" alt="" />
</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A micro Forth interpreter]]></title>
    <link href="http://demin.ws/blog/english/2012/09/27/fcode/"/>
    <updated>2012-09-27T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/27/fcode/</id>
    <content type="html"><![CDATA[<p>Being &ldquo;a low-level guy&rdquo; by nature, I couldn&rsquo;t miss the Forth language in life.
Forth occupies an interesting niche: on one hand it is a high-level assembler,
allowing to write almost on the assembly language, and on the other hand it
allows to quickly build sophisticated high-level interactive systems, even
with introspection but also staying at an adequate level of performance.</p>

<p>I know that C is THE low-level assembler, and when it is used properly
it generates code very close to the assembly. But nevertheless there are some
systems still where the C compiler is difficult to implement efficiently.
For example, I wanted a C compiler for Intel 8080 to write a program for
Radio-86RK. So far, I have found only a couple derivatives of the famous
<a href="http://en.wikipedia.org/wiki/Small-C">Small-C</a> &ndash; <a href="https://github.com/begoon/smallc-85">smallc-85</a> and <a href="https://github.com/begoon/smallc-scc3">smallc-scc3</a> which compile and work.</p>

<p>Unfortunately, even for trivial code:</p>

<pre><code>main() {
  static char a;
  for (a = 1; a &lt; 10; ++a) {
     ++a;
  }
}
</code></pre>

<p>It generates the following rubbish:</p>

<pre><code>;main() {
main:
;  static char a;
    dseg
?2: ds  1
    cseg
;  for (a = 1; a &lt; 10; ++a) {
    lxi h,?2
    push    h
    lxi h,1
    pop d
    call    ?pchar
?3:
    lxi h,?2
    call    ?gchar
    push    h
    lxi h,10
    pop d
    call    ?lt
    mov a,h
    ora l
    jnz ?5
    jmp ?6
?4:
    lxi h,?2
    push    h
    call    ?gchar
    inx h
    pop d
    call    ?pchar
    jmp ?3
?5:
;     ++a;
    lxi h,?2
    push    h
    call    ?gchar
    inx h
    pop d
    call    ?pchar
;  }
    jmp ?4
?6:
;}
?1:
    ret
</code></pre>

<p>Agreed, there are a lot of questions to the compiler, but in general Intel
8080 isn&rsquo;t quite friendly for the C compiler: no multiplication and division,
no indirect addressing on the stack, etc.</p>

<p>Okay, back to Forth. When thinking about Forth for I8080 I wrote a handy
macro assembler (it&rsquo;ll be a separate blog post) and along the way remembered
about my old project back to FidoNet times: F-CODE. To obfuscate the code
against tracing and disassembling I implemented a micro Forth kernel with
<a href="http://en.wikipedia.org/wiki/Threaded_code">direct threading</a>.</p>

<p>&ldquo;Implemented a micro Forth kernel&rdquo; sounds &ldquo;cool&rdquo; but in reality the direct
threading code interpreter is almost trivial:</p>

<pre><code>; F-Code Address Interpreter

GetNext$:       cld
                mov     si, IP$
                lodsw
                mov     IP$, si
                retn

CALLR$:         add     RP$, 2
                mov     bp, RP$
                mov     ax, IP$
                mov     [bp], ax
                pop     word ptr IP$
                next

RETR$:          mov     bp, RP$
                mov     ax, [bp]
                mov     IP$, ax
                sub     RP$, 2
                next

NEXT$:          call    GetNext$
                jmp     ax

osPush$:        call    GetNext$
                push    ax
                next

NEXT            MACRO
                jmp     NEXT$
                ENDM
</code></pre>

<p>Plus, a few extra primitives implemented in assembly:</p>

<pre><code>; Adc  ( a b -&gt; c isCarry )
; if a+b&gt;FFFF isCarry = FFFF else isCarry=0

osAdc$:         pop     ax  dx          ; -&gt; a b
                add     ax, dx
                sbb     dx, dx
                push    ax  dx          ; c isCarry -&gt;
                NEXT

; osSwap ( a b -&gt; b a )

osSwap$:        pop      ax bx
                push     ax bx
                NEXT

; osRot ( a b c -&gt; b c a )

osRot$:         pop      ax bx cx
                push     bx ax cx
                NEXT

osPut$:         add     RP$, 2
                mov     bp, RP$
                pop     word ptr [bp]
                NEXT

osGet$:         mov     bp, RP$
                push    word ptr [bp]
                sub     RP$, 2
                NEXT

osDrop$:        add     sp, 2
                NEXT

; osNor ( a b -&gt; a NOR b )

osNor$:         pop     ax bx
                or      ax, bx
                not     ax
                push    ax
                NEXT

osTrap$:        int     3
                NEXT

; osPeek ( addr -&gt; value )

osPeek$:        pop     bx
                push    word ptr [bx]
                NEXT

; osPoke ( Value Addr -&gt; )

osPoke$:        pop     bx              ; -&gt; Value Addr
                pop     word ptr [bx]   ; -&gt;
                NEXT
</code></pre>

<p>Now we have a complete stack machine which we can program. Obviously,
when tracing or disassembling the threaded code there are only jumps back and
fourth making it very difficult for reverse engineering (the purpose of the
obfuscation). If you&rsquo;re curious you may try digging into <a href="https://github.com/begoon/fcode/blob/master/FCODE.COM">fcode.com</a>. This
little program asks a password which you need to guest/crack/patch/etc.
Note that this is a DOS binary, so it needs, for instance, DOSBox to run.</p>

<p>For example, code to compute CRC on this stack machine:</p>

<pre><code>CalcCRC:        CALLR                 ; -&gt;
                ofPush  0             ; CRC
                ofPush  0             ; CRC 0
                ofPeekb Buffer+1      ; CRC 0 Size
                $For                  ; CRC
                    osI                   ; CRC i
                    ofPush  Buffer+2      ; CRC i Buffer+2
                    osAdd                 ; CRC Addr
                    osPeekb               ; CRC Value
                    osExch                ; CRC Value*256
                    $For    0, 8          ; CRC Value
                        osShl                 ; CRC Value*2 isCarry
                        osRot                 ; Value*2 isCarry CRC
                        osSwap                ; Value*2 CRC isCarry
                        osRcl                 ; Value*2 CRC*2 isCarry
                        $If &lt;&gt;0               ; Value*2 CRC*2
                            ofXor 8408h           ; Value*2 CRC*2^Const
                        $Endif
                        osSwap                ; CRC*2 Value*2
                    $Loop                   ; CRC Value*2
                    osDrop                ; CRC
                $Loop                 ; CRC
                RETR
</code></pre>

<p>Awesome, right?</p>

<p>When working on F-CODE a simple preprocessor for the assembler language was
born allowing to write code like this:</p>

<pre><code> lea dx, msg2
 cmp bh, 3
 $if &lt;&gt;0
   lea dx, msg1
 $else
   hlt
 $endif

 cmp dx, 0C0DEh
 $if =0
   lea dx, msg2
 $endif

 mov cx, 2
 $Do
   $Do
   cmp ax, 1
   $EndDo =
   dec cx
 $EndDo Loop

 Store ds, si, ax
     $Do
       cmp al, 1
       $if &lt;&gt;0
         $ExitDo
       $endif
       Store ax, bx, cx, es, bp
         ...
       Restore
       $ContDo
     $EndDo Loop
 Restore
</code></pre>

<p>Similar to other projects back in DOS times I wrote the preprocessor in Turbo
Pascal.</p>

<p>Of course the F-CODE project now has predominantly historical value, although
nothing stops to implement the interpreter, for instance, in JavaScript and
then re-use existing primitives without any changes.</p>

<p>The F-CODE project is available at GitHub &ndash; <a href="https://github.com/begoon/fcode">https://github.com/begoon/fcode</a>.</p>

<p>It requires TASM/TLINK and Turbo Pascal 5.+ to build. Obviously, it also
requires DOS to run.</p>

<p>P.S. By the way, people develop quite sophisticated software in Forth.
For example, <a href="http://www.nncron.ru/">nnbackup</a> is fully written in Forth.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[iPhone 5]]></title>
    <link href="http://demin.ws/blog/english/2012/09/22/iphone5/"/>
    <updated>2012-09-22T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/22/iphone5/</id>
    <content type="html"><![CDATA[<p>I visited the Apple Store today at Covent Garden to checkout the iPhone 5.</p>

<p>Lighter, thinner, faster.</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0986.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0992.JPG" alt="" />
</p>

<p>The new connector, plus the headset is at the bottom now.</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0993.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0995.JPG" alt="" />
</p>

<p>The new connector (male).</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0996.JPG" alt="" />
</p>

<p>People are seriously stuck to desks with the iPhone 5.</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0997.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0998.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0999.JPG" alt="" />
</p>

<p>By they way, the new 3D-maps in iOS6 are fantastic! Unfortunately, not
available for my iPhone 4 (not S).</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0985.JPG" alt="" />
</p>

<p>The traditional sound check on the right website.</p>

<p><img src="http://demin.ws/images/blog/iphone5/IMG_0984.JPG" alt="" />
</p>

<p>A little followup.</p>

<p>Regardless that I&rsquo;m fully on Apple products, I believe that I still have
at least a little bit of common sense. If some Apple products are bad or
even shit (like Magic Mouse, for instance) I joyfully state that.
But brothers! The iPhone 5 is an amazing product of design and engineering.
God bless Apple&rsquo;s designers and engineers. You may hate Apple for their
pathos and show off, you may try suing them and even win. But! (Samsung,
for example) Please! Create something even close to the iPhone 5. And
all Apple&rsquo;s money and glory will be yours.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Embedded compression libraries - miniz and minilzo]]></title>
    <link href="http://demin.ws/blog/english/2012/09/18/miniz-minilzo/"/>
    <updated>2012-09-18T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/18/miniz-minilzo/</id>
    <content type="html"><![CDATA[<p>For <a href="https://github.com/begoon/rk86-maximite">my emulator of the classic 8-bit computer called Radio-86RK</a>
running on the Maximite microcomputer I needed a compression library.
The emulator has a virtual ROM drive, but the overall amount of files
I wanted to put there was more than 1M, and the capacity of the PIC32
flash was only 512K. So, a cunning plan was to compress the data and then
decompress them on-the-fly inside the PIC.</p>

<p>Two compression libraries were discovered:</p>

<ul>
<li><a href="http://code.google.com/p/miniz/">miniz</a> (zlib and deflate algorithms)</li>
<li><a href="http://www.oberhumer.com/opensource/lzo/#minilzo">minilzo</a> (LZO algorithm)</li>
</ul>

<p>The selection criteria were:</p>

<ul>
<li>a single source library without any dependecies</li>
<li>scrict ANSI C (I used the Microchip XC32 compiler)</li>
<li>in-memory decompression</li>
<li>a small static amount of temporary memory for decompression
(no malloc/calloc) (ideally, it should use the output decompression
buffer only)</li>
</ul>

<p>The both libraries compiled and worked for PIC32 without any issues.</p>

<p>On my data miniz provided the 0.78 compression ratio and minilzo - 0.71.
So, both didn&rsquo;t squeeze my data into the 512KB flash of PIC32.</p>

<h3>Overall impression</h3>

<ul>
<li>miniz is slightly easier to use and more powerfull from the API perspective</li>
<li>minilzo provides better compression</li>
</ul>

<p>Also miniz uses <strong>only</strong> the output buffer for decompression, but minilzo
requries at least 16K static buffer.</p>

<p>P.S. I also tried <a href="http://tukaani.org/xz/embedded.html">XZ Embedded</a> (LZMA2).  It looked that it compressed
much better but it requires malloc/free API, so I didn&rsquo;t manage to build
it on PIC32 without extra development.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Buy Round: My second iPhone app]]></title>
    <link href="http://demin.ws/blog/english/2012/09/16/buyround-app/"/>
    <updated>2012-09-16T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/16/buyround-app/</id>
    <content type="html"><![CDATA[<p>The good half of this post in Russian was about explaining the great UK
pub culture and the concept of the round at the pub. This is quite pointless
information for English speaking readers, so I just jump straight to the
technical part.</p>

<p>I wanted a simple and quick app helping me to remember a list of drink in
the round. Plus, I wanted to write something for iOS in general. Eventually, I ended up with this:</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/0ba2Oacm8Dg" frameborder="0" allowfullscreen></iframe>

<p>Quick and dirty, but it solves the problem in 100%. I personally use this
app all the time. Unfortunately, AppStore has rejected it as the app having
too limited functionality. Well, bad for them, good for me. I have learned
a lot developing this app.</p>

<p>I had to learn the following classes:</p>

<ul>
<li>UITabBarController to manage two tab views.</li>
<li>UIViewController to work with tables via UITableViewDataSource and
UITableViewDelegate delegates.</li>
<li>Object serialization via NSKeyArchiver to save the list of drink to a file.</li>
</ul>

<p>The full project is available at GitHub - <a href="https://github.com/begoon/buyround">https://github.com/begoon/buyround</a>. Please, feel free to checkout and build
it.</p>

<p>As I wrote previously about my first iPhone app - <a href="http://demin.ws/blog/english/2012/09/05/usvisa-my-first-iphone-app/">US Visa</a>, the
quality of the artwork, especially, icons, plays the crucial role in the
success of a mobile application. I&rsquo;ve googled one (below) but it is much
better to design your own one.</p>

<p><img src="http://demin.ws/images/blog/buyround/beer-114x114.png" alt="" />
</p>

<p>P.S. For the sake of making this post complete I&rsquo;ve decided to attach a photo
of absolutely inhuman conditions of creating it.</p>

<p><img src="http://demin.ws/images/blog/buyround/about-buyround.jpg" alt="" />
</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A vintage game &#34;Karateka&#34;]]></title>
    <link href="http://demin.ws/blog/english/2012/09/15/karateka/"/>
    <updated>2012-09-15T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/15/karateka/</id>
    <content type="html"><![CDATA[<p>A rhetorical question: if you have never played Karateka it&rsquo;s worth doing it.
You can google for the <code>karateka.dsk.gz</code> file and load it into the AppleWin
emulator.</p>

<p><img src="http://demin.ws/images/blog/karateka/karateka-screenshot-applewin.png" alt="" />
</p>

<p>There is a DOS version, but, unfortunately, the gameplay was slightly changed.
In the Apple&rsquo;s version the opponents inside the house never approach you
first. There was a trick: a little step towards and immediately step back.
This was the only way to force them to attack you. Then you can low-kick them.
In the DOS version they always attack first, so just low-kick.</p>

<p><img src="http://demin.ws/images/blog/karateka/karateka-screenshot.png" alt="" />
</p>

<p>But for the DOS version there is a magic <a href="http://demin.ws/images/blog/karateka/KARATEKA.XCK">patch</a> allowing to speedrun
the game.</p>

<pre><code>Immortality
KARATEKA.EXE
00003066: 48 90
00003D7E: 48 90

Steel breast
KARATEKA.EXE
0000306E: 83 C6
0000306F: 3E 06
00003072: 3F 01
00003073: 7E 75

Flying kick for humans
KARATEKA.EXE
00002F30: 7E 00

Flying kick for bird
KARATEKA.EXE
00002E2F: 7F 00
00002E30: 01 00
00002E34: 3D 25
00002E35: 04 00
00002E44: 06 00

Kill bird by first kick
KARATEKA.EXE
000031BA: 85 33

Kill humans by first kick
KARATEKA.EXE
00002F3A: 85 33
</code></pre>

<p>For example:</p>

<iframe width="480" height="360" src="http://www.youtube.com/embed/HjeuB6pxMzI" frameborder="0" allowfullscreen></iframe>

<p>Don&rsquo;t miss at the end when the princess hopelessly kicks you when you
approach in the stance.</p>

<p>P.S. Unfortunately, the sources of this spectacular game are still closed.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A vintage Apple&#39;s game &#34;BOLO&#34;]]></title>
    <link href="http://demin.ws/blog/english/2012/09/10/bolo/"/>
    <updated>2012-09-10T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/10/bolo/</id>
    <content type="html"><![CDATA[<p>If you have never played BOLO, it&rsquo;s worth doing it. It was originally written
for Apple II. You control the tank in the maze and have to find and destroy
bases. You can download the AppleWin emulator, then google for &ldquo;bolo.dsk.gz&rdquo;
file and play almost the original game.</p>

<p><img src="http://demin.ws/images/blog/bolo/bolo-screenshot-applewin.png" alt="" />
</p>

<p>Its <a href="http://demin.ws/images/blog/bolo/BOLO.COM">DOS implementation</a> is a quite precise replica perfectly working on
modern systems in DOSBox:</p>

<pre><code>dosbox -exit BOLO.COM
</code></pre>

<p><img src="http://demin.ws/images/blog/bolo/bolo-screenshot.png" alt="" />
</p>

<p>Years ago I created a <a href="http://demin.ws/images/blog/bolo/BOLO.XCK">patch</a> to know what happens at the end:</p>

<pre><code>Unlimited lives
BOLO.COM
00000174: 4F 00
00000178: DF 4A
00000179: FE FF

Unlimited fuel
BOLO.COM
00000A38: 06 04

Immortality &amp; pass through the walls
BOLO.COM
00000C61: 01 00
0000172D: 01 00
00001817: 01 00
</code></pre>

<p>With this patch you can play like this:</p>

<iframe width="480" height="360" src="http://www.youtube.com/embed/pcqygeYP4qs" frameborder="0" allowfullscreen></iframe>

<p>Unfortunately, there are no sources of the original BOLO available, so
porting to SDL, for instance, is fully about reverse engineering of the
original binaries (either of the Apple II version or the DOS clone), which
is not that easy. I know there are some other BOLO clones for Windows are
available, but they are physically different games, not original BOLO.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Saleae Logic digital circuit analyzer]]></title>
    <link href="http://demin.ws/blog/english/2012/09/07/saleae-logic/"/>
    <updated>2012-09-07T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/07/saleae-logic/</id>
    <content type="html"><![CDATA[<p>When playing with the <a href="http://demin.ws/blog/english/2012/07/04/gmc-4/">GMC-4 microcomputer</a> and thinking about
<a href="http://demin.ws/blog/english/2012/07/25/gmc4-loader-assembled/">an automated loader</a> for it, I realised that
having an oscilloscope would be a nice idea because I wouldn&rsquo;t figure
out how the GMC-4 keyboard works only with a simple tester. It didn&rsquo;t happen
to buy a <em>proper</em> oscilloscope like Rigol, for instance, but
<a href="http://sensi.org/~svo/">Viacheslav Slavinsky</a> suggested to take a look at an interesting option:
<a href="http://www.saleae.com/logic/">Saleae Logic</a>. Of course, this is <strong>not</strong> a regular oscilloscope, but a
simple digital channel analyzer capable to capture 8 or 16 channels
simultaneously and decode protocol like UART, SPI, I2C or others. Exactly
what I wanted.</p>

<p>It costs 128€ + 25.80€ VAT for the 8 channel model. They have stock in
the UK, so delivery was free, fast and no customs involved.</p>

<p>At the beginning I had a cunning plan to buy, play for a while and then
return. They provide an option for full money back within a month <strong>without
explaining anything</strong>. This is very good. Frankly, if there was no such
option, I would never buy it.</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/IMG_0530.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/IMG_0531.JPG" alt="" />
</p>

<p>It turned out to be a match box size thing in the solid metal case.</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/IMG_0532.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/IMG_0534.JPG" alt="" />
</p>

<p>The complete set.</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/IMG_0535.JPG" alt="" />
</p>

<p>Connecting&hellip;</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/IMG_0536.JPG" alt="" />
</p>

<p>To begin with I connected it to a serial port on Raspberry Pi, which
I was using as a telnet console.</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/IMG_0537.JPG" alt="" />
</p>

<p>Here is a screen shot of the capture. We see that the <code>ls</code> command is flying
to one direction and being echoed back from the second one.</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/saleae-logic-analyser-ls-command.jpg" alt="" />
</p>

<p>Now the GMC-4 keyboard. This is a <a href="http://www.learningaboutelectronics.com/Articles/How-does-a-matrix-keyboard-scanning-algorithm-work">scanned keyboard</a> where one (out) port is
used to set a &ldquo;flying&rdquo; pin selecting the current row (or column) of
buttons, and the second (in) port represents the state of buttons in the
selected row.</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/gmc4-schematic.jpg" alt="" />
</p>

<p>I planned to simulate the keyboard, so I needed timings of the scanning
signal. I connected all four scanning lines to four channels, and got the
following:</p>

<p><img src="http://demin.ws/images/blog/saleae-logic/saleae-logic-analyser-gmc4-keyboard.jpg" alt="" />
</p>

<p>Now it is crystal clear what&rsquo;s going on. It allows to measure a variety of
parameters of the signal, scale it and compare against previous runs. There
is <a href="http://www.saleae.com/logic/videos">a good quality video</a> available on the official website showing
some use cases in details. My status in electronics is a layman, so I was
simply impressed by the ease of use. The guy, Viacheslav, who recommended me
this device, says that for debugging a complicated digital circuit design it
is crucial to be able to capture much more than one or two channels
simultaneously.</p>

<p>As you have probably realised, I didn&rsquo;t return the device, but I had a
complaint though. I wasn&rsquo;t able to capture on the highest frequency
of 24MHz. The Logic software complained about lack of USB bandwidth when
transferring data from the Logic to the computer. The Support suggested
an issue with my particular USB hub, but I tried different setups and the
problem still stands. But they were ready to take the device back and
refund anytime. Regardless, I liked the device and kept it. It perfectly
solves all my current needs.</p>

<h2>The conclusion</h2>

<h3>Pros</h3>

<ul>
<li>Extremely simple is use.</li>
<li>Configurable triggers to initiate capturing (by level, by front, etc.).</li>
<li>8 or 16 channels depending on the model for simultaneous capture.</li>
<li>100% money back within a month if you&rsquo;re uncertain.</li>
</ul>

<h3>Cons</h3>

<ul>
<li>No online mode. You capture first, then view, analyse etc. So, don&rsquo;t
expect &ldquo;regular oscilloscope experience&rdquo;.</li>
<li>My Mac Air wasn&rsquo;t able to capture on the maximal frequence of 24MHz.</li>
</ul>

<h3>One liner</h3>

<p>Recommended.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Aliases in Gmail]]></title>
    <link href="http://demin.ws/blog/english/2012/09/06/gmail-aliases/"/>
    <updated>2012-09-06T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/06/gmail-aliases/</id>
    <content type="html"><![CDATA[<p>It turns out that, if, for instance, your Gmail address is <code>comrade@gmail.com</code>,
e-mails addressed to <code>com.rade@gmail.com</code> or even to <code>c.o.m.r.a.d.e@gmail.com</code>
will be delivered to the first address.</p>

<p>It&rsquo;s cool but quite useless. There is another interesting feature. E-mails sent
to the addresses below:</p>

<ul>
<li><code>comrade+fred@gmail.com</code></li>
<li><code>comrade+john@gmail.com</code></li>
<li><code>comrade+peter@gmail.com</code>
&hellip;</li>
<li><code>comrade+a_somebodies_name@gmail.com</code></li>
</ul>

<p>will be also delivered to <code>comrade@gmail.com</code>. Then it is possible to set
some filtering rules in Gmail redirecting these e-mails to appropriate people
depending on that extra bit in the &ldquo;From:&rdquo; address between <code>+</code> and <code>@</code> symbols.</p>

<p>This may help organizing a free &ldquo;pseudo&rdquo; mail server with Gmail.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[US Visa: My First iPhone App]]></title>
    <link href="http://demin.ws/blog/english/2012/09/05/usvisa-my-first-iphone-app/"/>
    <updated>2012-09-05T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/05/usvisa-my-first-iphone-app/</id>
    <content type="html"><![CDATA[<p>The Pragmatic Bookshelf Magazine has published my article called
&ldquo;<a href="http://pragprog.com/magazines/2012-09/us-visa-my-first-iphone-app/">US Visa: My First iPhone App</a>&rdquo;. I don&rsquo;t want to duplicate it here, but
I&rsquo;ve recorded an additional video for your convenience:</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/m6pfXBHTyY4" frameborder="0" allowfullscreen></iframe>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A first hack of my motto]]></title>
    <link href="http://demin.ws/blog/english/2012/09/05/first-hack-of-motto/"/>
    <updated>2012-09-05T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/05/first-hack-of-motto/</id>
    <content type="html"><![CDATA[<p>Today I&rsquo;ve got an email with the motto which is encoded on my &ldquo;<a href="http://demin.ws/english/about/">About</a>&ldquo;
page. An early bird.</p>

<p>By the way, there is no prize for solving this problem except the honour
and a link which I can put with the solver&rsquo;s name.</p>

<p>Please, don&rsquo;t post the solution anywhere in comments letting others to try
solving it independently.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Levels for Sokoban]]></title>
    <link href="http://demin.ws/blog/english/2012/09/04/sokoban-maps/"/>
    <updated>2012-09-04T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/04/sokoban-maps/</id>
    <content type="html"><![CDATA[<p>At the times of XTs and DOS I loved playing Sokoban. The game I had was a
tiny executable (less than 10Kb) for DOS called <a href="http://demin.ws/files/pusher.zip">pusher.exe</a>:</p>

<p><img src="http://demin.ws/images/blog/pusher-sokoban-level-01.png" alt="" />
</p>

<p>That was the first, simplest level, but how about this one?</p>

<p><img src="http://demin.ws/images/blog/pusher-sokoban-level-59.png" alt="" />
</p>

<p><em>The game perfectly works in DOSEmu: <code>DOSEmu -exit pusher.exe</code>.</em></p>

<p>Lazy people can checkout a quick video instead:</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/3zi-ZuL6GKI" frameborder="0" allowfullscreen></iframe>

<p>I was curious how 60 maps fitted into such a tiny executable. After a bit
of fiddling with IDA I wrote a simple program to extract the maps from the
<code>pusher.exe</code> binary and print them out. For example:</p>

<pre><code>*************************************
Maze: 1
File offset: 148C, DS:00FC, table offset: 0000
Size X: 22
Size Y: 11
End: 14BD
Length: 50

    XXXXX
    X   X
    X*  X
  XXX  *XXX
  X  *  * X
XXX X XXX X     XXXXXX
X   X XXX XXXXXXX  ..X
X *  *             ..X
XXXXX XXXX X@XXXX  ..X
    X      XXX  XXXXXX
    XXXXXXXX

*************************************
</code></pre>

<p>All the map <a href="https://raw.github.com/begoon/sokoban-maps/master/maps/sokoban-maps-60-plain.txt">are available</a>.</p>

<p>The maps are compressed with a Huffman-like approach using bit sequences
of variable length. Each level has the following structure:</p>

<ul>
<li>map size X (1 byte)</li>
<li>map size Y (1 byte)</li>
<li>X*Y bytes of the map represented as a sequence of pairs &lt;COUNTER&gt;&lt;CODE&gt;.
&lt;COUNTER&gt; is either a single 0 bit which means one repetition,
or four bits <code>1 D3 D2 D1</code>, where the number of repetitions
<code>N = 2 + D3*4 + D2*2 + D1</code> (values 2 to 9). &lt;CODE&gt; has five different
values: 00 - an empty space, 01 - a wall, 10 - a barrel, 101 - a place
for the barrel, 111 - a barrel already in place.</li>
<li>Player&rsquo;s start position X (1 byte)</li>
<li>Player&rsquo;s start position Y (1 byte)</li>
</ul>

<p>And so for all 60 maps.</p>

<p>In the file <a href="https://github.com/begoon/sokoban-maps/blob/master/pushermaps.c">pushermaps.c</a> there is an implementation of the simple
decompressor.</p>

<p>When <a href="https://github.com/begoon/sokoban-maps/blob/master/disasm/pusher.lst">disassembling</a> the maps also had been presented in the
convenient plain text form but still compressed.</p>

<pre><code>level_01        db 16h, 0Bh, 0A2h, 0DFh, 38h, 32h, 1Fh, 38h, 2Ah, 3, 0E6h
                db 12h, 0C0h, 0A5h, 0F2h, 83h, 2, 81h, 3, 0E4h, 12h, 82h
                db 25h, 6, 0CDh, 64h, 22h, 51h, 0ACh, 11h, 0A1h, 0Ah, 5
                db 0E5h, 11h, 0B1h, 14h, 82h, 29h, 82h, 31h, 0A0h, 0E1h
                db 2Ch, 18h, 0D1h, 0CFh, 80h, 0Ch, 8
level_02        db 0Eh, 0Ah, 0F6h, 58h, 0Ch, 68h, 0Dh, 94h, 0C6h, 80h
                db 85h, 2, 82h, 18h, 0D0h, 15h, 4Ch, 10h, 0C6h, 0C2h, 18h
                db 21h, 8Dh, 1, 6, 4, 39h, 10h, 0A0h, 81h, 80h, 85h, 2
                db 8, 20h, 60h, 34h, 1Bh, 0Ch, 1Eh, 0CAh, 7, 4
level_03        db 11h, 0Ah, 0E3h, 9Fh, 0Eh, 7, 0C2h, 11h, 42h, 1Fh, 8
                db 50h, 23h, 0E0h, 85h, 4, 0Ch, 1Eh, 84h, 8, 0A6h, 0B4h
                db 10h, 85h, 2, 82h, 59h, 0D4h, 28h, 14h, 90h, 0D6h, 83h
                db 0DFh, 7Ch, 0Eh, 1
</code></pre>

<p>&hellip; etc.</p>

<p>So if you&rsquo;d like to implement a quick and compact Sokoban for some reason,
there is a <a href="https://github.com/begoon/sokoban-maps/blob/master/maps/sokoban-maps-60-compressed.txt">bunch of already created and nicely compressed maps</a>.</p>

<p>I know that there are tons of levels for Sokoban in the internet, plus
automated Sokoban solvers and similar stuff. But it still doesn&rsquo;t make
all that fun of dissecting the twenty years old or more binary less
interesting.</p>

<p>The project is available at GitHub&rsquo;e &ndash; <a href="https://github.com/begoon/sokoban-maps">https://github.com/begoon/sokoban-maps</a>.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Sinclair ZX Spectrum in person]]></title>
    <link href="http://demin.ws/blog/english/2012/09/01/sinclair-zx-spectrum/"/>
    <updated>2012-09-01T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/09/01/sinclair-zx-spectrum/</id>
    <content type="html"><![CDATA[<p>I had been thinking about it for a while and eventually I had bought it &ndash; the genuine Sinclair ZX Spectrum, the 48KB model, for fifty quid on Ebay. I had it years ago, but it was a clone called &ldquo;Leningrad&rdquo; built on Russian components.</p>

<p><em>(photo from Wikipedia)</em></p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/sinclair-zx-specturm-leningrad-board.jpg" alt="" />
</p>

<p>Now it is genuine!</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0702.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0705.JPG" alt="" />
</p>

<p>Open it up! It didn&rsquo;t risk to detach the keyboard, so I had to photograph from two angles.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0708.JPG" alt="" />
</p>

<p>The label &ldquo;1982 ISSUE TWO&rdquo; is visible at the bottom left.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0709.JPG" alt="" />
</p>

<p>There are a few lovely &ldquo;extra&rdquo; parts stuck on some chips. Maybe it was a result of the &ldquo;last minute tuning&rdquo; or maybe the previous owner did it.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0711.JPG" alt="" />
</p>

<p>The seller also gave a bunch of tapes. I haven&rsquo;t seen 15 minutes cassettes before.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0713.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0714.JPG" alt="" />
</p>

<p>Extras.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0715.JPG" alt="" />
</p>

<p>So lovely books.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0812.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0813.JPG" alt="" />
</p>

<p>People had guts to put proper illustrations in manuals at that time.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0814.JPG" alt="" />
</p>

<p>I also bought a very old TV at car boot sale for a pound.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0811.JPG" alt="" />
</p>

<p>Unfortunately, this machine didn&rsquo;t boot up. It beeped and printed rubbish on the screen. The seller argued for a while saying something about video synchronization problems but after the video (below) agreed to refund. Reluctantly I had to send it all back.</p>

<p><img src="http://demin.ws/images/blog/sinclair-zx-spectrum/IMG_0808.JPG" alt="" />
</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/ODSrvOOc_xg" frameborder="0" allowfullscreen></iframe>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An interview with Charles Wetherell]]></title>
    <link href="http://demin.ws/blog/english/2012/08/25/interview-with-charles-wetherell/"/>
    <updated>2012-08-25T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/25/interview-with-charles-wetherell/</id>
    <content type="html"><![CDATA[<p>Today my guest is Charles Wetherell, the author of &ldquo;Etudes for Programmers&rdquo;, published in 1978. It remains a source of fascinating and realistic problems for computer science students in a wide range of disciplines. Charles is now a Computer Scientist at Oracle and he agreed to write about himself and &ldquo;Etudes&rdquo;. Thanks, Charles, for the interview.</p>

<hr />

<p><img src="http://demin.ws/images/blog/charles-wetherell.jpg" alt="" />
</p>

<blockquote>
<p>Programs should always have the form of paragraphs of comments that describe the intention of the program followed by paragraphs of code that implement that intention. All of the formatting should be designed to make readers as able as possible to read the code easily; the compiler doesn&rsquo;t care. In particular, follow conventions of mathematics and your native language, not those you found in some random language manual. Write the comments first and then write the code, not the other way around. If you don&rsquo;t know what you want to achieve and why, any code you write is, by definition, incorrect.</p>
</blockquote>

<hr />

<p><strong>&ldquo;Etudes&rdquo; is very different from other computer science and programming textbooks. &ldquo;Etudes&rdquo; covers most of the important areas in a quite an unusual way. How did you come up with the idea to collect realistic problems from various areas and  put them in a play situation? Could you tell us a little story about how and why the &ldquo;Etudes&rdquo; were born?</strong></p>

<p>From 1974 to 1979, I was teaching at UC Davis. There was a new Computer Science graduate group there formed to give degrees in Computer Science, but it was really just a loose collection of faculty members from several departments. The department of Applied Science hired me as the first professor with a computer science degree to pull the program together. Along with a small group of other professors and adjunct instructors, we designed a new curriculum, put degree programs in place, and began teaching a number of new or redesigned courses.</p>

<p>During this redesign, I got the other faculty to agree that students needed to know how to work in the real world as well as to learn the theory surrounding computer science. By &ldquo;work&rdquo; in the real world, I don&rsquo;t mean that I wanted to teach them &ldquo;job relevant&rdquo; topics; in my experience, such knowledge becomes obsolete quickly. Rather, I wanted to have them work on problems that included making imprecise specifications precise, on problems whose requirements were unclear, on problems that had real world application, on problems that required working with other people. For example, in the compiler construction course, students were required to work in two or three person teams and the same grade was assigned to everybody on a team. Part of the assignment was to write up how they divided their work and whether they thought the division was successful.</p>

<p>After a bit, we decided to teach a programming projects course to consolidate student knowledge of how to build complete applications. We thought of a few projects and I wrote them up. But when I looked around for more, I could only find one book that had only &ldquo;toy&rdquo; exercises in it &ndash; for example, print a table of all the possible binary Boolean operators. I also found one or two problems that Carnegie-Mellon used in one of its courses. So before long, I was writing &ldquo;Etudes&rdquo;. As it turned out, I left UC Davis soon after the book was published, so I don&rsquo;t really know if they continued to use it in the projects course.</p>

<p><strong>How long did it take to write the book?</strong></p>

<p>&ldquo;Etudes&rdquo; took about 18-24 months start to finish. I had written up a few chapters for course work already. Contract negotiation was very fast, as I remember; perhaps only a month or so. I spent about a year writing the remaining chapters. Of course, I had to fit that around my other work. Then there was perhaps six months of review and revision. Once everything was in place, I only had to wait a month or two after final galley proofs went in to see my first copy.</p>

<p><strong>Why didn&rsquo;t you publish any other books after &ldquo;Etudes&rdquo;? Why wasn&rsquo;t &ldquo;Etudes&rdquo; republished?</strong></p>

<p>I left UC Davis to go work at Bell Labs. While I was there, I ran a project that built one of the first Ada compilers. We published technical papers, but there wasn&rsquo;t a lot of time to write another book. After Bell Labs, I came out to Silicon Valley for a startup and, again, there wasn&rsquo;t a lot of time for book writing. I also started a family and taking care of kids is (as most parents know) fairly time-consuming. And then you know how it goes.</p>

<p>Back in the early 70&rsquo;s, Juris Hartmanis (one of my favorite teachers) told me that if you wrote a computer science textbook, you would make enough money to buy a new car. The reason was that there were at the time enough libraries who would all buy a copy of the book that the minimum income would be enough to buy at least a Volkswagen (VW Bugs were still around then!). If you got lucky, you might be able to buy a Mercedes Benz. And, of course, if you wrote something like Samuelson&rsquo;s &ldquo;Economics&rdquo;, you could buy a new Lamborghini every year.</p>

<p>But for textbooks to do well, they have to be adopted in courses. Unfortunately, only a few colleges in the US adopted &ldquo;Etudes&rdquo;. So there wasn&rsquo;t a lot of income from it. And the publisher had no real incentive to publish a new edition. There were a lot of individual people who bought copies, but that doesn&rsquo;t help for textbooks.</p>

<p>One odd thing did happen, though. Right after &ldquo;Etudes&rdquo; was published, the Soviet academic publishing office reviewed it and decided to buy the copyright so that it could publish &ldquo;Etudes&rdquo; in Russia and the other Soviet Union states. This was a real diplomatic breakthrough, actually; quite commonly, the Soviet Union had simply ignored copyrights in the past. The payment from the Soviet purchase was a pleasant surprise.</p>

<p>Unfortunately, though, not a very profitable one. They paid $1,200 for the rights and that wasn&rsquo;t a lot of money even in the late 70&rsquo;s. I got half or $600. The good part was that &ldquo;Etudes&rdquo; was translated into Russian and used widely in the Soviet computer science curriculum. I work, for example, with two Russians who used it as undergraduates. Alexander, you are a third! I think that there were at least 60,000 Russian copies published.</p>

<p>And what kind of car did I buy? Actually, I bought a brand new piano that&rsquo;s still sitting in my living room.</p>

<p><strong>How did you find topics for the etudes?</strong></p>

<p>There were several ways. One or two were problems I had in practical life. For example, the gasoline mileage etude and the investment etude came from things I worked on for myself. Some came from my interest in playing games with computers and ideas in artificial intelligence; obviously, the kalah and the management game were of that sort. The language problems at the end were revisions of the materials from our compiler course. Some of the problems are straight computer science just dressed up: the Turing machine, the map coloring, the format scanner.</p>

<p>Chapter 4 on automatic text formatting was inspired by a colleague at Lawrence Livermore Laboratory. He had written one of the very first automatic formatters and I had used it when writing my dissertation and the drafts for &ldquo;Etudes&rdquo;. Remember, this was before Unix was well-known and even &ldquo;nroff&rdquo; was pretty fancy stuff. So a problem that introduced the topic seemed reasonable.</p>

<p>The problem solutions were just those that &ldquo;fit&rdquo; within the production confines of the book. And I wanted students to see what &ldquo;real&rdquo; code looks like. Notice that the last problem even says that the solution is incomplete.</p>

<p><strong>For each etude in the book you recommend how long it should take. Since 1978 programming languages have been &ldquo;slightly&rdquo; changed and become &ldquo;a little bit&rdquo; more powerful. But even nowadays, your timings recommendations look quite aggressive. Did you &ldquo;play&rdquo; the etudes yourself working over the book? Do you have your favorite one?</strong></p>

<p>In retrospect, this was a big flaw. The durations are aggressive even now, even with very good languages like Ruby (my current favorite) that would do a lot of the work for you. Remember that when &ldquo;Etudes&rdquo; was written, Unix was just becoming broadly available, Basic, Fortran, and Pascal were probably the most common teaching languages, and C was only just becoming known. There were essentially no terminals to program on (although my students actually did mostly have terminals because of their associations with Lawrence Livermore Laboratory) so that students still prepared program card decks.</p>

<p>I&rsquo;m not sure I have a favorite etude. I like the TRAC interpreter. It teaches a lot about the fundamental topics of programming languages, topics that are often ignored in course work. As &ldquo;Etudes&rdquo; mentions, TRAC and Strachey&rsquo;s GPM are languages that were invented simultaneously and independently; the two author&rsquo;s published papers appeared within a few months of one another. The two languages are very similar and both show how a focus on text manipulation can solve large problems. It is particularly rewarding to study them together and to understand how they agree and differ. I also like the EC loader etude because I think it solves problems in programming language translation that are still common; why techniques like this are not still in use is beyond me.</p>

<p>I did not actually get a chance to do a lot of problems when I was writing the book. However, when I went to work at Bell Labs, I had to teach myself Unix and all its tools. So I decided to try programming the gas mileage etude in &ldquo;awk&rdquo;. Oddly enough, I discovered a bug in &ldquo;awk&rdquo; itself that I reported to Brian Kernighan. He commented that he knew there was a problem, but nobody else had been able to pin it down. The bug turned out to be a computer science classic: &ldquo;awk&rdquo; was using some allocated memory after it had already been freed.</p>

<p><strong>I cannot skip a question about the etude about the Vigenere cipher. There were a couple of setups in that chapter, like a &ldquo;tiny&rdquo; typo in the form of a missing line in the crypto text, and also a slightly wrong hint about how to crack the cipher. Of course, it did not stop people from cracking it at all, and it turned out that those &ldquo;accidental complications&rdquo; made this etude even more attractive. Could you shed some light on what happened there?</strong></p>

<p>This is embarrassing. As it turns out, the publisher reset all the copy text before the book was printed, but I supplied the illustrations directly. Unfortunately, I supplied a bad illustration for the actual code text to crack. It wasn&rsquo;t until the Russian translation that anybody noticed (or, at least, told me about it). Any lack of clarity in the text itself was just because of my writing. If that is the only problem in the text of the book itself, I would be very happy.</p>

<p><strong>I presume that the preparation and maybe solving the problems in &ldquo;Etudes&rdquo; was not a straightforward process.  Were there other &ldquo;gotchas&rdquo; or Easter Eggs in &ldquo;Etudes&rdquo;?</strong></p>

<p>There are no other intentional &ldquo;gotchas&rdquo;. When I tried the mileage problem, I realized that it might not be as well specified as it might be. There are probably some other places that could be clarified.</p>

<p>Actually, writing was not too bad. Of course, making the solved problems be suitable took a lot more work than a student might put in; I didn&rsquo;t want to look silly to the readers.</p>

<p>Fortunately, I had a lot of help and that made a big difference. The text and the illustrations were originally produced using innovative formatting and drawing programs developed by Hank Moll and John Beatty. This made the work much easier. I wrote the book itself on &ldquo;coding sheets&rdquo;, paper specially marked to make it easy to keypunch cards. The sheets then went to our keypunch team who actually did a lot of proofreading as they went along. When they thought I had made a mistake (or had made an outrageous pun), they would punch both an original and a correction card so that I could choose which was correct.</p>

<p>My publisher asked several outside reviewers to read and comment on the book drafts. One reviewer of the complete book draft made comments on almost every line. He made the book much better than it would otherwise have been. At the time, I didn&rsquo;t know who this reviewer was. Later, I found out it was Steve Muchnick (well known for his compiler optimization book). I cannot thank him enough.</p>

<p><strong>If you write &ldquo;Etudes&rdquo; today, which topics would you add?</strong></p>

<p>Digital signatures and public key cryptography protocols would probably be a new topic. I would probably tune up the multiple precision arithmetic chapter. I would almost certainly change the compiler/language chapters to include more modern ideas. One thought (due originally to John Fletcher) would be to have a pair of etudes to write a Lisp interpreter in Ruby (maybe) and a simple Ruby system in Lisp. Or something else of the sort.</p>

<p>I would probably drop one or two of the simpler etudes. There is a lot of new artificial intelligence problems (particularly in genetic programming) that would be suitable. There are new ideas in data structures that would be fun to explore (how much better are red-black trees than simple-minded binary trees in terms of performance?). Honestly, though, I can&rsquo;t tell what would make a good problem until I work on it for a while.</p>

<p><strong>Most of the etudes were about implementation rather than figuring out a way to attack a problem in the first place, because you almost always gave quite solid background and enough details of a solution. Do you believe that it is also important to give students problems without even a clue of the solution? How such problems may look like? And how would you measure a degree of success of the solution?</strong></p>

<p>In the real world, you are always faced with some problem to solve and the first issue is figure out what the problem really is. It is good to train students to do that analysis &ndash; and in the real world, that skill is rare &ndash; but that wasn&rsquo;t really the idea in &ldquo;Etudes&rdquo;. That would be a course in itself. The point of &ldquo;Etudes&rdquo; was to give students a reasonable problem setup and to have them practice full application development. There is still a lot of room for student choices. For example, the solved problems make points about the quality of the code, the presentation of results to humans, and the performance of the final application.</p>

<p>There is a probably a course with problems like you propose, but then the course lectures would have to teach analysis techniques and the book itself would have to include materials on analysis. That&rsquo;s a different book.</p>

<p><strong>Charles, regarding your interests and work apart from &ldquo;Etudes&rdquo;, I know your background is compilers. For instance, you developed a compiler for the XPL language. What do you currently work on at Oracle? Still hands on programming?</strong></p>

<p>I am still a programmer. One of the things I like about computer science is that you can actually build the things you think about.</p>

<p>My basic background has always been the theory, design, and implementation of programming languages. When I was an undergraduate, computer science didn&rsquo;t exist yet so my undergrad degree is in applied mathematics. But my undergraduate thesis was on adding new features to TRAC (does that remind you of one of the &ldquo;Etudes&rdquo;?). I have been responsible for XPL, for a complete Ada compiler system, for the LR parser generator (with Al Shannon), for a proposal of array operations in Fortran, for a new dataflow language (with Jim McGraw), and (more recently) for the new code generator and optimizer in the Oracle programming language PL/SQL. Lately I have been working on some special projects at Oracle in the area of programming languages. If they work out, you&rsquo;ll see the papers on them.</p>

<p><strong>Looking at the topics in your book, it is not easy to guess which area of computer science is your favorite one. Even in the section about compilers you offered an interactive functional TRAC along with a regular procedural language. Do you have favorite areas of computer science?</strong></p>

<p>My favorite computer science topics are:</p>

<ol>
<li><p>Programming languages, particularly the specification of their semantics.</p></li>

<li><p>Data structures and algorithms and their performance.</p></li>

<li><p>Games and artificial intelligence.</p></li>
</ol>

<p>In practice, my professional career has mostly been spent on the first topic. I have spent a lot of time working on compiler/language/application performance. This is the second topic, of course. When I was in middle school, I was already interested in computers and I already liked games. That&rsquo;s where the third interest comes from. For me, computers are the world&rsquo;s greatest toys and always have been. But I won&rsquo;t see all the advances that my younger son with his iPad now takes for granted.</p>

<p>You can see the outgrowth of my interest in computer games in a couple of papers I wrote (with some friends) about Kriegspiel, a variant of chess. The papers are published in the &ldquo;Computer Journal&rdquo;. One of these is a complete program to check the legality of moves in chess and Kriegspiel. At the time the paper was written, there were a few example programs for students, but these were not very careful and missed some of the more subtle rules of chess. There were, of course, chess programs available, but this was long before open source software and at a time when a few chess programmers were trying to make a living selling chess products. So they obviously didn&rsquo;t publish their secrets. So far as I know, this was the first published paper to provide a complete rules checker and I haven&rsquo;t seen one since; it may still be the only refereed publication of a rules checker. You can find an audio interview about the project at the Computer Museum here in Silicon Valley.</p>

<p>My approach to computer science is generally to see if I can find some good theoretical model for a problem and then understand how to apply that in practice.</p>

<p><strong>Over the years, have you met that programming language which you liked most for some reason?</strong></p>

<p>Right now, I like Ruby a lot. I have written great gobs of C, but I don&rsquo;t like its lack of security. Back in the day, I liked XPL which seemed like a reasonable version of C (of course, it was developed independently) with much more safety.</p>

<p>When I was a grad student, I wrote one long Snobol program. I used it to model some research that had been done in code optimization. It was possible to turn constructive proofs of theorems directly into Snobol routines. That was eye-opening. It has made me partial to languages that have interesting inference mechanisms.</p>

<p>I&rsquo;d like to have a chance to learn and use Haskell or one of its friends for a good project. I think it would teach me a great deal. I should note that writing a toy program in a language is not the same as knowing the language. I have been doing Ruby for a year now on one project and I still learn something new every day.</p>

<p><strong>When languages like C were invented, people wanted to be close to the metal. Understanding how the metal worked was the must for any professional programmer, and as a consequence, it dictated a manner of teaching programming. How would you teach programming nowadays? Not computer science in general but hands on programming?</strong></p>

<p>I never understood the focus on hardware although I started doing assembly language on a machine that didn&rsquo;t even have mnemonic op codes in the first assembler I used.</p>

<p>Actually, I think you asked the wrong question. The problem is not &ldquo;programming&rdquo;, but problem analysis and application development. You can program anything in any language; the question is whether the language is a good &ldquo;human&rdquo; fit to the problem and whether or not it is efficient enough.</p>

<p>Thus, I would teach principles of programming languages and then ask students to try and understand those principles in each of a number of languages. For example, did you know that Fortran always includes an interpreter? (For format statements, of course!) And what&rsquo;s more, in Fortran 77, you need to implement call-by-name as part of that interpreter. You also probably want to use exceptions to build your interpreter. So the basic concepts pop up in surprising places.</p>

<p>(By the way, that tells you why the formatting etude is in the book. Over the years, I built two separate Fortran format interpreters.)</p>

<p><strong>We started this interview from the book. Did you have your own &ldquo;version&rdquo; of &ldquo;Etudes&rdquo;? Any books and people significantly influenced on you as a programmer and scientist?</strong></p>

<p>When I was in high school, a friend of my parents helped me get a summer job. That job turned into work at the local school system&rsquo;s data processing center. In those days, data processing meant cards, card sorters, card punchs, and the like. But the next summer, the school system bought an IBM 1401. Because nobody else knew more than me about it, my supervisor let me be one of the programmers. Within a few weeks, I was writing payroll programs for a large public system.</p>

<p>This experience helped me get a part-time job in college also working with 1401&rsquo;s. From then on, my life was working on computers and I decided to go to grad school in computer science instead of getting a full-time job. With more good luck than prior knowledge, I went to Cornell. The faculty there was incredibly helpful. Probably the two faculty members who taught me the most were Juris Hartmanis and John Hopcroft. I still think that Hopcroft&rsquo;s language theory book is a classic (in the first or second editions). But everybody on the faculty there was extremely concerned that their students did well. And, if you look at the Cornell graduates from the late 60&rsquo;s through the mid-70&rsquo;s, you&rsquo;ll see a really wide range of talent went through the program.</p>

<p>So far as books go, my favorites are probably those by Knuth. I really recommend reading the &ldquo;Art of Computer Programming&rdquo;. You won&rsquo;t understand most of it the first time. My theory is that you read it over and over, a few pages at a time. Each time you look at it, a little more sinks in.</p>

<p>I also read all of Newman&rsquo;s &ldquo;The World of Mathematics&rdquo; which I first saw in the 10th grade. This gave me a lot of historical background in math and mentioned enough about computers that I was helped along. I think this is still a useful introduction for young people (not to mention old people!).</p>

<p><strong>Everybody comes to the world of computers differently. Maybe nowadays it is much easier because computers are everywhere. How did it happen that you chose computers as your profession in the days of mainframes and punch cards?</strong></p>

<p>Well, some of the answer is in the previous question. My father owned a small hand-crank desk calculator with a design similar to that described by Felix Klein in his mathematical education book. My father&rsquo;s came from the Orient (he got it during WWII, I assume), had no instructions, and was covered in Japanese symbols &ndash; but fortunately Arabic numerals. I spent many hours figuring it out.</p>

<p>When I was in middle school, I already liked computers and mathematics. Sometime along in there I got a toy &ldquo;computer&rdquo; that was made out masonite, old-fashion clasp paper clips, screws, light bulbs, batteries, and wires. It was really what would be called a gate simulator today, but you could build some very simple circuits with switched inputs and lit-up light bulbs as outputs. I was fascinated. I also found some other books about early computers and they were very interesting to me.</p>

<p>In my first year of high school, I went to NSF summer camp where we took some college course in algebra and group theory, learned (well, in my case, was mystified by) some finite differences, and got to program a computer. I also learned to play bridge because two of girls wanted to have a fourth (when you are in high school, girls are a powerful incentive!).</p>

<p>So by the time I got out of college, between the experiences I have described and some college courses (notably with Tom Cheatham), I was pretty much hooked.</p>

<p><strong>Wrapping up, there is a saying about the three things a man must do. Can you name your three things a programmer must (or should) implement?</strong></p>

<p>I&rsquo;m not sure I have three things that I think programmers should implement. But I know some things that I think every programmer should either know or be able to do.</p>

<ol>
<li><p>Some ability to do formal mathematics. The level necessary to understand Hopcroft and Ullman combined with a little graph theory is enough. Discrete mathematics is essential; calculus is only necessary for folks working in special application areas.</p></li>

<li><p>Some ability to write clearly in their native language. Dijkstra said that if a person couldn&rsquo;t write their own language, they couldn&rsquo;t write a correct program. (Well, that&rsquo;s what I hope Dijkstra said!). Writing programs is essentially the same as writing a non-fiction essay. If you can&rsquo;t make the step-by-step connections clearly in your own language, why would we think you could in C, for example?</p></li>

<li><p>Remember that a program is primarily for communication with humans, not computers. When you write a program, the computer will do whatever you say. You must convince the humans who read the program that what you have asked the computer to do is the correct thing to do. Remember, the computer doesn&rsquo;t care about correctness.</p></li>

<li><p>(Bonus answer &ndash; 4 for the price of 3). The answer to the last question means that programs should always have the form of paragraphs of comments that describe the intention of the program followed by paragraphs of code that implement that intention. All of the formatting should be designed to make readers as able as possible to read the code easily; the compiler doesn&rsquo;t care. In particular, follow conventions of mathematics and your native language, not those you found in some random language manual. Write the comments first and then write the code, not the other way around. If you don&rsquo;t know what you want to achieve and why, any code you write is, by definition, incorrect.</p></li>
</ol>

<p>If you look at the last &ldquo;Etudes&rdquo; chapters, I hope that you can see that even back then, I was trying to apply these principles.</p>

<p><strong>Thanks, Charles for the interview answers. We (fans of &ldquo;Etudes&rdquo;) still hope for your new books or other publications and wish you all the best. In meanwhile, if you, my dear readers, have not seen &ldquo;Etudes&rdquo; so far, please grab a copy and take a look. It is worth it.</strong></p>

<p>&#9632;</p>

<p><em>// Charles Wetherell, Alexander Demin</em></p>

<p><em>// August 2012</em></p>

<p>P.S. If you have questions to Charles, please, put them in comments below.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[English hexadecimal &#34;magic&#34; words]]></title>
    <link href="http://demin.ws/blog/english/2012/08/25/english-words-in-hex/"/>
    <updated>2012-08-25T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/25/english-words-in-hex/</id>
    <content type="html"><![CDATA[<p>Programmers love &ldquo;magic&rdquo; numbers, numbers having second, often verbal, meaning. The hexadecimal digits suit perfectly here.</p>

<p>For instance, to form a stub number for a 16- or 32-bit value, people usually use words from the following set:</p>

<pre><code>ABBE
ACED
BABE
BADE
BEAD
BEEF
BODE
CADE
CAFE
CEDE
COCA
CODA
CODE
DACE
DADO
DEAD
DEAF
DECO
DEED
DODO
FACE
FADE
FEED
FOOD
OBOE
</code></pre>

<p>For example:</p>

<pre><code>DEADFACE
ACEDFEED  
</code></pre>

<p>If we don&rsquo;t care about the symmetrical split, the vocabulary is a bit wider:</p>

<pre><code>ABBE
ABE
ABODE
ACCEDE
ACCEDED
ACE
ACED
ADD
ADDED
ADO
ADOBE
BAA
BABE
BAD
BADE
BAOBAB
BE
BEAD
BEADED
BED
BEDDED
BEE
BEEF
BOA
BOB
BOBBED
BODE
BODED
BOO
BOOBOO
BOOED
CAB
CACAO
CAD
CADE
CAFE
CEDE
CEDED
COB
COCA
COCOA
COD
CODA
CODE
CODED
COFFEE
COO
COOED
DAB
DABBED
DACE
DAD
DADO
DEAD
DEAF
DEB
DECADE
DECAF
DECO
DECODE
DECODED
DEE
DEED
DEFACE
DEFACED
DO
DOC
DODO
DOE
DOFFED
EBB
EBBED
EFFACE
EFFACED
FAB
FACADE
FACE
FACED
FAD
FADE
FADED
FED
FEE
FEED
FOB
FOBBED
FOE
FOOD
OAF
OBOE
ODD
ODE
OF
OFF
</code></pre>

<p>For example:</p>

<pre><code>BADCOCOA
BADCODED
FADEDDOC
CODEDBOB
</code></pre>

<p>On 64-bit systems we can create almost complete sentences.</p>

<pre><code>EBBEDDEADBAOBAB
</code></pre>

<p>Does anybody know what to say to the next, 128-bit generation?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Algorithms: Design and Analysis, Part I]]></title>
    <link href="http://demin.ws/blog/english/2012/08/15/algorithms-design-and-analysis-part1/"/>
    <updated>2012-08-15T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/15/algorithms-design-and-analysis-part1/</id>
    <content type="html"><![CDATA[<p>Just received a <a href="http://demin.ws/files/education/2012/coursera/stanford/algo1/statement-of-accomplishment.pdf">Statement of Accomplishment</a> after the <a href="https://class.coursera.org/algo-2012-002/class/index">Algorithms: Design and Analysis, Part I</a> online source at <a href="http://coursera.org">coursera.org</a>.</p>

<p>In short &ndash; it is awesome! I&rsquo;m not talking about the material they provide. It is great without any concerns. I&rsquo;m talking about the technology of online education.</p>

<p>Briefly. The course lasts six weeks. Each week we are given video lectures, a hour and a half in total, broken down into 10-20 minutes episodes. The videos are interactive, and sometimes you&rsquo;ll get a quiz along with watching. For each episode there are two PDFs. The first has live commentaries written by hand. They appear on videos along with lector&rsquo;s voice. The second is a regular PDF with slides. You can watch videos as many times you want: in the browser or downloading it. English subtitle are available. There is a cool feature in the online video viewer &ndash; you can change the speed from 0.5 to 1.5, so it turns to too much &ldquo;blah-blah&rdquo;, there is a way to speed it up.</p>

<p>Also you&rsquo;re given with a list theoretical questions and one programming question each week. You only have a few attempts for submission. The best answers count.</p>

<p>There is no real deadline but submissions after the &ldquo;official&rdquo; deadline will be graded with 50% &ldquo;discount&rdquo;. So, if you&rsquo;re up the certificate after the course, it&rsquo;s worth doing it in time.</p>

<p>At the very end there is a final exam. You&rsquo;ll have 3 hours to complete.</p>

<p>There are forums available where you can communicate with other students and course owners.</p>

<p>Subjectively, I&rsquo;d make the course a bit &ldquo;tougher&rdquo;, but in general it has perfect balance for a couple of evenings a week.</p>

<p><strong>Conslusion</strong>: Strongly recommended. Not this particular course because everybody has different interests, but the technology in general.</p>

<p>Nowaday if someone says that he or she has no money for an expensive and famous university, you can recommend to save little money for internet and an inexpensive computer. That&rsquo;s it.</p>

<p>I&rsquo;m up to try <a href="https://www.edx.org/courses/MITx/6.002x/2012_Fall/about">6.002x: Circuits and Electronics</a> next. Just curious how they do a practical part for electronics online.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[USB stick RAID]]></title>
    <link href="http://demin.ws/blog/english/2012/08/10/usb-stick-raid/"/>
    <updated>2012-08-10T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/10/usb-stick-raid/</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve found a bag with a bunch of my old USB sticks I used some time ago. Usually only one or two with maximum capacity is in use, and others are here.</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/bunch-of-usb-stricks.jpg" alt="" />
</p>

<p>From 64MB to 32GB.</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/usb-stricks-sorted.jpg" alt="" />
</p>

<p>An idea occured to join them all together into RAID, for example, a concatenated disk. In OSX it can be done in a few clicks. The idea is pretty silly but it was interesting to try.</p>

<p>I&rsquo;ve bought an extender with 12 ports.</p>

<p><a href="http://www.amazon.co.uk/gp/product/B0051PGX2I/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B0051PGX2I&amp;linkCode=as2&amp;tag=prodiy-21">Satechi 12 Port USB Hub with Power Adapter &amp; 2 Control Switches</a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B0051PGX2I" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/satechi-12-usb-port-extender.jpg" alt="" />
</p>

<p>Plugging them all in&hellip;</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/usb-stricks-raid-assembled.jpg" alt="" />
</p>

<p>Start the Disk Utility and check that all the sticks are recognized.</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/disk-utility-disks-connected.png" alt="" />
</p>

<p>Create a &ldquo;concatenated disk&rdquo; named &ldquo;Crazy RAID&rdquo; and add the sticks into there.</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/disk-utility-crazy-raid-created.png" alt="" />
</p>

<p>Confirming&hellip;</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/disk-utility-crazy-raid-confirmation.png" alt="" />
</p>

<p>Wait for five minutes and it&rsquo;s done.</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/disk-utility-crazy-raid-completed.png" alt="" />
</p>

<p>&ldquo;df&rdquo; perfectly sees the drive.</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/df-crazy-raid.png" alt="" />
</p>

<p>Now we can copy something there and check the transfer rate.</p>

<p><img src="http://demin.ws/images/blog/usb-stick-raid/mc-crazy-raid-copying.png" alt="" />
</p>

<p>Of course, this is just a toy without real usage. All the sticks have different capacity, so the concatenated disk is the only choice in terms of the RAID features. Write speed depends on a particular stick which is currently in use. On concurrent read we may gain some speedup.</p>

<p>But it looks cool!</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The National Museum of Computing, Bletchley Park]]></title>
    <link href="http://demin.ws/blog/english/2012/08/10/national-museum-of-computing/"/>
    <updated>2012-08-10T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/10/national-museum-of-computing/</id>
    <content type="html"><![CDATA[<p><a href="http://demin.ws/blog/english/2012/07/06/bletchley-park-colossus/">Last time</a> I wasn&rsquo;t able to get into <a href="http://www.tnmoc.org/">The National Museum of Computing</a>, so this time I had double checked their open hours, and &ndash; I&rsquo;m going in.</p>

<p>Below there is a bunch of photos of things which had caught my eye. Of course, there is much more stuff in the museum.</p>

<p>The real BBS, even if running Windows.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0716.JPG" alt="" />
</p>

<p>The ancestors of an era.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0717.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0718.JPG" alt="" />
</p>

<p>The NeXT CUBE.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0719.JPG" alt="" />
</p>

<p>Brothers! This is an 1200 bps modem, or 300 full duplex.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0720.JPG" alt="" />
</p>

<p>Have you seen The Matrix? Remember the modem they used for teleportation?</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0721.JPG" alt="" />
</p>

<p>I&rsquo;d be surprised if there isn&rsquo;t Raspberry Pi in the British museum, so here it is.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0722.JPG" alt="" />
</p>

<p>A portable laser-disc storage.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0723.JPG" alt="" />
</p>

<p>Oh, I should probably buy this one and relax.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0724.JPG" alt="" />
</p>

<p>Brothers! Fasten your seat belts. This is the <strong>whole</strong> room of <strong>working</strong> BBC Micros. Books and manuals are ready to help. You can sit and program.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0725.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0726.JPG" alt="" />
</p>

<p>And I did.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0731.JPG" alt="" />
</p>

<p>BBC Micro inside.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0732.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0738.JPG" alt="" />
</p>

<p>Books are everywhere, new ones, old ones.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0733.JPG" alt="" />
</p>

<p>RML 380Z</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0727.JPG" alt="" />
</p>

<p>PET Commodore</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0728.JPG" alt="" />
</p>

<p>ELIZA can ask questions and answer.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0729.JPG" alt="" />
</p>

<p>The history of computer memory, from bulbs to SIMMs, DIMMs and all the rest of it.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0734.JPG" alt="" />
</p>

<p>A flash drive from the past.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0735.JPG" alt="" />
</p>

<p>Computer trainers. I love these charmy devices.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0736.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0737.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0741.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0743.JPG" alt="" />
</p>

<p>Would you like to study on this one? I would.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0730.JPG" alt="" />
</p>

<p>Ergonomic keyboards weren&rsquo;t invented yesterday.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0739.JPG" alt="" />
</p>

<p>A very expensive computer for business from the 80-th.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0740.JPG" alt="" />
</p>

<p>There are a few lovely cassettes on a huge bookshelf with manuals. It turns out that they were used not only at home.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0742.JPG" alt="" />
</p>

<p>Go to a middle heavy weight. Now floor-standing machines instead of desktops.</p>

<p>Cray</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0744.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0745.JPG" alt="" />
</p>

<p>PDP-8</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0772.JPG" alt="" />
</p>

<p>PDP-11</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0746.JPG" alt="" />
</p>

<p>A XEROX workstation.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0747.JPG" alt="" />
</p>

<p>VAX. I &ldquo;saw&rdquo; this guy only via a terminal when I was studying.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0748.JPG" alt="" />
</p>

<p>A graphical station.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0749.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0750.JPG" alt="" />
</p>

<p>Terminals, terminals.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0751.JPG" alt="" />
</p>

<p>A hall of epoch-making computers.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0752.JPG" alt="" />
</p>

<p>Recognize this guy?</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0753.JPG" alt="" />
</p>

<p>In the corner? We (Russians) knew it as a Zonov&rsquo;s clone implemented on Soviet parts, but this is the original.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0754.JPG" alt="" />
</p>

<p>In action.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0758.JPG" alt="" />
</p>

<p>It turns out that there were hell a lot of machines in the keyboard case form factor.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0755.JPG" alt="" />
</p>

<p>This computer had launched Microsoft.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0756.JPG" alt="" />
</p>

<p>This one had started Apple.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0757.JPG" alt="" />
</p>

<p>You can land your bottom on the bench and play rare games of epoch-making rare computers form the 80-th.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0773.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0759.JPG" alt="" />
</p>

<p>A room to play the Flight Simulator.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0760.JPG" alt="" />
</p>

<p>The mainframes.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0761.JPG" alt="" />
</p>

<p>UNIX. The Beginning.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0762.JPG" alt="" />
</p>

<p>A real radar monitor.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0763.JPG" alt="" />
</p>

<p>By the way, a true computer museum cannot be without WiFi, so here it is.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0764.JPG" alt="" />
</p>

<p>PDP-11</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0765.JPG" alt="" />
</p>

<p>An analog computer. In digital computers we break down tasks into primitive binary operations. In analog computers we have to use operational amplifiers to add, subtract, integrate or differentiate electrical signals.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0766.JPG" alt="" />
</p>

<p>Convenient, however.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0767.JPG" alt="" />
</p>

<p>A new, not yet complete exposition.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0771.JPG" alt="" />
</p>

<p>But something is already there.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0770.JPG" alt="" />
</p>

<p>Punch card machines.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0768.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0769.JPG" alt="" />
</p>

<p>A (attention) calculator!</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0774.JPG" alt="" />
</p>

<p>The archives of Computer Weekly.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/tnmoc/IMG_0775.JPG" alt="" />
</p>

<p>Brothers! This is just awesome, the must see place for computer enthusiasts. Unfortunately, I had only forty minutes for everything, so maybe I&rsquo;ll go there once again.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[MOXA NPort 5150]]></title>
    <link href="http://demin.ws/blog/english/2012/08/08/moxa-nport-5150/"/>
    <updated>2012-08-08T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/08/moxa-nport-5150/</id>
    <content type="html"><![CDATA[<p>My brother has presented me this animal &ndash; <a href="http://www.moxa.com/product/nport_5150.htm">MOXA NPort 5150</a>.</p>

<p><img src="http://demin.ws/images/blog/moxa/nport/5150/IMG_0699.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/moxa/nport/5150/IMG_0697.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/moxa/nport/5150/IMG_0698.JPG" alt="" />
</p>

<p>This device allows to connect legacy RS-232 devices to the world of TCP/IP. We used such things years ago developing software for POSes and ATMs. Just change a dialing script from something like <code>ATDT12345678</code> to <code>ATD192.168.1.1</code> and off you go.</p>

<p>Have no idea what to do with this now. I even have no proper RS-232 port, only via a USB cable. Interestingly, back those days such devices were very expensive.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[&#34;Programming 32-bit Microcontrollers in C, Exploring the PIC32&#34; by Lucio Di Jasio]]></title>
    <link href="http://demin.ws/blog/english/2012/08/08/exploring-pic32/"/>
    <updated>2012-08-08T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/08/exploring-pic32/</id>
    <content type="html"><![CDATA[<p>Working on <a href="http://demin.ws/blog/english/2012/08/07/interview-with-geoff-graham/">the interview with Geoff Graham</a>, he told me about a book where he took a lot of inspiration and working code as well for the Maximite software.</p>

<p><a href="http://www.amazon.co.uk/gp/product/B005VO36UG/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B005VO36UG&amp;linkCode=as2&amp;tag=prodiy-21">Programming 32-bit Microcontrollers in C: Exploring the PIC32 (Embedded Technology)</a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B005VO36UG" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p><a href="http://www.amazon.co.uk/gp/product/B005VO36UG/ref=as_li_qf_sp_asin_il?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B005VO36UG&amp;linkCode=as2&amp;tag=prodiy-21"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&amp;ASIN=B005VO36UG&amp;Format=_SL160_&amp;ID=AsinImage&amp;MarketPlace=GB&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=prodiy-21" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B005VO36UG" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>I stopped programming for PICs about ten year ago when we were developing a GSM phone based alarm system. We used the PIC16 chip and a DTFM decoder (be the way, the feature of controlling the alarm system dialing to it and using DTFM signals was pretty awesome that time) and a bunch of sensors.</p>

<p><img src="http://demin.ws/images/blog/sms-alarm-system.jpg" alt="" />
</p>

<p>I also worked with PIC12. I was stunned of just an 8-pin chip <strong>programmable in C</strong>!</p>

<p>Then I moved to the UK and left a lot of stuff at home. But recently it all has come back when I built <a href="http://demin.ws/blog/english/2012/01/19/maximite-kit/">Maximite</a> and <a href="http://demin.ws/blog/english/2012/07/11/raspberry-pi-arrived/">also bought</a> <a href="http://demin.ws/blog/english/2012/07/26/raspberry-pi-links/">Raspberry Pi</a>. Since then the technology has stepped forward, of course. Now PIC32 chips are based on the MIPS kernel, almost fully 32-bit and have a primitive virtual memory capabilities. It allows creating simple operating systems when the kernel has its own protected memory from users processes. For example, <a href="http://demin.ws/blog/english/2012/05/11/retrobsd-on-maximite/">RetroBSD perfectly works on Maximite</a>.</p>

<p>Back to the book. I wanted to refresh my PIC knowledge and opened the book. To my surprise I swallowed it in a couple of evenings non-stop.</p>

<p>The book is organized perfectly and suitable for people having minimal experience in microcontrollers. But it covers serious topics such that:</p>

<ul>
<li>memory model</li>
<li>interrupts (for example, timers or I/O)</li>
<li>serial or parallel interfaces (for example, connecting to a LCD display or a PS/2 keyboard)</li>
<li>ADC/DAC (for example, a temperature sensor or an analog joystick)</li>
<li>generating black/white video signal (for example, composite or VGA) using non-trivial DMA-based data transfer for a memory buffer to the SPI channel</li>
<li>SD/MMC cards interface</li>
<li>implementation of the FAT</li>
<li>sound generation via PWM</li>
</ul>

<p>All example are complete and working. It can be even better if you have a companion CD of the book.</p>

<p>The only little issue was that the author used MPLAB and the C32 compiler (remember, the book was released in 2008), but Microchip strongly recommend migrating to MPLAB-X (which, by the way, the only choice for Linux and OSX) and the XC32 compiler based on GCC. Of course, the project files can be easily converted to the new MPLAB-X format, the book lacks examples of simple Makefiles. But it compensates it with exhaustive screenshots and commentaries about configuration windows, the debugger and the simulator. It is possible to read the book even without a computer.</p>

<p>If you read the book, you&rsquo;ll understand what can be implemented with PIC32 and how things work in it. If you decide to implement a project, you have enough examples plus understanding how to start the crystal.</p>

<p><strong>The conclusion</strong>: Highly recommended.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An interview with Geoff Graham]]></title>
    <link href="http://demin.ws/blog/english/2012/08/07/interview-with-geoff-graham/"/>
    <updated>2012-08-07T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/07/interview-with-geoff-graham/</id>
    <content type="html"><![CDATA[<p>Today my guest is Geoff Graham, the creator of a popular homebrew
microcomputer called <a href="http://geoffg.net/maximite.html">Maximite</a>. Nowadays we see a boom of projects
based on microcontrollers. We still call them &ldquo;microcontrollers&rdquo; on a
habit but they are not anymore. For example, Microchip PIC32 crystals
provide much more functionality in a single chip than we had in
full-blown microcomputers from the 80th, like Apple 2 or ZX Spectrum
48.</p>

<p><img src="http://demin.ws/images/blog/maximite/geoff-graham/interview/geoff-graham.jpg" alt="" />
</p>

<blockquote>
<p>When I found that the PIC32 chip could be made to use a VGA display
and keyboard, it was only natural that I should try and recreate one
of the earlier computers that I had so much fun with in my youth.</p>
</blockquote>

<hr />

<p>Geoff built a microcomputer, Maximite, using a PIC32 chip. Maximite is
a complete appliance utilizing modern interfaces. It uses VGA for
video, PS/2 for the keyboard, SD cards as storage, USB for
communicating, and it runs BASIC! Doesn&rsquo;t it remind you something? In
my view, Maximite is a perfect tool to study microelectronics allowing
to touch how hardware meets with software.</p>

<p>Today we can ask Geoff a few questions in person. Geoff lives in the
suburb of Kensington in Perth, Western Australia. Perth is a long way
from anywhere but with the wonders of the Internet and FedEx the world
is a much smaller place now, so it doesn&rsquo;t stop Geoff to design and
produce great hardware and software.</p>

<p><strong>Hi Geoff, thanks for the interview. Let&rsquo;s begin with a light
question &ndash; why &ldquo;Maximite&rdquo;? How did you invent this name?</strong></p>

<p>At the beginning of the project I wanted to call it The Mighty Mite
meaning something that was small (mite) that was also powerful
(mighty).  When the design came to be published in Silicon Chip
magazine the editor discovered that the name had been trademarked by a
food manufacturer, so he suggested Maximite as an alternative.  By
then I could think of nothing better, so that became the name.  As it
turned out, that is also the name of an explosive which, in a strange
sort of way, is also appropriate.</p>

<p><strong>Maximite is very popular. Do you know at least rough figures of how many of them were built? Also when and how did you realise its incredible popularity?</strong></p>

<p>My standard answer is that &ldquo;thousands are in use&rdquo; but I believe that a
more accurate number is somewhere between 3000 and 4000.  About half
of them have been built by people with a soldering iron and the other
half purchased as an assembled board from companies who make copies of
the design.</p>

<p>I realised that it would be popular when I looked at the number of
visitors to my website, in the first few days after the magazine
article appeared the number of unique visitors to my website jumped by
100 times before settling down to a long term increase of 20 times the
pre Maximite days.  What was interesting was that my URL did not
appear in the first magazine article so many people read the article
and immediately used Google to find out more.</p>

<p>When I started on the design of the Maximite I was thinking of the
computers of the 80&rsquo;s which provided me with a lot of fun with back
then.  They were very popular in their day and, as the modern
computers have become more complicated and difficult to use, there was
a vacuum left behind.  I believe that the key to the success of the
Maximite was that it filled that space.</p>

<p><strong>For Maximite you had to build hardware and software. This is quite an unusual position nowadays for people working with computers. Professionals in software rarely look at hardware and vice versa. Where are you here? Are you more a hardware engineer by nature or a programmer?</strong></p>

<p>Yes, that is one of the things that I have found since the Maximite
design was published.  People tend to look at it through the eyes of a
hardware engineer and do not appreciate the software - they want to
add electronic features without regard to the firmware or how the
BASIC language could accommodate them.  There is always the reverse
too, people who only think in terms of the software.  I think that I
am best described as a programmer but with a strong electronic
background.</p>

<p>Another item that is often missed when people try to change the
Maximite is its &ldquo;look and feel&rdquo; (ie, how the user uses it).  This must
be consistent with the hardware and software.  All three are part of
the integrated whole and this is often not appreciated by either the
hardware or software specialists.</p>

<p><strong>I personally was amazed of how solid and complete the Maximite
project is. You designed the board, the case, software, and the kits
of Maximite are available online. In the world of individual homebrew
projects people usually don&rsquo;t tend to finish off their projects fully
to such a polished shape because they loose interest. How did you
manage that?</strong></p>

<p>This primarily came from my desire to have the project published in
Silicon Chip magazine.  Most of their projects are a complete
&ldquo;product&rdquo; designed by a professional engineer and I had to meet that
standard if I wanted them to publish the Maximite project.  This
attention to detail is unusual today as magazines tend to only half
finish the project, things like documentation, a box to put it in, a
nice front panel and so on are often ignored.</p>

<p>I find that the discipline of designing projects for the magazine is
quite good.  I have a number of personal projects (ie, ones not
published by the magazine) that are still sitting around today in a
half completed form because I do not have that discipline operating on
me.</p>

<p><strong>Geoff, you started your microelectronics hobby when you retired. How
much time a day you usually spend on it? Again, you delivered the
Maximite project in a such complete form, so seems it required some
time to put everything in place.</strong></p>

<p>Yes, I have spent far too much time on it since I have retired, but
interestingly it was something that I had to do.  It is as if there
was a design engineer hiding inside of me that could not get out while
I was following my professional career (which was not in electronics).<br />
The moment I retired he broke forth.</p>

<p>With the Maximite things seem to come in bursts, I would spend twelve
hours a day for a month or two then have a break for a few weeks.  It
is good that I enjoy working on projects like this because they do
take up a lot of time.  I estimate that the Maximite has taken about
nine months of solid eight hours a day, forty hours a week to get it
to where it is now.</p>

<p><strong>MMBasic. I know you struggled to find software for Maximite. A few
existing implementations of BASIC you tried didn&rsquo;t really fit, and you
ended up with your own implementation of BASIC. Could clarify the
licensing and distribution model of MMBasic? Any plans, maybe, to
develop a Maximite framework or a library allowing to deal with
Maximite peripherals in the form of device drivers? It could be useful
in developing alternative firmware for Maximite, for example, running
Lua or RetroBSD.</strong></p>

<p>Yes, when I started on the Maximite project my hope was to find a free
version of BASIC in the Internet and use that.  But I found that the
good implementations of the language were not available freely or had
some other issue.  So I decided to write my own.</p>

<p>Initially I released my version of BASIC (called MMBasic) under the
GPL GNU licence but I had a bad experience with one commercial
organisation who removed my name from the software and claimed it as
theirs, they even changed the copyright to their name.  So I created
my own license where the software is freely available but it cannot be
redistributed without my agreement.</p>

<p>This has worked out very well, a number of universities and commercial
organisations are using it and I have an agreement with them covering
what they will do with it.  This is much better than allowing someone
to anonymously download my software and then see it appear on the
Internet with their name and copyright.</p>

<p>At this time I do not have plans to develop a loadable device driver
type of architecture.  The main reason is that the PIC32 chip does not
have enough memory to do all the things that it already does (VGA,
keyboard, USB, etc) and implement a loadable device driver system.<br />
There are more powerful chips around but they are impossible to hand
solder so I have stayed with the PIC32.  Products like the Raspberry
Pi can have loadable device drivers but they also have a complex
operating system - just what I was trying to avoid with the Maximite.</p>

<p><strong>Let&rsquo;s move a bit to your personal background. When and how did you
study to solder, for instance? I know many people looking for some
experience in electronics but they are afraid of soldering seeing it
potentially difficult or even impossible. How would you recommend
people starting messing around with electronics hands-on?</strong></p>

<p>I cannot remember when I first started soldering but it was probably
around age 12.  I am probably the wrong person to ask but I cannot see
the problem with soldering &ndash; you only need a cheap soldering iron and
some wire solder.</p>

<p>One of the great things with electronics is that it can be a very
cheap hobby.  I would recommend starting with a simple and cheap
project like flashing a light or adding a clock chip to the Arduino
and just buy the bits including the soldering iron.  You might make a
mess of the first project but that is not important and by the time
you have reached the third project you will regard yourself as almost
professional.</p>

<p><strong>Would you recommend any books or websites where beginners could make
their first easy steps into the wonderful world in electronics? What
kind of minimal level of knowledge could be enough to design and
build, for example, Maximite?</strong></p>

<p>My recommendation would be to start with a magazine subscription.
There is Silicon Chip (in Australia), Elektor (in Europe) and Nuts and
Volts (in the USA).  All of these will accept international
subscriptions.  If you are starting with no knowledge at all probably
Nuts and Volts would be the best.  When you subscribe to a magazine
you will have a constant stream of ideas and projects to tempt you
into trying something different and fun.  So a subscription is well
worth the cost.</p>

<p>The level of knowledge required to build the Maximite is not great
because it comes already designed and with working software.  On the
other hand, to design it you would need a great amount of expertise.
I have a lot of expensive test gear, I trained as an electronics
engineer in my early days and I have about 30 years of experience in
systems programming - all that is necessary to create something like
the Maximite.</p>

<p><strong>Now we have plenty websites providing a marketplace for individual
hardware developers to sell their ideas and designs, for example,
SparkFun.com. The internet allows people to get some money from hobby.
You, as a person, whose hardware designs are being wildly sold over
the internet, do you think it is feasible to live on income from such
business? or volumes are still minor?</strong></p>

<p>It would be very hard to make a living income from that sort of thing.
There are a few, like the designers of the Arduino, who are probably
doing OK but there are many more who have to keep another job so that
they can pay the rent.  Part of the problem is people like me who
produce sophisticated designs and then give them away for free, it is
hard to compete with that and your customers come to expect products
or software as a very low price.</p>

<p><strong>A bit of personal stuff. Can you name any people, for example, engineers or programmers, which you did or would like to learn from?</strong></p>

<p>The programmer who was the most influential on me is Brian Kernighan
who, along with Dennis Ritchie, designed the C programming language
and wrote a book on it called &ldquo;The C Programming Language&rdquo; in 1978.
Even today that book is a wonderful introduction to the C programming
language and well worth a read if you want to get into programming in
C.  When I write my magazine articles and web pages I always remember
his clear and easy writing style and try to emulate it in what I do.</p>

<p>Probably the most influential engineer is Jim Rowe who was creating
projects and writing for electronics magazines in Australia when I was
a young teenager.  He is still doing it today 50 years later and I
always find his projects well designed and his magazine articles clear
and easy to understand.  He is someone else who I try to emulate in my
projects and articles.</p>

<p><strong>By the way, how did you come to the world of computers and
engineering? What was your first computer or programming language?</strong></p>

<p>This will date me somewhat (I am 64 years old).  I remember the Altair
computer when it was first released and a little later the company I
was working for became the distributor for Intel in Australia.  I was
studying as an electronics engineer at the time and my first computer
was one that I hand soldered using the Intel 8080 chip and 512 bytes
of RAM (yes bytes).</p>

<p>Back then BASIC was the only language that you could use because of
the limited memory capacity and hardware.  Much later, when we had
disk drives, you could use more sophisticated languages and in my time
I have written programs in most of them (Fortran, COBOL, PL/1,
assembler, Pascal, etc).</p>

<p>As you can see, I was involved in electronics, small computers and
BASIC a long time ago.  So, when I found that the PIC32 chip could be
made to use a VGA display and keyboard, it was only natural that I
should try and recreate one of the earlier computers that I had so
much fun with in my youth.</p>

<p><strong>Wrapping up, I&rsquo;d like to ask you to shed some light on your future
projects? Is Maximite finished or we should wait for the Maximite with
Ethernet or WiFi or something?</strong></p>

<p>There is the new Colour Maximite that will be published in the
September 2012 issue of Silicon Chip.  It will have eight colours on a
VGA display, stereo synthesised sound and an Arduino compatible
connector along with all the other features of the original Maximite
(USB, BASIC language, etc).  That has taken quite a lot of my time and
energy to create, so after it is published I might take a break for a
while before looking around for something else.</p>

<p>There is a couple of exclusive photos of the new colour Maximite.</p>

<p><img src="http://demin.ws/images/blog/maximite/geoff-graham/interview/maximite-colour.jpg" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/maximite/geoff-graham/interview/maximite-colour-tv-keyboard.jpg" alt="" />
</p>

<p><strong>Thanks, Geoff, for the interview and for Maximite. Looking forward
for your further projects.</strong></p>

<p><strong>I&rsquo;m personally incredibly excited that
today people have started to realise that teaching computers is not
only about Word and Excel, but also about understanding what is inside
and how all these guts actually work. And projects like Raspberry Pi
and your Maximite help enormously get beginners a bit closer to the
metal.</strong></p>

<p>&#9632;</p>

<p><em>// Geoff Graham, Alexander Demin</em></p>

<p><em>// August 2012</em></p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mini Wireless &#39;n&#39; pocket router WA-6220]]></title>
    <link href="http://demin.ws/blog/english/2012/08/02/mini-wireless-n-pocket-router/"/>
    <updated>2012-08-02T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/08/02/mini-wireless-n-pocket-router/</id>
    <content type="html"><![CDATA[<p>Quite often in hotel rooms you can only find Ethernet. But what am I supposed to do with iPhone and iPad then? So, I bought this tiny little device some time ago:</p>

<p><a href="http://www.amazon.co.uk/gp/product/B004YNK9O6/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B004YNK9O6&amp;linkCode=as2&amp;tag=prodiy-21">Palm-Size Portable Mini Travel 2 in 1 Wireless N 802.11n/g WLAN Network Router / Client Adapter</a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B004YNK9O6" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p><a href="http://www.amazon.co.uk/gp/product/B004YNK9O6/ref=as_li_qf_sp_asin_il?ie=UTF8&amp;camp=1634&amp;creative=6738&amp;creativeASIN=B004YNK9O6&amp;linkCode=as2&amp;tag=prodiy-21"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&amp;ASIN=B004YNK9O6&amp;Format=_SL160_&amp;ID=AsinImage&amp;MarketPlace=GB&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=prodiy-21" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&amp;l=as2&amp;o=2&amp;a=B004YNK9O6" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>This is called <a href="http://www.ccandc.com.tw/products_2.php?prod=100">WA-6220</a>.</p>

<p>The official website says:</p>

<p>WA-6220-V1 WLAN 11n Router is designed for people on the go, user can carry it travelling around and work at anywhere. It is compliant with 802.11n specifications, up to 300Mbps data rate, provides multi-functional capabilities, particularly the high performance throughput and high-quality security. Incorporating fast Ethernet ports and is compatible to other wireless (802.11a/b/g/ n) networking device, it enables your whole network sharing a high-speed cable or DSL. Its high performance is ideal for media-centric applications like streaming video, gaming and Voice over IP technology.</p>

<ul>
<li>Provides wireless speed up to 300Mbps data rate.</li>
<li>Supports WEB based management and configuration.</li>
<li>Supports UPnP, IGMP Snooping &amp; Proxy.</li>
<li>Supports Dynamic DNS, NTP client service.</li>
<li>Supports Log table and remote Log service.</li>
<li>Supports Setup Wizard mode.</li>
<li>Supports Wireless schedule.</li>
<li>Compatible with IEEE 802.11a/b/g/n Specifications.</li>
<li>Supports multiple AP, provides maximum 5 groups of SSID.</li>
<li>Supports IEEE 802.3x full duplex flow control on 10/100M Ethernet interface.</li>
<li>Supports bridging, routing and WISP functions between wireless and wired Ethernet interfaces.</li>
<li>Supports IEEE 802.1x, 64-bit and 128-bit WEP, WPA, WPA2 encryption/decryption and WPA with Radius.</li>
<li>Supports DHCP server to provide clients auto IP addresses assignment and static DHCP functions.</li>
<li>Supports DHCP client, static IP, PPPoE, PPTP, L2TP of WAN Interface.</li>
<li>Supports firewall security with port filtering, IP filtering, MAC filtering, port forwarding, URL Filtering and DMZ hosting functions.</li>
<li>Supports AP mode, Client mode, WDS, AP+WDS and Universal Repeater.</li>
<li>Supports QoS which controls the bandwidth by IP or MAC address.</li>
<li>Supports Denial-of-Service.</li>
<li>Supports WPS (Wi-Fi Protected Setup).</li>
<li>Supports WAPI (Wireless Authentication Privacy Infrastructure).</li>
<li>Supports Green Ethernet, IEEE802.3az draft2.0, EEE (Energy Efficient Ethernet).</li>
</ul>

<p>It is the matchbox in size.</p>

<p><img src="http://demin.ws/images/blog/wa-6220/IMG_0630.JPG" alt="" />
</p>

<p>And can be powered from USB (I connected it directly to the laptop).</p>

<p><img src="http://demin.ws/images/blog/wa-6220/IMG_0631.JPG" alt="" />
</p>

<p>Front.</p>

<p><img src="http://demin.ws/images/blog/wa-6220/IMG_0632.JPG" alt="" />
</p>

<p>The mode switch and reset button.</p>

<p><img src="http://demin.ws/images/blog/wa-6220/IMG_0634.JPG" alt="" />
</p>

<p>The quick user guide.</p>

<p><img src="http://demin.ws/images/blog/wa-6220/IMG_0635.JPG" alt="" />
</p>

<p>Unfortunately, I haven&rsquo;t met a hotel with properly installed WiFi coverage. Many can put a cable, but proper WiFi coverage with decent speed &ndash; no one. But this device makes you an ad-hoc instant router in minutes with no pain whatsoever.</p>

<p>P.S. By the way, a question &ndash; is WiFi hardware (chipset) in laptops, for instance, and regular WiFi access points different in any way? If the connection is duplex, it shouldn&rsquo;t be. So, how to turn a laptop into a proper WiFi access point then? I tried things like <a href="http://connectify.me/">Connectify</a> on Windows 7, but it didn&rsquo;t really work properly. And what should I also do on Linux and OSX?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Raspberry Pi links]]></title>
    <link href="http://demin.ws/blog/english/2012/07/26/raspberry-pi-links/"/>
    <updated>2012-07-26T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/26/raspberry-pi-links/</id>
    <content type="html"><![CDATA[<p>Playing with <a href="http://demin.ws/blog/english/2012/07/11/raspberry-pi-arrived/">Raspberry Pi</a> I have collected a bunch of
more or less useful links, so I decided to put them all together.</p>

<h2>Initial re-partitioning</h2>

<p>At the time of this writing the standard Debian images (stable)
distributed from the official Raspberry Pi website were built
for 2GB SD cards. It is possible to copy them to larger cards
and it will work but space above 2GB will be wasted.</p>

<p>There are a few simple steps to re-partition the card after
the first boot.</p>

<p>Images:</p>

<p><a href="http://raspberrypi.org/downloads/">http://raspberrypi.org/downloads/</a></p>

<p>Step by step:</p>

<p><a href="https://projects.drogon.net/raspberry-pi/initial-setup1/">https://projects.drogon.net/raspberry-pi/initial-setup1/</a></p>

<p>In short:</p>

<pre><code>printf &quot;d\n3\nd\n2\nn\np\n2\n157696\n\nw\n&quot; | sudo fdisk -cu /dev/mmcblk0
sudo shutdown -r now
sudo resize2fs /dev/mmcblk0p2
</code></pre>

<h2>Troubleshooting</h2>

<p><a href="http://elinux.org/R-Pi_Troubleshooting">http://elinux.org/R-Pi_Troubleshooting</a></p>

<h2>GPIO</h2>

<h3>General info</h3>

<p><a href="http://elinux.org/Rpi_Low-level_peripherals">http://elinux.org/Rpi_Low-level_peripherals</a></p>

<h3>WiringPi</h3>

<p><a href="https://projects.drogon.net/raspberry-pi/wiringpi/">https://projects.drogon.net/raspberry-pi/wiringpi/</a></p>

<ul>
<li><a href="https://projects.drogon.net/raspberry-pi/wiringpi/pins/">Pins</a>

<ul>
<li><a href="https://projects.drogon.net/raspberry-pi/wiringpi/special-pin-functions/">Special Pins</a></li>
</ul></li>
<li><a href="https://projects.drogon.net/raspberry-pi/wiringpi/download-and-install/">Download and install</a></li>
<li>Wrappers

<ul>
<li><a href="https://rubygems.org/gems/wiringpi/">Ruby</a></li>
</ul></li>
</ul>

<h3>RPI.GPIO</h3>

<p><a href="http://pypi.python.org/pypi/RPi.GPIO">http://pypi.python.org/pypi/RPi.GPIO</a></p>

<p>Homepage: <a href="http://raspberry-gpio-python.googlecode.com">http://raspberry-gpio-python.googlecode.com</a></p>

<p>How to install:</p>

<pre><code>cd /tmp
wget http://raspberry-gpio-python.googlecode.com/files/RPi.GPIO-0.2.0.tar.gz
tar xzvf RPi.GPIO-0.2.0.tar.gz
cd tar xzvf RPi.GPIO-0.2.0
python setup.py install
</code></pre>

<p>Sample program:</p>

<pre><code>import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
pin = 4
GPIO.setup(pin, GPIO.OUT)
while True:
    GPIO.output(pin, True)
    GPIO.output(pin, False)
</code></pre>

<h3>Benchmarking Raspberry Pi GPIO speed</h3>

<p><a href="http://codeandlife.com/2012/07/03/benchmarking-raspberry-pi-gpio-speed/">http://codeandlife.com/2012/07/03/benchmarking-raspberry-pi-gpio-speed/</a></p>

<h3>Example with 2 LEDs</h3>

<p><a href="https://projects.drogon.net/raspberry-pi/gpio-examples/tux-crossing/2-two-more-leds/">https://projects.drogon.net/raspberry-pi/gpio-examples/tux-crossing/2-two-more-leds/</a></p>

<h3>GPIO Port on the Raspberry Pi</h3>

<p><a href="http://chrishatton.org/archives/88">http://chrishatton.org/archives/88</a></p>

<h2>SPI/I2C 3.2 kernel</h2>

<p>This kernel is based the 3.2 branch. It comes with I2C drivers and a bunch
of staging drivers (for example, WiFi).</p>

<p><a href="http://bootc.net/projects/raspberry-pi-kernel">http://bootc.net/projects/raspberry-pi-kernel</a></p>

<h2>I2C</h2>

<h3>Quick2Write</h3>

<ul>
<li><a href="http://quick2wire.com/">http://quick2wire.com/</a></li>
<li><a href="http://quick2wire.com/blog/">http://quick2wire.com/blog/</a></li>
<li><a href="http://quick2wire.com/2012/05/an-experimental-gpio-python-library-for-the-raspberry-pi/">An experimental GPIO Python library for the Raspberry Pi</a></li>
</ul>

<h3>Linux I2C interface</h3>

<p><a href="http://kernel.org/doc/Documentation/i2c/dev-interface">http://kernel.org/doc/Documentation/i2c/dev-interface</a></p>

<h2>I2C examples</h2>

<p><a href="http://robot-electronics.co.uk/htm/raspberry_pi_examples.htm">I2C examples</a></p>

<p><a href="http://raspberrypi.org/phpBB3/viewtopic.php?f=44&amp;t=8043">Example I2C Code</a></p>

<pre><code>echo ds1307 0x68 &gt; /sys/class/i2c-adapter/i2c-0/new_device
</code></pre>

<h3>I2C and the Raspberry Pi</h3>

<p>Explanations why and how I2C was added to BootC RPi kernel:</p>

<p><a href="http://bootc.net/archives/2012/05/19/i2c-and-the-raspberry-pi/">http://bootc.net/archives/2012/05/19/i2c-and-the-raspberry-pi/</a></p>

<h3>MCP23017 I2C IO expander</h3>

<p><a href="http://nathan.chantrell.net/20120519/raspberry-pi-and-the-mcp23017-i2c-io-expander/">http://nathan.chantrell.net/20120519/raspberry-pi-and-the-mcp23017-i2c-io-expander/</a></p>

<h2>Complete I2C setup on Raspberry Pi</h2>

<p><a href="http://robot-electronics.co.uk/files/rpi_i2c_setup.doc">http://robot-electronics.co.uk/files/rpi_i2c_setup.doc</a></p>

<p>Set up for using i2c with Raspberry Pi running the standard Debian
squeeze distribution.</p>

<pre><code>sudo dpkg-reconfigure tzdata
sudo apt-get update
sudo apt-get upgrade 
sudo apt-get install ca-certificates
</code></pre>

<p>Install hexxeh&rsquo;s rpi-upgrade tool <a href="https://github.com/Hexxeh/rpi-update#readme:">https://github.com/Hexxeh/rpi-update#readme:</a></p>

<pre><code>sudo wget http://goo.gl/1BOfJ -O /usr/bin/rpi-update
sudo chmod +x /usr/bin/rpi-update
sudo apt-get install git-core

sudo rpi-update
</code></pre>

<p>Restart rpi for updates to finish:</p>

<pre><code>sudo shutdown -r now
</code></pre>

<p>Download Chris Boots&rsquo;s kernel with the i2c drivers in as a Debian package
from his website <a href="http://bootc.net">http://bootc.net</a>. Navigate to where the Debian package
was saved using command line and install the Debian package.</p>

<pre><code>dpkg -i linux-image-3.2.18-rpi1+_5_armel.deb
</code></pre>

<p>Copy /boot/vmlinuz-3.2.18rpi1+ to /boot/kernel.img:</p>

<pre><code>sudo cp /boot/vmlinuz-3.2.18rpi+ /boot/kernel.img
</code></pre>

<p>Restart RPi again:</p>

<pre><code>sudo shutdown -r now
</code></pre>

<p>Download i2c-tools:</p>

<pre><code>sudo apt-get install i2c-tools
</code></pre>

<p>If you run ls /dev/i2c* you will not be able to see any i2c ports
(e.g. /dev/i2c-0) listed. At start up the i2c ports will not be active.
Make it active using modprobe:</p>

<pre><code>sudo modprobe i2c-dev
</code></pre>

<p>Now look to see if your i2c ports exist in /dev:</p>

<pre><code>ls /dev/i2c*
i2cdetect -l
dmesg | grep i2c
</code></pre>

<p>You should see two i2c ports listed named /dev/i2c-0 and /dev/i2c-1.
/dev/i2c-0 is the one we will be using.  Another way of listing them
is to run i2cdetect -l (a tool that came with the i2c-tools you installed
earlier).</p>

<p>Change permissions of the i2c-0 port to let you access:</p>

<pre><code>sudo chmod 666 /dev/i2c-0
</code></pre>

<p>You should now be able to download and run some of our example c code.
You will need to modprobe i2c-dev and change the permissions of the i2c
port every time you boot up as these setting are not saved by default.</p>

<h2>Checking Firmware Version</h2>

<p>Firmware should be up-to-date. Its update is harmless and cannot
brick your RPi.</p>

<pre><code>/opt/vc/bin/vcgencmd version
</code></pre>

<h2>RPI update</h2>

<h3>Method 1</h3>

<p><a href="https://github.com/Hexxeh/rpi-update">https://github.com/Hexxeh/rpi-update</a></p>

<pre><code>wget https://raw.github.com/Hexxeh/rpi-update/master/rpi-update -O /usr/bin/rpi-update &amp;&amp; chmod +x /usr/bin/rpi-update

sudo apt-get install ca-certificates
rpi-update
</code></pre>

<h3>Method 2</h3>

<p><a href="http://iroylabs.blogspot.co.uk/2012/06/raspberrypi-mouse-and-keyboard-does-not.html">http://iroylabs.blogspot.co.uk/2012/06/raspberrypi-mouse-and-keyboard-does-not.html</a></p>

<pre><code>wget https://raw.github.com/Hexxeh/rpi-update/master/rpi-update
chmod +x rpi-update
mv rpi-update /usr/bin/rpi-update
sudo rpi-update
</code></pre>

<h2>Keeping Raspberry Pi fresh</h2>

<p><a href="http://wrightrocket.blogspot.co.uk/2012/06/keeping-your-raspberry-pi-fresh.html">http://wrightrocket.blogspot.co.uk/2012/06/keeping-your-raspberry-pi-fresh.html</a></p>

<h2>USB to serial cable</h2>

<p>Olimex USB-SERIAL-CABLE Olinuxino console cable alternative to Raspberry Pi.</p>

<ul>
<li>three wires for Breadboard connection</li>
<li>SERIAL output 3.3V voltage levels</li>
<li>GND=BLUE, RX(INPUT)=GREEN, TX(OUTPUT)=RED</li>
</ul>

<p>BLUE (GND) -&gt; 0v
GREEN (RX) -&gt; GPIO 14/TxD (BCM), or 15 (wiringPi)
RED (TX) -&gt; GPIO 15/RxD (BCD), or 16 (wiringPi)</p>

<h3>Driver for Mac OSX Lion</h3>

<p><a href="http://xbsd.nl/2011/07/pl2303-serial-usb-on-osx-lion.html">http://xbsd.nl/2011/07/pl2303-serial-usb-on-osx-lion.html</a></p>

<pre><code>cd /tmp
wget http://xbsd.nl/~martijn/log/osx-pl2303.kext.tgz
tar xvzf osx-pl2303.kext.tgz
cd osx-pl2303.kext
sudo cp -R osx-pl2303.kext /System/Library/Extensions/
cd /System/Library/Extensions
chmod -R 755 osx-pl2303.kext
chown -R root:wheel osx-pl2303.kext
cd /System/Library/Extensions

kextload ./osx-pl2303.kext
kextcache -system-cache
</code></pre>

<p>Check:</p>

<pre><code>kextstat -b nl.bjaelectronics.driver.PL2303

Index Refs Address            Size       Wired      Name (Version) &lt;Linked Against&gt;
   74    0 0xffffff7f808ee000 0xb000     0xb000     nl.bjaelectronics.driver.PL2303 (1.0.0d1) &lt;73 34 5 4 3&gt;
</code></pre>

<h3>Unload the driver (if needed)</h3>

<p>Check &ldquo;kextstat&rdquo; first, and if &ldquo;nl.bjaelectronics.driver.PL2303&rdquo; is there, it can be unloaded by:</p>

<pre><code>sudo kextunload /System/Library/Extensions/osx-pl2303.kext/
</code></pre>

<h3>Driver as a package</h3>

<p><a href="http://changux.co/osx-installer-to-pl2303-serial-usb-on-osx-lio">http://changux.co/osx-installer-to-pl2303-serial-usb-on-osx-lio</a></p>

<h3>PL-2303 cables on Mac</h3>

<p><a href="http://planet-rcs.de/article/mac_serial_port/">http://planet-rcs.de/article/mac_serial_port/</a></p>

<h2>WiFi</h2>

<p><a href="http://raspberrywifi.com/">http://raspberrywifi.com/</a></p>

<h3>ASUS N10 WiFi adaptor</h3>

<p>Kernel 3.2.21-rpi1+ already has this driver, but it requires firmware.</p>

<ol>
<li><p>Add the following line to /etc/apt/sources.list:</p>

<p>deb <a href="http://backports.debian.org/debian-backports">http://backports.debian.org/debian-backports</a> squeeze-backports non-free</p></li>

<li><p>Update the package index:</p>

<p>sudo apt-get update</p></li>

<li><p>Install firmware-realtek deb package:</p>

<p>sudo apt-get install firmware-realtek</p></li>
</ol>

<p>Check:</p>

<pre><code>sudo iwlist wlan0 scan
</code></pre>

<p>Post-setup:</p>

<pre><code>sudo vi /etc/network/interfaces

auto wlan0
iface wlan0 inet dhcp
wpa-ssid &quot;your_ssid&quot;
wpa-psk &quot;your_password&quot;
</code></pre>

<h2>Cool gadgets</h2>

<h3>VGA over serial port</h3>

<p><a href="http://hobbytronics.co.uk/serial-vga">http://hobbytronics.co.uk/serial-vga</a></p>

<h3>Cardboard case</h3>

<p><a href="http://squareitround.co.uk/Resources/Punnet_net_Mk1.pdf">http://squareitround.co.uk/Resources/Punnet_net_Mk1.pdf</a></p>

<h2>Blogs about Raspberry PI</h2>

<ul>
<li><a href="https://projects.drogon.net/raspberry-pi/">https://projects.drogon.net/raspberry-pi/</a></li>
<li><a href="http://bootc.net/projects/raspberry-pi-kernel">http://bootc.net/projects/raspberry-pi-kernel</a>

<ul>
<li><a href="http://bootc.net/">http://bootc.net/</a></li>
</ul></li>
<li><a href="http://raspberrypi.homelabs.org.uk/">http://raspberrypi.homelabs.org.uk/</a></li>
<li><a href="http://pi.gadgetoid.co.uk/">http://pi.gadgetoid.co.uk/</a></li>
<li><a href="http://codeandlife.com/topics/raspberry-pi/">http://codeandlife.com/topics/raspberry-pi/</a></li>
<li><a href="http://blog.mx17.net/category/hardware/raspberry-pi/">http://blog.mx17.net/category/hardware/raspberry-pi/</a></li>
</ul>

<h2>Useful sites</h2>

<ul>
<li><a href="https://projects.drogon.net/">https://projects.drogon.net/</a></li>
<li><a href="http://hobbytronics.co.uk/">http://hobbytronics.co.uk/</a></li>
<li><a href="http://codeandlife.com/">http://codeandlife.com/</a></li>
<li><a href="http://sparkfun.com/">http://sparkfun.com/</a></li>
<li><a href="http://gadgetoid.com/">http://gadgetoid.com/</a></li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Resources about GMC-4 Microcomputer]]></title>
    <link href="http://demin.ws/blog/english/2012/07/26/resources-about-gmc4-microcomputer/"/>
    <updated>2012-07-26T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/26/resources-about-gmc4-microcomputer/</id>
    <content type="html"><![CDATA[<p>Most of the resources are in Japanese but Google Translate in Chrome
does decent work instantly translating into English. The resources
in English are marked.</p>

<p>GMC-4 is cloned from other microcomputers, and its instruction
set is compatible with:</p>

<ul>
<li>FX-microcomputer R-165</li>
<li><a href="http://demin.ws/gmc4/doc/Tandy Microcomputer Trainer 28-260.pdf">Tandy Microcomputer Trainer</a> (english)</li>
</ul>

<h2>Links to various resources about GMC-4</h2>

<ul>
<li><p>Official magazine issues</p>

<ul>
<li><a href="http://otonanokagaku.net/feature/vol23/index.html">http://otonanokagaku.net/feature/vol23/index.html</a></li>
<li><a href="http://otonanokagaku.net/magazine/vol24/index.html">http://otonanokagaku.net/magazine/vol24/index.html</a></li>
<li><a href="http://otonanokagaku.net/english/magazine/vol24/index.html">http://otonanokagaku.net/english/magazine/vol24/index.html</a> (english)</li>
</ul></li>

<li><p>Review and documentation</p>

<ul>
<li><a href="http://demin.ws/gmc4/otona_gmc.html">Programming the Gakken GMC-4 Microcomputer</a>,
architecture and instruction set (english)</li>
<li><a href="http://demin.ws/gmc4/doc/GMC-4 Microcomputer Manual.pdf">GMC-4 Microcomputer Manual</a> (english)</li>
<li><a href="http://www.pwv.co.jp/~take/TakeWiki/index.php?GMC-4%E3%82%B3%E3%83%B3%E3%83%91%E3%82%A4%E3%83%A9%E3%83%BC">About GMC-4 (introduction, instruction set, simulator, compiler)</a></li>
<li><a href="http://demin.ws/blog/english/2012/07/04/gmc-4/">GMC-4 microcomputer</a> (english)</li>
</ul></li>

<li><p>Firmware</p></li>
</ul>

<p><strong>There are no sources available of the original GMC-4 firmware.</strong></p>

<ul>
<li><p>Hardware</p>

<ul>
<li>Schematic
(<a href="http://demin.ws/gmc4/hardware/schematic/GMC-4 Schematic.pdf">version 1</a>,
<a href="http://demin.ws/gmc4/hardware/schematic/GMC-4 Schematic v0.12.jpg">version 2</a>)</li>
<li><a href="http://100year.cocolog-nifty.com/blog/2009/08/gmc-4-2ea0.html">Keypad connector for the loader</a>
(<a href="http://demin.ws/gmc4/hardware/keypad-connection/gmc4-keypad-board-upside.jpg">upside</a>,
<a href="http://demin.ws/gmc4/hardware/keypad-connection/gmc4-keypad-board-downside.jpg">downside</a>,
<a href="http://demin.ws/gmc4/hardware/keypad-connection/gmc4-keypad-schematic.jpg">schematic</a>)</li>
<li><a href="http://100year.cocolog-nifty.com/blog/2009/08/gmc-4-loaderusb.html">USB loader 1</a>
(<a href="http://demin.ws/gmc4/usb-loader-100year/gmc4loader-assembled.jpg">assembled</a>,
<a href="http://demin.ws/gmc4/usb-loader-100year/gmc4loader-interface-board.jpg">interface board</a>,
<a href="http://demin.ws/gmc4/usb-loader-100year/gmc4loader-schematic-v101.jpg">schematic</a>,
<a href="http://demin.ws/gmc4/usb-loader-100year/gmc4-loader-port-layout.html">port layout</a>,
<a href="http://demin.ws/gmc4/usb-loader-100year/gmc4_loader_farm_v2.01.zip">firmware sources</a>,
<a href="http://demin.ws/gmc4/usb-loader-100year/74HC_HCT4051.pdf">74HC4051 datasheet</a>)</li>
</ul></li>

<li><p>Blogs</p>

<ul>
<li><a href="http://blog.nshdot.com/search/label/gmc-4/">http://blog.nshdot.com/search/label/gmc-4/</a></li>
<li><a href="http://airvariable.asablo.jp/blog/cat/gmc-4/">http://airvariable.asablo.jp/blog/cat/gmc-4/</a></li>
<li><a href="http://100year.cocolog-nifty.com/blog/gmc4/">http://100year.cocolog-nifty.com/blog/gmc4/</a></li>
<li><a href="http://www.geocities.jp/yasuho68k/gmc4/">http://www.geocities.jp/yasuho68k/gmc4/</a> (a bunch of sample programs)</li>
<li><a href="http://d.hatena.ne.jp/yasuho/searchdiary?word=%2A%5B4%A5%D3%A5%C3%A5%C8%A5%DE%A5%A4%A5%B3%A5%F3%5D">http://d.hatena.ne.jp/yasuho/searchdiary?word=%2A%5B4%A5%D3%A5%C3%A5%C8%A5%DE%A5%A4%A5%B3%A5%F3%5D</a></li>
</ul></li>

<li><p>Simulators</p>

<ul>
<li><a href="http://dansan.air-nifty.com/blog/gmc4-simulator.html">GMC-4 simulator</a>
(<a href="http://demin.ws/gmc4/images/gmc4-simulator-windows.png">screenshot</a>)</li>
<li><a href="http://homepage2.nifty.com/kocha_web/fxms/fxms.html">FX-microcomputer R-165 simulator</a>
(<a href="http://demin.ws/gmc4/images/fx-164-simulator.png">screenshot</a>)</li>
<li><a href="https://sites.google.com/site/shuitic2000/home22">On Android</a></li>
</ul></li>

<li><p>Loaders</p>

<ul>
<li><a href="http://demin.ws/blog/english/2012/07/25/gmc4-loader-assembled/">GMC-4 Microcomputer USB loader based on UBW</a> (english)</li>
<li><a href="http://100year.cocolog-nifty.com/blog/2009/08/gmc-4-loaderusb.html">GMC-4 USB loader based on the AVR controller</a></li>
<li><a href="http://airvariable.asablo.jp/blog/2009/08/21/4530702">GMC-4 loader based a PIC development board</a></li>
</ul></li>

<li><p>Assemblers</p>

<ul>
<li><a href="http://www.musashinodenpa.com/misc/GMC4/">http://www.musashinodenpa.com/misc/GMC4/</a></li>
<li><a href="http://slashdot.jp/~roto/journal/481254">http://slashdot.jp/~roto/journal/481254</a></li>
<li><a href="https://github.com/jasperla/gmc4-as/">https://github.com/jasperla/gmc4-as/</a></li>
<li><a href="http://fxm.piroyan.com/">http://fxm.piroyan.com/</a></li>
<li><a href="http://d.hatena.ne.jp/nicotakuya/20090702/1246521731">http://d.hatena.ne.jp/nicotakuya/20090702/1246521731</a></li>
</ul></li>

<li><p>Compilers</p>

<ul>
<li><a href="http://terus.jp/engineering/gmc4cc/">C Compiler</a></li>
<li><a href="http://softyasu.net/g4cbasic.html">BASIC Compiler</a></li>
</ul></li>

<li><p>Replications</p>

<ul>
<li><a href="http://code.google.com/p/avr-gmc-4/">avr-gmc-4</a> (AVR) (<a href="http://demin.ws/gmc4/replica/avr-gmc-4/avr-gmc-4-v0.1.zip">sources</a>)</li>
<li><a href="http://akkera102.sakura.ne.jp/gbadev/index.php?NO.102%20gmc4">devkitARM</a> (ARM)
(<a href="http://demin.ws/gmc4/replica/devkitARM/102_gmc4.png">screenshot</a>,
<a href="http://demin.ws/gmc4/replica/devkitARM/102_gmc4.zip">sources</a>)</li>
</ul></li>

<li><p>Links collection from the Official Wiki</p>

<ul>
<li><a href="http://www15.atwiki.jp/gmc4/pages/12.html">http://www15.atwiki.jp/gmc4/pages/12.html</a></li>
</ul></li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[GMC-4 Microcomputer USB loader]]></title>
    <link href="http://demin.ws/blog/english/2012/07/25/gmc4-loader-assembled/"/>
    <updated>2012-07-25T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/25/gmc4-loader-assembled/</id>
    <content type="html"><![CDATA[<p>I decided to build my own USB loader for <a href="http://demin.ws/blog/english/2012/07/04/gmc-4/">GMC-4</a>. Following the advice of Serg Vakulenko, the following board was purchased:</p>

<p><img src="http://demin.ws/images/blog/gmc4-loader/ubw-proto-pic.jpg" alt="" />
</p>

<p>This is a <a href="http://www.sparkfun.com/products/762">USB Bit Whacker</a>, a development board based on PIC18. Its default firmware allows to control I/O pins via <a href="http://schmalzhaus.com/UBW/Doc/FirmwareDDocumentation_v149.html">simple commands</a> over a virtual serial port.</p>

<p>Schematic.</p>

<p><img src="http://demin.ws/images/blog/gmc4-loader/gmc4-loader-schematic.jpg" alt="" />
</p>

<p>A prototype.</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/eg6OZMAI5mg" frameborder="0" allowfullscreen></iframe>

<p>I was lazy to etch the board, so soldered manually. Looks unsightly but works.</p>

<p><img src="http://demin.ws/images/blog/gmc4-loader/IMG_0586.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/gmc4-loader/IMG_0587.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/gmc4-loader/IMG_0588.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/gmc4-loader/IMG_0590.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/gmc4-loader/IMG_0589.JPG" alt="" />
</p>

<p>In action.</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/F2tciUH0NFg" frameborder="0" allowfullscreen></iframe>

<p>After all, GMC-4 is THE thing!</p>

<p>P.S. The sources are available on Github &ndash; <a href="https://github.com/begoon/gmc4-loader/">gmc4-loader</a>. I suspect that in Python or Ruby it might be much nicer, but it was a nice exercise programming serial ports in UNIX.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An interview with Anthony Williams]]></title>
    <link href="http://demin.ws/blog/english/2012/07/24/interview-with-anthony-williams/"/>
    <updated>2012-07-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/24/interview-with-anthony-williams/</id>
    <content type="html"><![CDATA[<p>Today my guest is <a href="http://www.boost.org/users/people/anthony_williams.html">Anthony Williams</a>, the author of the recently
released book &ldquo;C++ Concurrency in Action&rdquo;. Residing in West Cornwall
and being able to see the sea from his office, Anthony develops and
maintains C++ libraries, participates in proposals for the C++
standard and runs a company called &ldquo;<a href="http://www.justsoftwaresolutions.co.uk/">Just Software solutions</a>&rdquo;.</p>

<hr />

<p><img src="http://demin.ws/images/blog/anthony-williams.jpg" alt="" />
</p>

<blockquote>
<p>Unless the multithreaded code is going to
be clearly faster, then writing single-threaded code will save you a
lot of headaches.</p>
</blockquote>

<hr />

<p>I recently purchased his book about concurrency in C++. To be honest I
haven&rsquo;t met better material so far about C++ 2011 memory model. Today
we have an opportunity to ask Anthony a few questions, and, of course,
particularly about C++.</p>

<p><strong>Hi Anthony, thanks for the interview, and let me begin from
afar. Programming, computers, C++&hellip; Why had you chosen this way? What
dragged you on this route of bits and bytes?</strong></p>

<p>I&rsquo;ve always been interested in computers, and it turned out that I was
reasonably good at programming them. We had a Sinclair ZX81 at home,
and a BBC Micro at school when I was around 7 or 8, and it all started
from there. I used to examine the source code of the games to see how
they worked. When it came time to apply for jobs after my degree, I
was quite clear in my mind that I wanted to do programming. It
was fun, interesting, challenging, and you got paid for it!</p>

<p><strong>I suspect that C++ wasn&rsquo;t the first language you&rsquo;ve learned. Have
you ever programmed in some unusual languages at early days?</strong></p>

<p>C++ wasn&rsquo;t around when I started programming, so no it wasn&rsquo;t the
first language I learned. I started with BASIC. All home computers had
some variety of BASIC built in, and it was a while before I realised
there was anything else. Some programs were written in machine code,
so I learnt that next &mdash; converting Z80 assembly language to hex
codes by hand and typing them in as DATA statements of a BASIC loader
program.</p>

<p>I don&rsquo;t think I&rsquo;ve programmed in anything that was really unusual, but
I&rsquo;ve used quite a few languages for various different
systems. Programming a PIC with only 100 bytes of program space was a
challenge, and I don&rsquo;t suspect many people ever programmed the Psion
Organizer II, though the programming language for it was similar to
BASIC in many ways.</p>

<p><strong>Can you recall any influential or maybe even outstanding books that
helped establish yourself in the career?</strong></p>

<p>Hmm. It would have to be the Z80 programming reference I had when I
was around 10 or 11. I can&rsquo;t remember the title, but I devoured that
book. I knew every instruction by heart, including the hex opcodes and
the clock counts. I found a similar guide to the 8086 on a shareware
disk when we got a PC, printed it out and devoured that too.</p>

<p>These days my bookshelves have books like Design Patterns,
Refactoring, and The Art of Computer Programming, though I still like
to keep &ldquo;close to the metal&rdquo; with things like Intel&rsquo;s Software
Optimization Cookbook.</p>

<p><strong>Now C++, and concurrency. Missing on opportunity for a few
questions to the expert seems to be not such a good idea. So, to begin
with, what don&rsquo;t you like in the C++ 2011 concurrency support?</strong></p>

<p>Good question! I don&rsquo;t think there&rsquo;s anything that I can point at and
say &ldquo;I don&rsquo;t like the way that works&rdquo;. I think it was a shame the
&ldquo;is_ready()&rdquo; function got removed from future and shared_future, since
it&rsquo;s useful, and you can achieve the same goal with
wait_for(seconds(0)) anyway.</p>

<p><strong>You&rsquo;re a maintainer of the Boost thread library. At the same time
you develop your own library for concurrency in C++ called
<a href="http://www.stdthread.co.uk/">just::thread</a>. What is special in this library?</strong></p>

<p>Just::Thread is a strict implementation of the C++11 thread library,
highly optimized for the specific platforms targetted, whereas
Boost.Thread is aiming for portability, and doesn&rsquo;t have the same
interface or semantics in several cases. Though Boost.Thread is being
brought further in line with C++11, it still lacks std::async, which
is present in Just::Thread.</p>

<p>Just::Thread also has a special &ldquo;checked&rdquo; build which will identify
the call chain leading to a deadlock should one occur.</p>

<p><strong>Actors and the concept of sharing by communicating. It looks that the lack of this functionality doesn&rsquo;t allows the concurrency in C++11 to shine in full power. Can you recommend any libraries providing such functionality?</strong></p>

<p>The Just::thread Pro library currently in development will provide
actors. There is also an example in my book of using message queues to
create actor-style code.</p>

<p><strong>I recall your saying that multi-threading in computations is
tricky because it starts to make sense only after a certain volume. Do
you have any recommendations on when it&rsquo;s worth considering a
concurrent and multi-threaded solution, and when it isn&rsquo;t?</strong></p>

<p>Yes, there&rsquo;s an overhead to setting things up for multithreading. If
your computation is quick enough then you may well be better off
writing it single-threaded. Unless the multithreaded code is going to
be clearly faster, then writing single-threaded code will save you a
lot of headaches.</p>

<p>As ever, the key to optimizing for performance (and multithreading in
this scenario is just that &mdash; an optimization) is to profile your
application. Where is it spending its time? Can you parallelize that
section? As Jason McGuiness demonstrated in his presentation at ACCU
2012, if you parallelize the wrong part of the code then it can be a
lot of effort for no gain whatsoever.</p>

<p><strong>Now, TDD. Where are you in this area? Have you embraced TDD and
now use it everywhere? Is TDD applicable for developing concurrency
libraries, for example, in C++?</strong></p>

<p>I like TDD, and use it all the time. It encourages you to work in
small steps, and the test suite you build up ensures that scenarios
you&rsquo;ve tested already don&rsquo;t break as you address new scenarios.</p>

<p>It&rsquo;s a bit harder to do TDD when developing concurrency libraries, but
not impossible, and I still do it. The trick is in structuring your
test to check the right thing. You typically need some form of barrier
(I often use a std::promise with std::shared_future) so that you can
set up all your threads in the right state, and then say &ldquo;go!&rdquo; The
best way to test concurrent code is still to remove the concurrency
&mdash; have well-defined communication mechanisms, and then test each
thread in isolation.</p>

<p><strong>Do you think that the code must be ideal, no trade-offs, no
tolerance to inaccuracy or lack of the beauty? How do you judge your
own code for being ready to release?</strong></p>

<p>You should always /aim/ for perfect code. If you don&rsquo;t, then it is
very easy to end up with slap-dash unmaintainable code.</p>

<p>However, you don&rsquo;t always get to write perfect code. Sometimes you
can&rsquo;t see a way to make it better, or the changes required are too
extensive for the time frame you have. It is always better to have
code that works correctly rather than code that looks pretty. If you
have extensive tests then you can refactor your code later to a better
structure without worrying about breaking it.</p>

<p>I judge code to be ready to release when I can&rsquo;t think of a
circumstance that would break it. If I can think of such a
circumstance then I write a test for that, and fix it.</p>

<p><strong>Can you name your three biggest &ldquo;Never ever do that!&rdquo; for programmers? and also for C++ programmers?</strong></p>

<p>Tricky! &ldquo;Never&rdquo; is a strong word.</p>

<p>Here&rsquo;s some things you should rarely do, in no particular order:</p>

<ul>
<li><p>Use global variables. Pass things you need as parameters or hold
them as member variables rather than relying on globals, as globals
make access patterns hard to understand.</p></li>

<li><p>Use singletons. These are just global variables in disguise, and
should be used with the same caution.</p></li>

<li><p>Write multithreaded code without carefully thinking through the data
access patterns from the separate threads. If you&rsquo;re going to write
multithreaded code, take the time to do it properly. You&rsquo;ll save
yourself a lot of effort in the long run.</p></li>
</ul>

<p>For C++ specifically, you should rarely:</p>

<ul>
<li><p>Use malloc and free. This is C++, not C.</p></li>

<li><p>Write code that requires you to use &ldquo;delete&rdquo;. If you have to use
&ldquo;new&rdquo; then you should probably be using a smart pointer such as
std::shared_ptr or std::unique_ptr to manage the memory. Often
you&rsquo;re better off using a container like std::vector to manage
everything anyway.</p></li>

<li><p>Overload operators in an unconventional manner. Sometimes it can be
really useful (e.g. using &lt;&lt; for stream insertion), but having a+b
mean anything other than &ldquo;adding&rdquo; for the relevant data types is
likely to yield confusion.</p></li>
</ul>

<p><strong>You wrote a book. Please, shed some light on this process. Why
have you decided to write it in the first place, and how long did it
take to prepare &ldquo;C++ Concurrency in Action&rdquo;? What was the most
difficult part of it?</strong></p>

<p>I wrote &ldquo;C++ Concurrency in Action&rdquo; because the opportunity came up,
and I was one of those best-placed to write it, having been intimately
involved in the drafting of the relevant sections of the C++11
standard.</p>

<p>It has taken 4 years to put it all together. One of the reasons it
took so long is because the C++11 standard wasn&rsquo;t finished when I
started writing, and I had to add, remove and revise sections as the
draft standard evolved, but even without that it was a lot of
work. The hardest part was rewriting sections based on feedback from
reviews.</p>

<p><strong>Can you recommend other books about concurrency and multi-threading?</strong></p>

<p>&ldquo;Patterns for Parallel Programming&rdquo; by Mattson, Sanders and Masingill
is a good overview of how to structure parallel programs.</p>

<p>&ldquo;The Art of Multiprocessor Programming&rdquo; by Herlihy and Shavit is also
good, but much lower level. This covers things like visibility,
atomicity and consensus, and implementation of low-level structures
such as queues, spin locks and monitors.</p>

<p><strong>Now the question I ask everybody: sport programming and
programming contests. Is it important to any developer to spend some
time regularly solving puzzles? And have you even been involved in
developing or implementing sophisticated algorithms?</strong></p>

<p>I love puzzles. To an extent, programming is one big puzzle; that&rsquo;s
what makes it interesting.</p>

<p>I think puzzles use the same sort of thought processes as programming,
so regularly doing puzzles can improve your programming. Practising
anything helps make you better, so programming puzzles and contests
are good for that &mdash; you have to break from your &ldquo;normal&rdquo; programming
routine to focus yourself on something different, and try things
out. I like the Intel Threading Challenge that they&rsquo;ve been doing for
a couple of years now. Even if you don&rsquo;t enter, it can be good to do
the challenges &mdash; they are fun, and really stretch you.</p>

<p>I did have a lot of fun once working on an algorithm for assisting
helicopter maintenance engineers tune helicopters. They take a series
of measurements from the helicopter with special equipment whilst it
is flying in a series of different conditions, and then the software
tells them what to adjust to make it fly better. Since helicopter
flights are expensive, the goal was to tune the helicopter with the
minimum possible set of test flights.</p>

<p><strong>Are you an IDE or Vi/make guy? Do you think that it is still
possible to develop sophisticated software simply in Vi, or all those
days passed and considering proper IDEs is an inevitable step in
enterprise software development?</strong></p>

<p>I use emacs and make. I haven&rsquo;t yet found an IDE that makes life
easier for me. I think there&rsquo;s a lot of potential in Eclipse/CDT,
especially with the enhancements that <a href="http://demin.ws/blog/english/2012/05/19/peter-sommerlad-interview/">Peter Sommerlad</a>&rsquo;s team are adding, but I haven&rsquo;t found it enough to
switch yet.</p>

<p><strong>Do you think that &ldquo;The Last Programming Language&rdquo; exists? Or may
it exist at all? Is it C++?</strong></p>

<p>There is always scope for improvement in a programming language, and
any given language makes some things easy to express and others hard,
so I&rsquo;m not sure that the &ldquo;last&rdquo; programming language could really
exist.</p>

<p>If we ever get a sufficiently advanced AI, then we&rsquo;ll end up using
natural languages rather than specific programming languages, but I
think that&rsquo;s a long way off yet.</p>

<p><strong>Let&rsquo;s talk about hiring. If you need to hire a good C++
developer, what kind of questions you&rsquo;d prefer you ask?</strong></p>

<p>To some extent that depends on what I need from a new hire. If there&rsquo;s
time to train someone then specific C++ knowledge is not an issue, and
I&rsquo;d want to focus on things that highlighted general &ldquo;developer
aptitude&rdquo;.</p>

<p>If I needed someone who already knew C++ then I&rsquo;d want to ask
questions that demonstrated that knowledge as well.</p>

<p><strong>Wrapping up, do you have a list of, say, three things which each developer must implement through his or her career?</strong></p>

<p>I&rsquo;m not sure there are 3 things that <em>every</em> developer should
implement. However, there are definitely things to be learnt from
implementing basic data structures like lists and hash-maps, so I&rsquo;ll
take that as the first one.</p>

<p>For a second, I think a language parser can provide useful insight in
putting together data structures, even if it&rsquo;s a parser for a simple
configuration file language rather than something complicated like
C++. I think an arithmetic expression parser can be quite fun to write
as a simple exercise.</p>

<p>Finally, I think it is worthwhile writing a client-server
application. A web-app with Javascript code in the browser, and
something running on the server would work for this, but anything
where you are making calls from the client to the server over the
network will do. The point is to do something where making a server
call is considerably more expensive than making a local function
call, so you have to consider the cost when designing the API. If
there&rsquo;s a UI then it can also be an exercise in handling backend
latency whilst providing a &ldquo;responsive&rdquo; UI.</p>

<p><strong>Thanks, Anthony. Looking forward for your new talks and books, hope for your future appearances on conferences.</strong></p>

<p>&#9632;</p>

<p><em>// Anthony Williams, Alexander Demin</em></p>

<p><em>// July 2012</em></p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Raspberry Pi arrived]]></title>
    <link href="http://demin.ws/blog/english/2012/07/11/raspberry-pi-arrived/"/>
    <updated>2012-07-11T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/11/raspberry-pi-arrived/</id>
    <content type="html"><![CDATA[<p>After a few months of waiting and agiotage it finally arrived. I have dived again into a wonderful world on fiddling with kernels, patches, firmware, a bit of soldering, forums and blogs, trying to explore this wonderful piece of hardware.</p>

<p>I suspect there will be series of blog posts about Raspberry Pi.</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/arrived/IMG_0487.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/arrived/IMG_0488.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/arrived/IMG_0489.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/arrived/IMG_0490.JPG" alt="" />
</p>

<p>Frankly, even before receiving my own RPi I already had to solder the SD socket on another RPi which was broken. There is a rumor spreading that this type of SD sockets is very unreliable.</p>

<p><img src="http://demin.ws/images/blog/raspberry-pi/arrived/IMG_0491.JPG" alt="" />
</p>

<p>In contrast I cannot complain at all about an SD socket used in <a href="http://demin.ws/blog/english/2012/01/19/maximite-kit/">Maximite</a> but it was a different type.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0107.jpg" alt="" />
</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[USB Serial Console for Raspberry Pi on Mac OSX Lion: Olimex USB Serial Cable]]></title>
    <link href="http://demin.ws/blog/english/2012/07/10/usb-serial-console-for-rpi-on-macosx-olimex-usb-serial-cable/"/>
    <updated>2012-07-10T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/10/usb-serial-console-for-rpi-on-macosx-olimex-usb-serial-cable/</id>
    <content type="html"><![CDATA[<p>I recently started playing to Raspberry Pi. Along with other questions I wanted to try talking to RPi via a serial cable. The <a href="http://elinux.org/Rpi_Low-level_peripherals">documentation about RPi peripherals</a> says that at reset only pins GPIO 14 &amp; 15 (TxD, RxD) are assigned to the alternate function UART. So, it should work out of the box.</p>

<p>I decided to buy <a href="https://www.olimex.com/dev/usb-serial-cable.html">Olimex USB To Serial Cable</a>. It was available on eBay as <a href="http://www.ebay.co.uk/itm/Olimex-USB-SERIAL-CABLE-Olinuxino-console-cable-alternative-to-Raspberry-Pi-/280917749304?pt=UK_BOI_Electrical_Components_Supplies_ET&amp;hash=item416800ae38">Olimex USB-SERIAL-CABLE Olinuxino console cable alternative to Raspberry Pi</a>.</p>

<p>This cable provides 3.3V output levels which are strongly recommended for RPi (not 5V), and its 3 wires with female plugs can be directly connected to the RPi GPIO P1 header.</p>

<p><img src="http://demin.ws/images/blog/olimex-cable/olimex-usb-serial-cable-olinuxino-console-cable.png" alt="" />
</p>

<p>Unfortunately, at a time of this writing, there were no drivers for Mac OSX available on the <a href="https://www.olimex.com/dev/usb-serial-cable.html">official website</a>, and OSX Lion (10.7.4) didn&rsquo;t recognize this device. It was an unpleasant surprise because before I saw that Lion perfectly recognized other USB-RS232 hardware based on different chipsets (Microchip, for example).</p>

<p>I checked the Product ID and Manufacturer on the Olimex cable. When the cable is connected, click on &ldquo;About This Mac &gt; More Info… &gt; System Report… &gt; USB&rdquo;.</p>

<p><img src="http://demin.ws/images/blog/olimex-cable/pl2303-serial-usb-on-lion.png" alt="" />
</p>

<p>Googling for a Prolific driver for Mac brought me to a great blog post, called &ldquo;<a href="http://xbsd.nl/2011/07/pl2303-serial-usb-on-osx-lion.html">PL2303 Serial-USB on OSX Lion</a>&rdquo;. Following the instructions I installed the driver and connected to Raspberry Pi.</p>

<p>In short I did the following:</p>

<pre><code>cd /tmp
wget http://xbsd.nl/~martijn/log/osx-pl2303.kext.tgz
tar xvzf http://xbsd.nl/~martijn/log/osx-pl2303.kext.tgz
cd osx-pl2303.kext
sudo cp -R osx-pl2303.kext /System/Library/Extensions/
cd /System/Library/Extensions
chmod -R 755 osx-pl2303.kext
chown -R root:wheel osx-pl2303.kext
cd /System/Library/Extensions

kextload ./osx-pl2303.kext
kextcache -system-cache
</code></pre>

<blockquote>
<p>Note: Just in case, I made a copy of the &ldquo;<a href="http://demin.ws/files/olimex-cable/osx-pl2303.kext.tgz">osx-pl2303.kext.tgz</a>&rdquo; file.</p>
</blockquote>

<p>You can make sure that everything is installed correctly by:</p>

<pre><code>kextstat -b nl.bjaelectronics.driver.PL2303
</code></pre>

<p>It should print the following:</p>

<pre><code>Index Refs Address            Size       Wired      Name (Version) &lt;Linked Against&gt;
   74    0 0xffffff7f808ee000 0xb000     0xb000     nl.bjaelectronics.driver.PL2303 (1.0.0d1) &lt;73 34 5 4 3&gt;
</code></pre>

<blockquote>
<p>Note: If you need to <em>unload</em> the driver for some reason, you check that the driver is loaded (by <code>kextstat</code> command above), and then:</p>
</blockquote>

<pre><code>sudo kextunload /System/Library/Extensions/osx-pl2303.kext
</code></pre>

<p>When the driver is installed, reconnect the cable to USB. There should be two device drivers created <code>/dev/cu.PL2303-00002006</code> and <code>/dev/tty.PL2303-00002006</code>. You can check it by:</p>

<pre><code>ls /dev/*PL*
</code></pre>

<p>It should print:</p>

<pre><code>/dev/cu.PL2303-00002006     /dev/tty.PL2303-00002006
</code></pre>

<p>Now let&rsquo;s connect the cable to the RPi header P1. It&rsquo;s better to disconnect it from USB temporarily.</p>

<p>The pinout of the cable is the following:</p>

<table>
<thead>
<tr>
<td><strong>Wire</strong></td>
<td><strong>Desc</strong></td>
<td><strong>Rip GPIO</strong></td>
</tr>
</thead>

<tbody>
<tr>
<td>Blue</td>
<td>GND</td>
<td>0v</td>
</tr>

<tr>
<td>Green</td>
<td>Rx</td>
<td>14/TxD</td>
</tr>

<tr>
<td>Red</td>
<td>Tx</td>
<td>15/RxD</td>
</tr>
</tbody>
</table>

<p>An example of the connection:</p>

<p><img src="http://demin.ws/images/blog/olimex-cable/pl2303-serial-usb-on-lion-connected.jpg" alt="" />
</p>

<p>When all three wires are attached, you can connect the cable back to USB. Now any terminal emulator software can talk to RPi via the <code>/dev/cu.PL2303-00002006</code> device. I used Minicom:</p>

<pre><code>minicom -D /dev/cu.PL2303-00002006 -b 115200
</code></pre>

<p>It should print something like this:</p>

<pre><code>Welcome to minicom 2.6.1

OPTIONS: 
Compiled on May 10 2012, 07:16:49.
Port /dev/cu.PL2303-00002006

Press Meta-Z for help on special keys


Debian GNU/Linux 6.0 raspberrypi ttyAMA0

raspberrypi login:    
</code></pre>

<p>Finally, you may want to re-direct the RPi console from HDMI to the serial port (ttyAMA0). In this case RPi will be printing boot messages to the serial console instead of the monitor.</p>

<p><em>You need to login to your RPi</em> (via SSH, telnet or just established serial connection) and execute the following:</p>

<pre><code>sudo mount /dev/mmcblk0p1 /mnt
</code></pre>

<p>This will mount your boot partition to <code>/mnt</code>. Now you need to edit the kernel commund line:</p>

<pre><code>sudo vi /mnt/cmdline.txt
</code></pre>

<p>In <code>cmdline.txt</code> make sure that <code>console=ttyAMA0,115200</code> and <code>kgdboc=ttyAMA0,115200</code>, and there is no another <code>console=</code> assignment, for example to <code>tty0</code>. After you save the changes and reboot RPi, you may see RPi boot messages in the terminal emulator connected to <code>/dev/cu.PL2303-00002006</code>.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Enigma, Colossus, or the history of British cryptography]]></title>
    <link href="http://demin.ws/blog/english/2012/07/06/bletchley-park-colossus/"/>
    <updated>2012-07-06T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/06/bletchley-park-colossus/</id>
    <content type="html"><![CDATA[<p>I went to <a href="http://www.bletchleypark.org.uk/">Bletchley Park</a> today. One hour drive was a good reason to go. During The First World War it was a top secret military base. Here Alan Turing cracked <a href="http://en.wikipedia.org/wiki/Enigma_machine">Enigma</a> codes, and the <a href="http://en.wikipedia.org/wiki/Colossus_computer">Colossus</a>, the world&rsquo;s first electronic, digital, programmable computer, was built also here.</p>

<p>Now it is a museum of cryptography. Recently the Colossus was re-built, and now available to see it in action. My target was to see the Colossus and Enigma.</p>

<p>Today was a normal english day &ndash; raining all the way through. My lovely big brolly was incredibly useful.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0508.JPG" alt="" />
</p>

<p>If to skip a sticker on the windows, you may think that The War is still on.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0492.JPG" alt="" />
</p>

<p>Illustrations in the past were always created with love to details and general beauty.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0494.JPG" alt="" />
</p>

<p>A revolver. Just caught my eye because it was so close.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0495.JPG" alt="" />
</p>

<p>Frankly, I saw MP 38 (aka <a href="http://en.wikipedia.org/wiki/MP-36">Schmeisser</a>) so close first time in my life.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0496.JPG" alt="" />
</p>

<p>Do you recognized this tool? A twisted-pair crimp tool? This was from the 40th.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0498.JPG" alt="" />
</p>

<p>Looks like a key disc from Enigma-like machine.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0499.JPG" alt="" />
</p>

<p>In fact, the Enigma. To be exact &ndash; a bunch of them. I imagined the Enigma as a particular device which I saw in the American re-make of the &ldquo;Das Boot&rdquo; movie. But looks that even lazy people manufactured it.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0501.JPG" alt="" />
</p>

<p>A crypto device from Siemens.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0502.JPG" alt="" />
</p>

<p>Now a portable modification.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0503.JPG" alt="" />
</p>

<p>All exhibits are real and more than 70 years old.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0504.JPG" alt="" />
</p>

<p>The <a href="http://en.wikipedia.org/wiki/Bombe">Bombe</a> machine which was build particularly to crack the Enigma code.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0505.JPG" alt="" />
</p>

<p>The back view.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0506.JPG" alt="" />
</p>

<p>In action.</p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/yzxyn5G6cno" frameborder="0" allowfullscreen></iframe>

<p>In a radio cabin.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0509.JPG" alt="" />
</p>

<p>On the way to The Colossus.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0510.JPG" alt="" />
</p>

<p>So, this is it &ndash; the top secret computer of the British secret service during the First World War. Recently it was re-built and now available in action.</p>

<p>This is a two panels stuffed with bulbs. The front panel, from the left.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0512.JPG" alt="" />
</p>

<p>The front panel, from the right.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0513.JPG" alt="" />
</p>

<p>The back view. It is all moving and cracking. The modern fans on the floor are cooling the bulbs.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0514.JPG" alt="" />
</p>

<p>The back view from the left.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0515.JPG" alt="" />
</p>

<p>Between the panels. The oscilloscope even displays some figures.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0516.JPG" alt="" />
</p>

<p>How Colossus worked.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0518.JPG" alt="" />
</p>

<p>Frankly, it wasn&rsquo;t impressed at all. Yes, it is moving and cracking by tapes and spins, but&hellip; May be if they allow to code up a little program in place, I was much more excited.</p>

<p>In the same building with the Colossus, there is a <a href="http://www.tnmoc.org/">The National Museum of Computing</a>. Today it was, a shame, closed. Trying to bribe a person on duty to allow me to pop into mainframe and PC rooms did work out.</p>

<p>There is only a sad picture through the bars.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0511.JPG" alt="" />
</p>

<p>And this is the must have thing for any respectable bookstore (this is in the gift shop where they mostly sell books about the history of cryptography) &ndash; a sofa.</p>

<p><img src="http://demin.ws/images/blog/bletchley-park/IMG_0507.JPG" alt="" />
</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[GMC-4 microcomputer]]></title>
    <link href="http://demin.ws/blog/english/2012/07/04/gmc-4/"/>
    <updated>2012-07-04T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/04/gmc-4/</id>
    <content type="html"><![CDATA[<p>Following a <a href="http://ramlamyammambam.livejournal.com/190698.html">recommendation from Serge Vakulenko</a> I have purchased <a href="http://en.wikipedia.org/wiki/GMC-4">GMC-4</a> in a funny Japanese gadget stop, <a href="http://www.japantrendshop.com/gmc4-microcomputer-p-789.html">Japan Trend Shop</a>. To be honest, there is unique charm in such devices.</p>

<p><img src="http://demin.ws/images/blog/gmc4/gmc4.jpg" alt="" />
</p>

<p>GMC-4 is a 4-bit microcomputer:</p>

<ul>
<li>4-bit word</li>
<li>8 register, 1 flag</li>
<li>80 words in program memory</li>
<li>16 words in data memory</li>
<li>7 pre-loaded program (Organ, Sound Hit Game, Whack-a-mole, Tennis, Timer, Music Player, Morse Code Generator)</li>
<li>7 regular 2-pin LEDs</li>
<li>one 7-segment LED</li>
<li>a hex keypad</li>
<li>a speaker</li>
<li>hard reset button</li>
<li>powered from three AA elements</li>
</ul>

<p>The architecture is described in one small document &ndash; <a href="http://tsoj.manga.org/gakken/otona_gmc.html">Programming the Gakken GMC-4 Microcomputer</a>.</p>

<p>Yesterday my order arrived. GMC-4 is an add-on to an issue of a Japanese magazine called &ldquo;Gakken&rdquo;, #24, 2009. Unfortunately it&rsquo;s all in Japanese language.</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0458.JPG" alt="" />
</p>

<p>Funny that the back side of the box has a table of all GMC-4 instructions.</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0459.JPG" alt="" />
</p>

<p>The board, speaker, case, parts of the keyboard.</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0460.JPG" alt="" />
</p>

<p>The manual in Japanese is though.</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0469.JPG" alt="" />
</p>

<p>Set up batteries and the speaker.</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0463.JPG" alt="" />
</p>

<p>The board.</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0461.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0462.JPG" alt="" />
</p>

<p>Sticking the keyboard.</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0464.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0466.JPG" alt="" />
</p>

<p>Power on&hellip; It&rsquo;s alive! Alive!!!</p>

<p><img src="http://demin.ws/images/blog/gmc4/IMG_0468.JPG" alt="" />
</p>

<p>There is the keyboard, the 7-segment LED, the processor below it, then the &ldquo;hard reset&rdquo; button. There are seven independent LEDS on the top. They are used, for instance, to display the current address.</p>

<p>Let&rsquo;s write something. For example, a program waiting for a key pressed and then displaying it on the 7-segment readout.</p>

<pre><code>00: 0     KA 0       ; Read a key code (0-F) into A. If pressed, then Flag=0, else Flag=1.
01: F00   JUMP 00    ; If Flag=1 (not pressed), then go to 00.   
04: 1     AO         ; Out A to 7-segment readout and set Flag=1
05: F00   JUMP 00    ; If Flag=1 (it is always 1 here), then jump to 00.
</code></pre>

<p>To enter the code: <code>RESET 0 INCR F INCR 0 INCR 0 INCR 1 INCR F INCR 0 INCR 0 INCR RESET</code></p>

<p>To run: <code>RESET 1 RUN</code></p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/t-S86rICAPk" frameborder="0" allowfullscreen></iframe>

<p>Interestingly, this device allows <strong>step-by-step trace</strong>. If to run the program via <code>RESET 6 RUN</code>, it will be stopping after each instruction and displaying the current address on the top LEDs in binary code. To continue, we need to press <code>INCR</code> and so on. By pressing <code>RESET</code> we can interrupt the program and check out the registers (they are regular cells in memory). This is simple but convenient debugging.</p>

<p>Now slightly more complex example: a running light over the top LEDs displaying the number of the current one on the 7-segment readout.</p>

<pre><code>00: 80    TIA 0     ; A=0
02: 1     AO        ; Out A to 7-segment readout.
03: 3     CY        ; Store A to Y.
04: E1    CAL SETR  ; Turn on an LED which number is in Y.
06: 84    TIA 4     ; A=4
08: EC    CAL TMR   ; Wait (A+1)*0.1 seconds (0.5s).
0A: E2    CAL RSTR  ; Turn off an LED which number is in Y.
0C: 3     CY        ; Restore A from Y.
0D: 91    AIA 1     ; A = A + 1
0F: C7    CIA 7     ; If A=7, then Flag=0. Otherwise Flag=1.
11: F02   JUMP 02   ; Go to 02, if Flag=1, and set Flag=1.
13: F00   JUMP 00   ; Unconditional jump to 00 (Flag=1 after the previous instruction).
</code></pre>

<p>Code: <code>8 0 1 3 E 1 8 4 E C E 2 3 9 1 C 7 F 0 2 F 0 0</code></p>

<iframe width="640" height="360" src="http://www.youtube.com/embed/bdEUUtv93r0" frameborder="0" allowfullscreen></iframe>

<h2>Development tools</h2>

<p>Everything is in Japanese, but Google Translate does an amazing job.</p>

<h3><a href="http://dansan.air-nifty.com/blog/gmc4-simulator.html">Simulator</a></h3>

<p><img src="http://demin.ws/images/blog/gmc4/gmc4simulator.png" alt="" />
</p>

<h3>The loader</h3>

<iframe width="420" height="315" src="http://www.youtube.com/embed/lagnC5CpsUE" frameborder="0" allowfullscreen></iframe>

<h3>Programming languages</h3>

<ul>
<li><a href="http://musashinodenpa.com/misc/GMC4/">Assembler</a></li>
<li><a href="http://terus.jp/engineering/gmc4cc/">C compiler</a> and
<a href="http://terus.jp/engineering/gmc4cc/gmc4as.html">Assembler</a></li>
<li><a href="http://softyasu.net/g4cbasic.html">BASIC</a></li>
</ul>

<h1>Wrap up</h1>

<p>This is an amazing gadget. I started programming on <a href="http://radio86.googlecode.com/hg/online/radio86.html">Radio-86RK</a> in machine code typing in the Monitor. Same here. Also, the issue of the magazine, which GMC-4 is bundled with, according to illustrations (unfortunately, I don&rsquo;t read Japanese), is dedicated to the history of microprocessors starting from <a href="http://en.wikipedia.org/wiki/Intel_4004">Intel 4004</a>. Then there is a dozen of code examples and projects using GMC-4. Beautiful!</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Can Java be faster C++?]]></title>
    <link href="http://demin.ws/blog/english/2012/07/03/can-java-be-faster-cpp/"/>
    <updated>2012-07-03T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/07/03/can-java-be-faster-cpp/</id>
    <content type="html"><![CDATA[<p>I have a friend, <a href="http://stas-blogspot.blogspot.com/">Stas</a>. As true programmers we periodically argue on a million dollar question: what is faster, C++ (me) or Java (he), especially along with having various amounts of various drinks. Undoubtedly, not the technology, a social part of such disputes is the main one. But sometimes, sober-headed, when I think about such comparison, I cannot convince even myself that Java can work faster or at least with the same speed as C++.</p>

<p>Let&rsquo;s assume that:</p>

<ul>
<li>We compare C++ 2011 generating native code and vanilla Java 7 generating JVM code. The JVM code will be compiled into machine code by the JIT compiler later on at runtime when the code is executed first time.</li>
<li>Suppose, both C++ and Java compilers generate the most effective code as language semantics in a maximum.</li>
</ul>

<p>Denote <code>A</code> to be the linear machine code execution speed, <code>B</code> &ndash; the speed of compiling bytecode into  machine code. So, the overall execution speed is:</p>

<pre><code>V(C++) = A1 + B1
V(Java) = A2 + B2
</code></pre>

<p>Obviously, <code>B1 = 0</code>, because C++ generates native code and doesn&rsquo;t require extra work at all at runtime. But <code>B2</code> is <em>always</em> greater than zero by definition. Regardless how effective the JIT compiler is, it <em>always</em> requires some time to compile bytecode into native code. Furthermore, it doesn&rsquo;t compile all at once. It compiles &ldquo;just-in-time&rdquo; when the code is actually executed. There is always a non-zero probability that the program execution flow may be paused by the JIT compiler. Even we assume that the JIT compiler uses sophisticated code prediction algorithms to reduce <code>B2</code> as much as possible, it cannot eliminate <code>B2</code> completely.</p>

<p>Now let&rsquo;s have a look at <code>A1</code> and <code>A2</code>. These parameters define how fast the generated code is. In my personal, totally subjective and biased view, C++ (not C) has more chances for better optimization because of the templates (the compiler has full language semantics to inline) and the native machine code generation (the compiler can use the most effective machine instructions in each situation). Unfortunately, I&rsquo;m not an expert in Java generics. I have just heard that they are not &ldquo;native&rdquo; citizens in Java. Also the Java compiler has to generate portable bytecode and cannot optimize on each particular platform. I hope, the JIT compiler tries to optimize it at runtime but there is no semantics information available anymore. Then the JIT compiler faces the trade-off between the speed and quality of compilation. C++ doesn&rsquo;t have this problem because the compilation phase can be as long as necessary.</p>

<p>Well, I cannot convince even myself that Java can be faster than C++. I&rsquo;d like to, but I have no arguments.</p>

<p>With Stas we did a few straightforward benchmarks based on QuickSort. Java worked ~10% slower on average.</p>

<p>Prior to C++ 2011 we could say that C++ had no a well-defined memory model and a standard library for concurrency. It might allow Java to beat C++ using multi-threading and concurrency. But now C++ has these features. In general either C++ or Java provide pretty low-level API for concurrency comparing, for instance, to goroutines in Go or actors in Scala (though <code>std::async()</code> is quite powerful feature now in C++).</p>

<p>Agreed, 10% don&rsquo;t always play the key role. Sometimes, advanced mechanisms of introspection, IDEs, managed execution, code hot swapping, etc. &ndash; in fact, everything what the Java <em>platform</em> provides, are more important than just byte threshing. But there is nothing about speed, right?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Mini computers: MK802, CuBox, Raspberry PI]]></title>
    <link href="http://demin.ws/blog/english/2012/06/20/mk802-cubox-raspberry-pi/"/>
    <updated>2012-06-20T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/06/20/mk802-cubox-raspberry-pi/</id>
    <content type="html"><![CDATA[<p>Seems that homemade microcomputers are coming back. I already wrote about <a href="http://demin.ws/blog/english/2012/01/19/maximite-kit/">Maximite</a>.</p>

<p>Lately I had an opportunity to play with a few devices of such sort, but slightly upper class based on ARM, not PIC32.</p>

<p>I apologize at once for quality of pictures, but I didn&rsquo;t manage properly taking pictures of the bright computer screen neither on iPhone nor on a camera.</p>

<h1>MK802 (aka Mini Android 4.0)</h1>

<p>This is a device I have bought. It costs 70$ + delivery. There is another, more modern 1GB model already available on the <a href="https://www.miniand.com">official website</a>. Mine has 512MB only.</p>

<p>My photos:</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0362.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0363.JPG" alt="" />
</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0364.JPG" alt="" />
</p>

<p>The USB #1. The device can be powered via this socket but they say it needs at least two amps, so powering from a regular computer may not work. I connected a keyboard here.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0366.JPG" alt="" />
</p>

<p>Mini HDMI. I also managed to connect to a DVI monitor via an adapter.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0368.JPG" alt="" />
</p>

<p>At the end face there is another USB port and an external power connector.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0369.JPG" alt="" />
</p>

<p>Micro-SD. The case of the device as a whole is a just bit bigger than a regular USB stick.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0371.JPG" alt="" />
</p>

<p>Connected to TV. Android is built-in. Booting time to this splash-screen is ~5s.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0372.JPG" alt="" />
</p>

<p>Time of the full boot is ~25s.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0374.JPG" alt="" />
</p>

<p>Connected a mouse, somehow entered a WiFi password in the virtual keyboard and checked out the proper website.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0379.JPG" alt="" />
</p>

<p>The desktop is optimized as a media center, that&rsquo;s why everything is so big on the screen. After some fiddling with fonts, I had got this:</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0386.JPG" alt="" />
</p>

<p>Now another proper website.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0380.JPG" alt="" />
</p>

<p>Internal storage characteristics.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0383.JPG" alt="" />
</p>

<p>The version of Android.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0384.JPG" alt="" />
</p>

<p>Pre-installed applications.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0385.JPG" alt="" />
</p>

<p>Finally, yet another proper website. Unfortunately, JSLinux wasn&rsquo;t able to boot up fully. Maybe because of the web browser.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/mk802/IMG_0387.JPG" alt="" />
</p>

<p>Built-in Android doesn&rsquo;t require a flash card. If to prepare a card with another Linux, MK802 will boot from it. I have tried images of Ubuntu 12.04 and Lubuntu from the official website. Alas, it worked very slow and unresponsive. MK802 does require a proper distro optimized specifically for this platform.</p>

<p>On the <a href="https://www.miniand.com/forums/forums/2/topics/1">official forum</a> there are more photos of MK802. Also there are <a href="https://www.miniand.com/forums/forums/2/topics/19">disassembly slides</a> of a slightly different model.</p>

<p>Conclusion: It is not quite clear who is the audience of this device. Even Maximite allows to play with hardware, but here&hellip; Maybe running <a href="http://xbmc.org/">XBMC</a> as a media center might have at least little sense.</p>

<h1>CuBox</h1>

<p>Produced <a href="http://solid-run.com/">SolidRun</a>. The device was purchased by one of my colleagues, annoyed waiting his Raspberry PI (I&rsquo;m also still waiting mine), and I was able to play with it.</p>

<p>CPU is slower, but the <a href="http://solid-run.com/products/cubox">peripherals</a> are much more advanced (no WiFi, though), and they also promise 1080p video. So CuBox is more likely to be a media center.</p>

<p>It&rsquo;s a proper cube, which side is roughly as a match box.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/cubox/image_0.jpeg" alt="" />
</p>

<p>Power, Ethernet, HDMI, Micro-SD, USBx2, eSATA.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/cubox/image_1.jpeg" alt="" />
</p>

<p>SPDIF, micro-USB (console).</p>

<p><img src="http://demin.ws/images/blog/mini-computers/cubox/image_2.jpeg" alt="" />
</p>

<p>Frankly, the device looks being made in someone&rsquo;s kitchen. On the second picture it&rsquo;s clearly visible that the connectors are not quite aligned with the case. But the device in general works fine. It has Ubuntu 10.04 pre-installed.</p>

<h1>Raspberry PI</h1>

<p>This board was given to me by another colleague of mine who had eventually got it. It came as is, without a power supply and a flash card to boot from. You have to prepare everything by yourself. Fortunately, plenty of stuff is available online.</p>

<p><img src="http://demin.ws/images/blog/mini-computers/raspberry-pi/raspberry-pi.jpg" alt="" />
</p>

<p>What does make PI different from MK802 and CuBox is general purpose ports (GPIO) (in the top left corner). Theoretically you can plug in your own homemade devices into Raspberry PI. PI was developed as an educational device, not an end user one.</p>

<h1>Instead of the conclusion</h1>

<p>The market of tiny computers is exploding. They grow as mushrooms after the rain. ARM is great, apart from one little issue &ndash; Chrome isn&rsquo;t yet available on it due to obvious reasons.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What is faster: search in lists or deletion from vector]]></title>
    <link href="http://demin.ws/blog/english/2012/06/14/selecting-container-in-stl-for-intensive-lookup-and-deletion/"/>
    <updated>2012-06-14T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/06/14/selecting-container-in-stl-for-intensive-lookup-and-deletion/</id>
    <content type="html"><![CDATA[<p>Problem: given a container, in which we have to find arbitrary elements and delete them. If to skip initial requirements, its alternative implementations,  or example, using an extra index to avoid linear search time, and to focus on our implementation only, it turns to a question: is it faster to search with O(N) in lists and delete with O(1), or to index an element with O(1) in the vector and delete with O(N). Intuition says that the vector may beat them all (bunk shifts of data in the vector looks more suitable for an optimization rather than a traversal over the list), but I wanted some numbers.</p>

<pre class="hl">
<span class="hl ppc">#include &lt;future&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>
<span class="hl ppc">#include &lt;deque&gt;</span>
<span class="hl ppc">#include &lt;list&gt;</span>
<span class="hl ppc">#include &lt;forward_list&gt;</span>
<span class="hl ppc">#include &lt;typeinfo&gt;</span>
<span class="hl ppc">#include &lt;iterator&gt;</span>
<span class="hl ppc">#include &lt;iostream&gt;</span>

<span class="hl kwc">template</span> <span class="hl opt">&lt;</span>typename T<span class="hl opt">&gt;</span>
<span class="hl kwb">void</span> <span class="hl kwd">go</span><span class="hl opt">(</span>T f<span class="hl opt">) {</span>
  <span class="hl kwc">auto</span> start <span class="hl opt">=</span> std<span class="hl opt">::</span>chrono<span class="hl opt">::</span>high_resolution_clock<span class="hl opt">::</span><span class="hl kwd">now</span><span class="hl opt">();</span>
  <span class="hl kwd">f</span><span class="hl opt">();</span>
  <span class="hl kwc">auto</span> stop <span class="hl opt">=</span> std<span class="hl opt">::</span>chrono<span class="hl opt">::</span>high_resolution_clock<span class="hl opt">::</span><span class="hl kwd">now</span><span class="hl opt">();</span>
  <span class="hl kwc">auto</span> duration <span class="hl opt">=</span> std<span class="hl opt">::</span>chrono<span class="hl opt">::</span>duration<span class="hl opt">&lt;</span><span class="hl kwb">double</span><span class="hl opt">&gt;(</span>stop <span class="hl opt">-</span> start<span class="hl opt">).</span><span class="hl kwd">count</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> duration <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">erase</span><span class="hl opt">(</span>std<span class="hl opt">::</span>forward_list<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;&amp;</span> c<span class="hl opt">,</span> std<span class="hl opt">::</span>forward_list<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;::</span>iterator i<span class="hl opt">) {</span>
  c<span class="hl opt">.</span><span class="hl kwd">erase_after</span><span class="hl opt">(</span>i<span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwc">template</span> <span class="hl opt">&lt;</span>typename T<span class="hl opt">&gt;</span> <span class="hl kwb">void</span> <span class="hl kwd">erase</span><span class="hl opt">(</span>T<span class="hl opt">&amp;</span> c<span class="hl opt">,</span> typename T<span class="hl opt">::</span>iterator i<span class="hl opt">) {</span>
  c<span class="hl opt">.</span><span class="hl kwd">erase</span><span class="hl opt">(</span>i<span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwc">template</span> <span class="hl opt">&lt;</span>typename T<span class="hl opt">&gt;</span> <span class="hl kwb">void</span> <span class="hl kwd">test</span><span class="hl opt">() {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl kwc">typeid</span><span class="hl opt">(</span>T<span class="hl opt">).</span><span class="hl kwd">name</span><span class="hl opt">() &lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
  <span class="hl kwb">size_t const</span> N <span class="hl opt">=</span> <span class="hl num">100000</span><span class="hl opt">;</span>
  T <span class="hl kwd">v</span><span class="hl opt">(</span>N<span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">);</span>
  std<span class="hl opt">::</span><span class="hl kwd">srand</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">);</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwc">auto</span> t <span class="hl opt">=</span> N<span class="hl opt">;</span> t <span class="hl opt">&gt;</span> <span class="hl num">0</span><span class="hl opt">; --</span>t<span class="hl opt">) {</span>
    <span class="hl kwc">auto</span> i <span class="hl opt">=</span> v<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">();</span>
    std<span class="hl opt">::</span><span class="hl kwd">advance</span><span class="hl opt">(</span>i<span class="hl opt">,</span> std<span class="hl opt">::</span><span class="hl kwd">rand</span><span class="hl opt">() %</span> t<span class="hl opt">);</span>
    <span class="hl kwd">erase</span><span class="hl opt">(</span>v<span class="hl opt">,</span> i<span class="hl opt">);</span>
  <span class="hl opt">}</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwd">go</span> <span class="hl opt">(</span>test<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;&gt;);</span>
  <span class="hl kwd">go</span> <span class="hl opt">(</span>test<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>list<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;&gt;);</span>
  <span class="hl kwd">go</span> <span class="hl opt">(</span>test<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>forward_list<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;&gt;);</span>
  <span class="hl kwd">go</span> <span class="hl opt">(</span>test<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>deque<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;&gt;);</span>
<span class="hl opt">}</span>
</pre>

<p>The overloaded <code>erase</code> function is for uniformity of the <code>test</code> funtcion.</p>

<p>Compiling in VS11:</p>

<pre><code>cl /O2 /EHsc test.cpp &amp;&amp; test
</code></pre>

<p>Results:</p>

<pre><code>class std::vector&lt;int,class std::allocator&lt;int&gt; &gt;
1.40678
class std::list&lt;int,class std::allocator&lt;int&gt; &gt;
8.85827
class std::forward_list&lt;int,class std::allocator&lt;int&gt; &gt;
8.70124
class std::deque&lt;int,class std::allocator&lt;int&gt; &gt;
9.19784
</code></pre>

<p>The difference isn&rsquo;t huge but also not negligible at all as for <code>list</code> and <code>forward_list</code>.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[&#34;iWoz: How I Invented the Personal Computer and Had Fun Along the Way&#34;, Gina Smith]]></title>
    <link href="http://demin.ws/blog/english/2012/05/28/iwoz-how-i-invented-the-personal-computer/"/>
    <updated>2012-05-28T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/28/iwoz-how-i-invented-the-personal-computer/</id>
    <content type="html"><![CDATA[<p><a href="http://www.amazon.co.uk/gp/product/140015328X/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=140015328X"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=140015328X&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=140015328X" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>A quote from the book:</p>

<blockquote>
<p>I don&rsquo;t believe anything really revolutionary has ever been invented by committee.</p>
</blockquote>

<p>Huh!? Only for the sake of this quote this book is worth to be read.</p>

<p><a href="http://demin.ws/blog/english/2011/12/27/steve-jobs-the-exclusive-biography/">Steve Jobs biography</a> was interesting reading, even quite long though. Steve Wozniak&rsquo;s book is much shorter, and also closer to people with engineering background.</p>

<p>Steve Wozniak tells a story how it all happened. How he spent nights at school time designing, re-designing, then again and again re-designing non-existent yet computers just on paper. It helped him develop a unique habit to always use a minimum number of chips in his circuit designs. A perfect example is a first floppy disk controller for the Apple 2 computer. Instead of a complicated and costly purely hardware solution he put a few chips and then implemented the rest in 6502 assembly language, having masterly fulfilled requirements for signal timings. Additionally, he designed, again using a few chips, a state machine, which he programmed directly in 4-bit machines codes also designed by himself (a handmade programmable logic matrix approach). Eventually, at some day Steve had invented the Apple 2, a revolutionary personal computer with the color TV-display and the full keyboard. By the way, contrary to the ordinary opinion, Jobs didn&rsquo;t participate in its development. In a few years that computer made both Steves multi millionaires and started the Apple Computers. It is no wonder that the Apple surpassed everybody on the market &ndash; it was simpler, cheaper and have a bunch of unique features.</p>

<p>But that wasn&rsquo;t the end of the story. After Steve got into a plan crash on a small airplane, operating himself, and after that incident he was suffering from partial amnesia for some time. Then he quit Apple, and, again, contrary to the ordinary opinion, he wasn&rsquo;t fired, suspended or something because they all had quarreled. He just wanted to start another project &ndash; a universal remote control for consumer electronics. Formally, till now Steve is still an Apple employee, even with a salary.</p>

<p>But that wasn&rsquo;t also the end of the story. For some reason Steve decided to organize an open air rock gig, a festival, similar to Woodstock. In fact, he did a few of them. Of course, the technology was involved. These festivals had a live satellite connection to USSR (they used equipment installed for the Olympic games in Moscow in the eightieth), right through the &ldquo;iron curtain&rdquo;.</p>

<p>After that Steve taught bases of computers at school for more than ten years and was engaged in philanthropy.</p>

<p>The whole slice of the book is also devoted to pranks Steve have been constantly doing through his life. For example, a Dial-A-Joke service he ran in his own apartment, or a portable TV jammer, and that big one, &ldquo;The Zaltair Prank&rdquo;, when Steve spread a rumor about a competing computer company, called Zaltair (remember The Altair which launched Bill Gates to the orbit?). Even Jobs believed it and only after years realised that it was a setup.</p>

<p>So, if you have at least a little interest in biographies, it is worth to read this engaging story about the good fellow, genius engineer, who transformed the industry of personal computers once and for all.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[&#34;The biased attitude to your own product&#34; pattern]]></title>
    <link href="http://demin.ws/blog/english/2012/05/23/biased-attitude-to-your-own-product/"/>
    <updated>2012-05-23T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/23/biased-attitude-to-your-own-product/</id>
    <content type="html"><![CDATA[<p>Everybody loves inventing patterns. Noticed a situation? Realised that it happens not only for you? This is a pattern!</p>

<p>Seems I also have invented a pattern called &ldquo;The biased attitude to your own product&rdquo;. Here is a typical stream of thoughts when preparing a product release: &ldquo;Oh, a little glitch here, a tiny typo there, this could be done better, that should be refactored&rdquo;, etc. But when you open up a nicely packaged someone else&rsquo;s product you think &ldquo;Oh, man, how great and nicely polished it looks!&rdquo;. But, of course, that &ldquo;someone else&rdquo; went through exactly the same thoughts &ldquo;polishing&rdquo; that product.</p>

<p>I&rsquo;m regularly involved in producing releases, sorting bug reports, postmortem analysis, etc. I usually follow this kind of strategy: The sales grow? Yes. A number of customer issues decreases? Yes. A number of internal defects decreases? Yes. The conclusion: everything is fine, and we&rsquo;re doing great. The rest is just a normal development process.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Partner links in this blog]]></title>
    <link href="http://demin.ws/blog/english/2012/05/23/partner-links-in-this-blog/"/>
    <updated>2012-05-23T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/23/partner-links-in-this-blog/</id>
    <content type="html"><![CDATA[<p>Yesterday I have added my personal partner identifier to the Amazon links. I have no idea how it goes along, but I&rsquo;ll definitely keep you updated if something interesting comes out.</p>

<p>There is a &ldquo;Disclaimer&rdquo; link at the bottom of each post to avoid misunderstanding. I only refer to books which I read and reviewed by myself. It is not related in any way to publishers or authors.</p>

<p>Any information published commercially will be explicitly marked as advertising in the blog post content.</p>

<p>Any questions? Welcome to comments.</p>

<h3>Related links</h3>

<ul>
<li><a href="https://affiliate-program.amazon.co.uk/">Amazon affiliate program</a></li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[An interview with Peter Sommerlad]]></title>
    <link href="http://demin.ws/blog/english/2012/05/19/peter-sommerlad-interview/"/>
    <updated>2012-05-19T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/19/peter-sommerlad-interview/</id>
    <content type="html"><![CDATA[<p><img src="http://demin.ws/images/blog/peter-sommerlad.jpg" alt="" />
</p>

<blockquote>
<p>When you have a class where you believe you need to write a copy constructor and copy-assignment operator you are doing something wrong. // <strong>Peter Sommerlad</strong></p>
</blockquote>

<hr />

<p>Today my guest is <a href="http://wiki.hsr.ch/PeterSommerlad">Peter Sommerlad</a>. I was lucky to attend his sessions at the ACCU 2012 conference recently. Peter is a C++ veteran and a contributor to the C++ standard. He is a professor at HSR Rapperswil, Switzerland, and director of IFS Institute for Software (http://ifs.hsr.ch). With a team of assistants and students he develops various tools and frameworks for C++ and other languages based on Eclipse.</p>

<p>Now we&rsquo;ll have a chance to ask Peter a few questions, which could hide behind his talks and presentations but still be very interesting for the readers.</p>

<h3>Hi Peter, thanks for the interview. I won&rsquo;t be original here, but I cannot skip this question. What happened in the past that you turned to computers and become a programmer? Please, tell us your story.</h3>

<p>I was very good at maths in school and in the last year I could take an additional course that included programming a programmable calculator, a HP 33 which had a stack for operands. In contrast to some of my friends who had a Casio, a TI-59 or even a Commodore V(I)C 20 home computer, I had not yet any idea of programming. However, with some explanations by our teacher I was able to &ldquo;port&rdquo; a TI-59 register-based lunar lander I found in a magazine to the HP 33 provided by the school. Once I got the hang of it, I &ldquo;invented&rdquo; a simple game: a ballistic shooting game. Goal was to hit a target at a random distance that was obstructed by a random generated wall in between. Something like Angry Birds but in in 1982 on a pocket calculator with a 10 digit seven segment LED display. You needed a lot of imagination to understand the game. You input 2 numbers: angle and velocity and the program would tell you if you hit the wall or by what distance you missed the goal. That was the first program I remember to have written myself.</p>

<p>That course on programming the HP 33, and the suggestion by my older sister who knew someone studying &ldquo;Informatik&rdquo; who earned good money while still a student made me drop my plans to sign up for a maths major and start out to study computer science (named Informatik in German) in Frankfurt/Main. Before I started university I got my first &ldquo;real but home-&rdquo; computer, a Sinclair ZX Spectrum, with enormous 48kBytes and cassette tape mass storage. That meant programming in BASIC where according to our maths teacher the &ldquo;computer will assign the memory automatically to the named variables and you no longer needed to remember what you placed into register R1 and R2&rdquo;. One of the first programs on my ZX Spectrum was drawing a red heart shape on the screen (yes, filling irregular shapes was a big problem then). I showed that my then girlfriend, but I am not sure she really appreciated that, since the computer got sometimes a bit more attention than she. I remember that, because from time to time I get reminded by her of that episode (we are now married for more than 20 years :-).</p>

<p>Then came university time and I had to learn assembly programming in the first semester on a Univac 1100. After the lecture on indirect addressing, one of my mates and me wrote a 2 statement program that created an endless indirect load to itself. Running it caused a &ldquo;watchdog error&rdquo; to occur after 2 seconds of CPU time (which was much on a mainframe then and meant all other programs were suspended for 2 seconds). After starting the program about 3 times, a guy from the operating team bursted into the computer room and shouted who was the one with our account. We slowly raised our hands and he took us to his office. After asking what we were doing and our explanation, he told us that he learned something. We had to promise never to run that program again and also never to tell that to our fellow students and got away with it. In the second semester came Pascal and now &ldquo;real&rdquo; programs. Pointers (in Pascal) were the first hurdle, because they were introduced without any application or motivation, such as a linked list. Only after that I was able to grok them. Some semesters later I started a job as a programmer in a small programming shop run by older fellow students. There I could actually apply my learning and got a lot of practice in solving real problems in a variety of languages, like dBaseII, Dataflex, UCSD Pascal, and Microsoft Pascal. For example, I implemented a B*-index based &ldquo;data base&rdquo; framework in Microsoft Pascal running on DOS.</p>

<p>I guess a very great impact was access to UNIX source code, especially the tools like make, awk, etc, during my diploma thesis project. I wrote a Modula-2 front end in C with lex and yacc. To be able to work at home, I had to port all the tools I needed on my 16 bit DOS computer. That required to understand the code&rsquo;s inner working and structure and thus I learned from Dennis Ritchie and his colleagues a lot. It grew my taste for simple and elegant code.</p>

<h3>Do you remember that &ldquo;First Book&rdquo; you read about computers and programming? And also what is your the most influential book across the entire career?</h3>

<p>One of the first books on programming that I remember was Jensen/Wirth &ldquo;Pascal User Manual and Report&rdquo; and then Wirth&rsquo;s &ldquo;Algorithms and Data Structures = Programs&rdquo;. However, the latter contained many bugs when the code was blindly typed in, for example, in the version I got, merge sort was not stable, so in principle that is a stable sorting algorithm.</p>

<p>However, there are so many books that influenced my thinking about programming it is hard for me to pick just one. But I can pick one that I co-authored: Pattern-oriented Software Architecture: A System of Patterns aka POSA1. First, while writing it I learned so much about software, architecture and teams. As well after publishing and while presenting parts of its material on conferences I met so many influencing people who clearly shaped me heavily. Some of them I call friends today.</p>

<h3>I was excited about your saying at the ACCU, that before using some cool and sexy features of C++, I must be given a C++ driving license by you. I had found this idea to be very useful and practical for teaching C++ and also setting up company coding standards. But how do you split the language to &ldquo;allowed and recommended to everybody&rdquo; features and &ldquo;off-license&rdquo; ones?</h3>

<p>That is a tough question to answer. I was referring to C++11 and many language features that people learned in the past are no longer that relevant for non-library programmers. But I&rsquo;d like to give you an example.</p>

<p>Stroustrup&rsquo;s &ldquo;The C++ Programming Language&rdquo; introduces a class Vector that manages its memory by a pointer as one of the examples for building classes. Writing such a class in a correct, exception safe way is very hard and even C++ experts make mistakes. A reader of that book might be tempted to build his own vector or string class (women are typically not that way) which is first wrong and second completely unnecessary. If put in his first project&rsquo;s code and used throughout it also introduces a maintenance burden in the long run.</p>

<p>It is something like the situation with Wirth&rsquo;s algorithms and data structures. &ldquo;All&rdquo; students who had a hard time learning that will program a linked list as the first thing in their first job, because they will &ldquo;need&rdquo; it anyway. While that might have been true in C, we now have much better data structures in libraries that belong to our languages (not only C++). I could start ranting about the Java library&rsquo;s quality, but I leave that to my colleague who is teaching algorithms and data structures in Java at our university.</p>

<p>Now, after we learned what not to do, I recommend to use C++&rsquo;s standard library, especially the algorithms, because loops is also what you learned and what is encapsulated there. With C++11 we no longer have to do resource management by hand, but we can use std::vector, std::string, std::shared_ptr/std::unique_ptr, etc, which will do all resource management for us and allows the compiler generated default constructors and destructors to be correct automatically. When you have a class where you believe you need to write a copy constructor and copy-assignment operator you are doing something wrong. With boost this is almost also always true in C++03.</p>

<p>To sum up, unless you have acquired a deep understanding on library implementation practices, use libraries instead of inventing your own. Even then, avoid unnecessary DIY resource management. After myself learning more and more about how hard it is to implement the standard library components correctly and portable, I greatly appreciate those who have the experience and patience to do so. That is actually close to rocket science. But typical problems to be solved by C++ do not require that, when you use the standard library and other libraries provided by theses rocket scientists. But remember, we are on the edge of tourist space travel.</p>

<h3>You contributed to the C++ 2011 standard. What were you involved to?</h3>

<p>Not much, because I was late in the game. However, I managed to obtain funding from our school thanks to our headmaster Prof. Hermann Mettler to host the C++ standardization committee meeting in Rapperswil in August 2010. Some sentences in the section about std::async have been (re-)written by me with the support from many others in the committee and some other mostly editorial corrections. However, while writing my book on Simple C++ I often have to refer to the standard document and find minor mistakes regularly that will influence a future version when fixed by the editor.</p>

<h3>Is there something in C++ 2011 which you really hate?</h3>

<p>How do you define hate? I can accept the standard like it is, because I know how it is actually produced. All the deficits that might annoy me are a target for fixing and working on the next version of the standard and I can work on that to do so. Sometimes you also have to accept the compromises the committee has to come up with.</p>

<p>If I would have been involved earlier and one of the features I championed would have been forcefully put down by my fellows I might be upset. May be, after thinking about that, I do not like that const is consistently put to the left, where logic tells me it should be put to the right. Both versions are syntactically allowed. I asked some people, if I should submit a paper to change that for a future version I was more or less forcefully held back by the elders.</p>

<h3>Let&rsquo;s talk about TDD. I know you developed a unit testing framework called CUTE. I believe, you did have some major reasons developing your own library. Why CUTE? Which interesting features does it provide?</h3>

<p>First, it is header only and thus gives no hurdle such as linking to start with, especially for my students. I wrote an article on why I wrote it and it was published in an <a href="http://accu.org/var/uploads/journals/Overload75.pdf">ACCU Overload magazine #75</a> (a slightly update version is available on <a href="http://wiki.hsr.ch/PeterSommerlad/wiki.cgi?CuTe">http://wiki.hsr.ch/PeterSommerlad/wiki.cgi?CuTe</a>). Main reason was that I was disappointed by CppUnit and also by another unit testing framework that I myself wrote for my work in the 1990s. Inspired by Kevlin Henney I tried to utilize the standard library and minimize the use of macros, even though, this meant, tests must be registered &ldquo;manually&rdquo; and aren&rsquo;t &ldquo;automagically&rdquo; registered by static initializers (that GoogleTest will employ in its macros). I wanted to avoid relying on static initializers, because I have been bitten by them in the past with shared libraries and their inter-dependencies. The burden of test registration is mitigated by our CUTE Eclipse CDT plug-in (http://cute-test.com). The plug-in will generate the test registration code for you and even analyses if you forgot to register a test function and provides a quick fix doing so. Also nice is the diff viewer for failed ASSERT_EQUAL() checks, but that requires your values to be streamable on a std::ostream&amp;. That provides a slight hurdle for embedded developers who want to run the testing framework on an embedded target, because of the sometimes prohibitive size of the iostream code. However, I plan to release a version of CUTE later this year that allows to configure if diff output should be provided or not, enabling a run on an embedded target that doesn&rsquo;t allow iostreams.</p>

<p>Two of my students implemented the first TDD support for Eclipse CDT and it was productized by one of my assistants as part of our CUTE plug-in (http://cute-test.com). The TDD support will automatically generate variable definitions from using an unknown variable in code. It will furthermore generate class or enum types from using an unknown type in a declaration and it will also create (member-) function definition frames from calling an unknown function. This is very handy when either writing code in a test-driven or top-down design style. Soon the CUTE plug-in will integrate another student&rsquo;s work: Mockator. Mockator generates code and build-system settings within Eclipse CDT to enable dependency injection in existing C and C++ code by so-called seams. Seams were introduced by Michael Feathers in his great book &ldquo;Working Effectively with Legacy Code&rdquo;. Based on these seams, Mockator can also generate test stubs and mocks for functions and types. You can read more about Mockator and its features in <a href="http://accu.org/var/uploads/journals/overload108.pdf">ACCU&rsquo;s Overload magazine 108</a>.</p>

<h3>&ldquo;IDE vs Vi&rdquo; holy war. I know you actively use and enhance Eclipse CDT for easier unit testing and refactoring. Do you think that IDEs are the only future because of massively growing complexity of software over the years? or it is still possible just using Vi and &ldquo;make&rdquo; efficiently and quickly develop sophisticated software?</h3>

<p>I know vi since about 1985. I still use it regularly to create simple files, like one-off shell scripts. I love it for being available everywhere.</p>

<p>However, for serious programming a good IDE is today the tool of the trade. It is like using a powerful car compared to a children tricycle to travel hundreds of miles. Yes, there are people who are fast on a tricycle, however, a car is much more comfortable. May be a car is a bad metaphor and an agile helicopter would be better, since a good IDE such as Eclipse CDT allows to quickly navigate code that it is very easy to understand an existing code base even if it is huge. Definitions and declarations are a mouse hover or a click away and the IDE usually keeps track where you come from, so you can easily get back. Any Java programmer who has used an IDE like Eclipse intensively will only consider programming in another language if similar IDE features are available. We are working hard to make Eclipse CDT at least as good for C++ than it is for Java. That is hard work and any financial sponsorship to our institute is welcome.</p>

<h3>Do you believe that sport programming and programming contests should be a mandatory discipline for any student reading computer science?</h3>

<p>In our university&rsquo;s program we ask our students to perform a lot of lab exercises in programming. Also at least 3-4 major one term development projects are part of the bachelor degree. Doing lab exercises in a fun way can help students learn. For example, I often give exercises in C++ to solve a problem without explicit loops or recursion, only STL algorithms are allowed. A loop solution might be obvious, but figuring out a more elegant algorithm call helps a lot.</p>

<p>However, some contests are set up in a way that only speed is important and not the long term effects of clean code. That is one of the reasons I either provide or ask for unit tests in my lab exercises. I even provide unit tests in exams for code to be written by the students.</p>

<h3>We usually learn by examples. Can you recommend where a beginner can look at the examples of very good modern code?</h3>

<p>Such examples for C++11 are hard to find, since compilers aren&rsquo;t around so long. In addition, many current C++11 example code is used to demonstrate the new features such as move semantics without really having a use case that is benefiting from that. I&rsquo;ll try in my upcoming book to give good examples. Be aware, many C++ standard library implementations are much more complex than code you want to look at, because they have to cope with strange environments (macros), provide backward compatibility and need to compensate for compiler (version) deficiencies. Solving these problems are not typical for a beginner and give a wrong impression on how to write your own code. I&rsquo;ll try to lead by example, but even CUTE has some warts, because I wanted to support C++03 with boost, std::tr1 and C++11.</p>

<h3>What is the software development for you: craft or art? Do you think that good software must have beauty sources? Or if the requirements are satisfied, the tests passed, the coding standard is complied &ndash; the job is done, no art or beauty &ndash; just the result.</h3>

<p>Software creation is art but also a craft. It requires thorough learning and practice to master. Most of art always requires also craft. They can not be separated.</p>

<p>I believe in code beauty. But that is relative, what is often good for beginners often suffers from the expert&rsquo;s elegance. Knowing the tools available to you is essential to master them. Only knowing std::vector, for example, but not the STL&rsquo;s algorithms will provide you working code, but not elegance, even if that is only counted by a function&rsquo;s McCabe complexity (by the way another C++ CDT plug-in currently developed by students).</p>

<p>We were the first ones after Bill Opdyke to try to implement C++ refactoring. We co-created large parts of CDT&rsquo;s internals to support refactoring and code generation based on ASTs (abstract syntax tree). So running the tests is not enough, code must be cleanly refactored. I do a lot of code reviews, and I often see chances to simplify it. But I doubt that talent can be automated, it is a mixture of taste and experience. It requires not only seeing the smells but also their removal. On the other hand, if you look at Martin Fowler&rsquo;s smells and refactorings they often come in contrasting pairs.</p>

<p>Some coding standards even promote what I consider bad practice and introduce unnecessary complexity. For example, Google suggests that &ldquo;out&rdquo;-parameters for functions should be implemented as pointers, even in C++. The motivation behind that is, that at the call site one would need to write foo(&amp;var) to pass the address of the variable deliberately. This is thought to improve code readability. However, while necessary in C due to the lack of references, this guideline just imposes C problems solved by C++ references onto C++ code. Within such a function, one must check that the passed in pointer is not nullptr (to use a C++11 term) and one never can be sure it is actually valid if the caller made a mistake, or one could ignore the problem at all and crash when a user passes nullptr. A C++ solution should declare the function to take a reference instead, like void foo(type &amp; var); and an IDE will show that when you hover on the call site, without the additional need of marking it in the code by an ampersand. Using the language features effectively to write less and simpler code should be the guideline and not the protection of programmers sticking with legacy editors and not knowing their tool.</p>

<p>A coding standard or any rule is only good if it can actually be enforced. Tools like (PC-)lint help to do that. Often such classic tools are command-line and build-process based. More modern versions are integrated in an IDE and provide not only analysis but also quick-fixes for the found problems, for example, FindBugs for Java or FXCop for C#. Configuring them to avoid false positives without missing real problems is always an effort. To ease the application and use of lint, we created Linticator an Eclipse CDT plug-in that will automatically configure lint and run it and visualize its results within the IDE (http://linticator.com).</p>

<h3>Can you name three the biggest &ldquo;no-no&rdquo; for programmers in any area?</h3>

<p>Being too self confident, instead do write (Unit) Tests and run them regularly. Any current software without automated tests is unprofessional in my view.</p>

<p>Lack of architecture or architectural knowledge is one of the big problems I often encounter when doing code reviews. This is often fostered by lack of understanding of good design.</p>

<p>A simple last thing: global variables also in the disguise as singletons. Pass in all dependencies from the outside as arguments. This will also show you, where you have too much coupling. Know the patterns to deal with that and writing unit tests helps you to avoid that early.</p>

<h3>Which programming language would you recommend as a very first one for beginners?</h3>

<p>There are so many to choose from. I do not want to recommend one, because each will have its deficits. It is more important to learn more than one and those with different paradigms such as functional, object oriented, dynamically typed, statically typed, compiled, interpreted, virtual machine-based or machine language translated. An old saying is &ldquo;you can write FORTRAN code in any language&rdquo;. This should not be done with multiple languages, but you need to learn and apply the language&rsquo;s idioms consciously.</p>

<h3>Today there are plenty of educational resources available online. You can even be officially graded online. Do you believe that on-site education is still important?</h3>

<p>Yes. Interaction with students is so important. It is not only them getting feedback, but it also allows me to learn from them and improve my teaching. Both kinds of feedback are important and are more efficient when immediately. A remote learning environment can not provide that bi-directional feedback, but it can be a great help for those who can not be there for some reasons. But I believe it is very expensive to provide a good remote learning environment.</p>

<h3>In the martial arts they have the concept of schools, or styles, and they compete trying to prove the excellence. Is there something similar to the software development?</h3>

<p>I know of people to use martial arts metaphors, such as coding dojos. I have no idea about martial arts, the only sport I like, except regular cardio-vascular exercise, is skiing. This is not a team sport but allows me to get into flow and forget everything. Intensive work can be like that. But software is a team sport and regular exercises of standard moves, aka, code katas can help to shape your subconsciousness in taste for good code and style, but only if you either have that already or get the feedback to develop that. A problem I see is, that many teachers of programming novices lack the (current) practical experience of programming (including myself, but at least I try to be exposed to code regularly).</p>

<h3>Hiring. If you need to hire a good C++ developer, how would you do that? The language is very complicated, so how would you asses a good developer?</h3>

<p>I always have asked for code examples written by the person. Once I declined a very good PhD for exactly the reason that his code was badly written and &ldquo;smelly&rdquo;.</p>

<p>Today, also the willingness to adapt to change and architectural taste is important. A candidate must understand Patterns and must know there are more than 23 GOF patterns. And better even understand that some of them like Singleton are better not employed in a software&rsquo;s design.</p>

<h3>Well, wrapping up. The final question: do you think in software development that we choose our profession, or the profession chooses us?</h3>

<p>I started out by choosing my university subject. However, the great thing about software is that we are able to invent and create our own tools. It is like if a baker would be able to create a new oven or dough mixer by baking it. So after learning a bit of it, I actually got chosen by my profession. I am doing it for about 30 years now, teaching it for about 25 years (I started teaching programming while still university student), writing articles and books about it since about 18 years and still love doing all that. I have as my goal to make this world a better world for programmers and thus hope to rid our world from bad software. I understand that I will not achieve that, but it gives me a lot of direction.</p>

<p>&#9632;</p>

<p><strong>Thanks Peter for you time. Looking forward for your new software and talks.</strong></p>

<p><em>// May 16, 2012</em></p>

<p><em>// Peter Sommerlad, Alexander Demin</em></p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Printing std::string via printf() in Visual Studio]]></title>
    <link href="http://demin.ws/blog/english/2012/05/18/printing-std-string-via-printf-in-visual-studio/"/>
    <updated>2012-05-18T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/18/printing-std-string-via-printf-in-visual-studio/</id>
    <content type="html"><![CDATA[<p>So often in code reviews I see something like this:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;string&gt;</span>
<span class="hl ppc">#include &lt;cstdio&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  std<span class="hl opt">::</span>string s <span class="hl opt">=</span> <span class="hl str">&quot;12345678&quot;</span><span class="hl opt">;</span>
  std<span class="hl opt">::</span><span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;[%s]</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> s<span class="hl opt">);</span>
<span class="hl opt">}</span>
</pre>

<p>This is an obvious typo of missing <code>s.c_str()</code> instead of just <code>s</code>. Weirdly, Visual Studio doesn&rsquo;t warn you even with <code>/Wall</code>. More over, the code works!. But <code>gcc</code> warns though:</p>

<pre><code>warning: cannot pass objects of non-POD type 'struct std::string' through '...'; call will abort at runtime
</code></pre>

<p>and the program dies with <code>Illegal instruction</code>.</p>

<p>Did they really implement a trick in STL to make programs having such  typo working just because this typo is very common?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Veracity - an alternative to git, Mercurial, Bazaar and fossil]]></title>
    <link href="http://demin.ws/blog/english/2012/05/17/veracity/"/>
    <updated>2012-05-17T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/17/veracity/</id>
    <content type="html"><![CDATA[<p>I read about &ldquo;yet another&rdquo; distributed version control system some time ago, called <a href="http://veracity-scm.com">Veracity</a>. They said that this is a decent candidate able to compete with all flagship DVCS.</p>

<p>So, let&rsquo;s go right to the comparison table from the official web site.</p>

<p><img src="http://demin.ws/images/blog/veracity-comparison.png" alt="" />
</p>

<p>I wanted to figure out unique features for the sake of what they had started this project. I checked out a presentation from OSCON 2011.</p>

<p>#1</p>

<iframe width="560" height="420" src="http://www.youtube.com/embed/1qCIff0N3Yw?color=white&theme=light"></iframe>

<p>#2</p>

<iframe width="560" height="420" src="http://www.youtube.com/embed/iqDu7s7hSsg?color=white&theme=light"></iframe>

<p>#3</p>

<iframe width="560" height="420" src="http://www.youtube.com/embed/HH8nFadt9SA?color=white&theme=light"></iframe>

<p>Here is my subjective fifty cents:</p>

<ul>
<li>Clear &ldquo;no&rdquo; to GPL (a stone into git, hg, bzr). They say that &ldquo;Not-GPL&rdquo; is more attractive for enterprise use.</li>
<li>Ability to use external data storage for the repository (for example, MSSQL or Oracle). Again, large companies may like it.</li>
<li>File locks (a controversial feature, in my view)</li>
<li>Bug tracking (fossil also can do this).</li>
<li>Build tracking (seems to be a really unique feature).</li>
<li>Written in pure C, and it natively supports Windows, Linux and Mac from the day one.</li>
</ul>

<p>There are a few principle decisions:</p>

<ul>
<li>No &lsquo;index&rsquo; (as in git) and it will never be there.</li>
<li>There is no way to change the history, at all (for example, even a typo in a last commit cannot be fixed).</li>
</ul>

<p>Personally for me, these two &ldquo;features&rdquo; definitely don&rsquo;t fit into my way of using DVCS. For this reason I have stopped using fossil on my personal projects, though I loved the ability to have Wiki and a bug tracker built into the repository.</p>

<p>As a result it turns out that the key features of Veracity are &ldquo;Not-GPL&rdquo; and the external storages. It is obviously an attack on the corporate market. By the way, the company founder, Eric Sink, already had a DVCS product and company now acquired by Microsoft.</p>

<p>So, my subjective conclusion is that this is an attempt to bring DVCS into corporations.</p>

<h3>Extra fifty cents</h3>

<p>Eric Sink wrote a book, &ldquo;<a href="http://www.ericsink.com/vcbe/">Version Control by Example</a>&rdquo;, in which he gives more or less fair comparison of Veracity against a few flagship DCVS. I flipped through it in half an hour, and I found a super quote, which I furiously share and actively promote (the selection in bold is mine).</p>

<blockquote>
<p>11. Don&rsquo;t comment out code</p>

<p>When using a VCS, you shouldn&rsquo;t comment out a big section of code simply because you think you might need it someday. <strong>Just delete it</strong>. The previous version of the file is still in your version control history, so you can always get it back if and when you need it. This practice is particularly important for web developers, where the commented-out stuff may adversely affect your page load times.</p>
</blockquote>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why a getter doesn&#39;t need a &#34;get&#34; prefix]]></title>
    <link href="http://demin.ws/blog/english/2012/05/17/why-getter-does-not-need-get-prefix/"/>
    <updated>2012-05-17T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/17/why-getter-does-not-need-get-prefix/</id>
    <content type="html"><![CDATA[<h3>Idea</h3>

<p>Never use a <code>get</code> prefix for getters.</p>

<h3>Why?</h3>

<p>Usually we consider member functions to be getters if they simply return a reference or pointer to a private member, just for the sake of data incapsulation. Such functions don&rsquo;t do anything really, they have no payload.</p>

<p>So, there is nothing requiring a &ldquo;get&rdquo; verb to describe its meaning. The getter is just an alias of a member. The &ldquo;get&rdquo; prefix is only required when a function does a <strong>real</strong> data transformation or computation, for instance, <code>getLastTick()</code> or <code>getFullUserName()</code>. But it is even better here to replace &ldquo;get&rdquo; by something more meaningful, <code>extractLastTick()</code> and <code>buildFullUserName()</code>.</p>

<p>&#9632;</p>

<p>Related posts:</p>

<ul>
<li><a href="http://demin.ws/blog/english/2010/11/09/naming-convension-for-getters-and-setters-in-cpp/">Naming convension for getters and setters in C++</a></li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Standing office desk]]></title>
    <link href="http://demin.ws/blog/english/2012/05/13/standing-office-desk/"/>
    <updated>2012-05-13T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/13/standing-office-desk/</id>
    <content type="html"><![CDATA[<p>What&rsquo;s normally happening at office work? Yes, we make dents in seats. Why? We&rsquo;re lazy to get up and have a walk. In rare cases we go to a loo or for a cuppa. But there is a solution to move and stand on feet more at the office. Just use standing desks.</p>

<p>You can find plenty of options online to organize your standing desk. Here is my solution. It appeared by accident. When we rented an apartment, there was no room for a proper computer place in the kitchen (yes, we do need a computer place there, for sure), and my wife discovered this nice cheap table and a bar stool at IKEA.</p>

<p><a href="http://www.ikea.com/gb/en/catalog/products/90087541/">BJÖRKUDDEN</a></p>

<p><img src="http://demin.ws/images/blog/bjorkudden-bar-table.jpg" alt="" />
</p>

<p><a href="http://www.ikea.com/gb/en/catalog/products/S79873080/">HENRIKSDAL</a></p>

<p><img src="http://demin.ws/images/blog/henriksdal-bar-stool-with-backrest.jpg" alt="" />
</p>

<p>We used it for a while as a hotspot for quick googling or ordering food online. After some time at found myself spending more and more time at this place. It was very convenient for some reason. Normally you stand of feet, and sometimes, for example, during a long &ldquo;wave period&rdquo;, you can place your bottom at the high chair. After we moved, I used a regular computer workplace for a while at my office at home, but then switched to the standing desk. This is how it looks:</p>

<p><img src="http://demin.ws/images/blog/standing-desk-at-home.jpg" alt="" />
</p>

<p>By the way, its legs are perfect for fitting socket extensions and other stuff.</p>

<p>And the previous, classical workplace on the right:</p>

<p><img src="http://demin.ws/images/blog/standing-desk-at-home-regular.jpg" alt="" />
</p>

<p>P.S. By the way, I believe that people who invented a pull-out keyboard shelf for computer tables never worked at the computer. It&rsquo;s hard to imagine more inconvenient way of using the keyboard. Also I personally never use any office chair if I cannot sit, resting a foot under myself.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Fuss about REST, or Richardson L., Ruby S., &#34;RESTful Web Services&#34;]]></title>
    <link href="http://demin.ws/blog/english/2012/05/12/restful-web-services/"/>
    <updated>2012-05-12T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/12/restful-web-services/</id>
    <content type="html"><![CDATA[<p>Kill me, but I don&rsquo;t understand why people write books about REST. Why you torture yourself, the keyboard, and finally your readers with a topic which can be explained in a few sentences?</p>

<p><a href="http://shop.oreilly.com/product/9780596529260.do">Leonard Richardson, Sam Ruby, &ldquo;RESTful Web Services&rdquo;</a></p>

<p><img src="http://demin.ws/images/covers/english/restful-web-services-cover.gif" /></p>

<p>So, skipping a tedious chapter of HTTL libraries in Ruby, Python, Java and curl, more tedious chapter on HTML4, XHTML, HTML5, Atom, XML, a little less tedious chapter about a couple of Ajax libraries, extremely tedious chapter with standard HTTP response codes, unrealistically tedious chapter about standard HTTP headers, the essence of the book can be expressed very briefly. This is my summary of the entire book.</p>

<p>Developing a web-service you should follow some recommendations:</p>

<ol>
<li>(Main one) Designing a URL structure you put as much meaning into there as possible. You should treat URLs as a query language for your data, which is readable and writable by <strong>human</strong>. For example, instead of <code>http://domain/engine.php?func=123&amp;id=test</code> for get user details it should be something like <code>http://domain/users/test</code>.</li>
<li>Use all standard HTTP commands and response codes: not only GET and POST, but also PUT, DELETE, OPTION, HEAD, and not only 200 and 500, but the range of the standard <a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes">HTTP response codes</a>.</li>
<li>HTTP response should contain links to other resources reachable from the current one.</li>
</ol>

<p>That&rsquo;s it! Now you know the whole book.</p>

<p>This is a rare situation when I&rsquo;m seriously considering money back. Unfortunately I cannot re-sell because it&rsquo;s a bloody e-book.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[RetroBSD on Maximite]]></title>
    <link href="http://demin.ws/blog/english/2012/05/11/retrobsd-on-maximite/"/>
    <updated>2012-05-11T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/11/retrobsd-on-maximite/</id>
    <content type="html"><![CDATA[<p>I <a href="http://demin.ws/blog/english/2012/01/19/maximite-kit/">wrote</a> how I built Maximite.</p>

<p>Yesterday I was in mood and decided to install <a href="http://retrobsd.org/">RetroBSD</a> there.</p>

<p>RetroBSD is a real UNIX, derived from 2.11BSD and intended for embedded systems with fixed memory mapping. Its target platform is Microchip PIC32 microcontroller with 128KB RAM and 512KB of Flash, which can provide flexible RAM partitioning between user and kernel modes.</p>

<p>RetroBSD implements real preemptive multitasking and memory protection using hardware capabilities. It provides standard POSIX API (fork, exec, wait4, etc.), plus it may have a C compiler in the system allowing on-board development. The kernel is burned into the chip and the filesystem is loaded from an SD-card.</p>

<p>RetroBSD works not only on Maximite, but also on a few alternative boards based on PIC32 (chipKIT Max32, Sparkfun UBW32, Microchip Explorer 16, Microchip PIC32 USB/Ethernet Starter Kit, Olimex Duinomite, Duinomite-Mini and Duinomite-Mega, eflightworks).</p>

<p>After a little fiddling around with the <a href="http://code.google.com/p/mphidflash/">bootloader</a> and <a href="http://retrobsd.org/wiki/installation-2/">library dependencies</a> I managed to build the binaries and upload them onto the device.</p>

<p>A solemn moment of powering on&hellip;</p>

<p><img src="http://demin.ws/images/blog/retrobsd-on-maximite-login.png" alt="" />
</p>

<p>This is UNIX!</p>

<p>Of course, games first. The Worm.</p>

<p><img src="http://demin.ws/images/blog/retrobsd-on-maximite-worm.png" alt="" />
</p>

<p>Canfield</p>

<p><img src="http://demin.ws/images/blog/retrobsd-on-maximite-canfield.png" alt="" />
</p>

<p>Now a bit of programming &ndash; Forth.</p>

<p><img src="http://demin.ws/images/blog/retrobsd-on-maximite-forth.png" alt="" />
</p>

<p>At the moment RetroBSD only communicates via the serial port and doesn&rsquo;t support VGA and PS/2 interfaces provided by Maximite, but Serge Vakulenko, the author, has their support in the roadmap.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Comparing the performance of atomic, spinlock and mutex]]></title>
    <link href="http://demin.ws/blog/english/2012/05/05/atomic-spinlock-mutex/"/>
    <updated>2012-05-05T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/05/atomic-spinlock-mutex/</id>
    <content type="html"><![CDATA[<p>I was curious in benchmark of different synchronization mechanisms: atomic, spinlock, mutex.</p>

<h2>Without synchronization</h2>

<pre class="hl">
<span class="hl ppc">#include &lt;future&gt;</span>
<span class="hl ppc">#include &lt;iostream&gt;</span>

<span class="hl kwc">volatile</span> <span class="hl kwb">int</span> value <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>

<span class="hl kwb">int</span> <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwb">bool</span> inc<span class="hl opt">,</span> <span class="hl kwb">int</span> limit<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Started &quot;</span> <span class="hl opt">&lt;&lt;</span> inc <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot; &quot;</span> <span class="hl opt">&lt;&lt;</span> limit <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> limit<span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>inc<span class="hl opt">) {</span> 
      <span class="hl opt">++</span>value<span class="hl opt">;</span>
    <span class="hl opt">}</span> <span class="hl kwa">else</span> <span class="hl opt">{</span>
      <span class="hl opt">--</span>value<span class="hl opt">;</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwc">auto</span> f <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">async</span><span class="hl opt">(</span>std<span class="hl opt">::</span>launch<span class="hl opt">::</span>async<span class="hl opt">,</span> std<span class="hl opt">::</span><span class="hl kwd">bind</span><span class="hl opt">(</span>loop<span class="hl opt">,</span> <span class="hl kwa">true</span><span class="hl opt">,</span> <span class="hl num">20000000</span><span class="hl opt">));</span>
  <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwa">false</span><span class="hl opt">,</span> <span class="hl num">10000000</span><span class="hl opt">);</span>
  f<span class="hl opt">.</span><span class="hl kwd">wait</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> value <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Compiling via clang:</p>

<pre><code>clang++ -std=c++11 -stdlib=libc++ -O3 -o test test.cpp &amp;&amp; time ./test
</code></pre>

<p>Run:</p>

<pre><code>SSttaarrtteedd  10  2100000000000000

11177087

real    0m0.070s
user    0m0.089s
sys 0m0.002s
</code></pre>

<p>Obviously, the increment and decrement operations aren&rsquo;t atomic, and the <code>value</code> variable contains garbage at the end.</p>

<h2>LOCK</h2>

<pre class="hl">
<span class="hl ppc">#include &lt;future&gt;</span>
<span class="hl ppc">#include &lt;iostream&gt;</span>

<span class="hl kwc">volatile</span> <span class="hl kwb">int</span> value <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>

<span class="hl kwb">int</span> <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwb">bool</span> inc<span class="hl opt">,</span> <span class="hl kwb">int</span> limit<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Started &quot;</span> <span class="hl opt">&lt;&lt;</span> inc <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot; &quot;</span> <span class="hl opt">&lt;&lt;</span> limit <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> limit<span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>inc<span class="hl opt">) {</span> 
      <span class="hl kwa">asm</span><span class="hl opt">(</span><span class="hl str">&quot;LOCK&quot;</span><span class="hl opt">);</span>
      <span class="hl opt">++</span>value<span class="hl opt">;</span>
    <span class="hl opt">}</span> <span class="hl kwa">else</span> <span class="hl opt">{</span>
      <span class="hl kwa">asm</span><span class="hl opt">(</span><span class="hl str">&quot;LOCK&quot;</span><span class="hl opt">);</span>
      <span class="hl opt">--</span>value<span class="hl opt">;</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwc">auto</span> f <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">async</span><span class="hl opt">(</span>std<span class="hl opt">::</span>launch<span class="hl opt">::</span>async<span class="hl opt">,</span> std<span class="hl opt">::</span><span class="hl kwd">bind</span><span class="hl opt">(</span>loop<span class="hl opt">,</span> <span class="hl kwa">true</span><span class="hl opt">,</span> <span class="hl num">20000000</span><span class="hl opt">));</span>
  <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwa">false</span><span class="hl opt">,</span> <span class="hl num">10000000</span><span class="hl opt">);</span>
  f<span class="hl opt">.</span><span class="hl kwd">wait</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> value <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
<span class="hl opt">}</span> 
</pre>

<p>Run:</p>

<pre><code>SSttaarrtteedd  10  2000000100000000

10000000

real    0m0.481s
user    0m0.779s
sys 0m0.005s
</code></pre>

<p>Now <code>value</code> has the correct value at the end, but, of course, this is a dirty non-portable hack for x86 only. For example, this code works for me only if compiled with <code>-O3</code>. Otherwise it crashes with &ldquo;illegal instruction&rdquo; because the compiler injects extra stuff between the LOCK instruction and the following increment or decrement.</p>

<h2>Atomic</h2>

<pre class="hl">
<span class="hl ppc">#include &lt;future&gt;</span>
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include</span> <span class="hl pps">&quot;boost/interprocess/detail/atomic.hpp&quot;</span><span class="hl ppc"></span>

<span class="hl kwa">using namespace</span> boost<span class="hl opt">::</span>interprocess<span class="hl opt">::</span>ipcdetail<span class="hl opt">;</span>

<span class="hl kwc">volatile</span> boost<span class="hl opt">::</span><span class="hl kwb">uint32_t</span> value <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>

<span class="hl kwb">int</span> <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwb">bool</span> inc<span class="hl opt">,</span> <span class="hl kwb">int</span> limit<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Started &quot;</span> <span class="hl opt">&lt;&lt;</span> inc <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot; &quot;</span> <span class="hl opt">&lt;&lt;</span> limit <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> limit<span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>inc<span class="hl opt">) {</span> 
      <span class="hl kwd">atomic_inc32</span><span class="hl opt">(&amp;</span>value<span class="hl opt">);</span>
    <span class="hl opt">}</span> <span class="hl kwa">else</span> <span class="hl opt">{</span>
      <span class="hl kwd">atomic_dec32</span><span class="hl opt">(&amp;</span>value<span class="hl opt">);</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwc">auto</span> f <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">async</span><span class="hl opt">(</span>std<span class="hl opt">::</span>launch<span class="hl opt">::</span>async<span class="hl opt">,</span> std<span class="hl opt">::</span><span class="hl kwd">bind</span><span class="hl opt">(</span>loop<span class="hl opt">,</span> <span class="hl kwa">true</span><span class="hl opt">,</span> <span class="hl num">20000000</span><span class="hl opt">));</span>
  <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwa">false</span><span class="hl opt">,</span> <span class="hl num">10000000</span><span class="hl opt">);</span>
  f<span class="hl opt">.</span><span class="hl kwd">wait</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl kwd">atomic_read32</span><span class="hl opt">(&amp;</span>value<span class="hl opt">) &lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Run:</p>

<pre><code>SSttaarrtteedd  10  2100000000000000

10000000

real    0m0.457s
user    0m0.734s
sys 0m0.004s
</code></pre>

<p>The result is correct, and the time is almost the same as with <code>LOCK</code>. Not surprisingly, <code>atomic</code> under cover also uses <code>LOCK</code> but in a portable and guaranteed way.</p>

<h2>Spinlock</h2>

<pre class="hl">
<span class="hl ppc">#include &lt;future&gt;</span>
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include</span> <span class="hl pps">&quot;boost/smart_ptr/detail/spinlock.hpp&quot;</span><span class="hl ppc"></span>

boost<span class="hl opt">::</span>detail<span class="hl opt">::</span>spinlock lock<span class="hl opt">;</span>
<span class="hl kwc">volatile</span> <span class="hl kwb">int</span> value <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>

<span class="hl kwb">int</span> <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwb">bool</span> inc<span class="hl opt">,</span> <span class="hl kwb">int</span> limit<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Started &quot;</span> <span class="hl opt">&lt;&lt;</span> inc <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot; &quot;</span> <span class="hl opt">&lt;&lt;</span> limit <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> limit<span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>lock_guard<span class="hl opt">&lt;</span>boost<span class="hl opt">::</span>detail<span class="hl opt">::</span>spinlock<span class="hl opt">&gt;</span> <span class="hl kwd">guard</span><span class="hl opt">(</span>lock<span class="hl opt">);</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>inc<span class="hl opt">) {</span> 
      <span class="hl opt">++</span>value<span class="hl opt">;</span>
    <span class="hl opt">}</span> <span class="hl kwa">else</span> <span class="hl opt">{</span>
      <span class="hl opt">--</span>value<span class="hl opt">;</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwc">auto</span> f <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">async</span><span class="hl opt">(</span>std<span class="hl opt">::</span>launch<span class="hl opt">::</span>async<span class="hl opt">,</span> std<span class="hl opt">::</span><span class="hl kwd">bind</span><span class="hl opt">(</span>loop<span class="hl opt">,</span> <span class="hl kwa">true</span><span class="hl opt">,</span> <span class="hl num">20000000</span><span class="hl opt">));</span>
  <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwa">false</span><span class="hl opt">,</span> <span class="hl num">10000000</span><span class="hl opt">);</span>
  f<span class="hl opt">.</span><span class="hl kwd">wait</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> value <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Run:</p>

<pre><code>SSttaarrtteedd  10  2100000000000000

10000000

real    0m0.541s
user    0m0.675s
sys 0m0.089s
</code></pre>

<p>A bit slower but not much.</p>

<h2>Mutex</h2>

<pre class="hl">
<span class="hl ppc">#include &lt;future&gt;</span>
<span class="hl ppc">#include &lt;iostream&gt;</span>

std<span class="hl opt">::</span>mutex mutex<span class="hl opt">;</span>
<span class="hl kwc">volatile</span> <span class="hl kwb">int</span> value <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>

<span class="hl kwb">int</span> <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwb">bool</span> inc<span class="hl opt">,</span> <span class="hl kwb">int</span> limit<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Started &quot;</span> <span class="hl opt">&lt;&lt;</span> inc <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot; &quot;</span> <span class="hl opt">&lt;&lt;</span> limit <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> limit<span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>lock_guard<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>mutex<span class="hl opt">&gt;</span> <span class="hl kwd">guard</span><span class="hl opt">(</span>mutex<span class="hl opt">);</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>inc<span class="hl opt">) {</span> 
      <span class="hl opt">++</span>value<span class="hl opt">;</span>
    <span class="hl opt">}</span> <span class="hl kwa">else</span> <span class="hl opt">{</span>
      <span class="hl opt">--</span>value<span class="hl opt">;</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwc">auto</span> f <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">async</span><span class="hl opt">(</span>std<span class="hl opt">::</span>launch<span class="hl opt">::</span>async<span class="hl opt">,</span> std<span class="hl opt">::</span><span class="hl kwd">bind</span><span class="hl opt">(</span>loop<span class="hl opt">,</span> <span class="hl kwa">true</span><span class="hl opt">,</span> <span class="hl num">20000000</span><span class="hl opt">));</span>
  <span class="hl kwd">loop</span><span class="hl opt">(</span><span class="hl kwa">false</span><span class="hl opt">,</span> <span class="hl num">10000000</span><span class="hl opt">);</span>
  f<span class="hl opt">.</span><span class="hl kwd">wait</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> value <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Run:</p>

<pre><code>SSttaarrtteedd  10  2010000000000000

10000000

real    0m25.229s
user    0m7.011s
sys 0m22.667s
</code></pre>

<p>Now it works much slower, really.</p>

<h2>Benchmark</h2>

<table>
<thead>
<tr>
<td><strong>Method</strong></td>
<td><strong>Time (sec.)</strong></td>
</tr>
</thead>

<tbody>
<tr>
<td>No synchronization</td>
<td>0.070</td>
</tr>

<tr>
<td>LOCK</td>
<td>0.481</td>
</tr>

<tr>
<td>Atomic</td>
<td>0.457</td>
</tr>

<tr>
<td>Spinlock</td>
<td>0.541</td>
</tr>

<tr>
<td>Mutex</td>
<td>22.667</td>
</tr>
</tbody>
</table>

<p>Of course, the result depends really on the platform and the compiler (I tested on Mac Air and clang). But for me it was quite interesting to see that spinlock, in spite of its more sophisticated implementation comparing to atomics, works not much slower.</p>

<p>Sadly, my clang 3.1 still doesn&rsquo;t support <code>atomic</code>, and I had to use boost.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Pimpl and smart pointers]]></title>
    <link href="http://demin.ws/blog/english/2012/05/03/pimpl-and-smart-pointers/"/>
    <updated>2012-05-03T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/03/pimpl-and-smart-pointers/</id>
    <content type="html"><![CDATA[<p>Sometimes I realise that I don&rsquo;t know obvious things. My discovery of today is about Pimpl and smart pointers. For some reason I thought that the forward class declaration is only possible if the class is referenced by a pointer or a reference (#1), that is used in a form of <code>T*</code> or <code>T&amp;</code> (#2). Therefore, when I wanted Pimpl, I didn&rsquo;t use smart pointers because it seemed that it needed the full class definition.</p>

<p><code>A.h</code>:
<pre class="hl">
<span class="hl ppc">#include &lt;memory&gt;</span>
<span class="hl kwc">class</span> A_pimpl<span class="hl opt">;</span>
<span class="hl kwc">class</span> A <span class="hl opt">{</span>
  <span class="hl kwd">A</span><span class="hl opt">();</span>
  <span class="hl opt">~</span><span class="hl kwd">A</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>unique_ptr<span class="hl opt">&lt;</span>A_pimpl<span class="hl opt">&gt;</span> p<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre></p>

<p>I believed to some reason that it will not work because the class <code>A_pimpl</code> is partially defined. I was surprised as a child when tried and realised that it works! The fact #1 is not equivalent to the fact #2.</p>

<p>Now in <code>A.cpp</code> I can write:</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;module.h&quot;</span><span class="hl ppc"></span>
<span class="hl ppc">#include</span> <span class="hl pps">&quot;pimpl.h&quot;</span><span class="hl ppc"></span>

A<span class="hl opt">::</span><span class="hl kwd">A</span><span class="hl opt">() :</span> <span class="hl kwd">p</span><span class="hl opt">(</span><span class="hl kwa">new</span> <span class="hl kwd">A_pimpl</span><span class="hl opt">()) {}</span>
A<span class="hl opt">::~</span><span class="hl kwd">A</span><span class="hl opt">() {}</span>
</pre>

<p>Everything above also works for <code>std::shared_ptr</code> (C++ 2011), <code>boost::scoped_ptr</code>, and <code>boost::shared_ptr</code>.</p>

<p><strong>Update</strong></p>

<p>It is important that class <code>A</code> must an explicitly provided destructor. Moreover, its body must in <code>A.cpp</code>, not in the header. Otherwise, it will be a compilation error, for example, &ldquo;error C2338: can&rsquo;t delete an incomplete type&rdquo;.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Anthony Williams, &#34;C++ Concurrency in Action&#34;]]></title>
    <link href="http://demin.ws/blog/english/2012/05/02/cpp-concurrency-in-action/"/>
    <updated>2012-05-02T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/02/cpp-concurrency-in-action/</id>
    <content type="html"><![CDATA[<p>I managed to attend <a href="http://accu.org/index.php/conferences/accu_conference_2012">ACCU 2012</a> this year. It was almost all about C++ 2011. One of the presentations I have attended was &ldquo;C++11 concurrency tutorial&rdquo; from <a href="http://www.boost.org/users/people/anthony_williams.html">Anthony Williams</a>. He is, no more no less, the maintainer of boost::thread.</p>

<p>His presentation is <a href="http://www.justsoftwaresolutions.co.uk/files/c++11_concurrency.pdf">available</a> with <a href="http://www.justsoftwaresolutions.co.uk/files/c++11_concurrency_code.zip">examples</a>.</p>

<p>Unfortunately, I missed his second presentation, &ldquo;Dataflow, Actors and High Level Structures in Concurrent Applications&rdquo;. In fact, it was about implementing the concept of actors, similar as in Erlang, in C++ 2011.</p>

<p>This presentation is also <a href="http://www.justsoftwaresolutions.co.uk/files/dataflow_and_actors.pdf">available</a> with <a href="http://www.justsoftwaresolutions.co.uk/files/dataflow_and_actors_code.zip">examples</a>.</p>

<p>Recommend.</p>

<p>Going further. Anthony&rsquo;s book, &ldquo;C++ Concurrency in Action&rdquo;, has been released recently.</p>

<p><a href="http://www.amazon.co.uk/gp/product/1933988770/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=1933988770"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=1933988770&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=1933988770" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>If you want an exhaustive explanation about the C++ memory model, please read the chapters 5 (along with all others).</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Bug in std::async() in Visual Studio 11 (preview)]]></title>
    <link href="http://demin.ws/blog/english/2012/05/01/async-bug-in-visual-studio-11-preview/"/>
    <updated>2012-05-01T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/05/01/async-bug-in-visual-studio-11-preview/</id>
    <content type="html"><![CDATA[<p>Come across a bug in the Visual Studio 11 (preview).</p>

<pre class="hl">
<span class="hl ppc">#include &lt;future&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwc">auto</span> i <span class="hl opt">=</span> <span class="hl num">0L</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">1000000</span><span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl kwc">auto</span> f <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">async</span><span class="hl opt">([](){</span> <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">; });</span>
    f<span class="hl opt">.</span><span class="hl kwd">get</span><span class="hl opt">();</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>This code consistently crashes (and doesn&rsquo;t throw). When decreasing a number of iteration, at some point to stops crashing.</p>

<p>The compiler cl.exe 17.00.40825.2, IDE 11.0.40825.2 PREREL. <a href="http://stackoverflow.com/questions/10301432/number-of-async-futures-in-c11">Posted on Stack Overflow</a>. They say, likely it is the bug.</p>

<p>Where to file a bug to VS?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Multi-threaded QuickSort]]></title>
    <link href="http://demin.ws/blog/english/2012/04/28/multithreaded-quicksort/"/>
    <updated>2012-04-28T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/28/multithreaded-quicksort/</id>
    <content type="html"><![CDATA[<p>I complained recently, that C++, even on steroids of the new standard, still discourages concurrency and multithreading. In the attempt to break this ice in my heart, I&rsquo;ve tried implementing the multi-threaded QuickSort. After partitioning we can sort sub-arrays in separate threads.</p>

<p>This is my naive approach:</p>

<pre class="hl">
<span class="hl kwb">int</span> <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;::</span>iterator begin<span class="hl opt">,</span> std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;::</span>iterator end<span class="hl opt">) {</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> sz <span class="hl opt">=</span> end <span class="hl opt">-</span> begin<span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>sz <span class="hl opt">&lt;=</span> <span class="hl num">1</span><span class="hl opt">)</span> <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>

  <span class="hl kwc">auto</span> pivot <span class="hl opt">=</span> begin <span class="hl opt">+</span> sz<span class="hl opt">/</span><span class="hl num">2</span><span class="hl opt">;</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> pivot_v <span class="hl opt">= *</span>pivot<span class="hl opt">;</span>

  std<span class="hl opt">::</span><span class="hl kwd">swap</span><span class="hl opt">(*</span>pivot<span class="hl opt">, *(</span>end <span class="hl opt">-</span> <span class="hl num">1</span><span class="hl opt">));</span>
  <span class="hl kwc">auto</span> p <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">partition</span><span class="hl opt">(</span>begin<span class="hl opt">,</span> end<span class="hl opt">, [&amp;](</span><span class="hl kwb">const</span> Type<span class="hl opt">&amp;</span> a<span class="hl opt">) {</span> <span class="hl kwa">return</span> a <span class="hl opt">&lt;</span> pivot_v<span class="hl opt">; } );</span>
  std<span class="hl opt">::</span><span class="hl kwd">swap</span><span class="hl opt">(*</span>p<span class="hl opt">, *(</span>end <span class="hl opt">-</span> <span class="hl num">1</span><span class="hl opt">));</span>

  <span class="hl kwa">if</span> <span class="hl opt">(</span>sz <span class="hl opt">&gt;</span> <span class="hl num">4096</span><span class="hl opt">) {</span>
    <span class="hl kwc">auto</span> left <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">async</span><span class="hl opt">(</span>std<span class="hl opt">::</span>launch<span class="hl opt">::</span>async<span class="hl opt">, [&amp;]() {</span>
      <span class="hl kwa">return</span> <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>begin<span class="hl opt">,</span> p<span class="hl opt">);</span>
    <span class="hl opt">});</span>
    <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>p <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">,</span> end<span class="hl opt">);</span>
  <span class="hl opt">}</span> <span class="hl kwa">else</span> <span class="hl opt">{</span>
    <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>begin<span class="hl opt">,</span> p<span class="hl opt">);</span>
    <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>p <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">,</span> end<span class="hl opt">);</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">quick_sort</span><span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;&amp;</span> arr<span class="hl opt">) {</span>
  <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>arr<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> arr<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">());</span>
<span class="hl opt">}</span>
</pre>

<p>Everything is simple, but it&rsquo;s worth to consider some details. This is a threshold, <code>4096</code>, determining when we switch the parallelism off. Why <code>4096</code>? Just a guess, without a particular explanation.</p>

<h3>Benchmark</h3>

<p>The are three candidates:</p>

<ul>
<li>the naive implementation (using <code>async</code>)</li>
<li>the same naive implementation, but single threaded (replace <code>if (sz &gt; 4096)</code> to <code>if (false)</code>)</li>
<li>std::sort() (replace <code>naive_quick_sort(arr.begin(), arr.end())</code> to <code>std::sort(arr.begin(), arr.end())</code>)</li>
</ul>

<p>We sort an array of 50000000 elements of the type <code>int64</code> (signed) with 10 runs and take an average. The values are random:</p>

<pre class="hl">
std<span class="hl opt">::</span>tr1<span class="hl opt">::</span>uniform_int<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;</span> <span class="hl kwd">uniform</span><span class="hl opt">(</span>
  std<span class="hl opt">::</span>numeric_limits<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;::</span><span class="hl kwd">min</span><span class="hl opt">(),</span>
  std<span class="hl opt">::</span>numeric_limits<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;::</span><span class="hl kwd">max</span><span class="hl opt">());</span>
std<span class="hl opt">::</span>mt19937_64 engine<span class="hl opt">;</span>

<span class="hl kwb">void</span> <span class="hl kwd">generate</span><span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;&amp;</span> v<span class="hl opt">) {</span>
  std<span class="hl opt">::</span><span class="hl kwd">for_each</span><span class="hl opt">(</span>v<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> v<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(), [](</span>Type<span class="hl opt">&amp;</span> i<span class="hl opt">) {</span> i <span class="hl opt">=</span> <span class="hl kwd">uniform</span><span class="hl opt">(</span>engine<span class="hl opt">); });</span>
<span class="hl opt">}</span>
</pre>

<p>Don&rsquo;t ask me, why I convert the data between big and little endians back and fourth. It was implemented to compare this implementation with another one, in Java. In measurements we count only the &ldquo;pure&rdquo; time.</p>

<p>The compiler is VS 2011, 64-bit. CPU Intel Core i5 2.53GHz, 4 cores.</p>

<pre><code>Iteration  With async()   One thread   std::sort()
--------- --------------- ------------ ------------
 1         2512            6555         7309
 2         2337            6320         6977
 3         2450            6516         7180
 4         2372            6388         6933
 5         2387            7074         7189
 6         2339            7399         7040
 7         2434            6875         7040
 8         2562            7060         7187
 9         2470            7050         7145
10         2422            6846         6898
--------- --------------- ------------ ------------    
Среднее    2428.5          6808.3       7089.8
</code></pre>

<p>The time is in milliseconds.</p>

<p>It turns out that the naive implementation based on <code>async()</code> is three times faster then the single threaded <code>std::sort()</code>. A weird slowdown of the <code>std::sort()</code> against my naive single thread version can be explained, perhaps, that the data I generated <em>is good</em>, and my naive implementation is just lucky.</p>

<p>Any practical use out of it at all? Probably not. It is difficult to predict the behaviour of the implementation on different sets of data. For example, how to choose the threshold properly? Is it worth to start using thread pools?</p>

<p>The full source is below, including the generator.</p>

<p>Build and generate the data:</p>

<pre><code>call &quot;%VS110COMNTOOLS%..\..\VC\vcvarsall.bat&quot; amd64 &amp;&amp; ^
cl /Ox /DWIN32 sort_async.cpp &amp;&amp; ^
sort_async generate
</code></pre>

<p>Warning! It generates 8GB of data.</p>

<p>Build and test:</p>

<pre><code>call &quot;%VS110COMNTOOLS%..\..\VC\vcvarsall.bat&quot; amd64 &amp;&amp; ^
cl /Ox /DWIN32 sort_async.cpp &amp;&amp; ^
sort_async
</code></pre>

<p>File <code>sort_async.cpp</code>:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;vector&gt;                      </span>
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;fstream&gt;</span>
<span class="hl ppc">#include &lt;sstream&gt;</span>
<span class="hl ppc">#include &lt;algorithm&gt;</span>
<span class="hl ppc">#include &lt;iomanip&gt;</span>
<span class="hl ppc">#include &lt;future&gt;</span>
<span class="hl ppc">#include &lt;random&gt;</span>
<span class="hl ppc">#include &lt;chrono&gt;</span>
<span class="hl ppc">#include &lt;cstdlib&gt;</span>

<span class="hl kwb">const int</span> ITERATIONS_NUM <span class="hl opt">=</span> <span class="hl num">10</span><span class="hl opt">;</span>
<span class="hl kwb">const int</span> DATA_SIZE <span class="hl opt">=</span> <span class="hl num">50000000</span><span class="hl opt">;</span>

<span class="hl kwc">typedef</span> __int64 Type<span class="hl opt">;</span>

<span class="hl kwc">inline</span> <span class="hl kwb">void</span> <span class="hl kwd">endian_swap</span><span class="hl opt">(</span>Type<span class="hl opt">&amp;</span> x<span class="hl opt">) {</span>
  x <span class="hl opt">=</span>
    <span class="hl opt">(</span><span class="hl num">0x00000000000000FF</span> <span class="hl opt">&amp; (</span>x <span class="hl opt">&gt;&gt;</span> <span class="hl num">56</span><span class="hl opt">))</span>
  <span class="hl opt">| (</span><span class="hl num">0x000000000000FF00</span> <span class="hl opt">&amp; (</span>x <span class="hl opt">&gt;&gt;</span> <span class="hl num">40</span><span class="hl opt">))</span>
  <span class="hl opt">| (</span><span class="hl num">0x0000000000FF0000</span> <span class="hl opt">&amp; (</span>x <span class="hl opt">&gt;&gt;</span> <span class="hl num">24</span><span class="hl opt">))</span>
  <span class="hl opt">| (</span><span class="hl num">0x00000000FF000000</span> <span class="hl opt">&amp; (</span>x <span class="hl opt">&gt;&gt;</span>  <span class="hl num">8</span><span class="hl opt">))</span>
  <span class="hl opt">| (</span><span class="hl num">0x000000FF00000000</span> <span class="hl opt">&amp; (</span>x <span class="hl opt">&lt;&lt;</span>  <span class="hl num">8</span><span class="hl opt">))</span>
  <span class="hl opt">| (</span><span class="hl num">0x0000FF0000000000</span> <span class="hl opt">&amp; (</span>x <span class="hl opt">&lt;&lt;</span> <span class="hl num">24</span><span class="hl opt">))</span>
  <span class="hl opt">| (</span><span class="hl num">0x00FF000000000000</span> <span class="hl opt">&amp; (</span>x <span class="hl opt">&lt;&lt;</span> <span class="hl num">40</span><span class="hl opt">))</span>
  <span class="hl opt">| (</span><span class="hl num">0xFF00000000000000</span> <span class="hl opt">&amp; (</span>x <span class="hl opt">&lt;&lt;</span> <span class="hl num">56</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

std<span class="hl opt">::</span>tr1<span class="hl opt">::</span>uniform_int<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;</span> <span class="hl kwd">uniform</span><span class="hl opt">(</span>
  std<span class="hl opt">::</span>numeric_limits<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;::</span><span class="hl kwd">min</span><span class="hl opt">(),</span>
  std<span class="hl opt">::</span>numeric_limits<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;::</span><span class="hl kwd">max</span><span class="hl opt">());</span>
std<span class="hl opt">::</span>mt19937_64 engine<span class="hl opt">;</span>

<span class="hl kwb">void</span> <span class="hl kwd">generate</span><span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;&amp;</span> v<span class="hl opt">) {</span>
  std<span class="hl opt">::</span><span class="hl kwd">for_each</span><span class="hl opt">(</span>v<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> v<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(), [](</span>Type<span class="hl opt">&amp;</span> i<span class="hl opt">) {</span> i <span class="hl opt">=</span> <span class="hl kwd">uniform</span><span class="hl opt">(</span>engine<span class="hl opt">); });</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">check_sorted</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;&amp;</span> v<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> msg<span class="hl opt">) {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwc">auto</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> v<span class="hl opt">.</span><span class="hl kwd">size</span><span class="hl opt">() -</span> <span class="hl num">1</span><span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>v<span class="hl opt">[</span>i<span class="hl opt">] &gt;</span> v<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">]) {</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">Unsorted: &quot;</span> <span class="hl opt">&lt;&lt;</span> msg <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span> <span class="hl opt">&lt;&lt;</span> i <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> v<span class="hl opt">[</span>i<span class="hl opt">] &lt;&lt;</span> <span class="hl str">&quot; &quot;</span> <span class="hl opt">&lt;&lt;</span> v<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">] &lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
      std<span class="hl opt">::</span><span class="hl kwd">exit</span><span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">);</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span>
<span class="hl opt">}</span>

std<span class="hl opt">::</span>string <span class="hl kwd">data_file_name</span><span class="hl opt">(</span><span class="hl kwb">const int</span> i<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> suffix<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>ostringstream fmt<span class="hl opt">;</span>
  fmt <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;trash_for_sort_&quot;</span> <span class="hl opt">&lt;&lt;</span> i <span class="hl opt">&lt;&lt;</span> suffix <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;.bin&quot;</span><span class="hl opt">;</span>
  <span class="hl kwa">return</span> fmt<span class="hl opt">.</span><span class="hl kwd">str</span><span class="hl opt">();</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">save_file</span><span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;</span> array<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">) {</span>
  std<span class="hl opt">::</span><span class="hl kwd">for_each</span><span class="hl opt">(</span>array<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> array<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(), [](</span>Type<span class="hl opt">&amp;</span> i<span class="hl opt">) {</span> <span class="hl kwd">endian_swap</span><span class="hl opt">(</span>i<span class="hl opt">); });</span>
  std<span class="hl opt">::</span>ofstream <span class="hl kwd">os</span><span class="hl opt">(</span>name<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">(),</span> std<span class="hl opt">::</span>ios<span class="hl opt">::</span>binary<span class="hl opt">|</span>std<span class="hl opt">::</span>ios<span class="hl opt">::</span>out<span class="hl opt">);</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> bytes_to_write <span class="hl opt">=</span> array<span class="hl opt">.</span><span class="hl kwd">size</span><span class="hl opt">() *</span> <span class="hl kwa">sizeof</span><span class="hl opt">(</span>array<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">]);</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Saving &quot;</span> <span class="hl opt">&lt;&lt;</span> array<span class="hl opt">.</span><span class="hl kwd">size</span><span class="hl opt">() &lt;&lt;</span> <span class="hl str">&quot; bytes to &quot;</span> <span class="hl opt">&lt;&lt;</span> name <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
  os<span class="hl opt">.</span><span class="hl kwd">write</span><span class="hl opt">((</span><span class="hl kwb">char</span> <span class="hl opt">*)&amp;</span>array<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">],</span> bytes_to_write<span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main_generate</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Generation</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwc">auto</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> ITERATIONS_NUM<span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;</span> <span class="hl kwd">unsorted</span><span class="hl opt">(</span>DATA_SIZE<span class="hl opt">);</span>
    <span class="hl kwd">generate</span><span class="hl opt">(</span>unsorted<span class="hl opt">);</span>
    <span class="hl kwd">save_file</span><span class="hl opt">(</span>unsorted<span class="hl opt">,</span> <span class="hl kwd">data_file_name</span><span class="hl opt">(</span>i<span class="hl opt">,</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">));</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Sorting...</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
    std<span class="hl opt">::</span><span class="hl kwd">sort</span><span class="hl opt">(</span>unsorted<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> unsorted<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">());</span>
    <span class="hl kwd">check_sorted</span><span class="hl opt">(</span>unsorted<span class="hl opt">,</span> <span class="hl str">&quot;check sorted array&quot;</span><span class="hl opt">);</span>
    <span class="hl kwd">save_file</span><span class="hl opt">(</span>unsorted<span class="hl opt">,</span> <span class="hl kwd">data_file_name</span><span class="hl opt">(</span>i<span class="hl opt">,</span> <span class="hl str">&quot;_sorted&quot;</span><span class="hl opt">));</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">load_file</span><span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;&amp;</span> array<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> name<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Loading &quot;</span> <span class="hl opt">&lt;&lt;</span> name<span class="hl opt">;</span>
  array<span class="hl opt">.</span><span class="hl kwd">resize</span><span class="hl opt">(</span>DATA_SIZE<span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">);</span>

  std<span class="hl opt">::</span>ifstream <span class="hl kwd">is</span><span class="hl opt">(</span>name<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">(),</span> std<span class="hl opt">::</span>ios<span class="hl opt">::</span>binary<span class="hl opt">|</span>std<span class="hl opt">::</span>ios<span class="hl opt">::</span>in<span class="hl opt">);</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> to_load <span class="hl opt">=</span> array<span class="hl opt">.</span><span class="hl kwd">size</span><span class="hl opt">() *</span> <span class="hl kwa">sizeof</span><span class="hl opt">(</span>array<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">]);</span>
  is<span class="hl opt">.</span><span class="hl kwd">read</span><span class="hl opt">((</span><span class="hl kwb">char</span> <span class="hl opt">*)&amp;</span>array<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">],</span> to_load<span class="hl opt">);</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>is<span class="hl opt">.</span><span class="hl kwd">gcount</span><span class="hl opt">() !=</span> to_load<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>cerr <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, Bad file &quot;</span> <span class="hl opt">&lt;&lt;</span> name
      <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, loaded &quot;</span> <span class="hl opt">&lt;&lt;</span> is<span class="hl opt">.</span><span class="hl kwd">gcount</span><span class="hl opt">() &lt;&lt;</span> <span class="hl str">&quot; words but should be &quot;</span> <span class="hl opt">&lt;&lt;</span> to_load <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
    std<span class="hl opt">::</span><span class="hl kwd">exit</span><span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">);</span>
  <span class="hl opt">}</span>
  std<span class="hl opt">::</span><span class="hl kwd">for_each</span><span class="hl opt">(</span>array<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> array<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(), [](</span>Type<span class="hl opt">&amp;</span> v<span class="hl opt">){</span> <span class="hl kwd">endian_swap</span><span class="hl opt">(</span>v<span class="hl opt">); });</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;::</span>iterator begin<span class="hl opt">,</span> std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;::</span>iterator end<span class="hl opt">) {</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> sz <span class="hl opt">=</span> end <span class="hl opt">-</span> begin<span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>sz <span class="hl opt">&lt;=</span> <span class="hl num">1</span><span class="hl opt">)</span> <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>

  <span class="hl kwc">auto</span> pivot <span class="hl opt">=</span> begin <span class="hl opt">+</span> sz<span class="hl opt">/</span><span class="hl num">2</span><span class="hl opt">;</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> pivot_v <span class="hl opt">= *</span>pivot<span class="hl opt">;</span>

  std<span class="hl opt">::</span><span class="hl kwd">swap</span><span class="hl opt">(*</span>pivot<span class="hl opt">, *(</span>end <span class="hl opt">-</span> <span class="hl num">1</span><span class="hl opt">));</span>
  <span class="hl kwc">auto</span> p <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">partition</span><span class="hl opt">(</span>begin<span class="hl opt">,</span> end<span class="hl opt">, [&amp;](</span><span class="hl kwb">const</span> Type<span class="hl opt">&amp;</span> a<span class="hl opt">) {</span> <span class="hl kwa">return</span> a <span class="hl opt">&lt;</span> pivot_v<span class="hl opt">; } );</span>
  std<span class="hl opt">::</span><span class="hl kwd">swap</span><span class="hl opt">(*</span>p<span class="hl opt">, *(</span>end <span class="hl opt">-</span> <span class="hl num">1</span><span class="hl opt">));</span>

  <span class="hl kwa">if</span> <span class="hl opt">(</span>sz <span class="hl opt">&gt;</span> <span class="hl num">4096</span><span class="hl opt">) {</span>
    <span class="hl kwc">auto</span> left <span class="hl opt">=</span> std<span class="hl opt">::</span><span class="hl kwd">async</span><span class="hl opt">(</span>std<span class="hl opt">::</span>launch<span class="hl opt">::</span>async<span class="hl opt">, [&amp;]() {</span>
      <span class="hl kwa">return</span> <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>begin<span class="hl opt">,</span> p<span class="hl opt">);</span>
    <span class="hl opt">});</span>
    <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>p <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">,</span> end<span class="hl opt">);</span>
  <span class="hl opt">}</span> <span class="hl kwa">else</span> <span class="hl opt">{</span>
    <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>begin<span class="hl opt">,</span> p<span class="hl opt">);</span>
    <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>p <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">,</span> end<span class="hl opt">);</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">quick_sort</span><span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;&amp;</span> arr<span class="hl opt">) {</span>
  <span class="hl kwd">naive_quick_sort</span><span class="hl opt">(</span>arr<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> arr<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">());</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>argc <span class="hl opt">==</span> <span class="hl num">2</span> <span class="hl opt">&amp;&amp; !</span>std<span class="hl opt">::</span><span class="hl kwd">strcmp</span><span class="hl opt">(</span>argv<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">],</span> <span class="hl str">&quot;generate&quot;</span><span class="hl opt">))</span>
    <span class="hl kwa">return</span> <span class="hl kwd">main_generate</span><span class="hl opt">(</span>argc<span class="hl opt">,</span> argv<span class="hl opt">);</span>

  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">double</span><span class="hl opt">&gt;</span> times<span class="hl opt">;</span>
  <span class="hl kwc">auto</span> times_sum <span class="hl opt">=</span> <span class="hl num">0.0</span><span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwc">auto</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> ITERATIONS_NUM<span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;</span> unsorted<span class="hl opt">;</span>
    <span class="hl kwd">load_file</span><span class="hl opt">(</span>unsorted<span class="hl opt">,</span> <span class="hl kwd">data_file_name</span><span class="hl opt">(</span>i<span class="hl opt">,</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">));</span>

    std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>Type<span class="hl opt">&gt;</span> verify<span class="hl opt">;</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, &quot;</span><span class="hl opt">;</span>
    <span class="hl kwd">load_file</span><span class="hl opt">(</span>verify<span class="hl opt">,</span> <span class="hl kwd">data_file_name</span><span class="hl opt">(</span>i<span class="hl opt">,</span> <span class="hl str">&quot;_sorted&quot;</span><span class="hl opt">));</span>
    <span class="hl kwd">check_sorted</span><span class="hl opt">(</span>verify<span class="hl opt">,</span> <span class="hl str">&quot;verify array&quot;</span><span class="hl opt">);</span>

    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, Started&quot;</span><span class="hl opt">;</span>
    <span class="hl kwc">auto</span> start <span class="hl opt">=</span> std<span class="hl opt">::</span>chrono<span class="hl opt">::</span>high_resolution_clock<span class="hl opt">::</span><span class="hl kwd">now</span><span class="hl opt">();</span>

    <span class="hl kwd">quick_sort</span><span class="hl opt">(</span>unsorted<span class="hl opt">);</span>

    <span class="hl kwc">auto</span> stop <span class="hl opt">=</span> std<span class="hl opt">::</span>chrono<span class="hl opt">::</span>high_resolution_clock<span class="hl opt">::</span><span class="hl kwd">now</span><span class="hl opt">();</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, Stopped, &quot;</span><span class="hl opt">;</span>
    <span class="hl kwc">auto</span> duration <span class="hl opt">=</span> std<span class="hl opt">::</span>chrono<span class="hl opt">::</span>duration<span class="hl opt">&lt;</span><span class="hl kwb">double</span><span class="hl opt">&gt;(</span>stop <span class="hl opt">-</span> start<span class="hl opt">).</span><span class="hl kwd">count</span><span class="hl opt">();</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> duration<span class="hl opt">;</span>

    <span class="hl kwd">check_sorted</span><span class="hl opt">(</span>unsorted<span class="hl opt">,</span> <span class="hl str">&quot;sorted array&quot;</span><span class="hl opt">);</span>

    <span class="hl kwb">const</span> <span class="hl kwc">auto</span> match <span class="hl opt">=</span> unsorted <span class="hl opt">==</span> verify<span class="hl opt">;</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt; (</span>match ? <span class="hl str">&quot;, OK&quot;</span> <span class="hl opt">:</span> <span class="hl str">&quot;, DON'T MATCH&quot;</span><span class="hl opt">);</span>

    times<span class="hl opt">.</span><span class="hl kwd">push_back</span><span class="hl opt">(</span>duration<span class="hl opt">);</span>
    times_sum <span class="hl opt">+=</span> duration<span class="hl opt">;</span>

    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>

  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> average <span class="hl opt">=</span> times_sum <span class="hl opt">/</span> ITERATIONS_NUM<span class="hl opt">;</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> max_element <span class="hl opt">= *</span>std<span class="hl opt">::</span><span class="hl kwd">max_element</span><span class="hl opt">(</span>times<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> times<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">());</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> min_element <span class="hl opt">= *</span>std<span class="hl opt">::</span><span class="hl kwd">min_element</span><span class="hl opt">(</span>times<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> times<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">());</span>
  <span class="hl kwc">auto</span> <span class="hl kwb">const</span> average_fixed <span class="hl opt">= (</span>times_sum <span class="hl opt">-</span> max_element <span class="hl opt">-</span> min_element<span class="hl opt">) /</span>
                             <span class="hl opt">(</span>ITERATIONS_NUM <span class="hl opt">-</span> <span class="hl num">2</span><span class="hl opt">);</span>

  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Average: &quot;</span> <span class="hl opt">&lt;&lt;</span> average <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;s, &quot;</span> 
            <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Average without max/min: &quot;</span>
            <span class="hl opt">&lt;&lt;</span> average_fixed <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;s.&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Finally, a CPU utilization graph. We see 100% spikes on each iteration.</p>

<p><img src="http://demin.ws/images/blog/multithreaded-quicksort-cpu-utilization.png" /></p>

<h3>Update</h3>

<p>There is an article from Microsort, &ldquo;<a href="http://msdn.microsoft.com/en-us/library/gg663539.aspx">Dynamic Task Parallelism</a>&rdquo;, also showing how to implement multithreaded Quicksort.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Date and time formatting in Go]]></title>
    <link href="http://demin.ws/blog/english/2012/04/27/date-and-time-formatting-in-go/"/>
    <updated>2012-04-27T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/27/date-and-time-formatting-in-go/</id>
    <content type="html"><![CDATA[<p>Often, when we need a format or a template for date or time, we usually go for something like <code>YYYY</code>, <code>MM</code>, <code>mm:ss</code>, etc). Developing the static blog engine for this blog in Go, I&rsquo;ve come across another approach &ndash; a use the real hardcoded values instead of the special symbols. For instance:</p>

<pre class="hl">
<span class="hl kwa">func</span> <span class="hl kwd">format_time</span><span class="hl opt">(</span>t time<span class="hl opt">.</span>Time<span class="hl opt">)</span> <span class="hl kwb">string</span> <span class="hl opt">{</span>
  <span class="hl kwa">return</span> t<span class="hl opt">.</span><span class="hl kwd">Format</span><span class="hl opt">(</span><span class="hl str">&quot;2006.01.02-15.04.05&quot;</span><span class="hl opt">)</span>  <span class="hl slc">// Similar to YYYY.MM.DD-hh.mm.ss</span>
<span class="hl opt">}</span>
</pre>

<p>A full list of &ldquo;magic&rdquo; values (from <a href="http://golang.org/src/pkg/time/format.go">time/format.go</a>):</p>

<pre class="hl">
stdLongMonth      <span class="hl opt">=</span> <span class="hl str">&quot;January&quot;</span>
stdMonth          <span class="hl opt">=</span> <span class="hl str">&quot;Jan&quot;</span>
stdNumMonth       <span class="hl opt">=</span> <span class="hl str">&quot;1&quot;</span>
stdZeroMonth      <span class="hl opt">=</span> <span class="hl str">&quot;01&quot;</span>
stdLongWeekDay    <span class="hl opt">=</span> <span class="hl str">&quot;Monday&quot;</span>
stdWeekDay        <span class="hl opt">=</span> <span class="hl str">&quot;Mon&quot;</span>
stdDay            <span class="hl opt">=</span> <span class="hl str">&quot;2&quot;</span>
stdUnderDay       <span class="hl opt">=</span> <span class="hl str">&quot;_2&quot;</span>
stdZeroDay        <span class="hl opt">=</span> <span class="hl str">&quot;02&quot;</span>
stdHour           <span class="hl opt">=</span> <span class="hl str">&quot;15&quot;</span>
stdHour12         <span class="hl opt">=</span> <span class="hl str">&quot;3&quot;</span>
stdZeroHour12     <span class="hl opt">=</span> <span class="hl str">&quot;03&quot;</span>
stdMinute         <span class="hl opt">=</span> <span class="hl str">&quot;4&quot;</span>
stdZeroMinute     <span class="hl opt">=</span> <span class="hl str">&quot;04&quot;</span>
stdSecond         <span class="hl opt">=</span> <span class="hl str">&quot;5&quot;</span>
stdZeroSecond     <span class="hl opt">=</span> <span class="hl str">&quot;05&quot;</span>
stdLongYear       <span class="hl opt">=</span> <span class="hl str">&quot;2006&quot;</span>
stdYear           <span class="hl opt">=</span> <span class="hl str">&quot;06&quot;</span>
stdPM             <span class="hl opt">=</span> <span class="hl str">&quot;PM&quot;</span>
stdpm             <span class="hl opt">=</span> <span class="hl str">&quot;pm&quot;</span>
stdTZ             <span class="hl opt">=</span> <span class="hl str">&quot;MST&quot;</span>
stdISO8601TZ      <span class="hl opt">=</span> <span class="hl str">&quot;Z0700&quot;</span>  <span class="hl slc">// prints Z for UTC</span>
stdISO8601ColonTZ <span class="hl opt">=</span> <span class="hl str">&quot;Z07:00&quot;</span> <span class="hl slc">// prints Z for UTC</span>
stdNumTZ          <span class="hl opt">=</span> <span class="hl str">&quot;-0700&quot;</span>  <span class="hl slc">// always numeric</span>
stdNumShortTZ     <span class="hl opt">=</span> <span class="hl str">&quot;-07&quot;</span>    <span class="hl slc">// always numeric</span>
stdNumColonTZ     <span class="hl opt">=</span> <span class="hl str">&quot;-07:00&quot;</span> <span class="hl slc">// always numeric</span>
</pre>

<p>A few examples:</p>

<pre class="hl">
ANSIC       <span class="hl opt">=</span> <span class="hl str">&quot;Mon Jan _2 15:04:05 2006&quot;</span>
UnixDate    <span class="hl opt">=</span> <span class="hl str">&quot;Mon Jan _2 15:04:05 MST 2006&quot;</span>
RubyDate    <span class="hl opt">=</span> <span class="hl str">&quot;Mon Jan 02 15:04:05 -0700 2006&quot;</span>
RFC822      <span class="hl opt">=</span> <span class="hl str">&quot;02 Jan 06 15:04 MST&quot;</span>
RFC822Z     <span class="hl opt">=</span> <span class="hl str">&quot;02 Jan 06 15:04 -0700&quot;</span> <span class="hl slc">// RFC822 with numeric zone</span>
RFC850      <span class="hl opt">=</span> <span class="hl str">&quot;Monday, 02-Jan-06 15:04:05 MST&quot;</span>
RFC1123     <span class="hl opt">=</span> <span class="hl str">&quot;Mon, 02 Jan 2006 15:04:05 MST&quot;</span>
RFC1123Z    <span class="hl opt">=</span> <span class="hl str">&quot;Mon, 02 Jan 2006 15:04:05 -0700&quot;</span> <span class="hl slc">// RFC1123 with numeric zone</span>
RFC3339     <span class="hl opt">=</span> <span class="hl str">&quot;2006-01-02T15:04:05Z07:00&quot;</span>
RFC3339Nano <span class="hl opt">=</span> <span class="hl str">&quot;2006-01-02T15:04:05.999999999Z07:00&quot;</span>
Kitchen     <span class="hl opt">=</span> <span class="hl str">&quot;3:04PM&quot;</span>
<span class="hl slc">// Handy time stamps.</span>
Stamp      <span class="hl opt">=</span> <span class="hl str">&quot;Jan _2 15:04:05&quot;</span>
StampMilli <span class="hl opt">=</span> <span class="hl str">&quot;Jan _2 15:04:05.000&quot;</span>
StampMicro <span class="hl opt">=</span> <span class="hl str">&quot;Jan _2 15:04:05.000000&quot;</span>
StampNano  <span class="hl opt">=</span> <span class="hl str">&quot;Jan _2 15:04:05.000000000&quot;</span>
</pre>

<p>I didn&rsquo;t see such approach before, I&rsquo;ve found it clearer and more logical.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What is faster: std::endl vs &#34;\n&#34;?]]></title>
    <link href="http://demin.ws/blog/english/2012/04/25/endl-vs-new-line/"/>
    <updated>2012-04-25T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/25/endl-vs-new-line/</id>
    <content type="html"><![CDATA[<p>To this day I believed, that <code>std::endl</code> is always better that <code>\n</code> in C++ streams (portability, for instance). It turns out that no.</p>

<p>A code with <code>std::endl</code>:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;string&gt;</span>
<span class="hl ppc">#include &lt;iostream&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">1000000</span><span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>string <span class="hl kwd">s</span><span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">,</span> <span class="hl str">'x'</span><span class="hl opt">);</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> s <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Compile and run:</p>

<pre><code>clang++ -o endl -O3 endl.cpp &amp;&amp; time ./endl &gt;rubbish

real    0m4.518s
user    0m1.080s
sys 0m3.311s
</code></pre>

<p>A code with <code>\n</code>:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;string&gt;</span>
<span class="hl ppc">#include &lt;iostream&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">1000000</span><span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>string <span class="hl kwd">s</span><span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">,</span> <span class="hl str">'x'</span><span class="hl opt">);</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> s <span class="hl opt">&lt;&lt;</span> <span class="hl str">'</span><span class="hl esc">\n</span><span class="hl str">'</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Compile and run:</p>

<pre><code>clang++ -o endl -O3 endl.cpp &amp;&amp; time ./endl &gt;rubbish

real    0m0.263s
user    0m0.236s
sys 0m0.008s    
</code></pre>

<p>The difference is obvious. The second one is much faster.</p>

<p><code>std::endl</code> always <code>flush</code>es the stream. In turn, <code>\n</code> simply puts a new line character to the stream, and in most cases this is exactly what we need. And <code>std::flush</code>, if necessary, can be called afterwards, once, explicitly.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Josuttis N., &#34;The C++ Standard Library: A Tutorial and Reference&#34;, 2nd edition]]></title>
    <link href="http://demin.ws/blog/english/2012/04/25/cpp-standard-library-2nd-edition/"/>
    <updated>2012-04-25T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/25/cpp-standard-library-2nd-edition/</id>
    <content type="html"><![CDATA[<p>Nicolai M. Josuttis, &ldquo;The C++ Standard Library: A Tutorial and Reference&rdquo;, 2nd edition</p>

<p><a href="http://www.amazon.co.uk/gp/product/0321623215/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=0321623215"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=0321623215&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=0321623215" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>Yesterday the book had arrived. I wanted to write a proper detailed review, but realised it doesn&rsquo;t make sense at all. This is a must have book if you&rsquo;re interested in the new C++ 2011. The book is an exhaustive reference with a lot of examples of the new STL and the language itself. In my view, this is the first big C++ 2011 book at the moment.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Live programming in circa]]></title>
    <link href="http://demin.ws/blog/english/2012/04/24/live-programming-in-circa/"/>
    <updated>2012-04-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/24/live-programming-in-circa/</id>
    <content type="html"><![CDATA[<p>Remember that amazing presentation from Bret Victor &ldquo;<a href="http://vimeo.com/36579366">Inventing on Principle</a>&rdquo;?</p>

<p>It is called live coding. What You Code Is What You See - WYCIWYS.</p>

<p>I thought his demos were hardcoded. But it turns out, there is a real programming language allowing such crazy things in runtime. Check out a short video:</p>

<iframe src="http://player.vimeo.com/video/23773218" width="400" height="300" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

<p>The language is called <a href="http://circa-lang.org">circa</a>. Currently it is alpha. On my amateurish opinion in the game development, it is very convenient for experiements with gameplay, at least for 2D games.</p>

<p>Here is an interesting article from the author about <a href="http://circa-lang.org/about/inlined_state.html">preserving the runtime state</a> on live code changes.</p>

<p><a href="http://livecoding.co.uk/doku.php/videos">A collection is videos with more live coding</a>.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Test: Give, When, Then]]></title>
    <link href="http://demin.ws/blog/english/2012/04/23/test-given-when-then/"/>
    <updated>2012-04-23T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/23/test-given-when-then/</id>
    <content type="html"><![CDATA[<p>After Kevlin Henney&rsquo;s training I&rsquo;d realised that an unavailability of a specific unit testing framework in C++ isn’t an excuse to not doing TDD. Just a simple <code>assert</code> macro is enough for unit testing.</p>

<p>For instance, a mini project having one file, and you don’t want to drag the Google Test or cmockery in. I usually do something like this:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;cassert&gt;</span>

<span class="hl kwb">void</span> <span class="hl kwd">foo</span><span class="hl opt">(...) {</span>
  <span class="hl slc">// something</span>
<span class="hl opt">}</span>

<span class="hl opt">...</span>

<span class="hl ppc">#ifdef UNIT_TESTING</span>
<span class="hl kwb">void</span> <span class="hl kwd">Test_for_a_particular_use_case</span><span class="hl opt">() {</span>
  <span class="hl slc">// Initialization</span>
  <span class="hl opt">...</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>condition_1<span class="hl opt">);</span>
  <span class="hl opt">...</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>condition_N<span class="hl opt">);</span>
<span class="hl opt">}</span>
<span class="hl opt">...</span>
<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(...) {</span>
  <span class="hl kwd">Test_for_a_particular_use_case</span><span class="hl opt">();</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> “All tests passed<span class="hl opt">.</span>” <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl ppc">#else</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(...) {</span>
  <span class="hl slc">// a proper main</span>
<span class="hl opt">}</span>

<span class="hl ppc">#endif</span>
</pre>

<p>Of course, you still can forget to add your test to <code>main()</code>, and it seems working, but the test simply doesn’t run.</p>

<p>But! All this is trifles in comparison with the advantages which the tests provide.</p>

<h3>P.S.</h3>

<p>By the way, I’ve noticed an interesting habit: when I’m writing a function working with files, I always create two:</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">FunctionDoingSomethingFromStream</span><span class="hl opt">(</span>std<span class="hl opt">::</span>istream<span class="hl opt">*</span> is<span class="hl opt">) {</span>
  <span class="hl opt">...</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">FunctionDoingSomethingFromFile</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> filename<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>ifstream <span class="hl kwd">is</span><span class="hl opt">(</span>filename<span class="hl opt">);</span>
  <span class="hl kwa">return</span> <span class="hl kwd">FunctionDoingSomethingFromStream</span><span class="hl opt">(&amp;</span>is<span class="hl opt">);</span>  
<span class="hl opt">}</span>
</pre>

<p>The first function is perfect for testing because you can pass in a mocked <code>std::istringstream</code>. The second doesn’t really need to be tested due to its simplicity. It may be tested though in QA, but not in unit testing during within build.</p>

<p>There is another interesting trick from Kevlin Henny. Usually a subject of testing (a class or a function) has a pre-condition and a post-condition. It’s worth to highlight these stages in comments by “Given”, “When” and “Then” words. For example:</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">Test_for_a_particular_use_case_to_check</span><span class="hl opt">() {</span>
  <span class="hl slc">// Given:</span>
  ClassToTest a<span class="hl opt">;</span>
  <span class="hl slc">// When:</span>
  a<span class="hl opt">.</span><span class="hl kwd">do_this</span><span class="hl opt">(...);</span>
  a<span class="hl opt">.</span><span class="hl kwd">do_that</span><span class="hl opt">(...);</span>
  a<span class="hl opt">.</span><span class="hl kwd">setup_something</span><span class="hl opt">(...);</span>
  <span class="hl slc">// Then:</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>condition_1<span class="hl opt">);</span>
  <span class="hl opt">...</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>condition_N<span class="hl opt">);</span>
<span class="hl opt">}</span>
</pre>

<p>Such explicit split enforces proper test structuring: without loop and branches, and testing for only one scenario (for another scenario it will be another test).</p>

<p>&#9632;</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[vcprompt - information about SCM in the command line prompt]]></title>
    <link href="http://demin.ws/blog/english/2012/04/23/vcprompt/"/>
    <updated>2012-04-23T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/23/vcprompt/</id>
    <content type="html"><![CDATA[<p>Sometimes, working with git, you may forget which branch you are currently in. In this case <a href="https://github.com/djl/vcprompt">vcprompt</a> can help. It allows to see right in the command line prompt various information about your current repository, for example, a current branch name, or a fact of having changed or untracked files.</p>

<p>For example, my <code>PS1</code> variable is:</p>

<pre><code>\W `vcprompt -f &quot;%m%u %s:%b&quot;`\$
</code></pre>

<p>making the prompt in <code>bash</code> to be like this:</p>

<pre><code>_engine +? git:master$
</code></pre>

<p>It says that the current directory is <code>_engine</code> and there is a git repository here, the current branch is <code>master</code>, and there are changed (<code>+</code>) and also untracked files (<code>?</code>). If there is no repo in the current repository, the prompt will be normal.</p>

<p>vcprompt supports not only git, but bzr, cvs, darcs, fossil, hg, svn.</p>

<p>It requires Python, and is also hardly usable on Windows.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Goblog: A handmade static blog engine in Go running this blog]]></title>
    <link href="http://demin.ws/blog/english/2012/04/23/static-blog-engine-goblog/"/>
    <updated>2012-04-23T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/23/static-blog-engine-goblog/</id>
    <content type="html"><![CDATA[<p>I love writing, playing with examples, testing, thinking. But I don&rsquo;t like fiddling with formatting, uploading pictures, composing, etc.</p>

<p>Because of laziness I began using Blogspot. It gives plenty of bells and whistles: templates, widgets, instant indexing by Google, statistics, even comments become to be a tree at some point. Everything seems to be great, but alas, the online Blogspot editor isn&rsquo;t designed to create programmer posts. When it requires to insert a code or a table, sufferings begin. For example, for my another blog, not about programming, called &ldquo;<a href="http://english-eggs.blogspot.com">Boiled eggs, sir!</a>&rdquo;, &ldquo;the capabilities&rdquo; of Blogspot are more or less enough.</p>

<p>I want to keep sources of the posts in a nice and clear format, not spoiled by HTML. It turned out that the posts sources are spread across my computer here and there, sometimes in multiple copies. You begin creating a post simply in an editor only formatting paragraphs, without links and images, and eventually you save the final version. Then you compose HTML during that the post body maybe also changed. Thus I&rsquo;m lazy to update the original, non-HTML version, so finally, only the spoiled by HTML version remains up to date. But this is not the end of the store still. Often after publishing you spot on a typo, go to the Blogspot online editor and fix it right on the page. Again, that very first document and its local, prior to uploading the HTML version, don&rsquo;t have all the corrections. Ultimately, only the online edition in Blogspot is relevant. Of course, it is possible to export the entire blog from Blogspot (maybe even automatically, on regular basis) and back them up, but again, everything will be in the HTML format.</p>

<p>Some time ago I began using <a href="http://docutils.sourceforge.net/rst.html">ReST</a>. The life had become a bit easier. ReST allows to write text in the more or less predictable layout (paragraphs, links, code), and then HTML is generated from it, and then later pasted (again, manually) into the Blogspot editor. All my attempts using <a href="http://code.google.com/p/googlecl/">Google Command Line</a>, in fact, failed. The problem of the outdated original documents (after online fixed) still stood. Furthermore, ReST didn&rsquo;t solve the problem with pictures. I had to upload them somewhere in advance to do the a proper local preview.</p>

<p>I almost cannot explain why, but the idea of dynamic blog engines like WordPress scared me. Use of a database to keep posts seemed to me unnecessarily complicated.</p>

<p>I was almost ready to choose an intermediate solution &ndash; <a href="http://www.dokuwiki.org/dokuwiki">Doku Wiki</a>, for example, <a href="http://vak.ru/doku.php/proj">vak.ru</a>. This engine is dynamic, but it stores the posts as files. Plus, it supports versioning. Doku can be used as the engine for the whole site, not only the blog. Though its design is unsightly, but pictures and other arbitrary attachments are handled by Doku automatically.</p>

<p>There was another option, which I almost signed up for &ndash; <a href="http://www.tiddlywiki.com/">TiddlyWiki</a>. TiddlyWiki is my favorite tool on Windows for notes. Why only Windows? Because on Mac I simply use regular plain text files in Documents or Desktop, and <a href="http://en.wikipedia.org/wiki/Spotlight_(software)">Spotlight</a> provides the instant search. Therefore on Mac the instant search, the killer feature of TiddlyWiki, didn&rsquo;t make any sense. But I digressed.</p>

<p>It turns out, there are TiddlyWiki fans which converted it to a blog engine, a static-dynamic mutant.</p>

<p>For instance, here is an example of a blog running TiddlyWiki &ndash; <a href="http://rsignell.tiddlyspot.com/">Rich Signell&rsquo;s Work Log</a>. Esoterics, in my opinion. It isn&rsquo;t quite clear even how to implement comments, at least Disqus. But surprisingly, there is public hosting based on Tiddly &ndash; <a href="http://tiddlyspot.com/">tiddlyspot</a>.</p>

<p>Finally, I had got hooked on purely static blog engines. The charm of it is that such blog can be hosted anywhere. Neither database nor even no server scripting is required. But further &ndash; it is more. GitHub and Heroku provide not only free hosting but also git as the CMS.</p>

<p>For example, there is a static blog engine called <a href="http://jekyllrb.com/">Jekyll</a>. In Jekyll posts are created in Markdown or Textile, therefore the formatting issue is solved. No ugly HTML anymore. In fact, the engine can drive the entire website, not only the blog, plus some source files are deployed as a blog.</p>

<p>The comments, as the main dynamics in blogs, can be implemented via, for instance, <a href="http://disqus.com">Disqus</a>. By the way, there is a quite popular pure zen approach to the comments &ndash; static ones (to me, such word combination is the oxymoron in the first place). With the static comments there is a comment entering form somewhere on the page along with the <em>statically</em> rendered existing comments. You enter a comment and submit. Then it gets sent to the blog owner. He or she approves (or rejects) it, clicks somewhere, and the comment is placed to a file. Then the blog is re-compiled and finally deployed to public. Obviously, it is far from real-time, which is the heart of commenting, in my humble opinion.</p>

<p>I very much appreciate discussion, and such approach is not for me. I use Disqus. By the way, all the comments can be easily exported from Disqus, and, for instance, converted to a static form.</p>

<p>But let&rsquo;s go back to Jekyll. GitHub directly supports it (its author is the GitHub co-founder) and can render Jekyll projects for you (of course, you still can render locally). You simply <code>git push</code> your stuff to GitHub, and after a moment it becomes visible in GitHub Pages.</p>

<p>Heroku works slightly different. Heroku hosts Ruby, therefore a Heroku project is a bunch of pages, plus a mini web server application serving them. Looks a bit scary, but such server in Ruby is very simple:</p>

<pre class="hl">
<span class="hl kwa">require</span> <span class="hl str">'bundler/setup'</span>
<span class="hl kwa">require</span> <span class="hl str">'sinatra/base'</span>

<span class="hl kwa">class</span> SinatraStaticServer <span class="hl opt">&lt;</span> Sinatra<span class="hl opt">:</span><span class="hl kwc">:Base</span>  

  <span class="hl kwd">get</span><span class="hl opt">(</span><span class="hl kwc">/.+/</span>) <span class="hl kwa">do</span>
    <span class="hl kwd">send_sinatra_file</span><span class="hl opt">(</span>request<span class="hl opt">.</span>path) <span class="hl esc">{404}</span>
  <span class="hl kwa">end</span>

  <span class="hl kwa">def</span> <span class="hl kwd">send_sinatra_file</span><span class="hl opt">(</span>path<span class="hl opt">, &amp;</span>missing_file_block)
    file_path <span class="hl opt">=</span> File<span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>File<span class="hl opt">.</span><span class="hl kwd">dirname</span><span class="hl opt">(</span>__FILE__)<span class="hl opt">,</span> <span class="hl str">'public'</span><span class="hl opt">,</span>  path)
    file_path <span class="hl opt">=</span> File<span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>file_path<span class="hl opt">,</span> <span class="hl str">'index.html'</span>) <span class="hl kwa">unless</span> file_path <span class="hl opt">=</span>~ <span class="hl kwc">/\.[a-z]+$/</span>i  
    File<span class="hl opt">.</span>exist<span class="hl opt">?(</span>file_path) <span class="hl opt">?</span> <span class="hl kwd">send_file</span><span class="hl opt">(</span>file_path) <span class="hl opt">:</span> missing_file_block<span class="hl opt">.</span>call
  <span class="hl kwa">end</span>
<span class="hl kwa">end</span>

run SinatraStaticServer
</pre>

<p>As strangely enough it sounds, Heroku as blog hosting is simpler than GitHub. Additionally, your git repository on Heroku remains private, whereas on GitHub by default it is public. I don&rsquo;t see any problems with it though, because it is all available anyway to everybody via the web site, but some people prefer keeping blog guts or bits of unfinished work in private.</p>

<p>Also, both GitHub Pages and Heroku support a proper second level domain if you have one.</p>

<p>Well, I had chosen Jekyll and Heroku hosting. Alas, vanilla Jekyll has no HTML templates or themes, and you have to design it. If you&rsquo;re lazy, you can try <a href="http://octopress.org/">Octopress</a>.</p>

<p>Octopress is a static blog engine based on Jekyll. &ldquo;Based&rdquo; means, this is Jekyll plus a bunch of useful plugins, a very nice HTML5-compatible theme, and scripts helping in deployment to GitHub Pages and Heroku.</p>

<p>So, I had installed Octopress, tried a couple of posts, rendered locally, deployed to GutHub and Heroky. Everything was amazing, I had began the most tedious part &ndash; converting posts from lovely Blogspot. In fact, it was almost pure manual cut-and-paste work. Three weeks of struggle, and my poor three hundred posts were done.</p>

<p>Everything was ready to launch my nice or shiny static blog. But here I had met my main disappointment. The precious Jekyll, written in Ruby, rendered my hundred posts (attention!) 15 minutes (on Mac Air). As you can understand, at the beginning I had to rebuild a hundred of times &ndash; design changes, formatting etc. So, 15 minutes wasn&rsquo;t even close to any acceptable time, at all.</p>

<p>At random, I found a bottle neck in Jekyll/Octopress &ndash; the majority of those 15 minutes were spent generating the RSS file, <code>atom.xml</code>. For some reason, in original templates, that RSS filed included only the latest twenty posts. But my blog is small, and I included all posts there. It had caused that 15 minutes build.</p>

<p>All this seemed to me an absurdity (at all my love to Ruby). After some analysis (at that time I began to understand how Jekyll worked, more or less) and unwillingness to fix Jekyll trying to speed it up, I asked a question &ndash; what if I develop the static engine by myself? using Jekyll&rsquo;s principles? After all it is only work with files, strings, and templates. Besides, I wanted to blog in two languages, but Jekyll didn&rsquo;t support that. Having my own engine seemed to be a very cool idea because I would free to implement exactly that I wanted.</p>

<p>Instrumentation? As a real man in C++/boost? Perhaps. I suspect it would work very fast, but it is boring. I&rsquo;d chosen Go. It is natively compiled, has simplified memory management (thanks to the garbage collector), regular expressions, maps, templates, <a href="https://github.com/russross/blackfriday">Markdown library</a>. Everything, except the later, is out of the box. There should not be any performance issues. Here just the first release of Go had been arrived, now installation on both Windows and Mac became much easier.</p>

<p>So, after three nights, my own wheel had been made &ndash; <a href="https://github.com/begoon/begoon.github.com">Goblog</a>. The project is fully open. The web site and its source are in the same repository.</p>

<h2>Architecture</h2>

<p>There are two main locations: a project and a target web site/blog. The first contains source files. In the process of assembly the project files are copied to the target directory preserving the relative directory structure. By default, the files are copied &ldquo;as is&rdquo;, as binaries. If a file has one of the following extensions: <code>html</code>, <code>xml</code>, or <code>js</code>, it is processed by <a href="http://weekly.golang.org/pkg/text/template/">Go template library</a>. Files with the <code>markdown</code> extension are also processed by the <a href="https://github.com/russross/blackfriday">Markdown library</a>.</p>

<p>Directories:</p>

<ul>
<li><code>&lt;root&gt;</code> &ndash; Here is the compiled/built web site as it is visible at <a href="http://demin.ws/">http://demin.ws/</a>.</li>
<li><code>&lt;root&gt;/_engine</code> &ndash; This is the project: source files and the blog generator.</li>
</ul>

<p>Subdirectories and files in <code>_engine</code>:</p>

<ul>
<li><p><code>_includes</code> &ndash; Include files available by <code>&#123;{include &ldquo;filename&rdquo;}}</code> macro.</p></li>

<li><p><code>_layouts</code> &ndash; Layouts (see below).</p></li>

<li><p><code>_site</code> &ndash; Actually, the source directories and files. This directory is the root of a future site. Files from here are copied to the target directory. Some files are processed by templates.</p></li>

<li><p><code>_posts</code> &ndash; Posts. These files are process specially. Besides templates, they are renamed according to the blog structure, where the date is included to URL: <code>domain/blog/year/month/day/post-title</code>.</p></li>
</ul>

<p>The posts are Markdown files having a special preamble and name. These files are deployed to a separate directory, <code>/blog</code>. The post meta information is collected and propagated to the template place holders. Also the post sources are used to <a href="https://github.com/begoon/begoon.github.com/blob/9f088a83e86e54112696dd3954681b0450f40d91/_engine/main.go#L601">build the reverted index</a> of search.</p>

<h2>Layouts</h2>

<p>The concept of layouts is grabbed from Jekyll. If a post or a page has the <code>layout</code> attribute in its preamble (<a href="https://raw.github.com/begoon/begoon.github.com/master/_engine/_posts/english/2009-01-24-why-i-have-started-this-blog.markdown">for example</a>), a layout of the given name is loaded (from <code>_layouts</code> directory), the post body is put to the <code>Page.child</code> place holder, the layout is rendered, and the result becomes the final HTML page of the post. This is incredibly useful for similar pages, like posts. The layouts can be nested.</p>

<h2>Generator</h2>

<p>Now, the generator &ndash; <a href="https://github.com/begoon/begoon.github.com/blob/master/_engine/main.go">main.go</a>.</p>

<p>To build the blog, I go to the <code>_engine</code> directory and do:</p>

<pre><code>make
</code></pre>

<p>It prints roughly the following:</p>

<pre><code>_engine$ make
gofmt -w=true -tabs=false -tabwidth=2 main.go
go run main.go 
Go static blog generator  Copyright (C) 2012 by Alexander Demin
Words in russian index: 18452
Words in english index: 3563
15.672979s
Processed 344 posts.
</code></pre>

<p>If no errors, in the root directory (in <code>..</code> with regard to <code>_engine</code>) the compiled files should be created, ready for deployment. On my Mac Air the build takes 15 seconds (hello, Jekyll/Octopress and goodbye). The entire project is under git, so it is clear anytime which files are new, deleted, or changed.</p>

<p>Then the built site can be viewed locally (see below).</p>

<p>When you are happy with changes, let&rsquo;s add and submit them (the sources from <code>_site/</code> along with the assembled files) locally:</p>

<pre><code>git add ../*
git commit -m &quot;New post about ...&quot;
</code></pre>

<p>At last, let&rsquo;s deploy to GitHub:</p>

<pre><code>git push
</code></pre>

<p>Almost immediately the files become visible at <a href="http://demin.ws/">demin.ws</a>.</p>

<p>In <a href="https://github.com/begoon/begoon.github.com/blob/master/_engine/Makefile">Makefile</a> there is a couple of extra commands making life easier.</p>

<h2>Local testing</h2>

<p>To check/preview the site locally I temporarily add <code>127.0.0.1 demin.ws</code> to <code>/etc/hosts</code> and launch a mini web server. Remember, how it looked in Ruby? Tiny, right? Check out this:</p>

<pre class="hl">
<span class="hl kwa">package</span> main
<span class="hl kwa">import</span> <span class="hl str">&quot;net/http&quot;</span>
<span class="hl kwa">func</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwb">panic</span><span class="hl opt">(</span>http<span class="hl opt">.</span><span class="hl kwd">ListenAndServe</span><span class="hl opt">(</span><span class="hl str">&quot;:80&quot;</span><span class="hl opt">,</span> http<span class="hl opt">.</span><span class="hl kwd">FileServer</span><span class="hl opt">(</span>http<span class="hl opt">.</span><span class="hl kwd">Dir</span><span class="hl opt">(</span><span class="hl str">&quot;..&quot;</span><span class="hl opt">))))</span>
<span class="hl opt">}</span>
</pre>

<p>Nice? Now run it:</p>

<pre><code>go run server.go&amp;
</code></pre>

<p>It may require <code>sudo</code> to acquire the port 80.</p>

<p>Generally speaking, there is no need touching <code>/etc/hosts</code>, just use <code>localhost:80</code>. Only for checking the RSS file, <code>atom.xml</code>, having full URLs, you have to fiddle with hosts.</p>

<h2>Syntax highlighting</h2>

<p>As a Markdown extension I have a special tag for blocks of code:</p>

<pre><code>{% codeblock lang:xxx %}
...
{% endcodeblock %}
</code></pre>

<p>I inherited the idea from Octopress. Markdown library already has the syntax for code:</p>

<pre><code>``` xxx
...
```
</code></pre>

<p>where <code>xxx</code> is a language.</p>

<p>My own tag aims to add additional attributes easier, for example, turning on the line number, tabs conversion, etc.</p>

<p>Then I had to decide how to highlight the syntax. I tried a couple of online libraries, which color right on the page, but all of them had minor glitches here and there, and I went for static coloring.</p>

<p>The first, which came to my mind, was <a href="http://pygments.org/">pygments</a>. It seemed okay, but thanks to the Python, it worked really slow. The total built time had increased from 15 seconds to two minutes. The main time was spent for a code coloring. I started thinking about a cache for the already highlighted code and similar nonsense, but after a little research the problem was solved radically.</p>

<p>I just needed a colorizer, implemented in a language suitable for this problem. I found two options: <a href="http://www.gnu.org/software/src-highlite/">GNU Source-highlight</a> and <a href="http://www.andre-simon.de/doku/highlight/en/highlight.html">Highlight</a>. Both are in C++, the both worked almost instantly.</p>

<p>For example, a guy <a href="http://petereisentraut.blogspot.co.uk/2009/07/adding-color-to-console-pygments-vs.html">compared pygments vs syntax-highlight</a>.</p>

<p>I liked Highlight because it supports more languages (for example, the first one even didn&rsquo;t support Go). After migration to Highlight, the built time came to normal, ~15-16 seconds, and I was satisfied.</p>

<p>The colorizer is invoked from the regular expression callback parsing the <code>{% codeblock %}</code> tag (function <a href="https://github.com/begoon/begoon.github.com/blob/9f088a83e86e54112696dd3954681b0450f40d91/_engine/main.go#L656">highlight()</a>).</p>

<h2>Markdown editors</h2>

<p>There are plenty of editors having Markdown preview. I use <a href="http://markdownpad.com/">MarkdownPad</a> for Windows and <a href="http://markedapp.com/">Marked</a> on Mac.</p>

<h2>Tag (categories)</h2>

<p>At the moment I have decided not to use tags at all. Based on a personal experience, I have realised that I never use tag neither in my blog nor in others. Besides, views on the post categorization changes over time, and at times you have to maintain a completely outdated tag just for the sake of uniformity. For example, what is the point of the <code>c++</code> tag in my blog? Who on Earth even used it?</p>

<p>But the minimalism isn&rsquo;t a way to make life more complicated. On the contrary, I search in my old posts all the time. With Blogspot I went to the front page and used &#8984;-F (sorry, CTRL-F) to search across the post titles. Exactly for this purpose I started placing almost all informative posts into the right column on the front page.</p>

<p>In the new blog everything &ldquo;works&rdquo; similar with the post catalog on the front page. During the migration I had improved some titles to be more informative for search.</p>

<p>But! All of this doen&rsquo;t matter anymore because of the <a href="http://demin.ws/blog/english/2012/04/10/search-in-this-blog/">fully functional context search capability</a> in the new blog.</p>

<h2>Sanity checks</h2>

<p>One of annoying inconveniences of Jekyll is that it never checks anything in the content. But I passed though it fully converting posts from Blogspot: broken links, missing quotes, bad dates and so on. That&rsquo;s why the Goblog checks everything &ndash; formats, links, overall semantics, and it stops the build in the case of an error. When I added the <a href="https://github.com/begoon/begoon.github.com/blob/9f088a83e86e54112696dd3954681b0450f40d91/_engine/main.go#L581">check_links()</a> function, I had found a bunch of dead links.</p>

<h2>Two languages</h2>

<p>There was another issue with Jekyll &ndash; an absence of bilingualism. I want at least two languages in the blog, bit I didn&rsquo;t want to hard code the &ldquo;transparent&rdquo; support of Russian and English. So, I added the concept of the language to each post (or a file), and the language attribute is propagated to templates. Goblog doesn&rsquo;t know about particular languages, but it allows to figure it out in templates.</p>

<p>For example, the <a href="https://github.com/begoon/begoon.github.com/blob/master/_engine/_site/index.html">front page in Russian</a> and the <a href="https://github.com/begoon/begoon.github.com/blob/master/_engine/_site/english/index.html">front page in English</a>.</p>

<h2>Minor issues</h2>

<p>I don&rsquo;t like web programming: javascript, css, html, or web design, which I cannot do at all. But I had to do it for Goblog (Octopress was much easier in this). I based my design on the <a href="http://tom.preston-werner.com/">Jekyll&rsquo;s author site</a>. The design is very simple. Besides, many people read the blog via RSS anyway and go the blog web site for commenting only. Hence, I need the properly working RSS feed and the post page providing comfortable reading, without fancy fonts and weird formatting.</p>

<h2>Conclusion</h2>

<p>Do you think, I&rsquo;ll start convincing you to use my engine? Not at all. I tried to make it flexible and not hard coded specifically to this blog, but I had to migrate my old posts from Blogspot and comments, support two languages etc. At the result there are a couple of places still hard coded (especially in the area of Disqus links).</p>

<p>I can only recommend trying to implement the personal blog engine by yourself. Why? First, it usually takes a few nights only. Second, you will implement the only required bared minimum without complicated and unnecessary bell and whistles. Third, it is fun.</p>

<p>&#9632;</p>

<p>Related links:</p>

<ul>
<li><a href="http://www.gnu.org/software/src-highlite/">GNU Source-highlight</a></li>
<li><a href="http://www.andre-simon.de/doku/highlight/en/highlight.html">Highlight</a></li>
<li><a href="http://petereisentraut.blogspot.co.uk/2009/07/adding-color-to-console-pygments-vs.html">Adding Color to the Console: Pygments vs. Source-highlight</a></li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Feuer A., &#34;The C puzzle book&#34;]]></title>
    <link href="http://demin.ws/blog/english/2012/04/18/c-puzzle-book/"/>
    <updated>2012-04-18T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/18/c-puzzle-book/</id>
    <content type="html"><![CDATA[<p>Feuer A., &ldquo;The C puzzle book&rdquo;</p>

<p><a href="http://www.amazon.co.uk/gp/product/0201604612/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=0201604612"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=0201604612&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=0201604612" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>The first edition of this book was in 1982. Old code in C, which was considered to be &ldquo;good&rdquo; in the past, today quite often doesn&rsquo;t stand up to criticism (even though its criticising is a pointless exercise), but it&rsquo;s worth to study.</p>

<p>I was extremely curious to have a look at puzzles in C created in eighteenth. So, fasten your seat belts. If The Hell in C exists, this is it. I&rsquo;ve given a few &ldquo;problems&rdquo; from this book.</p>

<h2>Pointers</h2>

<p><img src="http://demin.ws/images/blog/c-puzzle-book/pointers-and-arrays-pointer-stew.png" alt="" />
</p>

<h2>Preprocessor</h2>

<p><img src="http://demin.ws/images/blog/c-puzzle-book/preprocessor-caution-pays.png" alt="" />
</p>

<h2>Storage classes</h2>

<p><img src="http://demin.ws/images/blog/c-puzzle-book/storage-classes-files.png" alt="" />
</p>

<p>For me, these snippets are obvious candidates for <a href="http://www.ioccc.org">Obfuscated C Code Context</a>. When have to deal with such code in real life, switching to another reality is the the best solution.</p>

<p>After skimming the book to the end (they give the solutions there), you begin to understand its usefulness. Without seeing bad code, it&rsquo;s difficult to recognize the good one.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Peter van der Linden, &#34;Expert C Programming&#34;]]></title>
    <link href="http://demin.ws/blog/english/2012/04/15/expert-c-programming/"/>
    <updated>2012-04-15T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/15/expert-c-programming/</id>
    <content type="html"><![CDATA[<p>&ldquo;Expert C Programming&rdquo;, Peter van der Linden</p>

<p><a href="http://www.amazon.co.uk/gp/product/0131774298/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=0131774298"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=0131774298&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=0131774298" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>Just have come across this book in Twitter. A simple search gives plenty of options to read it.</p>

<p>I wouldn&rsquo;t buy it for myself because for a more or less experienced programmer it doesn&rsquo;t give anything new. But if you have a hour or two, it makes sense, for a tea or a coffee, to browse and refresh in memory various quirks of pointers, memory models (thanks to the weird segmentation inherited from 8086 and 80286), ABI, peculiarities of linking in UNIX and Windows, and interesting facts from the history of the languagemand its editions over time.</p>

<p>This book has a little bit of everything.</p>

<p>P.S. By the way, I thought I know C much better than C++, just because the language is smaller and simpler. More over, I began programming in C much earlier. Thus I&rsquo;d taken a <a href="http://www.brainbench.com/xml/bb/common/testcenter/taketest.xml?testId=52">Brainbench C test</a> at some time, and it turned out that there are still many aspects of the language which I haven&rsquo;t come across so far.</p>

<p>Agreed, the Brainbench is only a test, in many respects far from reality, but nevertheless allowing to expand the scope of self-understanding.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to return a vector from a function: by value or by reference?]]></title>
    <link href="http://demin.ws/blog/english/2012/04/14/return-vector-by-value-or-pointer/"/>
    <updated>2012-04-14T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/14/return-vector-by-value-or-pointer/</id>
    <content type="html"><![CDATA[<p>Let&rsquo;s imagine there is a function creating a <code>vector</code>. This function needs to return this vector to the caller. What&rsquo;s the better way doing it?</p>

<p>From clarity perspective the best way is:</p>

<pre class="hl">
std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> <span class="hl kwd">create_vector</span><span class="hl opt">(</span><span class="hl kwb">const size_t</span> N<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> v<span class="hl opt">;</span>
  v<span class="hl opt">.</span><span class="hl kwd">resize</span><span class="hl opt">(</span>N<span class="hl opt">,</span> <span class="hl num">0xDEADC0DE</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> v<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Here the vector instance is being returned <em>by value</em>, which means potential deep copying of the object to the context of the caller.</p>

<p>Immediately a question raises: if the vector is huge, such deep copying can be expensive but absolutely redundant. A &ldquo;more clever&rdquo; approach could be:</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">create_vector</span><span class="hl opt">(</span><span class="hl kwb">const size_t</span> N<span class="hl opt">,</span> std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;*</span> v<span class="hl opt">) {</span>
  v<span class="hl opt">-&gt;</span><span class="hl kwd">resize</span><span class="hl opt">(</span>N<span class="hl opt">,</span> <span class="hl num">0xDEADC0DE</span><span class="hl opt">);</span>
<span class="hl opt">}</span>
</pre>

<p>Here the vector is passed by pointer which guarantees the absence of deep copying. But this code looks quite bad.</p>

<p>Let&rsquo;s compare the performance of these two approaches on the 100MB vector of ints. The compiler:</p>

<pre><code>Apple clang version 3.1 (tags/Apple/clang-318.0.45) (based on LLVM 3.1svn)
Target: x86_64-apple-darwin11.3.0
</code></pre>

<p>By value:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>

std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> <span class="hl kwd">__attribute__</span><span class="hl opt">((</span>noinline<span class="hl opt">))</span>
<span class="hl kwd">create_vector</span><span class="hl opt">(</span><span class="hl kwb">const size_t</span> N<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;by value&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> v<span class="hl opt">;</span>
  v<span class="hl opt">.</span><span class="hl kwd">resize</span><span class="hl opt">(</span>N<span class="hl opt">,</span> <span class="hl num">0xDEADC0DE</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> v<span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">size_t</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">10</span><span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl kwb">const size_t</span> N <span class="hl opt">=</span> <span class="hl num">1024</span> <span class="hl opt">*</span> <span class="hl num">1024</span> <span class="hl opt">*</span> <span class="hl num">100</span><span class="hl opt">;</span>
    std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> v <span class="hl opt">=</span> <span class="hl kwd">create_vector</span><span class="hl opt">(</span>N<span class="hl opt">);</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>v<span class="hl opt">[</span>i<span class="hl opt">] !=</span> <span class="hl num">0xDEADC0DE</span><span class="hl opt">) {</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Test is rubbish&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
      <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span> 
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Run:</p>

<pre><code>clang++ -O3 -o by_value by_value.cpp &amp;&amp; time ./by_value
</code></pre>

<p>Result:</p>

<pre><code>0m4.933s
</code></pre>

<p>Now by pointer:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>

<span class="hl kwb">void</span> <span class="hl kwd">__attribute__</span><span class="hl opt">((</span>noinline<span class="hl opt">))</span>
<span class="hl kwd">create_vector</span><span class="hl opt">(</span><span class="hl kwb">const size_t</span> N<span class="hl opt">,</span> std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;*</span> v<span class="hl opt">) {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;by pointer&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  v<span class="hl opt">-&gt;</span><span class="hl kwd">resize</span><span class="hl opt">(</span>N<span class="hl opt">,</span> <span class="hl num">0xDEADC0DE</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">size_t</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">10</span><span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl kwb">const size_t</span> N <span class="hl opt">=</span> <span class="hl num">1024</span> <span class="hl opt">*</span> <span class="hl num">1024</span> <span class="hl opt">*</span> <span class="hl num">100</span><span class="hl opt">;</span>
    std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> v<span class="hl opt">;</span>
    <span class="hl kwd">create_vector</span><span class="hl opt">(</span>N<span class="hl opt">, &amp;</span>v<span class="hl opt">);</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>v<span class="hl opt">[</span>i<span class="hl opt">] !=</span> <span class="hl num">0xDEADC0DE</span><span class="hl opt">) {</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;Test is rubbish&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
      <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
    <span class="hl opt">}</span>
  <span class="hl opt">}</span> 
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Run:</p>

<pre><code>clang++ -O3 -o by_pointer by_pointer.cpp &amp;&amp; time ./by_pointer
</code></pre>

<p>Result:</p>

<pre><code>0m4.852s
</code></pre>

<p>Time is both cases is the same. It turns out that it&rsquo;s worth to choose the first one. It looks nicer and cleaner, and it&rsquo;s as fast as &ldquo;by pointer&rdquo;.</p>

<p>There are two explanations. The first, probably the main one, is <a href="http://en.wikipedia.org/wiki/Return_value_optimization">RVO, Return value optimization</a>. In RVO the compiler figures out that the local instance of the vector is supposed to be a return value, and it allocates it directly in the caller context. So it doesn&rsquo;t need to copy it afterwards. In fact, the compiler implements passing by reference, but it does it implicitly, without spoiling the beauty of the source code. This trick works for any classes, not only from STL.</p>

<p>But the optimization isn&rsquo;t guaranteed thing, and there is one more tool. The standard STL containers are implemented such way that even on deep copying they only copy by value a small control structure, and the payload is &ldquo;moved&rdquo; by flipping pointers. It&rsquo;s small overhead, but perhaps it&rsquo;s worthwhile for the sake of preserving the code clarity.</p>

<p>Also in the context of move semantics in C++11 there won&rsquo;t be unnecessary copying at all if the class is &ldquo;properly&rdquo; implemented (which is true for STL classes).</p>

<p>Conclusion: use STL containers where ever possible and trust the compiler. Sometimes, of course, the compiler is wrong, but such cases are much less than vice versa.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Dustin Boswell, Trevor Foucher, &#34;The art of readable code&#34;]]></title>
    <link href="http://demin.ws/blog/english/2012/04/12/art-of-readable-code/"/>
    <updated>2012-04-12T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/12/art-of-readable-code/</id>
    <content type="html"><![CDATA[<p><a href="http://shop.oreilly.com/product/9780596802301.do">Dustin Boswell, Trevor Foucher, &ldquo;The art of readable code&rdquo;</a></p>

<p><img src="http://demin.ws/images/covers/english/art-of-readable-code-cover.gif" alt="" />
</p>

<p>There are plenty of books published about writing code. Thus I was skeptical after a friend of mine showed me yet another one. To my surprise, without a long introduction it went straight to the point and coined the following statements right in the first chapter:</p>

<ul>
<li>Code should be easy to understand.</li>
<li>What make code &ldquo;better&rdquo;?</li>
<li>The fundamental theorem of readability.</li>
<li>Code should be written to minimise the time it would take for someone else to understand it.</li>
<li>Is smaller always better?</li>
<li>It is better to clean and precise that to be cute.</li>
</ul>

<p>The style of the book was precise and concrete. I felt that in less than two hundred of pages it&rsquo;s quite ambitious to cover the subject of &ldquo;the art&rdquo; and decided to order the book to find out how they&rsquo;re going to do that.</p>

<p>Eventually, a few hours of reading on weekend were worthy. Though an experienced programmer will barely find any eye openings in the book, but surprisingly, this is a compact, concise and solid handout for juniors. Without too much theory, always using real examples, the authors go through many key points of writing code: how to name variables, functions and classes, how to structure the code, how to deal with efficiency-readability trade off, how to comment, where to compromise and where be a perfectionist. Again, it&rsquo;s all in less then two hundred pages. Plus they briefly touched unit testing.</p>

<p>The authors not only tell you what is good and bad, they always demonstrate &ldquo;why&rdquo; on examples gradually improving &ldquo;regular&rdquo; code. At the end they put a real example of a class counting network traffic and returning a number of bytes transferred in the last hour and day.</p>

<p>They began with a naive implementation and then worked through two more versions showing that sensitive balance between efficiency and readability. I think that even experienced developers may find this example interesting to play with.</p>

<p>To sum up, this book can fit perfectly into your team book shelf and be used as a quick reference of how-tos. Buying for yourself is questionable, because at home you&rsquo;d probably prefer something more fundamental.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Macro for unused parameters]]></title>
    <link href="http://demin.ws/blog/english/2012/04/12/macro-for-unused-parameters/"/>
    <updated>2012-04-12T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/12/macro-for-unused-parameters/</id>
    <content type="html"><![CDATA[<p>Sometimes there is a function (or a method) having declared but unused parameters. It can be legacy code or just bad design. Normally the compiler gives a warning about this.</p>

<p>It could be fixed this way:</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">f</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> <span class="hl com">/* b */</span><span class="hl opt">) {</span>
  <span class="hl opt">...</span>
<span class="hl opt">}</span>
</pre>

<p>But it looks ugly.</p>

<p>There is a better way:</p>

<pre class="hl">

<span class="hl ppc">#define DISCARD_UNUNSED_PARAMETER(x) (void)x</span>

<span class="hl kwb">void</span> <span class="hl kwd">f</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> b<span class="hl opt">) {</span>
  <span class="hl kwd">DISCARD_UNUNSED_PARAMETER</span><span class="hl opt">(</span>b<span class="hl opt">);</span>
  <span class="hl opt">...</span>
<span class="hl opt">}</span>
</pre>

<p>This macro is clear, and you can easily find all such places in the project.</p>

<p>By they way, in <code>Go</code> this situation is treated as the error, not warning. It can be annoying when you add, remove, comment out and put back things all the time, because sometimes you do have unused stuff. But eventually such approach doesn&rsquo;t allow that temporary garbage to spread and stay in the code (for example, in C++ who on Earth wants to clean up the list of included STL headers after hours of coding?)</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Asynchronous JavaScript loading]]></title>
    <link href="http://demin.ws/blog/english/2012/04/10/asynchronous-javascript-loading/"/>
    <updated>2012-04-10T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/10/asynchronous-javascript-loading/</id>
    <content type="html"><![CDATA[<p>If you look closely, the search field on the main page appears with a little delay. It becomes visible only when the search index script is fully loaded. But the script is being loaded asynchronously, in background. I googled the following example:</p>

<pre class="hl">
<span class="hl opt">&lt;</span>script language<span class="hl opt">=</span><span class="hl str">&quot;javascript&quot;</span><span class="hl opt">&gt;</span>
<span class="hl opt">(</span><span class="hl kwa">function</span><span class="hl opt">() {</span>
    <span class="hl kwa">function</span> <span class="hl kwd">async_load</span><span class="hl opt">(){</span>
        <span class="hl kwa">var</span> s <span class="hl opt">=</span> document<span class="hl opt">.</span><span class="hl kwd">createElement</span><span class="hl opt">(</span><span class="hl str">'script'</span><span class="hl opt">);</span>
        s<span class="hl opt">.</span>type <span class="hl opt">=</span> <span class="hl str">'text/javascript'</span><span class="hl opt">;</span>
        s<span class="hl opt">.</span>async <span class="hl opt">=</span> <span class="hl kwa">true</span><span class="hl opt">;</span>
        s<span class="hl opt">.</span>src <span class="hl opt">=</span> <span class="hl str">'URL of a script to load'</span><span class="hl opt">;</span>
        <span class="hl kwa">var</span> x <span class="hl opt">=</span> document<span class="hl opt">.</span><span class="hl kwd">getElementsByTagName</span><span class="hl opt">(</span><span class="hl str">'script'</span><span class="hl opt">)</span><span class="hl kwc">[0]</span><span class="hl opt">;</span>
        x<span class="hl opt">.</span>parentNode<span class="hl opt">.</span><span class="hl kwd">insertBefore</span><span class="hl opt">(</span>s<span class="hl opt">,</span> x<span class="hl opt">);</span>
    <span class="hl opt">}</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>window<span class="hl opt">.</span>attachEvent<span class="hl opt">)</span>
        window<span class="hl opt">.</span><span class="hl kwd">attachEvent</span><span class="hl opt">(</span><span class="hl str">'onload'</span><span class="hl opt">,</span> async_load<span class="hl opt">);</span>
    <span class="hl kwa">else</span>
        window<span class="hl opt">.</span><span class="hl kwd">addEventListener</span><span class="hl opt">(</span><span class="hl str">'load'</span><span class="hl opt">,</span> async_load<span class="hl opt">,</span> <span class="hl kwa">false</span><span class="hl opt">);</span>
<span class="hl opt">})();</span>
<span class="hl opt">&lt;/</span>script<span class="hl opt">&gt;</span>
</pre>

<p>They say, this is a modern HTML5 compatible method, the idiom.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to search in this blog?]]></title>
    <link href="http://demin.ws/blog/english/2012/04/10/search-in-this-blog/"/>
    <updated>2012-04-10T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/04/10/search-in-this-blog/</id>
    <content type="html"><![CDATA[<p>As noted, the posts in this blog have no tags anymore. Technically the tags are still supported, but not displayed (no individual feeds per tag, or a cloud of tag, or other kinds of navigation).</p>

<p>Why?</p>

<p>I&rsquo;ve decided to change the approach and implemented Google&rsquo;s way: Don&rsquo;t sort. Search!</p>

<p>Now, on the <a href="http://demin.ws/english/">main page</a> there is a search. The search allows to filter out the posts containing particular word(s) in the title or body.</p>

<p>The search is based on the reverted index, without sorting by relevance. The posts, containing required words, are displayed sorted by default by date.</p>

<p>Try to search for &ldquo;maximite&rdquo; or &ldquo;ruby nor&rdquo;. If there are several words are given in the search, it&rsquo;ll show the posts containing <strong>all</strong> these words. The words, which are shorter that 3 characters, are ignored.</p>

<p>For me - this is very convenient!</p>

<p>Checked in Chrome and Safari on Mac.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[NOR Machine in Ruby]]></title>
    <link href="http://demin.ws/blog/english/2012/03/07/nor-machine-in-ruby/"/>
    <updated>2012-03-07T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/03/07/nor-machine-in-ruby/</id>
    <content type="html"><![CDATA[<p>My <a href="http://pragprog.com/magazines/2012-03/the-nor-machine">article about a virtual CPU, a machine, computing only one instruction - NOR</a>, in The Pragmatic Bookshelf magazine.</p>

<p>The idea was previously described in a series of posts:</p>

<ul>
<li>NORCPU hackme challenge (part 1, part 2)</li>
<li>One-command NORCPU program hacking challenge: analysis and solutions</li>
<li>CPU executing just one operation</li>
</ul>

<p>The article discovers an implementation in Ruby. Now NOR assembly code looks almost as a regular assembler language. I was amazed how powerful Ruby is in creating domain specific languages (DSL). Mostly because it allows to omit parentheses in function calls.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Born by copy-paste]]></title>
    <link href="http://demin.ws/blog/english/2012/02/06/born-by-copy-paste/"/>
    <updated>2012-02-06T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/02/06/born-by-copy-paste/</id>
    <content type="html"><![CDATA[<p>I usually start crying when see a copy-paste with numbered variables. A probability to screw up is very high, just forget to change a single number after pasting. Here is a horrifying piece of code (don&rsquo;t you mind to spot on an incy wincy typo?)</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">Test_SplitPair</span><span class="hl opt">() {</span>
  <span class="hl kwc">typedef</span> std<span class="hl opt">::</span>pair<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>string<span class="hl opt">,</span> std<span class="hl opt">::</span>string<span class="hl opt">&gt;</span> Pair<span class="hl opt">;</span>
  <span class="hl kwa">using</span> string<span class="hl opt">::</span>SplitPair<span class="hl opt">;</span>

  <span class="hl kwb">const</span> Pair p1 <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot;&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p1<span class="hl opt">.</span>first<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p1<span class="hl opt">.</span>second<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>

  <span class="hl kwb">const</span> Pair p2 <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot;=&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p2<span class="hl opt">.</span>first<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p2<span class="hl opt">.</span>second<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>

  <span class="hl kwb">const</span> Pair p3 <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot;name=value&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p3<span class="hl opt">.</span>first <span class="hl opt">==</span> <span class="hl str">&quot;name&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p3<span class="hl opt">.</span>second <span class="hl opt">==</span> <span class="hl str">&quot;value&quot;</span><span class="hl opt">);</span>

  <span class="hl kwb">const</span> Pair p4 <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot;name = value&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p3<span class="hl opt">.</span>first <span class="hl opt">==</span> <span class="hl str">&quot;name&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p3<span class="hl opt">.</span>second <span class="hl opt">==</span> <span class="hl str">&quot;value&quot;</span><span class="hl opt">);</span>

  <span class="hl kwb">const</span> Pair p5 <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot; n ame</span>  <span class="hl esc">\t</span> <span class="hl str">=  va lue</span>  <span class="hl esc">\r\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p5<span class="hl opt">.</span>first <span class="hl opt">==</span> <span class="hl str">&quot; n ame</span>  <span class="hl esc">\t</span> <span class="hl str">&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p5<span class="hl opt">.</span>second <span class="hl opt">==</span> <span class="hl str">&quot;  va lue</span>  <span class="hl esc">\r\n</span><span class="hl str">&quot;</span><span class="hl opt">);</span>
<span class="hl opt">}</span>
</pre>

<p>Any ways to make to better? The ideal solution is to split to multiple tests. But even less radical approach works to avoid copy-paste problems:</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">Test_SplitPair</span><span class="hl opt">() {</span>
  <span class="hl kwc">typedef</span> std<span class="hl opt">::</span>pair<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>string<span class="hl opt">,</span> std<span class="hl opt">::</span>string<span class="hl opt">&gt;</span> Pair<span class="hl opt">;</span>
  <span class="hl kwa">using</span> string<span class="hl opt">::</span>SplitPair<span class="hl opt">;</span>
  <span class="hl opt">{</span>
  <span class="hl kwb">const</span> Pair p <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot;&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>first<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>second<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>
  <span class="hl opt">}</span>
  <span class="hl opt">{</span>
  <span class="hl kwb">const</span> Pair p <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot;=&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>first<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>second<span class="hl opt">.</span><span class="hl kwd">empty</span><span class="hl opt">());</span>
  <span class="hl opt">}</span>
  <span class="hl opt">{</span>
  <span class="hl kwb">const</span> Pair p <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot;name=value&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>first <span class="hl opt">==</span> <span class="hl str">&quot;name&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>second <span class="hl opt">==</span> <span class="hl str">&quot;value&quot;</span><span class="hl opt">);</span>
  <span class="hl opt">}</span>
  <span class="hl opt">{</span>
  <span class="hl kwb">const</span> Pair p <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot;name = value&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>first <span class="hl opt">==</span> <span class="hl str">&quot;name&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>second <span class="hl opt">==</span> <span class="hl str">&quot;value&quot;</span><span class="hl opt">);</span>
  <span class="hl opt">}</span>
  <span class="hl opt">{</span>
  <span class="hl kwb">const</span> Pair p <span class="hl opt">=</span> <span class="hl kwd">SplitPair</span><span class="hl opt">(</span><span class="hl str">&quot; n ame</span>  <span class="hl esc">\t</span> <span class="hl str">=  va lue</span>  <span class="hl esc">\r\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> <span class="hl str">'='</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>first <span class="hl opt">==</span> <span class="hl str">&quot; n ame</span>  <span class="hl esc">\t</span> <span class="hl str">&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">assert</span><span class="hl opt">(</span>p<span class="hl opt">.</span>second <span class="hl opt">==</span> <span class="hl str">&quot;  va lue</span>  <span class="hl esc">\r\n</span><span class="hl str">&quot;</span><span class="hl opt">);</span>
  <span class="hl opt">}</span>
<span class="hl opt">}</span>
</pre>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Bruce Tate, &#34;Seven languages in seven weeks&#34;]]></title>
    <link href="http://demin.ws/blog/english/2012/02/02/seven-languages-in-seven-weeks/"/>
    <updated>2012-02-02T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/02/02/seven-languages-in-seven-weeks/</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve finished accelerated reading of &ldquo;<a href="http://pragprog.com/book/btlang/seven-languages-in-seven-weeks">Seven languages in seven weeks</a>&rdquo; by Bruce Tate.</p>

<p><img src="http://demin.ws/images/covers/english/7-languages-in-7-weeks-cover.jpg" /></p>

<p>In my case it was &ldquo;Seven languages in seven evenings&rdquo;. For each language there is an introduction, which makes sense only if a language is brand new for you. There are also interviews with creators of the languages. One of the asked interesting questions was about what the author would like to change in the language if he could re-design it from scratch now.</p>

<p>Languages:</p>

<ul>
<li>Ruby</li>
<li>Io</li>
<li>Prolog</li>
<li>Scala</li>
<li>Erlang</li>
<li>Clojure</li>
<li>Haskell</li>
</ul>

<p>The reviews of each chapter below are my subjective views two things at once: a programming language and a material about it. Why? For familiar languages it hardly makes any sense to describe the language per se, but to note interesting distinctive features could be useful. But if a languages is a green field, it is worth describe it in general.</p>

<p><strong>Ruby</strong></p>

<p>The Ruby chapter was quite useless for me because I thoughtfully read &ldquo;<a href="http://pragprog.com/book/ruby3/programming-ruby-1-9">Programming Ruby 1.9</a>&rdquo;, and have been hooked. Ruby is an amazing scripting language. Each time when programming in Ruby I feel so delighted similar to when I tried PHP first time after Perl.</p>

<p>Ruby&rsquo;s creator, <a href="http://en.wikipedia.org/wiki/Yukihiro_Matsumoto">Yukihiro Matsumoto</a>, says in the interview, that if he could re-design Ruby today, he&rsquo;d like to change the concept of multi-threading to <a href="http://en.wikipedia.org/wiki/Actor_model">Actor</a>.</p>

<p>In short, &ldquo;Actor&rdquo; is when concurrent threads don&rsquo;t share memory and don&rsquo;t use mutex or semaphores for synchronization. Instead, they send and receive messages to each other, and messaging is provided by runtime and built-in to the languages syntax. Examples: Scala, Go, Erlang, Io.</p>

<p><strong>Io</strong></p>

<p><a href="http://iolanguage.com/">Io</a> is a very small, compact language, based on prototypes like JavaScript, where there is no distinction between classes and objects.</p>

<p>There is an interesting concurrency feature in addition to actors and coroutines (cooperative multi-threading as in <a href="http://www.lua.org/manual/5.2/manual.html#2.6">Lua</a>), called futures. &ldquo;Futures&rdquo; are similar to the actor. There the only difference is when the caller thread tries to use the result of the future, it will be blocked until the future completes and gives the result back.</p>

<p>An example from the book:</p>

<pre class="hl">
<span class="hl opt">//</span> Fire up the future<span class="hl opt">.</span>
futureResult <span class="hl opt">:=</span> <span class="hl kwb">URL</span> <span class="hl kwd">with</span><span class="hl opt">(</span><span class="hl str">&quot;http://google.com/&quot;</span><span class="hl opt">) &#64;</span>fetch
<span class="hl kwd">writeln</span><span class="hl opt">(</span><span class="hl str">&quot;Continue immediately when future is running in background.&quot;</span><span class="hl opt">)</span>
<span class="hl opt">//</span> This line will be executed immediately after spawning the future<span class="hl opt">.</span>
<span class="hl kwd">writeln</span><span class="hl opt">(</span><span class="hl str">&quot;fetched &quot;</span><span class="hl opt">,</span> futureResult size<span class="hl opt">,</span> <span class="hl str">&quot; bytes&quot;</span><span class="hl opt">)</span>
<span class="hl opt">//</span> But this line will be blocked until the future returns<span class="hl opt">.</span>
</pre>

<p><strong>Prolog</strong></p>

<p>I&rsquo;ve been gnawing this animal for years. But thanks to Erlang recently, all this functional stuff in general is now giving up for me, and monsters like Prolog or Haskell don&rsquo;t look so scary anymore.</p>

<p>It turned out that the depth of the material about Prolog has matched precisely with my level. The eight queens problem and a Sudoku solver were excellent examples for me.</p>

<p>Shortly, a program in Prolog is a pile of facts and rules. Then the Prolog runtime performs a depth-first search amongst possible results and tries to find those satisfying all the given facts and rules.</p>

<p>In fact, the Sudoku solver program is a set of variables, representing the Sudoku field, and a list of rules (summations by columns, rows and squared groups) according to the rules of Sudoku. Then Prolog performs an exhaustive search to find the values and their combinations satisfying the rules.</p>

<p>Of course, this is very much a superficial glance, but this has given me much more understanding of Prolog.</p>

<p><strong>Scala</strong></p>

<p>I will note only a few facts interesting to me.</p>

<p>Multi-threading is based on actors. After Erlang and Go you understand how good and handy it is.</p>

<p>I think that Scala has all possible bells and whistles even invented for programming languages. But sometimes it has not only good consequences.</p>

<p><strong>Erlang</strong></p>

<p>I&rsquo;m a big fan of Erlang and already read a few big books. That&rsquo;s why this book hasn&rsquo;t given to me anything new. But for novices this introduction may give quite solid view on Erlang functional approach and concurrency model.</p>

<p><strong>Clojure</strong></p>

<p>Clojure is a Lisp-based language driven by Java VM.</p>

<p>It has an interesting feature called <a href="http://en.wikipedia.org/wiki/Software_transactional_memory">STM, software transactional memory</a>. In STM a piece of code is declared to be a transaction. It is executed atomically or all the changes of variables are rolled back.</p>

<p>And finally, Haskell</p>

<p>Haskell is a taught guy. The introduction in this book is very light and minimal, just to remember the word &ldquo;Haskell&rdquo;. I read &ldquo;<a href="http://www.amazon.co.uk/Programming-Haskell-Graham-Hutton/dp/0521692695">Programming in Haskell</a>&rdquo; and currently I&rsquo;m on &ldquo;<a href="http://www.amazon.co.uk/Real-World-Haskell-Bryan-OSullivan/dp/0596514980">Real World Haskell</a>&rdquo;, that&rsquo;s why I simply skimmed the chapter in this book.</p>

<p>Okay, to sum up. This book is to be read just once, to broaden your outlook.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[My current languages]]></title>
    <link href="http://demin.ws/blog/english/2012/01/30/my-current-languages/"/>
    <updated>2012-01-30T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/01/30/my-current-languages/</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve realised recently that I like to learn new programming languages. A symptom is a very easy to spot: I have a permanent pile of books I&rsquo;m reading. Thanks for the iPad, I can have them all with me all the time and choose depending on mood. Surprisingly, but books about languages are being read first and replaced with new ones.</p>

<p>Simply wanted to share current interests.</p>

<p>Everyday work (design, planning, coding and reviews): C and C++. C++ 0x11 goes at full speed and it is worth to catch up. <a href="http://accu.org/index.php/conferences/accu_conference_2012/accu2012_schedule">ACCU 2012</a> is almost fully dedicated to the new C++.</p>

<p>For fun:</p>

<ul>
<li>scripting - Ruby</li>
<li>a server side and multi-threading: Erlang and Go</li>
<li>embedded: Lua and Scheme</li>
</ul>

<p>To &ldquo;gnaw&rdquo; in hope to write something real - Haskell and Prolog.</p>

<p>In a queue at least minimum acquaintance: Clojure. This one is more promising because it is Lisp.</p>

<p>After overall migration to Mac, I wish to try Objection-C and AppleScript in action. But what to write on Mac, in Objective-C? Of course, UI! But UI is totally out of my interests. But, Objective-C still looks tempting because of so quickly growing mobile apps market.</p>

<p>From recently touched, but not involved:</p>

<ul>
<li>Scala - a sophisticated language requiring a &ldquo;deep dive&rdquo;, and without a real suitable problem the interest is gone. Twitter is already re-written in Scala ;-).</li>
<li>Racket - an interesting Lisp based animal on steroids of a very powerful library.</li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Graph visualization in DOT]]></title>
    <link href="http://demin.ws/blog/english/2012/01/26/graph-visualization-in-dot/"/>
    <updated>2012-01-26T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/01/26/graph-visualization-in-dot/</id>
    <content type="html"><![CDATA[<p>Background. We do financial transactions processing. At some point we decided that we need profiling. We could record a path of how a transaction being passed amongst modules. There are two options - either to do static analysis or to trace the runtime.</p>

<p>So, the connections are determined and now we have to formalize and visualize them.</p>

<p>At the first glance this is not an easy task, but it turned out there is a simple and elegant solution.</p>

<p>There is a plain text language to declare graphs &ndash; <a href="http://en.wikipedia.org/wiki/DOT_language">DOT</a>. Its beauty is in ultimate simplicity. For example, a trivial graph:</p>

<pre><code>graph name {
  a -- b
  b -- c
  b -- d
}
</code></pre>

<p>Feed it to special software and get this:</p>

<p><img src="http://demin.ws/images/blog/dot-graph.png" /></p>

<p>That&rsquo;s it! The output is in SVG, ready to stick on a wall.</p>

<p>Unfortunately, the best software I&rsquo;ve found to visualize DOT is <a href="http://www.graphviz.org/">Graphviz</a>. It does pretty decent job properly processing quite sophisticated graphs, but in terms of user experience it&rsquo;s shite.</p>

<p>If anyone is interested, I&rsquo;ve shared a <a href="http://demin.ws/downloads/dot/graph.gv">real trace</a> (obviously, names are obfuscated). It gives an idea about simplicity of the source and visualization capabilities - <a href="http://demin.ws/downloads/dot/graph.png">PNG</a> and <a href="http://demin.ws/downloads/dot/graph.svg">SVG</a>.</p>

<p>Again, the graph formalization is dead simple - you only need to specify pairs of connected vertices. Also, in DOT you can describe directed graphs and extra attributes of the vertices.</p>

<p>To sum up, great technology.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Maximite - 8-bit nostalgia with a soldering iron]]></title>
    <link href="http://demin.ws/blog/english/2012/01/19/maximite-kit/"/>
    <updated>2012-01-19T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/01/19/maximite-kit/</id>
    <content type="html"><![CDATA[<p>Recently I have come across an interesting project - Maximite.</p>

<p>This is a micro-computer based on Microchip PIC32 running BASIC. It is so simple that even a novice can build it in a few hours.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0099.jpg" /></p>

<p>It is a bit more powerful than <a href="http://en.wikipedia.org/wiki/History_of_computer_hardware_in_Soviet_Bloc_countries#Radio-86RK">Radio-86RK</a> and ZX Spectrum 48. But its peripherals are fantastic: SD/FAT card, USB, VGA, PS/2, timers, RS232, I2C, SPI, PWM, ADC/DAC and individual general purpose pins.</p>

<p>If you build it on a mock up board buying parts by yourself, it will cost less then ten Australian dollars.</p>

<p>The <a href="http://geoffg.net/maximite.html">project is open-sourced</a> (schematics, PCB artwork, sources).</p>

<p>Even if quickly flip through the <a href="http://mmbasic.com/downloads.html">documentation</a>, no doubts - a list features is impressive. All peripherals are available directly from BASIC.</p>

<p>Programs and data can be stored on a SD card. If there is a &ldquo;AUTORUN.BAS&rdquo; file on the card, BASIC will run at the start.</p>

<p>I liked Maximite, but soldering is not my favourite activity. Unfortunately it is only possible to buy a kit, but not a fully assembled unit.</p>

<p>I ordered the <a href="http://www.altronics.com.au/index.asp?area=item&amp;id=K9550">kit from Altronics</a> and soon after it arrived.</p>

<p>Only the microprocessor was already soldered because soldering such form factor chip isn’t an easy task.</p>

<p>Anyway, screw it, let’s do it.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0102.jpg" /></p>

<p>Here a few parts are already in place. I’m not a complete newbie in soldering but last time I took a soldering iron in my hands was about five years ago. I had no acid for soldering, so I was crumbling rosin right to soldering points. The effect is similar to acid. The soldering iron (the one on the plate) with a sharp sting.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0103.jpg" /></p>

<p>I spent the first hour struggling with only a few parts, but eventually it went smoother.</p>

<p>A half is ready.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0106.jpg" /></p>

<p>After one more hour it was all done.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0107.jpg" /></p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0110.jpg" /></p>

<p>Maximite can be powered from an external 9V source or form USB. I used USB.</p>

<p>Plug into USB and VGA. An off you go!</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0111.jpg" /></p>

<p>BASIC is ready but there is no keyboard. I hand’t a proper PS/2 one and I tried a USB-PS/2 connector. Alas, it didn’t fit.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0119.jpg" /></p>

<p>Next day I found the PS/2 keyboard and finally connected.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0114.jpg" /></p>

<p>The case.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0115.jpg" /></p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0112.jpg" /></p>

<p>Fully assembled.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0113.jpg" /></p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0116.jpg" /></p>

<p>I have to admit - the kit from Altronics is a very good quality product. The holes are metallized on the board, and the case fits perfectly.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/img_0118.jpg" /></p>

<p>Then I had to upgrade the firmware to the latest version. Maximite can flash itself over USB without a special programmer. Just open the case and hold a special button when switching Maximite on. It goes to a boot loader mode.</p>

<p>Maximite is a standard CDC device in USB infrastructure. Windows still requires a driver though, but Mac has it built-in.</p>

<p>Plug-in.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01130.jpg" /></p>

<p>Flashing.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01129.jpg" /></p>

<p>Right, the firmware is upgraded up to 3.0A.</p>

<p>As I said, Maximite supports VGA and PS/2, but you can also connect it to a PC via USB. In this case Maximite mirrors the VGA output to that serial connection to the PC, also treats the data coming from that connection as keyboard input.</p>

<p>So, it is possible to detach VGA and PS/2 at all and talk to Maximite over the serial USB connection only.</p>

<p>For example, VGA dispay (voltmeter):</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01125.jpg" /></p>

<p>The same data on in a terminal emulation application on the PC:</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01123.jpg" /></p>

<p>Interestingly, Maximite works with pixels, not characters. So when a character is being displayed, it is also copied to the console, but when Maxitile draws graphics it is not visible in the serial console.</p>

<p>BASIC language in Maximite gives full control over the peripherals using operators.</p>

<p>There is an archive of BASIC programs running on Maximite available of the project website.</p>

<p>There are a few screenshots.</p>

<p>Clock.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01132.jpg" /></p>

<p>Character editor.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01128.jpg" /></p>

<p>Voltmeter.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01133.jpg" /></p>

<p>Puzzles.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01126.jpg" />
<img src="http://demin.ws/images/blog/maximite-kit/dsc01131.jpg" /></p>

<p>I believe, no comment here.</p>

<p><img src="http://demin.ws/images/blog/maximite-kit/dsc01134.jpg" /></p>

<p>Conclusion</p>

<p>Every penny I have spent on Maximite is worth that fun I’ve got.</p>

<p>The Maximite project is surprisingly solid. Everything is nice and simple. And it works!</p>

<p>For beginners, even kids, interested in microelectronics, Maximite is simply a godsend. Easy and nice to build. I as an amateur have built everything in a few hours only.</p>

<p>When my brother was building <a href="http://radio86.googlecode.com/hg/online/radio86.html">Radio-86RK Emulator</a> and Spectrum about twenty years ago, there was a joke about DIY projects published in radio electronics magazines: if a author says that his device doesn’t required any tuning, there is at least a little chance to get it working; but the author says that his device does require some minor tuning&hellip;</p>

<p>Anyway, if you want to come back to your 8-bit youth with a soldering iron in hands — build Maximite.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Stuck process detector]]></title>
    <link href="http://demin.ws/blog/english/2012/01/05/stuck-process-detector/"/>
    <updated>2012-01-05T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/01/05/stuck-process-detector/</id>
    <content type="html"><![CDATA[<p>There is a problem — how to automatically detect stuck long running server processes? Say if a process is stuck it means there is a deadlock or it is spinning in an infinite loop.</p>

<p>An idea — periodically take a snapshot of the process stack trace. For instance:</p>

<pre><code>#0  0x991a8c22 in mach_msg_trap ()
#1  0x991a81f6 in mach_msg ()
#2  0x968870ea in __CFRunLoopServiceMachPort ()
#3  0x96890214 in __CFRunLoopRun ()
#4  0x9688f8ec in CFRunLoopRunSpecific ()
#5  0x9688f798 in CFRunLoopRunInMode ()
#6  0x92158a7f in RunCurrentEventLoopInMode ()
#7  0x9215fd9b in ReceiveNextEventCommon ()
#8  0x9215fc0a in BlockUntilNextEventMatchingListInMode ()
#9  0x90010040 in _DPSNextEvent ()
#10 0x9000f8ab in -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] ()
#11 0x9000bc22 in -[NSApplication run] ()
#12 0x902a018a in NSApplicationMain ()
#13 0x0012e356 in main ()
</code></pre>

<p>For Linux, HPUX and Solaris there is a tool called <code>pstack</code>, and <code>procstack</code> on AIX. I’m sure it is possible to do the same on Windows because Process Explorer can do it.</p>

<p>Comparing the current stack trace with the previous one we can measure how much it has been changed. If the stack wasn’t changed at all or only a few deepest lines were changed (for example, inside the kernel), we may assume that this process is stuck. The deadlock on a file or database is even simpler because the code will be blocked on a function inside the kernel.</p>

<p>Of course, such detector has to be adjusted for specifics of the monitored processes. But it can be configurable via regular expressions or a script language as Lua, for instance.</p>

<p>The good thing is that such monitor doesn’t require any changes in the target software, and can be implemented on any language suitable for easy text parsing, for example, Ruby or Python.</p>

<p>Am I reinventing a wheel?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Trade-off with const in legacy code]]></title>
    <link href="http://demin.ws/blog/english/2012/01/04/trade-off-with-const-in-legacy-code/"/>
    <updated>2012-01-04T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2012/01/04/trade-off-with-const-in-legacy-code/</id>
    <content type="html"><![CDATA[<p>Today we argued an hour with a colleague regarding the following code:</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">foo</span><span class="hl opt">(</span>T<span class="hl opt">*</span> t<span class="hl opt">) {</span>
  <span class="hl kwd">bar</span><span class="hl opt">(</span>t<span class="hl opt">);</span>
<span class="hl opt">}</span>
</pre>

<p>The problem is that the function <code>bar</code> is a part of a legacy library which we cannot refactor right now. The signature of <code>bar</code> is <code>void bar(T*)</code>. <code>T</code> is not <code>const</code>. But in reality <code>bar</code> never changes an object referenced by <code>t</code>. This is how it was implemented.</p>

<p>But <code>foo</code> is a part of a brand new API, and we want to make nice or clean. The contract of the function <code>foo</code> says that it doesn’t need to change its parameter.</p>

<p>I think the code should be like this:</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">foo</span><span class="hl opt">(</span><span class="hl kwb">const</span> T<span class="hl opt">*</span> t<span class="hl opt">) {</span>
  <span class="hl kwd">bar</span><span class="hl opt">(</span><span class="hl kwa">const_cast</span><span class="hl opt">&lt;</span>T<span class="hl opt">*&gt;(</span>t<span class="hl opt">));</span>
<span class="hl opt">}</span>
</pre>

<p>Why? The contact of foo doesn’t require the pointer t to be non-const. We must reflect this in the API by making <code>t</code> <code>const</code>. It doesn’t matter that for some reason a particular implementation of <code>foo</code> is based on the legacy <code>bar</code> function not having <code>const</code> in the argument but never changing it. Yes, we have to use the ugly <code>const_cast</code> but this bad code is nicely isolated inside <code>foo</code> only and doesn’t affect our nice and clean brand new API. Moreover, if we refactor <code>foo</code> at some point and get rid of legacy <code>bar</code> at all, the problem will disappear completely.</p>

<p>Here is a counterargument from my colleague: it may turn out that the function <code>foo</code> can have a bug and accidentally change <code>t</code> even it is declared as <code>const</code>. The solution is to simply keep the argument of <code>foo</code> non-const. In this case we don’t need that cast, we explicitly show to an end user of <code>foo</code> that she should expect its parameter to be <code>const</code>, and eventually we never violate the contact of the function <code>foo</code>.</p>

<p>Eventually we haven’t agreed. My flaw is that <code>const</code> doesn’t really protect from side effects coming from legacy <code>bar</code> and the argument of <code>foo</code> may be changed regardless being <code>const</code>. My friend’s flaw is that it is not easy to explain in the documentation how and why the argument of <code>foo</code> may be changed. Just because our particular implementation dictates this? Such approach spreads the drawback of the legacy code to our nice and shiny new code.</p>

<p>Dilemma.</p>

<p>P.S. There is another esoteric approach — to create a temporary deep copy of <code>T</code> inside <code>foo</code> and pass it to <code>bar</code> by non-const pointer. Personally if I have to choose between quick but badly designed code and slow but nicely written code I usually go for the second one. Tomorrow we can buy another faster computer and the slow code will be faster, but that computer will make the bad code better.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Walter Isaacson, &#34;Steve Jobs: The Exclusive Biography&#34;]]></title>
    <link href="http://demin.ws/blog/english/2011/12/27/steve-jobs-the-exclusive-biography/"/>
    <updated>2011-12-27T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/12/27/steve-jobs-the-exclusive-biography/</id>
    <content type="html"><![CDATA[<p>&ldquo;Steve Jobs: The Exclusive Biography&rdquo; by Walter Isaacson</p>

<p><a href="http://www.amazon.co.uk/gp/product/1408703742/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=1408703742"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=1408703742&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=1408703742" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>I thought that biographies are for &ldquo;old people&rdquo;. This book has changed that mindset in me. Being driven by massive ads and recently emerged love with Apple products and philosophy I had started reading.</p>

<p>Initially it was like an expanded version of &ldquo;<a href="http://www.imdb.com/title/tt0168122/">Pirates of Silicon Valley</a>&rdquo; which I, frankly, liked, but as reading progressed I had just fallen in love with this book and weren&rsquo;t able to stop.</p>

<p>The book can be treated as conjuncture or just an attempt to leverage the situation that Steve has just passed away. I was fully biased but after the first chapter I was hooked.</p>

<p>It is fascinating reading. Maybe just because the author is talented, I don&rsquo;t know.</p>

<p>Conclusion: strongly recommend.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Thomas L. Friedman, &#34;The world is flat 3.0: A Brief History of the Twenty-first Century&#34;]]></title>
    <link href="http://demin.ws/blog/english/2011/12/24/world-is-flat/"/>
    <updated>2011-12-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/12/24/world-is-flat/</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve come back to audiobooks. 40-50 minutes per day when heading an office and then back allow to consume books with decent speed.</p>

<p>A recent.</p>

<p>&ldquo;The world is flat 3.0: A Brief History of the Twenty-first Century&rdquo;, Thomas L. Friedman</p>

<p><a href="http://www.amazon.co.uk/gp/product/0312425074/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=0312425074"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=0312425074&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=0312425074" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>This is a killer book to understand or even discover that nowadays:</p>

<ul>
<li>individuals can compete with corporations</li>
<li>an importance of engineering and especially computer education is increasing enormously</li>
<li>a number of places on the Earth when you can have decent life doing what you love to do is not narrowed to the US and a few EU countries anymore</li>
<li>India, China, Russia and many other countries have a very strong position competing with even US now without immigration permanent self education and nurturing your curiosity (CQ + PQ always greater that IQ) is the only way to remain valuable</li>
</ul>

<p>And many other topics.</p>

<p>Frankly, there were moments in my life when I doubted and thought I would be better off doing, for instance, real estate, natural resources, ads or media rather than software. If you have even a tiny similar concern this book will wipe it out forever, and maybe even show the way.</p>

<p>To conclude: very useful, interesting and fascinating reading.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Virtual private functions in C++]]></title>
    <link href="http://demin.ws/blog/english/2011/12/21/virtual-private-functions-in-cpp/"/>
    <updated>2011-12-21T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/12/21/virtual-private-functions-in-cpp/</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve come across an interesting in my point of view bit of code. There was a virtual private function. The approach is odd at the first place and I thought it shouldn&rsquo;t even compile, but surprisingly it did. I felt that this was yet another gap in my C++.</p>

<p>I wrote this code:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>

<span class="hl kwc">class</span> A <span class="hl opt">{</span>
<span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwb">void</span> <span class="hl kwd">bar</span><span class="hl opt">() {</span> <span class="hl kwd">foo</span><span class="hl opt">(); }</span>
<span class="hl kwc">private</span><span class="hl opt">:</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">foo</span><span class="hl opt">() =</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">};</span>

<span class="hl kwc">class</span> B<span class="hl opt">:</span> <span class="hl kwc">public</span> A <span class="hl opt">{</span>
<span class="hl kwc">private</span><span class="hl opt">:</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">foo</span><span class="hl opt">() {</span> std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;B::foo()&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">; }</span>
<span class="hl opt">};</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  A<span class="hl opt">*</span> a <span class="hl opt">=</span> <span class="hl kwa">new</span> <span class="hl kwd">B</span><span class="hl opt">();</span>
  a<span class="hl opt">-&gt;</span><span class="hl kwd">bar</span><span class="hl opt">();</span>
  <span class="hl kwa">delete</span> a<span class="hl opt">;</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>VS2010 and GCC compile it perfectly and it prints out <code>B::foo()</code>.</p>

<p>I have concluded that the virtual function mechanism usually implemented via vtable is runtime, but public/private is compile time, and they don&rsquo;t depend on each other.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[GitHub as a blog engine]]></title>
    <link href="http://demin.ws/blog/english/2011/12/18/blogging-on-github/"/>
    <updated>2011-12-18T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/12/18/blogging-on-github/</id>
    <content type="html"><![CDATA[<p>To say that Blogspot (Blogger) infuriates me is to say nothing. The only benefit of it is fast indexing by Google.</p>

<p>Artemy Lebedev said that he despises all this <a href="http://en.wikipedia.org/wiki/Search_engine_optimization">SEO</a> bullshit because it is much more productive to focus on creating great posts rather than thinking how to attract more readers. His <a href="http://tema.livejournal.com/">LJ</a> uses a default template without even minor tweaks to make it looking “cool”. Despite of this his blog is in Russian Top 10.</p>

<p>Nobody reads blogs directly nowadays. Everybody uses Google Reader or other aggregators making the design of blogs absolutely pointless.</p>

<p>Anyway let’s leave odious Lebedev and come back to our techy blogs. Tom Preston-Werner, one of the Github founders, <a href="http://tom.preston-werner.com/2008/11/17/blogging-like-a-hacker.html">said that he wanted to write posts</a> but not tweaking different templates or keeping the version of WordPress or Mephisto up to date.</p>

<p>A similar thought haunts me from the day one of using Blogspot. Only recently I have sorted a way of creating post by using <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">ReST</a>. Now I write posts in this markup and convert to HTML before publishing by a few handcrafted scripts. Unfortunately hosting for images is not automated in anyway.</p>

<p>Many times I wanted to migrate to a standalone platform, for example, WordPress. But my laziness and unwillingness to spend even a second on its maintenance always stopped me.</p>

<p>At the moment I have another attack of hate to Blogspot and as a consequence look for alternatives.</p>

<p>Surprisingly I never considered using <a href="http://www.subspacefield.org/~travis/static_blog_generators.html">static blog engines</a>.</p>

<p>What if just simply migrate to <a href="http://pages.github.com/">GitHub Pages</a>? It converts one of your repositories to a website which can be also processed by <a href="http://jekyllrb.com/">Jekyll</a>, a static engine from Tom Preston-Werner.</p>

<p>I could kill a few birds with one stone – to use a proper markup language, <a href="http://daringfireball.net/projects/markdown/syntax">Markdown</a> or <a href="http://en.wikipedia.org/wiki/Textile_(markup_language)">Textile</a>, instead of bloody HTML and to manage publishing by git. Of course ReST is better but I can cope with it.</p>

<p>Also GitHub Pages can be integrated with your own domain if needed.</p>

<p>Comments and discussions. <a href="http://disqus.com/">Disqus</a> seems to be an easiest way to sort it without any hassle.</p>

<p>Google Analytics perfectly works with any engine where you can insert their JavaScript hook into pages.</p>

<p>What is still missing?</p>

<p>Sometimes people still visit blogs directly, for instance, to find previous posts or explore “social” details. In this case all these bells and whistles in a form of JavaScript gadgets are very useful and save a lot of time. Blogspot allows adding them in a few clicks.</p>

<p>But coming back to the question at the beginning – do I really need them? If the content is interesting the audience will inevitably find you. A word of mouth in a form of Twitter or Facebook will attract people. But if the content is crap all those bells and whistles (and SEO) will not help.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Chromebook Samsung 5 5G review]]></title>
    <link href="http://demin.ws/blog/english/2011/10/02/chromebook-samsumg-5-3g-review/"/>
    <updated>2011-10-02T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/10/02/chromebook-samsumg-5-3g-review/</id>
    <content type="html"><![CDATA[<p>I read in papers that Google has <a href="http://www.telegraph.co.uk/technology/google/8800002/Worlds-first-Google-store-opens-in-London.html">launched an offline shop for Chromebooks</a>.</p>

<p>I went to check out the stop and the Chromebook.</p>

<p>The &ldquo;Shop&rdquo; is a two desk place with a dozen of demo notebooks in the <a href="http://www.pcworld.co.uk/gbuk/s/find-a-store.html?iStoreId=696">PC World</a> nearby Apple, Sony and other departments.</p>

<p>The Chromebook demoing there is <a href="http://www.currys.co.uk/gbuk/samsung-series-5-3g-chromebook-white-10822582-pdt.html">Samsung Series 5 3G</a>.</p>

<p>Below there are a few not quite good quality pictures I&rsquo;ve done during an hour playing with this device at the shop.</p>

<p>Closed lid.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-closed-lid.jpg" /></p>

<p>Left - power, a weird video connector, USB and audio.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-left-side.jpg" /></p>

<p>Right - one more USB.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-right-side.jpg" /></p>

<p>Front - SD.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-sd-port.jpg" /></p>

<p>The power socket is quite fragile.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-power-connector.jpg" /></p>

<p>Look at the keyboard.</p>

<p>Above Shift there is an interesting button called &ldquo;Search&rdquo; opening a new tab and pointing the cursor to the URL bar. In fact, CTRL-T. I liked this button.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-search-button.jpg" /></p>

<p>There are internet related buttons in the top row. The button between full screen and the brightness is the switch amongst Chrome windows when there are multiple of them opened.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-inet-buttons.jpg" /></p>

<p>There are no Ins, Del, Page Up and Page Down.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-no-ins-del-pgup-pgwn.jpg" /></p>

<p>After 8 seconds of boot time you see a login window for your Google Account (I used a demo one), and then the main screen comes out.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-main-screen.jpg" /></p>

<p>In Chromebook there is only one application - the Chrome browser. It is not possible to exit from it. You can only open new tabs and windows.</p>

<p>The Chrome itself differs from its desktop version. There are extra menus. For example, network settings.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-network-settings.jpg" /></p>

<p>WiFi</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-wifi-selector.jpg" /></p>

<p>Russian keyboard layout is configurable through the settings.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-russian.jpg" /></p>

<p>Printing works via a direct connection to a USB printer (HCL is provided), or a &ldquo;proper&rdquo; Google way printing via Cloud Print.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-cloud-print.jpg" /></p>

<p>It is possible to keep files locally. For instance, you can attach them to e-mails.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-local-file-open.jpg" /></p>

<p>Only a few types of files allow to do anything with them. For example, photos and vides can be uploaded to WebPicasa.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-local-file-storage.jpg" /></p>

<p>All downloads and screenshots also go to the local storage.</p>

<p>Skype was not available, so I tried GTalk (this is mine shaved head in the window).</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-gtalk.jpg" /></p>

<p>GTalk settings.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-gtalk-setup.jpg" /></p>

<p>After a few minutes of jiggling around GTalk crashed.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-gtalk-crash.jpg" /></p>

<p>Of course, I checked out the <a href="http://easy-coding.blogspot.com">right website</a>.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-easycoding.jpg" /></p>

<p>And <a href="http://radio86.googlecode.com/hg/online/radio86.html">another one</a>.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-volcano.jpg" /></p>

<p>And <a href="http://bellard.org/jslinux/">another one</a> to figure out the overall performance.</p>

<p><img src="http://demin.ws/images/blog/chromebook-samsumg-5-3g-review/chromebook-jslinux.jpg" /></p>

<p>Linux booted in 33 seconds. On my Mac Air Core Due it boots in 8 seconds. But bogomips were the same (~20) for some reason.</p>

<p>Now my biased conclusion.</p>

<p>400 quid is nuts. The notebook itself isn&rsquo;t light, tiny and slick, which could be an excuse for such high price, but there are a dozen of other netbooks around doing the same stuff, plus the rest.</p>

<p>Even at the shop, where WiFi was really fast, working fully online becomes annoying very soon due to network lags. The official &ldquo;Offline Gmail&rdquo; is available but it is a joke, and barely usable seriously.</p>

<p>For 50 quid I could buy it right there, just because I use Google&rsquo;s products and is willing to play with this &ldquo;Google Console&rdquo;, but 400 is &ldquo;no, thank you&rdquo;.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cast to incomplete type in C and C++]]></title>
    <link href="http://demin.ws/blog/english/2011/08/17/cast-to-incomplete-type-in-c-and-cpp/"/>
    <updated>2011-08-17T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/08/17/cast-to-incomplete-type-in-c-and-cpp/</id>
    <content type="html"><![CDATA[<p>This compiles in C and C++ without any problems:</p>

<pre class="hl">
<span class="hl kwb">void</span><span class="hl opt">*</span> p <span class="hl opt">= (</span><span class="hl kwb">struct</span> this_does_not_exist <span class="hl opt">*) -</span><span class="hl num">1</span><span class="hl opt">;</span>
</pre>

<p>Remove <code>struct</code>, compile as C++ and get an error:</p>

<pre><code>cast.cpp
cast.cpp(1) : error C2065: 'this_does_not_exist' : undeclared identifier
cast.cpp(1) : error C2059: syntax error : ')'
</code></pre>

<p>Adding a forward declaration:</p>

<pre class="hl">
<span class="hl kwc">class</span> this_does_not_exist<span class="hl opt">;</span>
<span class="hl kwb">void</span><span class="hl opt">*</span> p <span class="hl opt">= (</span>this_does_not_exist <span class="hl opt">*) -</span><span class="hl num">1</span><span class="hl opt">;</span>
</pre>

<p>And it again compiles cleanly.</p>

<p>All examples conform the Standard but to be honest the first one is really odd.</p>

<p>GCC gives a warning at least.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Software development in one picture]]></title>
    <link href="http://demin.ws/blog/english/2011/07/17/software-development-in-one-picture/"/>
    <updated>2011-07-17T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/07/17/software-development-in-one-picture/</id>
    <content type="html"><![CDATA[<p>I don&rsquo;t remember where and when I dug this picture but since then I keep it. It nicely visualizes a software development process.</p>

<p><img src="http://demin.ws/images/blog/software-development-in-one-picture.jpg" /></p>

<p>Every time I come across famous Shakespeare&rsquo;s trade off &ldquo;to refactor or not refactor&rdquo; I come back to this picture. You can keep going to put more and more cheap crutches preventing your house from irreversible falling down. It can help for sometime but at some point there will be a point of no return. Or you can get all the people out of the house for a while and rebuilt it of bricks.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[strcpy() on overlapped strings]]></title>
    <link href="http://demin.ws/blog/english/2011/07/14/strcpy-on-overlapped-strings/"/>
    <updated>2011-07-14T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/07/14/strcpy-on-overlapped-strings/</id>
    <content type="html"><![CDATA[<p>Consider the code:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;string.h&gt;</span>
<span class="hl ppc">#include &lt;stdio.h&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">char</span> b<span class="hl opt">[</span><span class="hl num">32</span><span class="hl opt">];</span>
  <span class="hl kwd">strcpy</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;123456789012345&quot;</span><span class="hl opt">);</span>
  <span class="hl kwd">strcpy</span><span class="hl opt">(</span>b <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">,</span> b<span class="hl opt">);</span>
  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;[%s]</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> b<span class="hl opt">);</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>There is a problem here because the parameters of <code>strcpy()</code> overlap.</p>

<p>This is an unpredictable behaviour because <code>strcpy()</code> doesn&rsquo;t guarantee the order of moving bytes (from left to right or vice versa) but the result depends on it.</p>

<p>Check on different compilers and platforms.</p>

<p><strong>Visual Studio 2010 64-bit</strong></p>

<pre><code>[1123446788012245]
</code></pre>

<p>The result is corrupted every four bytes. Obviously, it has been copied 32 bit words.</p>

<p><strong>Linux 64-bit</strong></p>

<pre><code>[1123456788012345]
</code></pre>

<p>The result is now different. Compiler and libc:</p>

<pre><code>ldd --version
ldd (GNU libc) 2.5

gcc --version
gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-50)
</code></pre>

<p><code>man strcpy</code> says:</p>

<pre><code>The strings may not overlap...
</code></pre>

<p>Why not &ldquo;must not&rdquo;?</p>

<p><strong>Solaris (SPARC)</strong></p>

<pre><code>[1123446788012245]
</code></pre>

<p>Compiler and libc:</p>

<pre><code>cc -V
cc: Sun C 5.8 2005/10/13

version /usr/lib/libC*
version of &quot;/usr/lib/libC.so.3&quot;: SC2.0.1 12/20/94 Sun C++ 3.0.1 patch 100962-09
version of &quot;/usr/lib/libC.so.5&quot;: Sun SUNWlibC SunOS 5.10 Patch 119963-06 2006/04/21
version of &quot;/usr/lib/libCrun.so.1&quot;: Sun SUNWlibC SunOS 5.10 Patch 119963-06 2006/04/21
version of &quot;/usr/lib/libCstd.so.1&quot;: Sun SUNWlibC SunOS 5.10 Patch 119963-06 2006/04/21
</code></pre>

<p><strong>AIX</strong></p>

<pre><code>[1111111111012245]
</code></pre>

<p>This result is clearly wrong. The man pages are pretty clear on it:</p>

<p><em>String movement is performed on a character-by-character basis and starts at the left. Overlapping moves toward the left work as expected, but overlapping moves to the right may give unexpected results.</em></p>

<p>Compiler and libc:</p>

<pre><code>lslpp -L | grep Compiler
vacpp.cmp.core            8.0.0.20    C     F    IBM XL C/C++ Compiler

lslpp -L | grep libc
bos.rte.libc               5.3.9.1    C     F    libc Library
</code></pre>

<p><strong>HP-UX</strong></p>

<pre><code>[1123456789012345]
</code></pre>

<p>Compiler:</p>

<pre><code>what `which cc`

HP C/aC++ for Integrity Servers B3910B A.06.22 [Nov 14 2008]
</code></pre>

<p>This result is correct but man pages warn in a funny way:</p>

<p><em>Character movement is performed differently in different implementations, so moves involving overlapping source and destination strings may yield surprises.</em></p>

<p><strong>Conclusion</strong>: <code>strcpy()</code> is bad, due to many reasons.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Number of crossings in bipartite graph]]></title>
    <link href="http://demin.ws/blog/english/2011/05/24/number-of-crossings-in-bipartite-graph/"/>
    <updated>2011-05-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/05/24/number-of-crossings-in-bipartite-graph/</id>
    <content type="html"><![CDATA[<p>Given a <a href="http://en.wikipedia.org/wiki/Bipartite_graph">bipartite graph</a>: &ldquo;n&rdquo; vertices on the left, &ldquo;m&rdquo; on the right and edges. The question is: how many edges in this graph are crossed?</p>

<p>In this example n=5, m=4, ten edges: 1-1, 1-2, 2-1, 2-2, 3-3, 4-1, 4-3, 5-1, 5-2, 5-4, a number of crossings: 10.</p>

<p><img src="http://demin.ws/images/blog/bipartite-graph.gif" /></p>

<p>Crossings are always considered in pairs. For example, if three edges are crossed in one physical point, formally there are still three crossings, not one.</p>

<p>O(n*m) solution exists.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Safer sizeof for arrays in C++]]></title>
    <link href="http://demin.ws/blog/english/2011/05/24/safer-sizeof-for-arrays-in-cpp/"/>
    <updated>2011-05-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/05/24/safer-sizeof-for-arrays-in-cpp/</id>
    <content type="html"><![CDATA[<p>Sometimes you have to deal with raw arrays and pointers to them in C++, and also determine a number of elements in the array at compile time.</p>

<p>For example, it can be done this way:</p>

<pre class="hl">
<span class="hl ppc">#define arraysize(array) (sizeof(array) / sizeof(array[0]))</span>
</pre>

<p>But there is a little problem over there. If accidently a pointer is passed to the this macro instead of an array, the code still compiles but the value will be far from being conceived.</p>

<p>There is a way to make this macro safer.</p>

<pre class="hl">
<span class="hl kwc">template</span> <span class="hl opt">&lt;</span>typename T<span class="hl opt">,</span> <span class="hl kwb">size_t</span> N<span class="hl opt">&gt;</span>
<span class="hl kwb">char</span> <span class="hl opt">(&amp;</span><span class="hl kwd">ArraySizeHelper</span><span class="hl opt">(</span><span class="hl kwd">T</span> <span class="hl opt">(&amp;</span>array<span class="hl opt">)[</span>N<span class="hl opt">]))[</span>N<span class="hl opt">];</span>
<span class="hl ppc">#define arraysize(array) (sizeof(ArraySizeHelper(array)))</span>
</pre>

<p>Looks cryptic, but we can break it apart:</p>

<ul>
<li><code>T (&amp;array)[N])</code> - an array definition (<code>T array[N]</code>) passed by reference</li>
<li><code>char (&amp;ArraySizeHelper(...)[N]</code> - a function returning a array by reference</li>
<li><code>sizeof(ArraySizeHelper(array))</code> - take a size of the function return value type</li>
<li>This is a template function, parameterized by an array type and its size deduced automatically by the compiler. The function isn&rsquo;t called, so its definition is not required.</li>
</ul>

<p>Frankly, it is not easy to get it. But this macro is great.</p>

<p>By the way, we can play with <code>sizeof()</code> of the function return value type:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;string&gt;</span>

std<span class="hl opt">::</span>string <span class="hl kwd">f</span><span class="hl opt">() {</span>
  <span class="hl kwa">return</span> std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">();</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl kwa">sizeof</span><span class="hl opt">( (&amp;</span>f<span class="hl opt">)() ) &lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl kwa">sizeof</span><span class="hl opt">(</span> std<span class="hl opt">::</span>string <span class="hl opt">) &lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>My VS2010 prints out &ldquo;28&rdquo; twice.</p>

<p>Interestingly, in C it is also possible:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;stdio.h&gt;</span>

<span class="hl kwb">struct</span> t <span class="hl opt">{</span>
  <span class="hl kwb">char</span> x<span class="hl opt">[</span><span class="hl num">1024</span><span class="hl opt">];</span>
<span class="hl opt">};</span>

<span class="hl kwb">struct</span> t <span class="hl kwd">f</span><span class="hl opt">() {</span>
  <span class="hl kwb">struct</span> t a<span class="hl opt">;</span>
  <span class="hl kwa">return</span> a<span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%d</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> <span class="hl kwa">sizeof</span><span class="hl opt">(</span><span class="hl kwb">struct</span> t<span class="hl opt">));</span>
  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%d</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> <span class="hl kwa">sizeof</span><span class="hl opt">( (*</span>f<span class="hl opt">)() ));</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>It prints out <code>1024</code> twice.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[In-place string literal subscripting]]></title>
    <link href="http://demin.ws/blog/english/2011/05/22/in-place-string-literal-subscripting/"/>
    <updated>2011-05-22T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/05/22/in-place-string-literal-subscripting/</id>
    <content type="html"><![CDATA[<p>I confess, I had never occurred before to subscript a string literal in-place. For example:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;stdio.h&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwb">int</span> i<span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">8</span><span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%c&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;12345678&quot;</span><span class="hl opt">[</span>i<span class="hl opt">]);</span>
  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>To me personally the expression <code>&quot;12345678&quot;[i]</code> cuts the eye. But from the language point of view everything is fine.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[ACCU 2011 videos]]></title>
    <link href="http://demin.ws/blog/english/2011/05/09/accu-2011-videos/"/>
    <updated>2011-05-09T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/05/09/accu-2011-videos/</id>
    <content type="html"><![CDATA[<p>Alas, it is necessary to give just links, because they don&rsquo;t allow embedding code for viewing directly from the page.</p>

<p>Scott Meyers</p>

<p><a href="http://skillsmatter.com/podcast/home/cpu-caches-and-why-you-care">CPU caches and why you care</a></p>

<p><a href="http://skillsmatter.com/podcast/home/move-semanticsperfect-forwarding-and-rvalue-references">Move semantics, perfect forwarding, and rvalue references</a></p>

<p>John Lakos (Bloomberg)</p>

<p><a href="http://skillsmatter.com/podcast/home/defensive-programming-done-right">Defensive programming done right</a></p>

<p>Dietmar Kuhl (Bloomberg)</p>

<p><a href="http://skillsmatter.com/podcast/home/generic-programming-with-c-plus-plus-0x">Generic Programming with C++ 0x</a></p>

<p><a href="http://skillsmatter.com/event/home/accu-2011">Other videos are also available</a>.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Symbolic links to files and directories in Windows]]></title>
    <link href="http://demin.ws/blog/english/2011/05/09/symbolic-links-to-files-and-directories-in-windows/"/>
    <updated>2011-05-09T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/05/09/symbolic-links-to-files-and-directories-in-windows/</id>
    <content type="html"><![CDATA[<p>To my shame, I thought that Windows still lives in the previous century without links in the file system. I knew about junctions, links to directories, which can be created, for instance, in FAR via Alt-F6.</p>

<p>But today, thumbing through &ldquo;Windows Internals&rdquo;, I came across a paragraph about it.</p>

<p>So, there is a little log from the console (Windows 7).</p>

<pre><code>ver

Microsoft Windows [Version 6.1.7601]
</code></pre>

<p>Create a file and a directory:</p>

<p>cd C:\Temp\links
C:\temp\links&gt;mkdir folder
C:\temp\links&gt;echo &gt;file</p>

<p>Create a symbolic link to the directory:</p>

<pre><code>C:\temp\links&gt;mklink /D link1 folder
symbolic link created for link1 &lt;&lt;===&gt;&gt; folder
</code></pre>

<p>Create a junction to the directory (it isn&rsquo;t possible to point it to a file):</p>

<pre><code>C:\temp\links&gt;mklink /J link2 folder
Junction created for link2 &lt;&lt;===&gt;&gt; folder
</code></pre>

<p>Create a symbolic link slightly differently:</p>

<pre><code>C:\temp\links&gt;mklink link3 folder
symbolic link created for link3 &lt;&lt;===&gt;&gt; folder
</code></pre>

<p>Create a symbolic link to a file:</p>

<pre><code>C:\temp\links&gt;mklink link4 file
symbolic link created for link4 &lt;&lt;===&gt;&gt; file
</code></pre>

<p>Result:</p>

<pre><code>C:\temp\links&gt;dir
 Volume in drive C has no label.
 Volume Serial Number is C021-6C9F

 Directory of C:\temp\links

09/05/2011  18:26    &lt;DIR&gt;          .
09/05/2011  18:26    &lt;DIR&gt;          ..
09/05/2011  18:26                13 file
09/05/2011  18:25    &lt;SYMLINKD&gt;     link1 [folder]
09/05/2011  18:25    &lt;JUNCTION&gt;     link2 [C:\temp\links\folder]
09/05/2011  18:25    &lt;SYMLINK&gt;      link3 [folder]
09/05/2011  18:26    &lt;SYMLINK&gt;      link4 [file]
09/05/2011  18:23    &lt;DIR&gt;          folder
               3 File(s)             13 bytes
               5 Dir(s)  208,278,925,312 bytes free
</code></pre>

<p>Note the interesting types of files: <code>&lt;SYMLINKD&gt;</code>, <code>&lt;JUNCTION&gt;</code>, <code>&lt;SYMLINK&gt;</code>. The book says the first two are identical in functionality, simply <code>&lt;JUNCTION&gt;</code> is older mechanism available in older versions of Windows and supporting links within the same volume only.</p>

<p>Also, note that even <code>link3</code> points to a directory, it doesn&rsquo;t behave as a regular directory (in contrast to <code>link1</code> and <code>link2</code> which work normally as directories). FAR, by the way, also doesn&rsquo;t see <code>link3</code> as a directory.</p>

<p>In general, such simple task as links in the file system, solved in UNIX more than twenty years ago, has been solved in Windows in traditional for this operating system way - there are multiple solutions with different level of compatibility.</p>

<p>By the way, &ldquo;Windows Internals&rdquo; is bloody fantastic, strongly recommend.</p>

<p><a href="http://www.amazon.co.uk/gp/product/0735625301/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=0735625301"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=0735625301&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=0735625301" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Process exit code after crash]]></title>
    <link href="http://demin.ws/blog/english/2011/04/06/process-exit-code-after-crash/"/>
    <updated>2011-04-06T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/04/06/process-exit-code-after-crash/</id>
    <content type="html"><![CDATA[<p>Just come across an interesting bug. Being executed from a Makefile script a unit test runner crashed. It looked like another memory corruption. But the consequence was more interesting. That Makefile kept going regardless the crash of the unit test runner. It means the runner still returned zero exit code instead of non-zero.</p>

<p>We fixed that bug (including Makefile problem) but a generic question occured: what exit code is returned to the parent when the process crashes before executing <a href="http://linux.die.net/man/3/exit">exit()</a>?</p>

<p>In UNIX there are special macros inspecting the status returned from <a href="http://linux.die.net/man/2/wait">wait()</a>. But all UNIXes are different and there is Windows as well.</p>

<p>Eventually I wrote a simple self-killing program:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;stdio.h&gt;</span>
<span class="hl ppc">#include &lt;stdlib.h&gt;</span>
<span class="hl ppc">#include &lt;string.h&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">char</span> cmd<span class="hl opt">[</span><span class="hl num">80</span><span class="hl opt">];</span>
  <span class="hl kwb">int</span> r<span class="hl opt">;</span>
  <span class="hl kwd">sprintf</span><span class="hl opt">(</span>cmd<span class="hl opt">,</span> <span class="hl str">&quot;%s ?&quot;</span><span class="hl opt">,</span> argv<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">]);</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>argc <span class="hl opt">&gt;</span> <span class="hl num">1</span><span class="hl opt">) {</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>argv<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">][</span><span class="hl kwd">strlen</span><span class="hl opt">(</span>argv<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]) -</span> <span class="hl num">1</span><span class="hl opt">] ==</span> <span class="hl str">'1'</span><span class="hl opt">)</span>
      <span class="hl opt">*(</span><span class="hl kwb">char</span> <span class="hl opt">*)</span><span class="hl num">0</span> <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
    <span class="hl kwd">exit</span><span class="hl opt">(</span><span class="hl num">0x77</span><span class="hl opt">);</span>
  <span class="hl opt">}</span>
  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;Normal: %08X</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> <span class="hl kwd">system</span><span class="hl opt">(</span>cmd<span class="hl opt">));</span>
  cmd<span class="hl opt">[</span><span class="hl kwd">strlen</span><span class="hl opt">(</span>cmd<span class="hl opt">) -</span> <span class="hl num">1</span><span class="hl opt">] =</span> <span class="hl str">'1'</span><span class="hl opt">;</span>
  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;Crash : %08X</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> <span class="hl kwd">system</span><span class="hl opt">(</span>cmd<span class="hl opt">));</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>And run it on different systems.</p>

<p>Windows 7, Visual Studio 2010, <code>cl crash.c &amp;&amp; crash</code>:</p>

<pre><code>Normal: 00000077
Crash : C0000005
</code></pre>

<p>Linux x86_64 (<code>cc -o crash crash.c &amp;&amp; ./crash</code>):</p>

<pre><code>Normal: 00007700
Crash : 0000000B
</code></pre>

<p>Signal 0x0B (13), by the way, is <code>SIGSEGV</code>, segmentation violation.</p>

<p>Solaris SPARC 5.10:</p>

<pre><code>Normal: 00007700
Segmentation Fault - core dumped
Crash : 00008B00
</code></pre>

<p>HP-UX Itanium 2:</p>

<pre><code>Normal: 00007700
sh: 25112 Memory fault(coredump)
Crash : 00008B00
</code></pre>

<p>AIX 5.2:</p>

<p>Normal: 00007700
Crash : FFFFFFFF</p>

<p>Here seems the exit code wasn&rsquo;t even propagated to <code>system()</code>.</p>

<p>Conclusion: it (as usually) really depends on the operating system.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Unit tests for syntax highlighting]]></title>
    <link href="http://demin.ws/blog/english/2011/04/02/unit-tests-for-syntax-highlighting/"/>
    <updated>2011-04-02T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/04/02/unit-tests-for-syntax-highlighting/</id>
    <content type="html"><![CDATA[<p>Quite often people argue whether all those efforts to use unit tests are worth those benefits in code maintenance and regression bugs. Despite of many pros and cons being said there could be situations when it is not obvious that is better, but I can give a very representative example below.</p>

<p>At the moment I&rsquo;m working on a project customizing putty to support of-the-fly syntax highlighting for a proprietary programming language. The main difficulty is that the language has very complicated and not well defined and irregular grammar with lots of ambiguities.</p>

<p>As a result what I&rsquo;m doing is fixing different special cases here and there. But syntax highlighting is complicated in general - you fix one thing and easily break ten others at the same time.</p>

<p>After some time of maintenance I gave up and I spent a day setting up <a href="http://code.google.com/p/cmockery/">cmockery</a> and all the rest of unit testing plumbing. Then I remade all code examples I used to verify everything manually in a form of unit tests.</p>

<p>Once I&rsquo;ve done that life become simpler. Now after every change I can automatically check by running tests that all previous cases are not broken. I&rsquo;m confident to change things without being afraid of regression. Of course I spent an extra day to two developing, debugging and configuring unit tests infrastructure but it has paid off already, fully or even more.</p>

<p>Every new feature or bug fix I start from creating a test demonstrating how it should work, and, obviously, this test must fail. Then I implement a bit of functionality to make this test working. I cannot image how I might develop this project further without unit tests.</p>

<p>By the way, this is a classical approach when tests are written beforehand. And the main code complements the tests afterwards.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Common misconceptions about plastic bank cards]]></title>
    <link href="http://demin.ws/blog/english/2011/03/27/common-misconceptions-about-plastic-bank-cards/"/>
    <updated>2011-03-27T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/03/27/common-misconceptions-about-plastic-bank-cards/</id>
    <content type="html"><![CDATA[<p>Having more than ten years of experience working in banking, in particular with electronic payments, with the help of colleagues I&rsquo;ve created a mini FAQ about plastic bank cards. Some questions are obvious, but some can be quite vague.</p>

<p>Thus, there are ten common misconceptions.</p>

<p>1. The amount of money stored on the card.</p>

<p>On regular credit or debit cards (even having a chip) there is no money counter. The card is just an identifier. There are exceptions in the form of additional wallet applications on the chip cards. Usually it can be discount or loyalty programs, virtual money (for instance, petrol liters) etc. In general this is not related to the normal card usage. Such applications are usually accepted in special stores that only support these cards.</p>

<p>2. Anyone, who wants to accept the plastic cards, can be connected directly to Visa, MasterCard or to other international payment networks.</p>

<p>It&rsquo;s not possible for just anyone to connect directly to Visa or MasterCard. Only major banks or independent processing centers can do it because it requires special equipment, considerable insurance accounts, security certification and lots of other &ldquo;little things&rdquo;. Furthermore not every bank can afford it. All others wishing to take cards use their services.</p>

<p>3\ ATMs or POS terminals are connected directly to Visa or MasterCard.</p>

<p>Major international payment networks do not have their own ATMs or payment terminals. ATMs or POS terminals must belong to a bank, which, in turn, is either directly or indirectly (see #2) connected to the payment network.</p>

<p>4. I have $200 &ldquo;on the card&rdquo;. That&rsquo;s all that I can spend.</p>

<p>The card balance and the amount you can spend daily using the card are not entirely related to each other. It is more constructive discussing the daily limit on the card. The daily limit depends on many factors, and can be either less than the card balance or even greater. For example, even having one million on the account, you may not be allowed to withdraw more than a few thousand in cash a day at the ATM (and this is not an ATM hardware limitation). And vice versa, if you are a VIP customer, usually having millions in the bank, but at the moment you&rsquo;ve lost everything in a casino, after the call to the bank, individually, some of the top managers can give the command to increase your daily limit allowing you to pay off. In this situation the bank takes all the responsibility that you will return everything back.</p>

<p>5. ATM or POS terminals validate the PIN.</p>

<p>In the overwhelming number of cases, any use of the card refers to a connection with the bank that issued the card. If you insert a card issued by HSBC UK in Australia, an approval to withdraw money will be requested from the HSBC UK anyway right before your eyes. This is because the PIN can be verified only by the bank that issued the card. The only exceptions are cards with a chip. Such cards can verify the PIN without connecting to the bank. These cards are microcomputers able to calculate crypto functions. Sometimes when making a purchase (not cash withdraw), a store may not connect to the bank when a non-chip card is being used if the amount is less than a certain limit. The reason for this is the transactional and communication costs. When the amount is not significant the risk of loss after possible fraud is also not significant.</p>

<p>6. The PIN is stored on the magnetic stripe and any bank or store employee can &ldquo;steal&rdquo; it when holding your card while you turn away.</p>

<p>In fact, there is only a crypto convolution of the PIN recorded on the magnetic stripe, and it is calculated using a crypto key stored in a bank HSM (high security module). Using data from the magnetic stripe can only verify the PIN, and only if you know the secret key. Usually the 3DES algorithm is used. HSM is a hardware device for storing keys and cryptographic operations using those keys. After initial input of keys to HSM (personalization) they are never sent outside the physical case of HSM in the plain form.</p>

<p>In addition to the major effort for the physical protection of these devices, they themselves are protected from an unauthorized intrusion. For example, if you try to open the case connecting a &ldquo;sniffer&rdquo;, all the keys will be automatically erased.</p>

<p>There is an interesting technique of primary keys input. For example, here is a realistic scenario. We choose N security officers of the bank, for example 3 (ideally, they shouldn&rsquo;t know each other personally). Each officer generates a key and doesn&rsquo;t show it to anyone else. Then, they in turn go into the room with HSM and enter their keys. After all the keys are entered, the HSM computes bitwise XOR amongst them and keeps the result as the master key. It turns out that nobody knows that master key at all. To restore the master key you have to know all original components from those N security officers, who must take care of keeping it secret.</p>

<p>There are no &ldquo;unimportant&rdquo; questions in the security, and such procedures are mandatory when the power of cryptography ends and the human factor starts.</p>

<p>This is very important: nobody from the bank staff, ever, under any circumstances will ask you the PIN. However, you cannot imagine how often countless customers, when being asked by the bank operator the security question say the PIN.</p>

<p>7. When making the purchase, money immediately comes directly from the customer&rsquo;s account to the account of the merchant.</p>

<p>Usually clearing happens in the end of the business day. When making the purchase the amount from the available day limit (see #4) is only taken on hold. The account is debited a few days later when the bank issued the card receives the financial representation from the bank that accepted the card and processed the payment (bank-acquirer).</p>

<p>8. The amount, printed on your receipt when paying by card, is precisely what will be deducted from your account.</p>

<p>In fact, the authorized amount may differ significantly from the amount that was withdrawn by the financial transaction. It often happens in car rentals and hotels. Such merchants are allowed to charge extras (for example, for petrol and minibar). And these are not the only type of merchants allowed to adjust the final amount.</p>

<p>Also the amount taken on hold on purchase and the amount eventually withdrawn from the account can differ if the account currency is different to the transaction currency. Clearing usually takes a few days but the exchange rate could change in this time.</p>

<p>9. The amount, taken on hold when paying by card, will be withdrawn from the account anyway.</p>

<p>The amount on hold may be never debited from the account. After 10 (for ATM) or 45 (for other types of terminals) days, if there is no financial representation received from the bank-acquirer, the hold will be lifted. This is &ldquo;good&rdquo; and &ldquo;bad&rdquo;. It is &ldquo;good&rdquo; if you have just paid but want to cancel. You can contact your bank immediately, explain the reason for the cancellation, and if everything is okay with the payment, the operator cancels the transaction and the hold disappears. In this case if your bank receives a financial representation of this payment from the merchant (in a few days period) the bank will be dealing with this problem without you (and your money). It is &ldquo;bad&rdquo; if you waited a couple of days and the financial representation has been delivered before your call. In this case it will be much harder to cancel the transaction and get your money back. The bank will have to start an investigation, which can take up to 45 days. Meanwhile that amount will still be on hold.</p>

<p>10. Debit card users cannot go to overdraft.</p>

<p>As explained in #4, the purchase authorization logic is not based on the account balance, but on the daily limits. And it works similarly for debit and credit cards. The bank can adjust the daily limit, slightly exceeding the account balance, even for debit cards.</p>

<p>Hope all this information will help you avoid some unpleasant surprises when using plastic cards.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[MicroXP - a lightweight Windows XP]]></title>
    <link href="http://demin.ws/blog/english/2011/02/23/microxp/"/>
    <updated>2011-02-23T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/02/23/microxp/</id>
    <content type="html"><![CDATA[<p>The problem &ndash; a need to connect to a remote network via <a href="http://en.wikipedia.org/wiki/Remote_Desktop_Protocol">RDP</a>. To establish such connection, special software must be installed on a client workstation to create an encrypted tunnel between the workstation and the remote network. When that software is up and running, any application (telnet/ssh, ftp, radmin etc), including RDP client (mstsc.exe), might access to the remote network.</p>

<p>Not a problem when a client workstation runs Windows. You just go to a web site and logon, and then an ActiveX component gets started from the page, installs and runs everything required.</p>

<p>It becomes complicated if the workstation is not Windows. Indeed, there are RDP clients available for Linux and Mac, but it doesn&rsquo;t help much because without that encrypted channel it just doesn&rsquo;t have any meaning.</p>

<p>What do Linux and Mac users have to do? Install Windows in a virtual machine and run RDP in there. This is a good solution but with a drawback. A virtual machine hosting standard Windows usually takes a few gigabytes minimum and boots considerably slow.</p>

<p>I googled a bit and found <a href="http://www.google.co.uk/search?q=MicroXP-0.82.iso">MicroXP</a>. This is a very stripped-down version of XP SP3. The distribution ISO takes around ~100 MB, and when installed ~250. In VirtualBox on Mac Air the installation lasts five minutes and the already installed system boots in 10 seconds or less. The virtual machine requirements are minimal &ndash; a dynamic 300 MB disk and 64 MB of RAM.</p>

<p>After the installation of MicroXP you have to add Virtual Box Guest Additions (~200 KB) to share directories and not to struggle with the mouse, and then add a <a href="http://www.google.co.uk/search?q=RemoteDesktop-MicroXp-0.82.zip">RDP client</a> (it can be transferred to the VM via the shared folders).</p>

<p>In summary, if you need minimalistic and fast XP, MicroXP is a very good candidate.</p>

<p>P.S. Don&rsquo;t visit microxp.org. This is a fake to fish e-mails.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[One-command NORCPU program hacking challenge: analysis and solutions (link)]]></title>
    <link href="http://demin.ws/blog/english/2011/02/16/norcpu-hacking-challenge-analisys-and-solutions-link/"/>
    <updated>2011-02-16T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/02/16/norcpu-hacking-challenge-analisys-and-solutions-link/</id>
    <content type="html"><![CDATA[<p>For some reason Google Reader wasn&rsquo;t able to index my last huge post - <a href="http://demin.ws/blog/english/2011/02/16/norcpu-hacking-challenge-analisys-and-solutions/">One-command NORCPU program hacking challenge: analysis and solutions</a>.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[One-command NORCPU program hacking challenge: analysis and solutions]]></title>
    <link href="http://demin.ws/blog/english/2011/02/16/norcpu-hacking-challenge-analisys-and-solutions/"/>
    <updated>2011-02-16T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/02/16/norcpu-hacking-challenge-analisys-and-solutions/</id>
    <content type="html"><![CDATA[<p>Publishing the <a href="http://demin.ws/blog/english/2011/02/08/norcpu-hackme-challenge/">announcement of the problem to hack</a> a program running on the CPU executing just one single command, I hoped to get a solution to the end of March, not earlier.</p>

<p>Note: Quoted materials below are provided &ldquo;as is&rdquo; in the original author edition. Only minor formatting changes are applied. Of course, the texts on Russian are translated to English.</p>

<p>But the reality was different. Literally a few hours after the announcement, I received an e-mail from <strong>Vasiliy Artemev</strong>.</p>

<blockquote>
<p>Secret code: 139471</p>
</blockquote>

<p>That was the correct answer. Vasiliy was a winner and received the 100$ prize. He kindly shared that he bruteforced the problem. In fact, a simple bruteforce attach forced the program printing out the magic message even on a 3-character attempt. Alas, my hash function used to check the password had many collisions and become a weak link.</p>

<p>But there was no complete analysis of the password checking algorithm, and Vasiliy offered to sponsor the rest of the challenge to figure out the algorithm with 50$ from his prize. The challenge kept going.</p>

<p>In meanwhile I wrote the <a href="http://demin.ws/projects/norcpu/challenge/norcpu2.html">second version of the problem</a> without hashing but just an encrypted password. I hoped this makes the analysis harder. But in the same day evening I received an e-mail from <strong>Anton Bukov</strong>:</p>

<blockquote>
<p>Answer for NORCPU hackme challenge, Version 2: &ldquo;R0und2 D0ne!&rdquo; ?</p>
</blockquote>

<p>It was the correct one. I wondered how is it possible to figure out so quickly?</p>

<p>Anton also shared his approach.</p>

<blockquote>
<p>My hack is based on the line:</p>
</blockquote>

<pre><code>mem = mem_0.slice(0);
</code></pre>

<blockquote>
<p>An array gets copied here, and if you call <code>calc()</code> function twice on the same array, then for any incorrect password it will print out the answer. In code it looked as:</p>
</blockquote>

<pre><code>wcout &lt;&lt; calc(L&quot;0&quot;) &lt;&lt; endl &lt;&lt; calc(L&quot;0&quot;) &lt;&lt; endl;
</code></pre>

<blockquote>
<p>I guess that copying was used to prevent it. I&rsquo;m afraid this is not the way you expected. Even I was surprised when got the answer in the output. Afterwards I figured out where it appeared from.</p>
</blockquote>

<p>Accidentally Anton discovered a bug causing the program itself to reveal the secret, again. It needed just to run the interpreter twice without resetting memory.</p>

<p>The root of the problem:</p>

<pre class="hl">
...
  IS_0<span class="hl opt">(</span>flag<span class="hl opt">)</span>
  <span class="hl kwa">JZ</span> okay
  EXIT<span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">)</span>
<span class="hl kwc">okay:</span>
  <span class="hl slc">; print the secret</span>
  ...
</pre>

<p>After the first wrong run and refusing to print out the secret the program has stopped at the line 4, the <code>ip</code> register points to the <code>okay</code> label. If the interpreter gets started again without resetting memory (all registers including <code>ip</code> reside in memory), it keeps executing right from the <code>okay</code> and prints out the secret.</p>

<p>It was a shame. I fixed the problem quickly and released the version 2.1 without this side effect.</p>

<p>A couple of days left.</p>

<p>I received an e-mail from a guy with <strong>a5b</strong> nickname.</p>

<blockquote>
<p>Hot-patch of branching and the answer pw: <code>abcd</code> resp: <code>R0und2 D0ne!</code></p>

<ul>
<li>the password, obviously, is incorrect</li>
<li>inverted data being written to <code>(i == 27692 i==31712)</code></li>
</ul>
</blockquote>

<p>Formally, this is the solution, but there is no password which means the algorithm is not analysed so far.</p>

<p>But after an hour I received an addendum:</p>

<pre><code>h1cKmE1fUsAn

input data:
chr conI LEET xor
CHR1 13417 13313 104 h
CHR2 39953 39968 49 1
CHR3 54302 54397 99 c
CHR4 32223 32148 75 K
CHR5 30900 30937 109 m
CHR6 27373 27304 69 E
CHR7 16420 16405 49 1
CHR8 49210 49244 102 f
CHR9 16740 16689 85 U
CHR10 50115 50096 115 s
CHR11 19308 19245 65 A
CHR12 57802 57764 110 n

static init:
CHRi 59609= 59651
CONi 59610= 59634
CNTR 59611=12
SUM 59608=0
LEET 59607 = 13313

1:
[59609]+1 -&gt; [59609] // select next chr
[59610]+1 -&gt; [59610] // select next con

SUM |= CHRi ^ LEET ^ CONi
LEET = LEET * 3 + 29

[59611]: if([59611] != 0) Loop 1

...
if(SUM != 0) exit
else print R0und2 D0ne // haven't analysed this part.
// Based on the code modifications (moving the index), it loads 12 constants:
// 29528 22899 2971 9089 27542 17353 52278 25635 11626 34909 39131 51838,
// deals with each one and prints out.
</code></pre>

<p>This is the solution now. <strong>a5b</strong> became the first one who sent the algorithm of the <a href="http://demin.ws/projects/norcpu/challenge/norcpu2.html">problem 2</a>.</p>

<p>In the same evening I received a solution from <strong>Max Filippov</strong>.</p>

<blockquote>
<p>Algorithm that was used to check password correctness in the first round was the following:</p>
</blockquote>

<pre class="hl">
<span class="hl kwb">bool</span> <span class="hl kwd">check</span><span class="hl opt">(</span><span class="hl kwb">const char</span> <span class="hl opt">*</span>p<span class="hl opt">)</span>
<span class="hl opt">{</span>
   <span class="hl kwb">int</span> v <span class="hl opt">=</span> <span class="hl num">0x1040</span><span class="hl opt">;</span>

   <span class="hl kwa">for</span><span class="hl opt">(; *</span>p<span class="hl opt">; ++</span>p<span class="hl opt">)</span>
   <span class="hl opt">{</span>
       v <span class="hl opt">^= *</span>p<span class="hl opt">;</span>
       <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">8</span><span class="hl opt">; ++</span>i<span class="hl opt">)</span>
       <span class="hl opt">{</span>
           <span class="hl kwb">int</span> f <span class="hl opt">=</span> v <span class="hl opt">&amp;</span> <span class="hl num">1</span><span class="hl opt">;</span>
           v <span class="hl opt">&gt;&gt;=</span> <span class="hl num">1</span><span class="hl opt">;</span>
           <span class="hl kwa">if</span> <span class="hl opt">(</span>f<span class="hl opt">)</span>
               v <span class="hl opt">^=</span> <span class="hl num">0x1408</span><span class="hl opt">;</span>
       <span class="hl opt">}</span>
   <span class="hl opt">}</span>
   <span class="hl kwa">return</span> v <span class="hl opt">==</span> <span class="hl num">0x1c89</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<blockquote>
<p>that is, sort of CRC.</p>

<p>To discover it I&rsquo;ve collected NORCPU execution trace and &ldquo;disassembled&rdquo; it.</p>

<p>Modified NORCPU source and disassembler are attached, and also may be found <a href="http://jcmvbkbc.spb.ru/git/?p=dumb/norcpu.git;a=summary">there</a>.</p>
</blockquote>

<p>And a little add-on:</p>

<blockquote>
<p>The method used is pretty straightforward:</p>

<ul>
<li>collect execution trace;</li>
<li>recognize instruction patterns and collapse sequences of primitive instructions to more complex ones;</li>
<li>analyze disassembled trace.</li>
</ul>

<p>So, first I needed trace: I copied javascript text into cpp source, fixed lingual differences and inserted the following printf:</p>
</blockquote>

<pre class="hl">
<span class="hl kwa">while</span> <span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">) {</span>
  <span class="hl kwb">int</span> i <span class="hl opt">=</span> mem<span class="hl opt">[</span>ip<span class="hl opt">];</span>
  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%04x:NOR(%04x, %04x =&gt; %04x) &quot;</span><span class="hl opt">,</span> i<span class="hl opt">,</span> mem<span class="hl opt">[</span>i<span class="hl opt">],</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">],</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">2</span><span class="hl opt">]);</span>
  <span class="hl kwb">int</span> a <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">0</span><span class="hl opt">];</span>
</pre>

<blockquote>
<p>so that I got a long line (about 8Mb) of primitive instruction execution trace.</p>

<p>Then I started constructing sed script that would make it readable.</p>

<p>First, it broke the trace linewise, one instruction per line (288323 lines, will read it in case of insomnia). I took a look at processed trace and recorded several obvious instruction patterns into sed. Then reran script, took next look, recorded more patterns, &hellip;</p>

<p>This way I figured out all boolean logic commands and jumps. Then rotations left. Each time new command got recognized, new filtered processed trace was suggesting next step, e.g. 15 ROTL equals ROTR etc.</p>

<p>Then I looked into <a href="http://demin.ws/blog/english/2010/04/06/modelling-a-cpu-with-only-one-operation/">your article</a>. And found addition pattern in disassembly. And recorded it in sed script.</p>

<p>After that I was able to just read the trace (which shrink to 1035 lines). Its inner loop fit into one page, I just made some notes on a scratchpad:</p>
</blockquote>

<pre><code>[f1ba]: current in-T index (i)
[f1b4]: LEN
[f1b5]: 8

0012-0035:[f1b9] ^= (T[i] &amp; 0xff)

006d-007b:[f1b8] = [f1b9] &amp; 1
008a-0158:[f1b9] &gt;&gt;= 1
0167-10c7:[f1aa] = [f1b8] + -1, [f1ab] = !carry
10ca-10e6:jmp on carry to 1145:110d

110d-111b:[f1b9] ^= 1408

1145-1f4f:--[f1b5]
20a5-3005:[f1aa] = [f1b5] + -1, f1ab = !carry
3008-3024:jmp on carry to 006d:304b

304b-304b:++i
3fab-3fab:--LEN
4f0b-5e8a:jmp on carry to 5eb1:6
</code></pre>

<blockquote>
<p>then I browsed through the repetitions of this inner loop and found the end of the outer loop.</p>
</blockquote>

<pre><code>5eb1-6e74:check 1c89
</code></pre>

<blockquote>
<p>Then just translated it into C. It all took me three evenings.</p>
</blockquote>

<p>Then Max Filippov sent the solution for the <a href="http://demin.ws/projects/norcpu/challenge/norcpu2.html">problem 2</a>.</p>

<blockquote>
<p>The second problem answer &ndash; <code>h1cKmE1fUsAn</code></p>

<p>The result &ndash; <code>R0und2 D0ne!</code></p>

<p>The password check algorithm is:</p>
</blockquote>

<pre class="hl">
<span class="hl kwb">bool</span> <span class="hl kwd">check</span><span class="hl opt">(</span><span class="hl kwb">const char</span> <span class="hl opt">*</span>p<span class="hl opt">)</span>
<span class="hl opt">{</span>
   <span class="hl kwb">static const int</span> xor_array<span class="hl opt">[] = {</span>
       <span class="hl num">0x3469</span><span class="hl opt">,</span>
       <span class="hl num">0x9c11</span><span class="hl opt">,</span>
       <span class="hl num">0xd41e</span><span class="hl opt">,</span>
       <span class="hl num">0x7ddf</span><span class="hl opt">,</span>
       <span class="hl num">0x78b4</span><span class="hl opt">,</span>
       <span class="hl num">0x6aed</span><span class="hl opt">,</span>
       <span class="hl num">0x4024</span><span class="hl opt">,</span>
       <span class="hl num">0xc03a</span><span class="hl opt">,</span>
       <span class="hl num">0x4164</span><span class="hl opt">,</span>
       <span class="hl num">0xc3c3</span><span class="hl opt">,</span>
       <span class="hl num">0x4b6c</span><span class="hl opt">,</span>
       <span class="hl num">0xe1ca</span><span class="hl opt">,</span>
   <span class="hl opt">};</span>

   <span class="hl kwb">int</span> v <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
   <span class="hl kwb">int</span> x <span class="hl opt">=</span> <span class="hl num">0x3401</span><span class="hl opt">;</span>

   <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">12</span><span class="hl opt">; ++</span>i<span class="hl opt">)</span>
   <span class="hl opt">{</span>
       <span class="hl kwb">int</span> f <span class="hl opt">=</span> p<span class="hl opt">[</span>i<span class="hl opt">] ^</span> x <span class="hl opt">^</span> xor_array<span class="hl opt">[</span>i<span class="hl opt">];</span>
       <span class="hl slc">// printf(&quot;x: %04x, f: %04x\n&quot;, x, f);</span>
       v <span class="hl opt">|=</span> f<span class="hl opt">;</span>
       x <span class="hl opt">= (</span>x <span class="hl opt">*</span> <span class="hl num">3</span> <span class="hl opt">+</span> <span class="hl num">0x1d</span><span class="hl opt">) &amp;</span> <span class="hl num">0xffff</span><span class="hl opt">;</span>
   <span class="hl opt">}</span>
   <span class="hl kwa">return</span> <span class="hl opt">!</span>v<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<blockquote>
<p>The commented printf prints out the secret phrase on-the-fly.</p>

<p>The method of analysis &ndash; similar to the first problem &ndash; disassembling of the trace.</p>

<p>The first round was frankly more interestintg.</p>
</blockquote>

<p>And, finally, the last solution of the <a href="http://demin.ws/projects/norcpu/challenge/norcpu.html">first problem</a> is received from <strong>Salo Kril</strong>.</p>

<p>No comments &ndash; just sources.</p>

<pre class="hl">
<span class="hl slc">// Password generation.</span>

<span class="hl slc">// Brute_force(3);</span>

WORD <span class="hl kwd">ks_f</span><span class="hl opt">(</span><span class="hl kwb">char</span> <span class="hl opt">*</span>buff<span class="hl opt">,</span> <span class="hl kwb">int</span> len<span class="hl opt">)</span>
<span class="hl opt">{</span>
   <span class="hl kwb">int</span> i<span class="hl opt">,</span> j<span class="hl opt">;</span>
   WORD ks <span class="hl opt">=</span> <span class="hl num">0x1040</span><span class="hl opt">;</span>

   <span class="hl kwa">for</span> <span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> len<span class="hl opt">;</span> i<span class="hl opt">++)</span>
   <span class="hl opt">{</span>
       ks <span class="hl opt">^=</span> buff<span class="hl opt">[</span>i<span class="hl opt">];</span>
       <span class="hl kwa">for</span> <span class="hl opt">(</span>j <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> j <span class="hl opt">&lt;</span> <span class="hl num">8</span><span class="hl opt">;</span> j<span class="hl opt">++)</span>
       <span class="hl opt">{</span>
           <span class="hl kwa">if</span><span class="hl opt">((</span>ks <span class="hl opt">&amp;</span> <span class="hl num">1</span><span class="hl opt">) ==</span> <span class="hl num">0</span><span class="hl opt">)</span>
               ks <span class="hl opt">=</span> ks <span class="hl opt">&gt;&gt;</span> <span class="hl num">1</span><span class="hl opt">;</span>
           <span class="hl kwa">else</span>
               ks <span class="hl opt">= (</span>ks <span class="hl opt">&gt;&gt;</span> <span class="hl num">1</span><span class="hl opt">) ^</span> <span class="hl num">0x1408</span><span class="hl opt">;</span>
       <span class="hl opt">}</span>
   <span class="hl opt">}</span>
   <span class="hl kwa">return</span> ks<span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">Brute_force</span><span class="hl opt">(</span><span class="hl kwb">int</span> n<span class="hl opt">)</span>
<span class="hl opt">{</span>
   <span class="hl kwb">int</span> i<span class="hl opt">;</span>
   <span class="hl kwb">static char</span> alphabet<span class="hl opt">[] =</span>
       <span class="hl str">&quot;</span><span class="hl esc">\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F</span><span class="hl str">&quot;</span>
       <span class="hl str">&quot;</span><span class="hl esc">\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F</span><span class="hl str">&quot;</span>
       <span class="hl str">&quot;</span><span class="hl esc">\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F</span><span class="hl str">&quot;</span>
       <span class="hl str">&quot;</span><span class="hl esc">\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F</span><span class="hl str">&quot;</span>
       <span class="hl str">&quot;</span><span class="hl esc">\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F</span><span class="hl str">&quot;</span>
       <span class="hl str">&quot;</span><span class="hl esc">\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E</span><span class="hl str">&quot;</span><span class="hl opt">;</span>

   <span class="hl kwa">if</span><span class="hl opt">(</span>n <span class="hl opt">==</span> <span class="hl num">0</span><span class="hl opt">)</span>
   <span class="hl opt">{</span>
       <span class="hl kwa">if</span><span class="hl opt">(</span><span class="hl kwd">ks_f</span><span class="hl opt">(</span>buff_bf<span class="hl opt">,</span> BF_N<span class="hl opt">) ==</span> <span class="hl num">0x1c89</span><span class="hl opt">)</span>
           <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%s</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span>buff_bf<span class="hl opt">);</span>
       <span class="hl kwa">return</span><span class="hl opt">;</span>
   <span class="hl opt">}</span>

   n<span class="hl opt">--;</span>
   <span class="hl kwa">for</span> <span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> alphabet<span class="hl opt">[</span>i<span class="hl opt">];</span> i<span class="hl opt">++)</span>
   <span class="hl opt">{</span>
       buff_bf<span class="hl opt">[</span>n<span class="hl opt">] =</span> alphabet<span class="hl opt">[</span>i<span class="hl opt">];</span>
       <span class="hl kwd">Brute_force</span><span class="hl opt">(</span>n<span class="hl opt">);</span>
   <span class="hl opt">}</span>
<span class="hl opt">}</span>
</pre>

<p>and re-constructed code:</p>

<pre class="hl">
<span class="hl ppc">#define DEST_COUNT  0xF1FE</span>
<span class="hl kwc">extern</span> WORD mem<span class="hl opt">[];</span>

<span class="hl com">/*</span>
<span class="hl com">    Secret code: 139471</span>
<span class="hl com">*/</span>
<span class="hl kwb">void</span> <span class="hl kwd">reconstructed_fn</span><span class="hl opt">(</span><span class="hl kwb">void</span><span class="hl opt">)</span>
<span class="hl opt">{</span>
    <span class="hl kwb">int</span> i<span class="hl opt">,</span> j<span class="hl opt">;</span>
    WORD src<span class="hl opt">,</span> dest<span class="hl opt">,</span> key<span class="hl opt">,</span> count<span class="hl opt">,</span> hash<span class="hl opt">,</span> hash_OK<span class="hl opt">,</span> key_const<span class="hl opt">;</span>

    src <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BA</span><span class="hl opt">];</span>     <span class="hl slc">// input string</span>
    count <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1ED</span><span class="hl opt">];</span>   <span class="hl slc">// input string length</span>
    dest <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BB</span><span class="hl opt">];</span>    <span class="hl slc">// 0xf1ff</span>
    hash_OK <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BC</span><span class="hl opt">];</span> <span class="hl slc">// 0x1c89</span>
    hash <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1B9</span><span class="hl opt">];</span>    <span class="hl slc">// 0x1040</span>


    <span class="hl kwa">for</span><span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> count<span class="hl opt">;</span> i<span class="hl opt">++)</span>
    <span class="hl opt">{</span>
        hash <span class="hl opt">^=</span> mem<span class="hl opt">[</span>src <span class="hl opt">+</span> i<span class="hl opt">] &amp;</span> <span class="hl num">0xFF</span><span class="hl opt">;</span>

        <span class="hl kwa">for</span> <span class="hl opt">(</span>j <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> j <span class="hl opt">&lt;</span> <span class="hl num">8</span><span class="hl opt">;</span> j<span class="hl opt">++)</span>
        <span class="hl opt">{</span>
            <span class="hl kwa">if</span> <span class="hl opt">((</span>hash <span class="hl opt">&amp;</span> <span class="hl num">1</span><span class="hl opt">) ==</span> <span class="hl num">0</span><span class="hl opt">)</span>
                hash <span class="hl opt">=</span> hash <span class="hl opt">&gt;&gt;</span> <span class="hl num">1</span><span class="hl opt">;</span>
            <span class="hl kwa">else</span>
                hash <span class="hl opt">= (</span>hash <span class="hl opt">&gt;&gt;</span> <span class="hl num">1</span><span class="hl opt">) ^</span> <span class="hl num">0x1408</span><span class="hl opt">;</span>
        <span class="hl opt">}</span>
    <span class="hl opt">}</span>

    <span class="hl kwa">if</span> <span class="hl opt">(</span>hash <span class="hl opt">==</span> hash_OK<span class="hl opt">)</span>
    <span class="hl opt">{</span>
        src <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0x6EB6</span><span class="hl opt">];</span>              <span class="hl slc">// &quot;Secret code: 139471&quot;</span>
        count <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1C7</span><span class="hl opt">];</span>            <span class="hl slc">// 19</span>
        key <span class="hl opt">= ((</span>hash <span class="hl opt">&gt;&gt;</span> <span class="hl num">8</span><span class="hl opt">) ^</span> hash<span class="hl opt">) +</span> <span class="hl num">1</span><span class="hl opt">;</span>
        key_const <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0x6EA8</span><span class="hl opt">];</span>        <span class="hl slc">// 11</span>
    <span class="hl opt">}</span>
    <span class="hl kwa">else</span>
    <span class="hl opt">{</span>
        src <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0x5EBE</span><span class="hl opt">];</span>          <span class="hl slc">// &quot;Wrong password!&quot;</span>
        count <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1DC</span><span class="hl opt">];</span>        <span class="hl slc">// 15</span>
        key <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BD</span><span class="hl opt">];</span>
        key_const <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BE</span><span class="hl opt">];</span>    <span class="hl slc">// 17</span>
    <span class="hl opt">}</span>

    mem<span class="hl opt">[</span>DEST_COUNT<span class="hl opt">] =</span> count<span class="hl opt">;</span>
    <span class="hl kwa">for</span> <span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> count<span class="hl opt">;</span> i<span class="hl opt">++)</span>
    <span class="hl opt">{</span>
        mem<span class="hl opt">[</span>dest <span class="hl opt">+</span> i<span class="hl opt">] =</span> mem<span class="hl opt">[</span>src <span class="hl opt">+</span> i<span class="hl opt">] ^</span> key<span class="hl opt">;</span>
        key <span class="hl opt">=</span> key <span class="hl opt">*</span> <span class="hl num">3</span> <span class="hl opt">+</span> key_const<span class="hl opt">;</span>
    <span class="hl opt">}</span>
<span class="hl opt">}</span>

<span class="hl com">/*</span>
<span class="hl com">--------------------------------------------------------------------------------------------</span>
<span class="hl com">~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~</span>
<span class="hl com">--------------------------------------------------------------------------------------------</span>
<span class="hl com">*/</span>
WORD <span class="hl kwa">and</span><span class="hl opt">(</span>WORD w1<span class="hl opt">,</span> WORD w2<span class="hl opt">)</span>
<span class="hl opt">{</span>
    <span class="hl kwa">return</span> w1 <span class="hl opt">&amp;</span> w2<span class="hl opt">;</span>
<span class="hl opt">}</span>

WORD <span class="hl kwa">or</span><span class="hl opt">(</span>WORD w1<span class="hl opt">,</span> WORD w2<span class="hl opt">)</span>
<span class="hl opt">{</span>
    <span class="hl kwa">return</span> w1 <span class="hl opt">|</span> w2<span class="hl opt">;</span>
<span class="hl opt">}</span>

WORD <span class="hl kwa">xor</span><span class="hl opt">(</span>WORD w1<span class="hl opt">,</span> WORD w2<span class="hl opt">)</span>
<span class="hl opt">{</span>
    <span class="hl kwa">return</span> w1 <span class="hl opt">^</span> w2<span class="hl opt">;</span>
<span class="hl opt">}</span>

WORD <span class="hl kwd">rol</span><span class="hl opt">(</span>WORD w1<span class="hl opt">,</span> WORD n<span class="hl opt">)</span>
<span class="hl opt">{</span>
    <span class="hl kwa">return</span> <span class="hl opt">(</span>w1 <span class="hl opt">&lt;&lt;</span> n<span class="hl opt">) | (</span>w1 <span class="hl opt">&gt;&gt; (</span><span class="hl num">16</span> <span class="hl opt">-</span> n<span class="hl opt">));</span>
<span class="hl opt">}</span>

WORD <span class="hl kwd">ror</span><span class="hl opt">(</span>WORD w1<span class="hl opt">,</span> WORD n<span class="hl opt">)</span>
<span class="hl opt">{</span>
    <span class="hl kwa">return</span> <span class="hl opt">(</span>w1 <span class="hl opt">&gt;&gt;</span> n<span class="hl opt">) | (</span>w1 <span class="hl opt">&lt;&lt; (</span><span class="hl num">16</span> <span class="hl opt">-</span> n<span class="hl opt">));</span>
<span class="hl opt">}</span>
WORD <span class="hl kwd">extend_16</span><span class="hl opt">(</span>WORD k1<span class="hl opt">)</span>
<span class="hl opt">{</span>
    <span class="hl kwb">int</span> i<span class="hl opt">,</span> k2<span class="hl opt">;</span>

    <span class="hl kwa">for</span> <span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">,</span> k2 <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">16</span><span class="hl opt">;</span> i<span class="hl opt">++)</span>
    <span class="hl opt">{</span>
        k2 <span class="hl opt">=</span> <span class="hl kwa">or</span><span class="hl opt">(</span>k2<span class="hl opt">,</span> k1<span class="hl opt">);</span>
        k1 <span class="hl opt">=</span> <span class="hl kwd">rol</span><span class="hl opt">(</span>k1<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>
    <span class="hl opt">}</span>

    <span class="hl kwa">return</span> k2<span class="hl opt">;</span>
<span class="hl opt">}</span>

WORD <span class="hl kwd">add</span><span class="hl opt">(</span>WORD <span class="hl opt">*</span>kk1<span class="hl opt">,</span> WORD a<span class="hl opt">,</span> WORD b<span class="hl opt">)</span>
<span class="hl opt">{</span>
    WORD mask_bit<span class="hl opt">,</span> aa0<span class="hl opt">,</span> aa1<span class="hl opt">,</span> tmp1<span class="hl opt">,</span> i<span class="hl opt">,</span> k1<span class="hl opt">,</span> k2<span class="hl opt">;</span>
    k1 <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
    k2 <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
    mask_bit <span class="hl opt">=</span> <span class="hl num">1</span><span class="hl opt">;</span>

    <span class="hl kwa">for</span> <span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> <span class="hl num">16</span><span class="hl opt">;</span> i<span class="hl opt">++)</span>
    <span class="hl opt">{</span>
        k1 <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>k1<span class="hl opt">,</span> mask_bit<span class="hl opt">);</span>
        aa0 <span class="hl opt">=</span> <span class="hl kwa">xor</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">);</span>
        tmp1 <span class="hl opt">=</span> <span class="hl kwa">xor</span><span class="hl opt">(</span>aa0<span class="hl opt">,</span> k1<span class="hl opt">);</span>
        tmp1 <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>tmp1<span class="hl opt">,</span> mask_bit<span class="hl opt">);</span>
        k2 <span class="hl opt">=</span> <span class="hl kwa">or</span><span class="hl opt">(</span>tmp1<span class="hl opt">,</span> k2<span class="hl opt">);</span>
        aa1 <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">);</span>
        aa0 <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>k1<span class="hl opt">,</span> aa0<span class="hl opt">);</span>
        k1 <span class="hl opt">=</span> <span class="hl kwa">or</span><span class="hl opt">(</span>aa1<span class="hl opt">,</span> aa0<span class="hl opt">);</span>
        k1 <span class="hl opt">=</span> <span class="hl kwd">rol</span><span class="hl opt">(</span>k1<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>
        mask_bit <span class="hl opt">=</span> <span class="hl kwd">rol</span><span class="hl opt">(</span>mask_bit<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>
    <span class="hl opt">}</span>
    k1 <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>k1<span class="hl opt">,</span> mask_bit<span class="hl opt">);</span>
    <span class="hl opt">*</span>kk1 <span class="hl opt">=</span> <span class="hl kwd">extend_16</span><span class="hl opt">(</span>k1<span class="hl opt">);</span>

    <span class="hl kwa">return</span> k2<span class="hl opt">;</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">reconstr</span><span class="hl opt">(</span><span class="hl kwb">void</span><span class="hl opt">)</span>
<span class="hl opt">{</span>
    WORD k1<span class="hl opt">,</span> k2<span class="hl opt">,</span> src<span class="hl opt">,</span> dest<span class="hl opt">,</span> tmp1<span class="hl opt">,</span> key<span class="hl opt">,</span> count<span class="hl opt">,</span> tmp2<span class="hl opt">,</span> tmp3<span class="hl opt">,</span> i<span class="hl opt">,</span> ks<span class="hl opt">,</span> ks_OK<span class="hl opt">,</span> key_a<span class="hl opt">;</span>
    WORD mask_bit<span class="hl opt">,</span> aa1<span class="hl opt">,</span> aa0<span class="hl opt">;</span>

    k1 <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1AF</span><span class="hl opt">];</span>    <span class="hl slc">// 0x88</span>
    k2 <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1A3</span><span class="hl opt">];</span>    <span class="hl slc">// 0x47</span>
    src <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BA</span><span class="hl opt">];</span>   <span class="hl slc">// input string</span>
    count <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1ED</span><span class="hl opt">];</span> <span class="hl slc">// input string length</span>
    dest <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BB</span><span class="hl opt">];</span>  <span class="hl slc">// 0xf1ff</span>
    ks_OK <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BC</span><span class="hl opt">];</span> <span class="hl slc">// 0x1c89             &quot;w&quot;:ks=0x0ACC   &quot;WWW&quot;:0x0FCE   &quot;123456789&quot;:ks=0x05E3</span>
    ks <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1B9</span><span class="hl opt">];</span>    <span class="hl slc">// 0x1040</span>


l_0006<span class="hl opt">:</span>
    ks <span class="hl opt">=</span> <span class="hl kwa">xor</span><span class="hl opt">(</span>ks<span class="hl opt">,</span> <span class="hl kwa">and</span><span class="hl opt">(</span>mem<span class="hl opt">[</span>src<span class="hl opt">],</span> <span class="hl num">0xFF</span><span class="hl opt">));</span>
    i <span class="hl opt">=</span> <span class="hl num">8</span><span class="hl opt">;</span>

l_006D<span class="hl opt">:</span>
    tmp3 <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>ks<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>
    ks <span class="hl opt">=</span> <span class="hl kwd">ror</span><span class="hl opt">(</span>ks<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>
    ks <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>ks<span class="hl opt">,</span> <span class="hl num">0x7FFF</span><span class="hl opt">);</span>
    tmp2 <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k2<span class="hl opt">,</span> tmp3<span class="hl opt">, -</span><span class="hl num">1</span><span class="hl opt">);</span>
    <span class="hl kwa">if</span><span class="hl opt">(</span>k2 <span class="hl opt">!=</span> <span class="hl num">0</span><span class="hl opt">)</span>
    <span class="hl opt">{</span>
        ks <span class="hl opt">=</span> <span class="hl kwa">xor</span><span class="hl opt">(</span>ks<span class="hl opt">,</span> <span class="hl num">0x1408</span><span class="hl opt">);</span>
    <span class="hl opt">}</span>

l_1145<span class="hl opt">:</span>
    i <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> i<span class="hl opt">, -</span><span class="hl num">1</span><span class="hl opt">);</span>
    tmp2 <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k2<span class="hl opt">,</span> i<span class="hl opt">, -</span><span class="hl num">1</span><span class="hl opt">);</span>
    <span class="hl kwa">if</span><span class="hl opt">(</span>k2 <span class="hl opt">!=</span> <span class="hl num">0</span><span class="hl opt">)</span>
        <span class="hl kwa">goto</span> l_006D<span class="hl opt">;</span>

l_304B<span class="hl opt">:</span>
    src <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> src<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>
    count <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> count<span class="hl opt">, -</span><span class="hl num">1</span><span class="hl opt">);</span>
    tmp2 <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k2<span class="hl opt">,</span> count<span class="hl opt">, -</span><span class="hl num">1</span><span class="hl opt">);</span>
    <span class="hl kwa">if</span><span class="hl opt">(</span>k2 <span class="hl opt">!=</span> <span class="hl num">0</span><span class="hl opt">)</span>
        <span class="hl kwa">goto</span> l_0006<span class="hl opt">;</span>


    src <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0x5EBE</span><span class="hl opt">];</span>    <span class="hl slc">// Wrong password!</span>
    count <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1DC</span><span class="hl opt">];</span>  <span class="hl slc">// 15</span>
    key <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BD</span><span class="hl opt">];</span>
    key_a <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1BE</span><span class="hl opt">];</span>
    ks_OK <span class="hl opt">=</span> <span class="hl kwa">xor</span><span class="hl opt">(</span>ks_OK<span class="hl opt">,</span> ks<span class="hl opt">);</span>
    tmp2 <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k2<span class="hl opt">,</span> ks_OK<span class="hl opt">, -</span><span class="hl num">1</span><span class="hl opt">);</span>

    <span class="hl kwa">if</span><span class="hl opt">(</span>k2 <span class="hl opt">!=</span> <span class="hl num">0</span><span class="hl opt">)</span>
        <span class="hl kwa">goto</span> l_8552<span class="hl opt">;</span>

l_6E9B<span class="hl opt">:</span>
    src <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0x6EB6</span><span class="hl opt">];</span>     <span class="hl slc">// Secret code: 139471</span>
    count <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0xF1C7</span><span class="hl opt">];</span>   <span class="hl slc">// 19</span>
    key <span class="hl opt">=</span> ks<span class="hl opt">;</span>
    key_a <span class="hl opt">=</span> mem<span class="hl opt">[</span><span class="hl num">0x6EA8</span><span class="hl opt">];</span>

    key <span class="hl opt">=</span> <span class="hl kwd">ror</span><span class="hl opt">(</span>key<span class="hl opt">,</span> <span class="hl num">8</span><span class="hl opt">);</span>
    key <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>key<span class="hl opt">,</span> <span class="hl num">0xFF</span><span class="hl opt">);</span>
    key <span class="hl opt">=</span> <span class="hl kwa">xor</span><span class="hl opt">(</span>ks<span class="hl opt">,</span> key<span class="hl opt">);</span>
    key <span class="hl opt">=</span> <span class="hl kwa">and</span><span class="hl opt">(</span>key<span class="hl opt">,</span> <span class="hl num">0x7FFF</span><span class="hl opt">);</span>
    key <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> key<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>


l_8552<span class="hl opt">:</span>
    mem<span class="hl opt">[</span>DEST_COUNT<span class="hl opt">] =</span> count<span class="hl opt">;</span>
l_8558<span class="hl opt">:</span>
    mem<span class="hl opt">[</span>dest<span class="hl opt">] =</span> <span class="hl kwa">xor</span><span class="hl opt">(</span>mem<span class="hl opt">[</span>src<span class="hl opt">],</span> key<span class="hl opt">);</span>
    tmp3 <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> key<span class="hl opt">,</span> key<span class="hl opt">);</span>
    key <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> key<span class="hl opt">,</span> tmp3<span class="hl opt">);</span>
    key <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> key<span class="hl opt">,</span> key_a<span class="hl opt">);</span>
    src <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> src<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>
    dest <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> dest<span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">);</span>
    count <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k1<span class="hl opt">,</span> count<span class="hl opt">, -</span><span class="hl num">1</span><span class="hl opt">);</span>
    tmp2 <span class="hl opt">=</span> <span class="hl kwd">add</span><span class="hl opt">(&amp;</span>k2<span class="hl opt">,</span> count<span class="hl opt">, -</span><span class="hl num">1</span><span class="hl opt">);</span>
    <span class="hl kwa">if</span><span class="hl opt">(</span>k2 <span class="hl opt">!=</span> <span class="hl num">0</span><span class="hl opt">)</span>
        <span class="hl kwa">goto</span> l_8558<span class="hl opt">;</span>

l_F186<span class="hl opt">:</span>
    mem<span class="hl opt">[</span><span class="hl num">0xF1B2</span><span class="hl opt">] =</span> mem<span class="hl opt">[</span><span class="hl num">0xF193</span><span class="hl opt">];</span> <span class="hl slc">// nc</span>
<span class="hl opt">}</span>
</pre>

<p>Well, as you understand the solutions have been fully comprehensive.</p>

<p>Thanks to all participants.</p>

<p>I&rsquo;m putting the original sources below. Just run the Python script to compile the code written on the function-macros, to run through and to generate an html-page (&ldquo;template.html&rdquo; is required).</p>

<p>All the sources are available on as a git <a href="https://github.com/begoon/norcpu/">repository</a>.</p>

<h2>Problem 1</h2>

<p>File <a href="https://github.com/begoon/norcpu/blob/master/v1/norcpu.py">norcpu.py</a> (<a href="https://github.com/begoon/norcpu/blob/master/v1/template.html">template.html</a>):</p>

<pre class="hl">
<span class="hl kwa">import</span> sys<span class="hl opt">,</span> re<span class="hl opt">,</span> time<span class="hl opt">,</span> string<span class="hl opt">,</span> binascii

verbose <span class="hl opt">=</span> <span class="hl kwa">False</span>
verbose_cpu <span class="hl opt">=</span> <span class="hl kwa">False</span>
scramble <span class="hl opt">=</span> <span class="hl kwa">True</span>

test_wrong_crc <span class="hl opt">=</span> <span class="hl num">0</span>

secret_code <span class="hl opt">=</span> <span class="hl str">&quot;Secret code: 139471&quot;</span>
password <span class="hl opt">=</span> <span class="hl str">&quot;h0cKmE1fUsAn&quot;</span>
guess    <span class="hl opt">=</span> <span class="hl str">&quot;123456789012&quot;</span>
guess    <span class="hl opt">=</span> password

<span class="hl slc"># Secret code message encryption mask.</span>
secret_coef_add <span class="hl opt">=</span> <span class="hl num">17</span>

message_text <span class="hl opt">=</span> <span class="hl str">&quot;Wrong password!&quot;</span>
<span class="hl slc"># Wrong password message encryption mask.</span>
message_mask <span class="hl opt">=</span> <span class="hl num">0x6301</span>
message_coef_add <span class="hl opt">=</span> <span class="hl num">11</span>

<span class="hl slc"># Non-standard CRC initial value (should be 0xFFFF).</span>
crc16_initial_value <span class="hl opt">=</span> <span class="hl num">0x1040</span>

<span class="hl slc"># Non-standard CRC constant (should be 0x8401).</span>
crc16_constant <span class="hl opt">=</span> <span class="hl num">0x1408</span>

code_segment <span class="hl opt">= []</span>
data_segment <span class="hl opt">= []</span>

label_count <span class="hl opt">=</span> <span class="hl num">0</span>

<span class="hl kwa">def</span> <span class="hl kwd">dump</span><span class="hl opt">(</span>data<span class="hl opt">,</span> length <span class="hl opt">=</span> <span class="hl num">8</span><span class="hl opt">):</span>
  result <span class="hl opt">= []</span>
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">xrange</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwb">len</span><span class="hl opt">(</span>data<span class="hl opt">),</span> length<span class="hl opt">):</span>
    line <span class="hl opt">=</span> data<span class="hl opt">[</span>i<span class="hl opt">:</span>i <span class="hl opt">+</span> length<span class="hl opt">]</span>
    hex_line <span class="hl opt">=</span> <span class="hl str">' '</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">([</span><span class="hl str">&quot;%04X&quot;</span> <span class="hl opt">%</span> x <span class="hl kwa">for</span> x <span class="hl kwa">in</span> line<span class="hl opt">])</span>
    result<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">&quot;%04X: %-*s</span><span class="hl esc">\n</span><span class="hl str">&quot;</span> <span class="hl opt">% (</span>i<span class="hl opt">,</span> length<span class="hl opt">*</span><span class="hl num">5</span><span class="hl opt">,</span> hex_line<span class="hl opt">))</span>
  <span class="hl kwa">return</span> <span class="hl str">''</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>result<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">dump_js</span><span class="hl opt">(</span>data<span class="hl opt">,</span> length <span class="hl opt">=</span> <span class="hl num">8</span><span class="hl opt">):</span>
  result <span class="hl opt">= []</span>
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">xrange</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwb">len</span><span class="hl opt">(</span>data<span class="hl opt">),</span> length<span class="hl opt">):</span>
    line <span class="hl opt">=</span> data<span class="hl opt">[</span>i<span class="hl opt">:</span>i <span class="hl opt">+</span> length<span class="hl opt">]</span>
    hex_line <span class="hl opt">=</span> <span class="hl str">' '</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">([</span><span class="hl str">&quot;0x%04X,&quot;</span> <span class="hl opt">%</span> x <span class="hl kwa">for</span> x <span class="hl kwa">in</span> line<span class="hl opt">])</span>
    result<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">&quot;%-*s</span><span class="hl esc">\n</span><span class="hl str">&quot;</span> <span class="hl opt">% (</span>length<span class="hl opt">*</span><span class="hl num">5</span><span class="hl opt">,</span> hex_line<span class="hl opt">))</span>
  <span class="hl kwa">return</span> <span class="hl str">''</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>result<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">calc_crc16</span><span class="hl opt">(</span>data<span class="hl opt">):</span>
  <span class="hl kwa">global</span> crc16_initial_value
  <span class="hl kwa">global</span> crc16_constant

  crc16 <span class="hl opt">=</span> crc16_initial_value
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwb">len</span><span class="hl opt">(</span>data<span class="hl opt">)):</span>
    ch <span class="hl opt">=</span> <span class="hl kwb">ord</span><span class="hl opt">(</span>data<span class="hl opt">[</span>i<span class="hl opt">]) &amp;</span> <span class="hl num">0xff</span>
    crc16 <span class="hl opt">=</span> crc16 ^ ch
    <span class="hl kwa">for</span> j <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl num">8</span><span class="hl opt">):</span>
      <span class="hl kwa">if</span> <span class="hl opt">((</span>crc16 <span class="hl opt">&amp;</span> <span class="hl num">1</span><span class="hl opt">) !=</span> <span class="hl num">0</span><span class="hl opt">):</span>
        crc16 <span class="hl opt">= (</span>crc16 <span class="hl opt">&gt;&gt;</span> <span class="hl num">1</span><span class="hl opt">)</span> ^ crc16_constant
      <span class="hl kwa">else</span><span class="hl opt">:</span>
        crc16 <span class="hl opt">=</span> crc16 <span class="hl opt">&gt;&gt;</span> <span class="hl num">1</span>
  <span class="hl kwa">return</span> crc16

crc16 <span class="hl opt">=</span> <span class="hl kwd">calc_crc16</span><span class="hl opt">(</span>password<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">encode_string</span><span class="hl opt">(</span>data<span class="hl opt">,</span> name<span class="hl opt">,</span> mask<span class="hl opt">,</span> coef_add<span class="hl opt">):</span>
  <span class="hl kwa">global</span> mem<span class="hl opt">,</span> names
  offset <span class="hl opt">=</span> names<span class="hl opt">[</span>name<span class="hl opt">]</span>
  offset_sz <span class="hl opt">=</span> names<span class="hl opt">[</span>name <span class="hl opt">+</span> <span class="hl str">&quot;_sz&quot;</span><span class="hl opt">]</span>
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwb">len</span><span class="hl opt">(</span>data<span class="hl opt">)):</span>
    mem<span class="hl opt">[</span>offset <span class="hl opt">+</span> i<span class="hl opt">] =</span> <span class="hl kwb">ord</span><span class="hl opt">(</span>data<span class="hl opt">[</span>i<span class="hl opt">])</span> ^ mask
    mask <span class="hl opt">= (</span>mask <span class="hl opt">*</span> <span class="hl num">3</span> <span class="hl opt">+</span> coef_add<span class="hl opt">) &amp;</span> <span class="hl num">0xffff</span>
  mem<span class="hl opt">[</span>offset_sz<span class="hl opt">] =</span> <span class="hl kwb">len</span><span class="hl opt">(</span>data<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">put_string</span><span class="hl opt">(</span>data<span class="hl opt">,</span> name<span class="hl opt">):</span>
  <span class="hl kwa">global</span> mem<span class="hl opt">,</span> names
  offset <span class="hl opt">=</span> names<span class="hl opt">[</span>name<span class="hl opt">]</span>
  offset_sz <span class="hl opt">=</span> names<span class="hl opt">[</span>name <span class="hl opt">+</span> <span class="hl str">&quot;_sz&quot;</span><span class="hl opt">]</span>
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwb">len</span><span class="hl opt">(</span>data<span class="hl opt">)):</span>
    mem<span class="hl opt">[</span>offset <span class="hl opt">+</span> i<span class="hl opt">] =</span> <span class="hl kwb">ord</span><span class="hl opt">(</span>data<span class="hl opt">[</span>i<span class="hl opt">])</span>
  mem<span class="hl opt">[</span>offset_sz<span class="hl opt">] =</span> <span class="hl kwb">len</span><span class="hl opt">(</span>data<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">save_mem</span><span class="hl opt">(</span>name<span class="hl opt">,</span> size <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">):</span>
  f <span class="hl opt">=</span> <span class="hl kwb">open</span><span class="hl opt">(</span>name<span class="hl opt">,</span> <span class="hl str">&quot;w&quot;</span><span class="hl opt">)</span>
  <span class="hl kwa">if</span> size <span class="hl opt">== -</span><span class="hl num">1</span><span class="hl opt">:</span> size <span class="hl opt">=</span> <span class="hl kwb">len</span><span class="hl opt">(</span>mem<span class="hl opt">)</span>
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl opt">(</span>mem<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">:</span>size<span class="hl opt">]):</span>
    <span class="hl kwb">hex</span> <span class="hl opt">=</span> <span class="hl str">&quot;%04X&quot;</span> <span class="hl opt">%</span> i
    bin <span class="hl opt">=</span> binascii<span class="hl opt">.</span><span class="hl kwd">a2b_hex</span><span class="hl opt">(</span><span class="hl kwb">hex</span><span class="hl opt">)</span>
    f<span class="hl opt">.</span><span class="hl kwd">write</span><span class="hl opt">(</span>bin<span class="hl opt">)</span>
  f<span class="hl opt">.</span><span class="hl kwd">close</span><span class="hl opt">()</span>

<span class="hl kwa">def</span> <span class="hl kwd">next_label</span><span class="hl opt">():</span>
  <span class="hl kwa">global</span> label_count
  label_count <span class="hl opt">=</span> label_count <span class="hl opt">+</span> <span class="hl num">1</span>
  <span class="hl kwa">return</span> <span class="hl str">&quot;label_%04d&quot;</span> <span class="hl opt">%</span> label_count

<span class="hl kwa">def</span> <span class="hl kwd">code_rem</span><span class="hl opt">(</span>comment<span class="hl opt">):</span>
  code_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">'; '</span> <span class="hl opt">+</span> comment<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">data_rem</span><span class="hl opt">(</span>comment<span class="hl opt">):</span>
  data_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">'; '</span> <span class="hl opt">+</span> comment<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">data_label</span><span class="hl opt">(</span>name<span class="hl opt">):</span>
  data_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span>name <span class="hl opt">+</span> <span class="hl str">&quot;:&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">code_label</span><span class="hl opt">(</span>name<span class="hl opt">):</span>
  code_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span>name <span class="hl opt">+</span> <span class="hl str">&quot;:&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">code</span><span class="hl opt">(</span>value<span class="hl opt">):</span>
  printed <span class="hl opt">=</span> value
  <span class="hl kwa">if</span> <span class="hl kwb">type</span><span class="hl opt">(</span>value<span class="hl opt">).</span>__name__ <span class="hl opt">==</span> <span class="hl str">'int'</span><span class="hl opt">:</span>
    printed <span class="hl opt">=</span> <span class="hl str">&quot;%d&quot;</span> <span class="hl opt">%</span> value
  code_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">&quot;  dw %s&quot;</span> <span class="hl opt">%</span> printed<span class="hl opt">)</span>

scramble_counter <span class="hl opt">=</span> <span class="hl num">0x27</span>

<span class="hl kwa">def</span> <span class="hl kwd">next_scramble_counter</span><span class="hl opt">():</span>
  <span class="hl kwa">global</span> scramble_counter
  scramble_counter <span class="hl opt">=</span> scramble_counter <span class="hl opt">*</span> <span class="hl num">3</span> <span class="hl opt">+</span> <span class="hl num">7</span>
  <span class="hl kwa">return</span> scramble_counter <span class="hl opt">&amp;</span> <span class="hl num">0xff</span>

<span class="hl kwa">def</span> <span class="hl kwd">word</span><span class="hl opt">(</span>value<span class="hl opt">):</span>
  <span class="hl kwa">if</span> value <span class="hl opt">== -</span><span class="hl num">1</span><span class="hl opt">:</span>
    <span class="hl kwa">if</span> scramble<span class="hl opt">:</span>
      value <span class="hl opt">=</span> <span class="hl kwd">next_scramble_counter</span><span class="hl opt">()</span>
    <span class="hl kwa">else</span><span class="hl opt">:</span>
      value <span class="hl opt">=</span> <span class="hl num">0</span>
  printed <span class="hl opt">=</span> value
  <span class="hl kwa">if</span> <span class="hl kwb">type</span><span class="hl opt">(</span>value<span class="hl opt">).</span>__name__ <span class="hl opt">==</span> <span class="hl str">'int'</span><span class="hl opt">:</span>
    printed <span class="hl opt">=</span> <span class="hl str">&quot;%d&quot;</span> <span class="hl opt">%</span> value
  data_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">&quot;  dw %s&quot;</span> <span class="hl opt">%</span> printed<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwb">buffer</span><span class="hl opt">(</span>length<span class="hl opt">,</span> value <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">):</span>
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> length<span class="hl opt">):</span>
    <span class="hl kwd">word</span><span class="hl opt">(</span>value<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">var</span><span class="hl opt">(</span>name<span class="hl opt">,</span> value <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">):</span>
  <span class="hl kwd">data_label</span><span class="hl opt">(</span>name<span class="hl opt">);</span>
  <span class="hl kwd">word</span><span class="hl opt">(</span>value<span class="hl opt">);</span>

<span class="hl kwa">def</span> <span class="hl kwd">NOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'NOR '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>a<span class="hl opt">) +</span> <span class="hl str">' '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>b<span class="hl opt">) +</span> <span class="hl str">' '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>r<span class="hl opt">))</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>a<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>b<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>r<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">NOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> a<span class="hl opt">,</span> r<span class="hl opt">);</span>

<span class="hl kwa">def</span> <span class="hl kwd">OR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">NOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> <span class="hl str">&quot;or_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;or_reg&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;or_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;and_reg_b&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">OR</span><span class="hl opt">(</span><span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;and_reg_b&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;and_reg_b&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">ANDi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> imm<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> <span class="hl str">&quot;and_i_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;and_i_reg&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;and_i_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">XOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">OR</span><span class="hl opt">(</span><span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">XORi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> imm<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> <span class="hl str">&quot;xor_i_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">XOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;xor_i_reg&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;xor_i_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'MOV '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>a<span class="hl opt">) +</span> <span class="hl str">' '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>b<span class="hl opt">))</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">,</span> b<span class="hl opt">)</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'MOV END'</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">JMP</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'JMP '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>a<span class="hl opt">))</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;ip&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">JMPi</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'JMPi '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>a<span class="hl opt">))</span>
  label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">JMP</span><span class="hl opt">(</span>label<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>a<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> a<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'MOVi #'</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>imm<span class="hl opt">) +</span> <span class="hl str">' '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>a<span class="hl opt">))</span>
  label_data <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  label_jump <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>label_data<span class="hl opt">,</span> a<span class="hl opt">)</span>
  <span class="hl kwd">JMPi</span><span class="hl opt">(</span>label_jump<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label_data<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>imm<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label_jump<span class="hl opt">)</span>

<span class="hl slc"># [a] -&gt; b</span>
<span class="hl kwa">def</span> <span class="hl kwd">PEEK</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  label1 <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  label2 <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> label1<span class="hl opt">)</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> label2<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label1<span class="hl opt">)</span>  <span class="hl slc"># NOT(0, 0, move_reg)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">)</span>             <span class="hl slc"># &lt;- a</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label2<span class="hl opt">)</span>  <span class="hl slc">#</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">)</span>             <span class="hl slc"># &lt;- a</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>    <span class="hl slc">#</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">,</span> b<span class="hl opt">)</span>

<span class="hl slc"># a -&gt; [b]</span>
<span class="hl kwa">def</span> <span class="hl kwd">POKE</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'POKE '</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>a<span class="hl opt">) +</span> <span class="hl str">' ['</span> <span class="hl opt">+</span> <span class="hl kwb">str</span><span class="hl opt">(</span>b<span class="hl opt">) +</span> <span class="hl str">']'</span><span class="hl opt">)</span>
  label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>b<span class="hl opt">,</span> label<span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>  <span class="hl slc"># +3 (three operations)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>    <span class="hl slc"># +4</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>    <span class="hl slc"># +5</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">)</span>             <span class="hl slc"># &lt;- b</span>

<span class="hl slc"># imm -&gt; [a]</span>
<span class="hl kwa">def</span> <span class="hl kwd">POKEi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> a<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> <span class="hl str">&quot;poke_i_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">POKE</span><span class="hl opt">(</span><span class="hl str">&quot;poke_i_reg&quot;</span><span class="hl opt">,</span> a<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;poke_i_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">EXIT</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;exit_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">EXITi</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;exit_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">FADD</span><span class="hl opt">(</span>mask<span class="hl opt">,</span> carry<span class="hl opt">,</span> a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> mask<span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_a&quot;</span><span class="hl opt">)</span>  <span class="hl slc"># zero bits in 'a' except mask'ed</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>b<span class="hl opt">,</span> mask<span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_b&quot;</span><span class="hl opt">)</span>  <span class="hl slc"># zero bits in 'b' except mask'ed</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>carry<span class="hl opt">,</span> mask<span class="hl opt">,</span> carry<span class="hl opt">)</span>     <span class="hl slc"># zero bits in 'carry' except mask'ed</span>

  <span class="hl slc"># SUM = (a ^ b) ^ carry</span>
  <span class="hl kwd">XOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_t1&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">XOR</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_t1&quot;</span><span class="hl opt">,</span> carry<span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_bit_r&quot;</span><span class="hl opt">)</span>

  <span class="hl slc"># Leave only 'mask'ed bit in bit_r.</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_bit_r&quot;</span><span class="hl opt">,</span> mask<span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_bit_r&quot;</span><span class="hl opt">)</span>

  <span class="hl slc"># Add current added bit to the result.</span>
  <span class="hl kwd">OR</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_bit_r&quot;</span><span class="hl opt">,</span> r<span class="hl opt">,</span> r<span class="hl opt">)</span>

  <span class="hl slc"># CARRY = (a &amp; b) | (carry &amp; (a ^ b))</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_t2&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>carry<span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_t1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_t1&quot;</span><span class="hl opt">)</span>

  <span class="hl slc"># CARRY is calculated, and 'shift_reg' contains the same value</span>
  <span class="hl slc"># but shifted the left by 1 bit.</span>
  <span class="hl kwd">OR</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_t2&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_t1&quot;</span><span class="hl opt">,</span> carry<span class="hl opt">)</span>

  <span class="hl slc"># CARRY is shifted the left by 1 bit to be used on the next round.</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;shift_reg&quot;</span><span class="hl opt">,</span> carry<span class="hl opt">)</span>

  <span class="hl slc"># shift_reg = mask &lt;&lt; 1</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>mask<span class="hl opt">,</span> mask<span class="hl opt">)</span>
  <span class="hl slc"># mask = shift (effectively &quot;mask = mask &lt;&lt; 1&quot;)</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;shift_reg&quot;</span><span class="hl opt">,</span> mask<span class="hl opt">)</span>

  <span class="hl kwd">AND</span><span class="hl opt">(</span>carry<span class="hl opt">,</span> mask<span class="hl opt">,</span> carry<span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_a&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_b&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_bit_r&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_t1&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;fadd_reg_t2&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">ZERO</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">XOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> a<span class="hl opt">,</span> a<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">FADC</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">ZERO</span><span class="hl opt">(</span><span class="hl str">&quot;fadc_reg_t&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;const_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;fadc_reg_mask&quot;</span><span class="hl opt">)</span>
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl num">16</span><span class="hl opt">):</span>
    <span class="hl kwd">FADD</span><span class="hl opt">(</span><span class="hl str">&quot;fadc_reg_mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">,</span> a<span class="hl opt">,</span> b<span class="hl opt">,</span> <span class="hl str">&quot;fadc_reg_t&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;fadc_reg_t&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>

  <span class="hl kwd">ZERO</span><span class="hl opt">(</span><span class="hl str">&quot;fadc_reg_t&quot;</span><span class="hl opt">)</span>

  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl num">16</span><span class="hl opt">):</span>
    <span class="hl kwd">OR</span><span class="hl opt">(</span><span class="hl str">&quot;fadc_reg_t&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;fadc_reg_t&quot;</span><span class="hl opt">)</span>
    <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">)</span>
    <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;shift_reg&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">)</span>

  <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;fadc_reg_t&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;fadc_reg_mask&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;fadc_reg_t&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">ADD</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">ZERO</span><span class="hl opt">(</span><span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">FADC</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">ADDi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> imm<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> <span class="hl str">&quot;add_i_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">ADD</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;add_i_reg&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;add_i_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">PUSH</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;stack_reg&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_minus_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;stack_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">POKE</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;stack_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">PUSHi</span><span class="hl opt">(</span>imm<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> <span class="hl str">&quot;push_i_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">PUSH</span><span class="hl opt">(</span><span class="hl str">&quot;push_i_reg&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;push_i_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">POP</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">PEEK</span><span class="hl opt">(</span><span class="hl str">&quot;stack_reg&quot;</span><span class="hl opt">,</span> a<span class="hl opt">)</span>
  <span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;stack_reg&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;stack_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">CALL</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">PUSHi</span><span class="hl opt">(</span>label<span class="hl opt">)</span>
  <span class="hl kwd">JMP</span><span class="hl opt">(</span>a<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">CALLi</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">PUSHi</span><span class="hl opt">(</span>label<span class="hl opt">)</span>
  <span class="hl kwd">JMPi</span><span class="hl opt">(</span>a<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">RET</span><span class="hl opt">():</span>
  <span class="hl kwd">POP</span><span class="hl opt">(</span><span class="hl str">&quot;ip&quot;</span><span class="hl opt">)</span>

<span class="hl slc"># Jump 'a', if cond = FFFF, and 'b' if conf = 0000</span>
<span class="hl kwa">def</span> <span class="hl kwd">BRANCH</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> cond<span class="hl opt">):</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> cond<span class="hl opt">,</span> <span class="hl str">&quot;branch_reg_a&quot;</span><span class="hl opt">)</span>              <span class="hl slc"># reg_a = a &amp; cond</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>cond<span class="hl opt">,</span> <span class="hl str">&quot;branch_reg_b&quot;</span><span class="hl opt">)</span>                 <span class="hl slc"># reg_b = !cond</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;branch_reg_b&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;branch_reg_b&quot;</span><span class="hl opt">)</span>    <span class="hl slc"># reg_b = b &amp; reg_b = b &amp; !cond</span>
  <span class="hl kwd">OR</span><span class="hl opt">(</span><span class="hl str">&quot;branch_reg_a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;branch_reg_b&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ip&quot;</span><span class="hl opt">)</span>  <span class="hl slc"># ip = (a &amp; cond) | (b &amp; !cond)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;branch_reg_a&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;branch_reg_b&quot;</span><span class="hl opt">)</span>

<span class="hl slc"># Jump 'a', if cond = FFFF, and 'b' if conf = 0000</span>
<span class="hl kwa">def</span> <span class="hl kwd">BRANCHi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> cond<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;branch_i_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;branch_i_reg_b&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">BRANCH</span><span class="hl opt">(</span><span class="hl str">&quot;branch_i_reg_a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;branch_i_reg_b&quot;</span><span class="hl opt">,</span> cond<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;branch_i_reg_a&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;branch_i_reg_b&quot;</span><span class="hl opt">)</span>

<span class="hl slc"># if a != 0 -&gt; carry = FFFF else carry = 0000</span>
<span class="hl kwa">def</span> <span class="hl kwd">IS_0</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">ZERO</span><span class="hl opt">(</span><span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">FADC</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;const_minus_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;is_0_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;zero_reg&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;is_0_reg&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;zero_reg&quot;</span><span class="hl opt">)</span>

<span class="hl slc"># ip = (zero_reg == FFFF ? a : ip)</span>
<span class="hl kwa">def</span> <span class="hl kwd">JZi</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">BRANCHi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> label<span class="hl opt">,</span> <span class="hl str">&quot;zero_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label<span class="hl opt">)</span>

<span class="hl slc"># ip = (zero_reg == FFFF ? a : ip)</span>
<span class="hl kwa">def</span> <span class="hl kwd">JNZi</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">BRANCHi</span><span class="hl opt">(</span>label<span class="hl opt">,</span> a<span class="hl opt">,</span> <span class="hl str">&quot;zero_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">ROL</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> a<span class="hl opt">)</span>            <span class="hl slc"># shift_reg = a &lt;&lt; 1</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;shift_reg&quot;</span><span class="hl opt">,</span> b<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">ROR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;ror_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl num">15</span><span class="hl opt">):</span>
    <span class="hl kwd">ROL</span><span class="hl opt">(</span><span class="hl str">&quot;ror_reg&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ror_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;ror_reg&quot;</span><span class="hl opt">,</span> b<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;ror_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">SHL</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwd">ROL</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">)</span>
  <span class="hl kwd">ANDi</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl num">0x0001</span><span class="hl opt">,</span> b<span class="hl opt">)</span>

<span class="hl kwa">def</span> <span class="hl kwd">SHR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwd">ROR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">)</span>
  <span class="hl kwd">ANDi</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl num">0x7FFF</span><span class="hl opt">,</span> b<span class="hl opt">)</span>

<span class="hl slc"># NORCPU code</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;ip&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;start&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;shift_reg&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;const_1&quot;</span><span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;const_minus_1&quot;</span><span class="hl opt">,</span> <span class="hl num">0xFFFF</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;exit_reg&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;stack_reg&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;stack&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">code_label</span><span class="hl opt">(</span><span class="hl str">&quot;start&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;i&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;j&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;ch&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;t&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;crc16&quot;</span><span class="hl opt">,</span> crc16_initial_value<span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;ptr&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;password&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;password_sz&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;i&quot;</span><span class="hl opt">)</span>

crc_loop <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
<span class="hl kwd">code_label</span><span class="hl opt">(</span>crc_loop<span class="hl opt">)</span>          <span class="hl slc"># crc_loop</span>
<span class="hl slc"># ch = *ptr</span>
<span class="hl kwd">PEEK</span><span class="hl opt">(</span><span class="hl str">&quot;ptr&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ch&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># ch &amp;= 0xFF</span>
<span class="hl kwd">ANDi</span><span class="hl opt">(</span><span class="hl str">&quot;ch&quot;</span><span class="hl opt">,</span> <span class="hl num">0xFF</span><span class="hl opt">,</span> <span class="hl str">&quot;ch&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># crc16 ^= ch</span>
<span class="hl kwd">XOR</span><span class="hl opt">(</span><span class="hl str">&quot;crc16&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ch&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;crc16&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">MOVi</span><span class="hl opt">(</span><span class="hl num">8</span><span class="hl opt">,</span> <span class="hl str">&quot;j&quot;</span><span class="hl opt">)</span>
crc_loop_j <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
<span class="hl kwd">code_label</span><span class="hl opt">(</span>crc_loop_j<span class="hl opt">)</span>        <span class="hl slc"># crc_loop_j</span>

<span class="hl slc"># t = crc16 &amp; 1</span>
<span class="hl kwd">ANDi</span><span class="hl opt">(</span><span class="hl str">&quot;crc16&quot;</span><span class="hl opt">,</span> <span class="hl num">1</span><span class="hl opt">,</span> <span class="hl str">&quot;t&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># crc16 &gt;&gt;= 1</span>
<span class="hl kwd">SHR</span><span class="hl opt">(</span><span class="hl str">&quot;crc16&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;crc16&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">IS_0</span><span class="hl opt">(</span><span class="hl str">&quot;t&quot;</span><span class="hl opt">)</span>
crc_loop_1 <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
<span class="hl kwd">JZi</span><span class="hl opt">(</span>crc_loop_1<span class="hl opt">)</span>
<span class="hl slc"># crc16 ^= crc16_constant</span>
<span class="hl kwd">XORi</span><span class="hl opt">(</span><span class="hl str">&quot;crc16&quot;</span><span class="hl opt">,</span> crc16_constant<span class="hl opt">,</span> <span class="hl str">&quot;crc16&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">code_label</span><span class="hl opt">(</span>crc_loop_1<span class="hl opt">)</span>        <span class="hl slc"># crc_loop_1</span>

<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;j&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_minus_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;j&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">IS_0</span><span class="hl opt">(</span><span class="hl str">&quot;j&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">JNZi</span><span class="hl opt">(</span>crc_loop_j<span class="hl opt">)</span>

<span class="hl slc"># ptr += 1</span>
<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;ptr&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ptr&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># i = i - 1</span>
<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;i&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_minus_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;i&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">IS_0</span><span class="hl opt">(</span><span class="hl str">&quot;i&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">JNZi</span><span class="hl opt">(</span>crc_loop<span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;ptr2&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;result&quot;</span><span class="hl opt">)</span>

correct_crc <span class="hl opt">=</span> crc16 <span class="hl opt">+</span> test_wrong_crc

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;correct_crc&quot;</span><span class="hl opt">,</span> correct_crc<span class="hl opt">)</span>

<span class="hl slc"># By default we're going to decrypt 'Wrong...' message.</span>
<span class="hl kwd">MOVi</span><span class="hl opt">(</span><span class="hl str">&quot;message&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ptr&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;message_sz&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;i&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;message_mask&quot;</span><span class="hl opt">,</span> message_mask<span class="hl opt">)</span>
<span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;message_mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;coef_add&quot;</span><span class="hl opt">,</span> message_coef_add<span class="hl opt">)</span>

wrong_label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>

<span class="hl kwd">XOR</span><span class="hl opt">(</span><span class="hl str">&quot;correct_crc&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;crc16&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;correct_crc&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">IS_0</span><span class="hl opt">(</span><span class="hl str">&quot;correct_crc&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">JNZi</span><span class="hl opt">(</span>wrong_label<span class="hl opt">)</span>

<span class="hl slc"># Now we switch to descrypt the secret message.</span>
<span class="hl kwd">MOVi</span><span class="hl opt">(</span>secret_coef_add<span class="hl opt">,</span> <span class="hl str">&quot;coef_add&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">MOVi</span><span class="hl opt">(</span><span class="hl str">&quot;secret&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ptr&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;secret_sz&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;i&quot;</span><span class="hl opt">)</span>

<span class="hl slc"># mask = ((crc16 &amp; 0xff) | ((crc16 &gt;&gt; 8) &amp; 0xff)) + 1</span>
<span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;crc16&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>
<span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl num">8</span><span class="hl opt">):</span>
  <span class="hl kwd">SHR</span><span class="hl opt">(</span><span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">XOR</span><span class="hl opt">(</span><span class="hl str">&quot;crc16&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">ANDi</span><span class="hl opt">(</span><span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl num">0xff</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">code_label</span><span class="hl opt">(</span>wrong_label<span class="hl opt">)</span>

<span class="hl kwd">MOV</span><span class="hl opt">(</span><span class="hl str">&quot;i&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;result_sz&quot;</span><span class="hl opt">)</span>

loop <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
<span class="hl kwd">code_label</span><span class="hl opt">(</span>loop<span class="hl opt">)</span>              <span class="hl slc"># loop</span>
<span class="hl slc"># ch = *ptr</span>
<span class="hl kwd">PEEK</span><span class="hl opt">(</span><span class="hl str">&quot;ptr&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ch&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># ch ^= mask</span>
<span class="hl kwd">XOR</span><span class="hl opt">(</span><span class="hl str">&quot;ch&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ch&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">POKE</span><span class="hl opt">(</span><span class="hl str">&quot;ch&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ptr2&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># mask = mask * 3 + 11</span>
<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;t&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;t&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;mask&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;coef_add&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;mask&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># ptr += 1</span>
<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;ptr&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ptr&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># ptr2 += 1</span>
<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;ptr2&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;ptr2&quot;</span><span class="hl opt">)</span>
<span class="hl slc"># i = i - 1</span>
<span class="hl kwd">ADD</span><span class="hl opt">(</span><span class="hl str">&quot;i&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;const_minus_1&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;i&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">IS_0</span><span class="hl opt">(</span><span class="hl str">&quot;i&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">JNZi</span><span class="hl opt">(</span>loop<span class="hl opt">)</span>

<span class="hl kwd">EXITi</span><span class="hl opt">(</span><span class="hl num">0x00</span><span class="hl opt">)</span>

<span class="hl kwb">buffer</span><span class="hl opt">(</span><span class="hl num">8</span><span class="hl opt">)</span>
<span class="hl kwd">data_label</span><span class="hl opt">(</span><span class="hl str">&quot;stack&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;secret_sz&quot;</span><span class="hl opt">,</span> <span class="hl kwb">len</span><span class="hl opt">(</span>secret_code<span class="hl opt">))</span>
<span class="hl kwd">data_label</span><span class="hl opt">(</span><span class="hl str">&quot;secret&quot;</span><span class="hl opt">)</span>
<span class="hl kwb">buffer</span><span class="hl opt">(</span><span class="hl kwb">len</span><span class="hl opt">(</span>secret_code<span class="hl opt">) +</span> <span class="hl num">1</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;message_sz&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">data_label</span><span class="hl opt">(</span><span class="hl str">&quot;message&quot;</span><span class="hl opt">)</span>
<span class="hl kwb">buffer</span><span class="hl opt">(</span><span class="hl num">16</span><span class="hl opt">)</span>

<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;password_sz&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">data_label</span><span class="hl opt">(</span><span class="hl str">&quot;password&quot;</span><span class="hl opt">)</span>
<span class="hl kwb">buffer</span><span class="hl opt">(</span><span class="hl num">16</span><span class="hl opt">)</span>

<span class="hl slc"># The buffer holding the result string.</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;result_sz&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">data_label</span><span class="hl opt">(</span><span class="hl str">&quot;result&quot;</span><span class="hl opt">)</span>
<span class="hl kwb">buffer</span><span class="hl opt">(</span><span class="hl num">32</span><span class="hl opt">)</span>

<span class="hl slc"># Compiler</span>

text <span class="hl opt">=</span> code_segment
text<span class="hl opt">.</span><span class="hl kwd">extend</span><span class="hl opt">(</span>data_segment<span class="hl opt">)</span>

<span class="hl kwa">if</span> verbose<span class="hl opt">:</span>
  <span class="hl kwa">print</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>text<span class="hl opt">)</span>

<span class="hl slc"># Phase 1. Calculate names.</span>

addr <span class="hl opt">=</span> <span class="hl num">0</span>
names <span class="hl opt">= {}</span>
<span class="hl kwa">for</span> line <span class="hl kwa">in</span> text<span class="hl opt">:</span>
  <span class="hl kwa">if</span> line<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">] ==</span> <span class="hl str">';'</span><span class="hl opt">:</span> <span class="hl kwa">continue</span>
  <span class="hl kwa">if</span> line<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">] !=</span> <span class="hl str">' '</span><span class="hl opt">:</span>
    name <span class="hl opt">=</span> line<span class="hl opt">.</span><span class="hl kwd">partition</span><span class="hl opt">(</span><span class="hl str">':'</span><span class="hl opt">)[</span><span class="hl num">0</span><span class="hl opt">]</span>
    names<span class="hl opt">[</span>name<span class="hl opt">] =</span> addr
  <span class="hl kwa">else</span><span class="hl opt">:</span>
    addr <span class="hl opt">=</span> addr <span class="hl opt">+</span> <span class="hl num">1</span>

<span class="hl kwa">if</span> verbose<span class="hl opt">:</span>
  <span class="hl kwa">print</span> names

raw_text <span class="hl opt">=</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>text<span class="hl opt">)</span>

<span class="hl slc"># Resolve names.</span>

<span class="hl kwa">for</span> name <span class="hl kwa">in</span> names<span class="hl opt">:</span>
  <span class="hl kwa">if</span> verbose<span class="hl opt">:</span>
    <span class="hl kwa">print</span> name<span class="hl opt">,</span> names<span class="hl opt">[</span>name<span class="hl opt">],</span> <span class="hl kwb">type</span><span class="hl opt">(</span>names<span class="hl opt">[</span>name<span class="hl opt">])</span>
  name_re <span class="hl opt">=</span> re<span class="hl opt">.</span><span class="hl kwb">compile</span><span class="hl opt">(</span>r<span class="hl str">'dw '</span> <span class="hl opt">+</span> name <span class="hl opt">+</span> <span class="hl str">'$'</span><span class="hl opt">,</span> re<span class="hl opt">.</span>M<span class="hl opt">)</span>
  value <span class="hl opt">=</span> <span class="hl str">&quot;%d&quot;</span> <span class="hl opt">%</span> names<span class="hl opt">[</span>name<span class="hl opt">]</span>
  raw_text <span class="hl opt">=</span> name_re<span class="hl opt">.</span><span class="hl kwd">sub</span><span class="hl opt">(</span><span class="hl str">'dw '</span> <span class="hl opt">+</span> value<span class="hl opt">,</span> raw_text<span class="hl opt">)</span>

text <span class="hl opt">=</span> raw_text<span class="hl opt">.</span><span class="hl kwd">split</span><span class="hl opt">(</span><span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">if</span> verbose<span class="hl opt">:</span>
  <span class="hl kwa">print</span> <span class="hl str">&quot;</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>text<span class="hl opt">)</span>

<span class="hl slc"># Phase 2. Compilation.</span>

addr <span class="hl opt">=</span> <span class="hl num">0</span>
comment <span class="hl opt">=</span> <span class="hl str">&quot;&quot;</span>
mem <span class="hl opt">= []</span>
<span class="hl kwa">for</span> line <span class="hl kwa">in</span> text<span class="hl opt">:</span>
  <span class="hl kwa">if</span> line<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">] ==</span> <span class="hl str">';'</span> <span class="hl kwa">or</span> line<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">] !=</span> <span class="hl str">' '</span><span class="hl opt">:</span>
    comment <span class="hl opt">=</span> comment <span class="hl opt">+</span> line <span class="hl opt">+</span> <span class="hl str">' '</span>
  <span class="hl kwa">else</span><span class="hl opt">:</span>
    value <span class="hl opt">=</span> <span class="hl kwb">int</span><span class="hl opt">(</span>line<span class="hl opt">.</span><span class="hl kwd">strip</span><span class="hl opt">().</span><span class="hl kwd">partition</span><span class="hl opt">(</span><span class="hl str">&quot; &quot;</span><span class="hl opt">)[</span><span class="hl num">2</span><span class="hl opt">])</span>
    <span class="hl kwa">if</span> verbose<span class="hl opt">:</span>
      <span class="hl kwa">print</span> <span class="hl str">&quot;%04X: %04X ; %s&quot;</span> <span class="hl opt">% (</span>addr<span class="hl opt">,</span> value<span class="hl opt">,</span> comment<span class="hl opt">)</span>
    mem<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span>value<span class="hl opt">)</span>
    addr <span class="hl opt">=</span> addr <span class="hl opt">+</span> <span class="hl num">1</span>
    comment <span class="hl opt">=</span> <span class="hl str">&quot;&quot;</span>

<span class="hl slc"># Interpretation</span>

ip <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;ip&quot;</span><span class="hl opt">]</span>
exit_reg <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;exit_reg&quot;</span><span class="hl opt">]</span>
shift_reg <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;shift_reg&quot;</span><span class="hl opt">]</span>
carry_reg <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;carry_reg&quot;</span><span class="hl opt">]</span>

<span class="hl kwa">def</span> <span class="hl kwd">nor</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  r <span class="hl opt">=</span> a | b
  r <span class="hl opt">=</span> r ^ <span class="hl num">0xFFFF</span>
  <span class="hl kwa">return</span> r <span class="hl opt">&amp;</span> <span class="hl num">0xFFFF</span>

<span class="hl kwa">def</span> <span class="hl kwd">norcpu</span><span class="hl opt">():</span>
  <span class="hl kwa">while</span> <span class="hl num">1</span><span class="hl opt">:</span>
    i <span class="hl opt">=</span> mem<span class="hl opt">[</span>ip<span class="hl opt">];</span>
    a <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">0</span><span class="hl opt">]</span>
    b <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">]</span>
    r <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">2</span><span class="hl opt">]</span>
    mem<span class="hl opt">[</span>ip<span class="hl opt">] =</span> i <span class="hl opt">+</span> <span class="hl num">3</span>
    f <span class="hl opt">=</span> <span class="hl kwd">nor</span><span class="hl opt">(</span>mem<span class="hl opt">[</span>a<span class="hl opt">],</span> mem<span class="hl opt">[</span>b<span class="hl opt">])</span>
    mem<span class="hl opt">[</span>r<span class="hl opt">] =</span> f
    mem<span class="hl opt">[</span>shift_reg<span class="hl opt">] = ((</span>f <span class="hl opt">&gt;&gt;</span> <span class="hl num">15</span><span class="hl opt">) &amp;</span> <span class="hl num">1</span><span class="hl opt">)</span> | <span class="hl opt">((</span>f <span class="hl opt">&amp;</span> <span class="hl num">0x7FFF</span><span class="hl opt">) &lt;&lt;</span> <span class="hl num">1</span><span class="hl opt">)</span>

    <span class="hl kwa">if</span> verbose_cpu<span class="hl opt">:</span>
      <span class="hl kwa">print</span> <span class="hl str">&quot;%04X: %04X [%04X] %04X [%04X] -&gt; %04X [%04X]&quot;</span> <span class="hl opt">%</span> \
            <span class="hl opt">(</span>i<span class="hl opt">,</span> a<span class="hl opt">,</span> mem<span class="hl opt">[</span>a<span class="hl opt">],</span> b<span class="hl opt">,</span> mem<span class="hl opt">[</span>b<span class="hl opt">],</span> r<span class="hl opt">,</span> mem<span class="hl opt">[</span>r<span class="hl opt">])</span>
    <span class="hl kwa">if</span> r <span class="hl opt">==</span> exit_reg<span class="hl opt">:</span>
      <span class="hl kwa">break</span>

<span class="hl kwa">print</span> <span class="hl str">&quot;Starting from [%04X]&quot;</span> <span class="hl opt">%</span> mem<span class="hl opt">[</span>ip<span class="hl opt">]</span>

<span class="hl slc"># Encrypt the secret code.</span>
secret_mask <span class="hl opt">= ((</span>crc16 <span class="hl opt">&amp;</span> <span class="hl num">0xff</span><span class="hl opt">)</span> ^ <span class="hl opt">((</span>crc16 <span class="hl opt">&gt;&gt;</span> <span class="hl num">8</span><span class="hl opt">) &amp;</span> <span class="hl num">0xff</span><span class="hl opt">)) +</span> <span class="hl num">1</span>
<span class="hl kwd">encode_string</span><span class="hl opt">(</span>secret_code<span class="hl opt">,</span> <span class="hl str">&quot;secret&quot;</span><span class="hl opt">,</span> secret_mask<span class="hl opt">,</span> secret_coef_add<span class="hl opt">);</span>

<span class="hl slc"># Encrypt 'Wrong...' message.</span>
<span class="hl kwd">encode_string</span><span class="hl opt">(</span>message_text<span class="hl opt">,</span> <span class="hl str">&quot;message&quot;</span><span class="hl opt">,</span> message_mask<span class="hl opt">,</span> message_coef_add<span class="hl opt">);</span>

mem_js <span class="hl opt">=</span> <span class="hl kwd">dump_js</span><span class="hl opt">(</span>mem<span class="hl opt">)</span>
<span class="hl kwd">save_mem</span><span class="hl opt">(</span><span class="hl str">&quot;norcpu-1-before.bin&quot;</span><span class="hl opt">)</span>
mem_sz <span class="hl opt">=</span> <span class="hl kwb">len</span><span class="hl opt">(</span>mem<span class="hl opt">)</span>

<span class="hl kwa">if</span> <span class="hl kwb">len</span><span class="hl opt">(</span>mem<span class="hl opt">) &gt;=</span> <span class="hl num">0x10000</span><span class="hl opt">:</span>
  <span class="hl kwa">print</span> <span class="hl str">&quot;Too much code (%08X, %04X)&quot;</span> <span class="hl opt">% (</span><span class="hl kwb">len</span><span class="hl opt">(</span>mem<span class="hl opt">),</span> <span class="hl kwb">len</span><span class="hl opt">(</span>mem<span class="hl opt">) -</span> <span class="hl num">0x10000</span><span class="hl opt">)</span>
  sys<span class="hl opt">.</span><span class="hl kwd">exit</span><span class="hl opt">()</span>

<span class="hl slc"># Inject plain password in the last moment (for testing).</span>
<span class="hl kwd">put_string</span><span class="hl opt">(</span>guess<span class="hl opt">,</span> <span class="hl str">&quot;password&quot;</span><span class="hl opt">)</span>

<span class="hl kwd">save_mem</span><span class="hl opt">(</span><span class="hl str">&quot;norcpu-2-before-with-password.bin&quot;</span><span class="hl opt">)</span>

<span class="hl kwa">if</span> verbose<span class="hl opt">:</span>
  <span class="hl kwa">print</span> <span class="hl str">&quot;Original memory:&quot;</span>
  <span class="hl kwa">print</span> <span class="hl kwd">dump</span><span class="hl opt">(</span>mem<span class="hl opt">)</span>

start_time <span class="hl opt">=</span> time<span class="hl opt">.</span><span class="hl kwd">time</span><span class="hl opt">()</span>

<span class="hl kwd">norcpu</span><span class="hl opt">()</span>

end_time <span class="hl opt">=</span> time<span class="hl opt">.</span><span class="hl kwd">time</span><span class="hl opt">()</span>

<span class="hl kwd">save_mem</span><span class="hl opt">(</span><span class="hl str">&quot;norcpu-3-after.bin&quot;</span><span class="hl opt">,</span> mem_sz<span class="hl opt">)</span>

<span class="hl kwa">if</span> verbose<span class="hl opt">:</span>
  <span class="hl kwa">print</span> <span class="hl str">&quot;Memory after:&quot;</span>
  <span class="hl kwd">dump</span><span class="hl opt">(</span>mem<span class="hl opt">)</span>

<span class="hl kwa">print</span>
<span class="hl kwa">print</span> <span class="hl str">&quot;Size: %X&quot;</span> <span class="hl opt">%</span> <span class="hl kwb">len</span><span class="hl opt">(</span>mem<span class="hl opt">)</span>
<span class="hl kwa">print</span> <span class="hl str">&quot;Time: %d&quot;</span> <span class="hl opt">% (</span>end_time <span class="hl opt">-</span> start_time<span class="hl opt">)</span>
<span class="hl kwa">print</span> <span class="hl str">&quot;Exit: %04X&quot;</span> <span class="hl opt">%</span> mem<span class="hl opt">[</span>exit_reg<span class="hl opt">]</span>

<span class="hl kwa">print</span><span class="hl opt">(</span><span class="hl str">&quot;CRC : %04X (%04X)&quot;</span> <span class="hl opt">% (</span>crc16<span class="hl opt">,</span> correct_crc<span class="hl opt">))</span>

result <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;result&quot;</span><span class="hl opt">]</span>
result_value <span class="hl opt">=</span> <span class="hl str">&quot;&quot;</span>
<span class="hl kwa">for</span> i <span class="hl kwa">in</span> <span class="hl kwb">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> mem<span class="hl opt">[</span>names<span class="hl opt">[</span><span class="hl str">&quot;result_sz&quot;</span><span class="hl opt">]]):</span>
  result_value <span class="hl opt">=</span> result_value <span class="hl opt">+</span> <span class="hl kwb">chr</span><span class="hl opt">(</span>mem<span class="hl opt">[</span>result <span class="hl opt">+</span> i<span class="hl opt">] &amp;</span> <span class="hl num">0xff</span><span class="hl opt">)</span>

<span class="hl kwa">if</span> result_value <span class="hl opt">!=</span> secret_code<span class="hl opt">:</span>
  <span class="hl kwa">print</span> <span class="hl str">&quot;ERROR: [%s] != [%s]&quot;</span> <span class="hl opt">% (</span>secret_code<span class="hl opt">,</span> result_value<span class="hl opt">)</span>

js <span class="hl opt">=</span> string<span class="hl opt">.</span><span class="hl kwd">Template</span><span class="hl opt">(</span><span class="hl kwb">open</span><span class="hl opt">(</span><span class="hl str">'template.html'</span><span class="hl opt">,</span> <span class="hl str">'r'</span><span class="hl opt">).</span><span class="hl kwd">read</span><span class="hl opt">())</span>

js <span class="hl opt">=</span> js<span class="hl opt">.</span><span class="hl kwd">substitute</span><span class="hl opt">(</span> \
  ip <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;ip&quot;</span><span class="hl opt">],</span>
  exit_reg <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;exit_reg&quot;</span><span class="hl opt">],</span>
  shift_reg <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;shift_reg&quot;</span><span class="hl opt">],</span>
  password <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;password&quot;</span><span class="hl opt">],</span>
  password_sz <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;password_sz&quot;</span><span class="hl opt">],</span>
  result <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;result&quot;</span><span class="hl opt">],</span>
  result_sz <span class="hl opt">=</span> names<span class="hl opt">[</span><span class="hl str">&quot;result_sz&quot;</span><span class="hl opt">],</span>
  mem_js <span class="hl opt">=</span> mem_js
<span class="hl opt">)</span>

f <span class="hl opt">=</span> <span class="hl kwb">open</span><span class="hl opt">(</span><span class="hl str">&quot;norcpu.html&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;w&quot;</span><span class="hl opt">)</span>
f<span class="hl opt">.</span><span class="hl kwd">write</span><span class="hl opt">(</span>js<span class="hl opt">)</span>
f<span class="hl opt">.</span><span class="hl kwd">close</span><span class="hl opt">()</span>
</pre>

<h2>Problem 2</h2>

<p>File <a href="https://github.com/begoon/norcpu/blob/master/v2/norcpu.py">norcpu.py</a> (<a href="https://github.com/begoon/norcpu/blob/master/v2/template.html">template.html</a>):</p>

<pre class="hl">
import sys<span class="hl opt">,</span> re<span class="hl opt">,</span> time<span class="hl opt">,</span> string<span class="hl opt">,</span> binascii

verbose <span class="hl opt">=</span> False
verbose_cpu <span class="hl opt">=</span> False
scramble <span class="hl opt">=</span> True

secret_password <span class="hl opt">=</span> <span class="hl str">&quot;h1cKmE1fUsAn&quot;</span>
secret_password_xor_mask <span class="hl opt">=</span> <span class="hl num">0x3401</span>
secret_password_add <span class="hl opt">=</span> <span class="hl num">29</span>

secret_code <span class="hl opt">=</span> <span class="hl str">&quot;R0und2 D0ne!&quot;</span>
secret_code_xor_mask <span class="hl opt">=</span> <span class="hl num">0x730A</span>
secret_code_add <span class="hl opt">=</span> <span class="hl num">37</span>

guess <span class="hl opt">=</span> <span class="hl str">&quot;123456789012&quot;</span>
guess <span class="hl opt">=</span> secret_password

code_segment <span class="hl opt">= []</span>
data_segment <span class="hl opt">= []</span>

label_count <span class="hl opt">=</span> <span class="hl num">0</span>

def <span class="hl kwd">dump</span><span class="hl opt">(</span>data<span class="hl opt">,</span> length <span class="hl opt">=</span> <span class="hl num">8</span><span class="hl opt">):</span>
  result <span class="hl opt">= []</span>
  <span class="hl kwa">for</span> i in <span class="hl kwd">xrange</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">len</span><span class="hl opt">(</span>data<span class="hl opt">),</span> length<span class="hl opt">):</span>
    line <span class="hl opt">=</span> data<span class="hl opt">[</span>i<span class="hl opt">:</span>i <span class="hl opt">+</span> length<span class="hl opt">]</span>
    hex_line <span class="hl opt">=</span> <span class="hl str">' '</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">([</span><span class="hl str">&quot;%04X&quot;</span> <span class="hl opt">%</span> x <span class="hl kwa">for</span> x in line<span class="hl opt">])</span>
    result<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">&quot;%04X: %-*s</span><span class="hl esc">\n</span><span class="hl str">&quot;</span> <span class="hl opt">% (</span>i<span class="hl opt">,</span> length<span class="hl opt">*</span><span class="hl num">5</span><span class="hl opt">,</span> hex_line<span class="hl opt">))</span>
  <span class="hl kwa">return</span> <span class="hl str">''</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>result<span class="hl opt">)</span>

def <span class="hl kwd">dump_js</span><span class="hl opt">(</span>data<span class="hl opt">,</span> length <span class="hl opt">=</span> <span class="hl num">8</span><span class="hl opt">):</span>
  result <span class="hl opt">= []</span>
  <span class="hl kwa">for</span> i in <span class="hl kwd">xrange</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">len</span><span class="hl opt">(</span>data<span class="hl opt">),</span> length<span class="hl opt">):</span>
    line <span class="hl opt">=</span> data<span class="hl opt">[</span>i<span class="hl opt">:</span>i <span class="hl opt">+</span> length<span class="hl opt">]</span>
    hex_line <span class="hl opt">=</span> <span class="hl str">' '</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">([</span><span class="hl str">&quot;0x%04X,&quot;</span> <span class="hl opt">%</span> x <span class="hl kwa">for</span> x in line<span class="hl opt">])</span>
    result<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">&quot;%-*s</span><span class="hl esc">\n</span><span class="hl str">&quot;</span> <span class="hl opt">% (</span>length<span class="hl opt">*</span><span class="hl num">5</span><span class="hl opt">,</span> hex_line<span class="hl opt">))</span>
  <span class="hl kwa">return</span> <span class="hl str">''</span><span class="hl opt">.</span><span class="hl kwd">join</span><span class="hl opt">(</span>result<span class="hl opt">)</span>

def <span class="hl kwd">encode_string</span><span class="hl opt">(</span>data<span class="hl opt">,</span> name<span class="hl opt">,</span> mask<span class="hl opt">,</span> coef_add<span class="hl opt">):</span>
  global mem<span class="hl opt">,</span> names
  offset <span class="hl opt">=</span> names<span class="hl opt">[</span>name<span class="hl opt">]</span>
  offset_sz <span class="hl opt">=</span> names<span class="hl opt">[</span>name <span class="hl opt">+</span> <span class="hl str">&quot;_sz&quot;</span><span class="hl opt">]</span>
  <span class="hl kwa">for</span> i in <span class="hl kwd">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">len</span><span class="hl opt">(</span>data<span class="hl opt">)):</span>
    mem<span class="hl opt">[</span>offset <span class="hl opt">+</span> i<span class="hl opt">] =</span> <span class="hl kwd">ord</span><span class="hl opt">(</span>data<span class="hl opt">[</span>i<span class="hl opt">]) ^</span> mask
    mask <span class="hl opt">= (</span>mask <span class="hl opt">*</span> <span class="hl num">3</span> <span class="hl opt">+</span> coef_add<span class="hl opt">) &amp;</span> <span class="hl num">0xffff</span>
  mem<span class="hl opt">[</span>offset_sz<span class="hl opt">] =</span> <span class="hl kwd">len</span><span class="hl opt">(</span>data<span class="hl opt">)</span>

def <span class="hl kwd">put_string</span><span class="hl opt">(</span>data<span class="hl opt">,</span> name<span class="hl opt">):</span>
  global mem<span class="hl opt">,</span> names
  offset <span class="hl opt">=</span> names<span class="hl opt">[</span>name<span class="hl opt">]</span>
  offset_sz <span class="hl opt">=</span> names<span class="hl opt">[</span>name <span class="hl opt">+</span> <span class="hl str">&quot;_sz&quot;</span><span class="hl opt">]</span>
  <span class="hl kwa">for</span> i in <span class="hl kwd">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">len</span><span class="hl opt">(</span>data<span class="hl opt">)):</span>
    mem<span class="hl opt">[</span>offset <span class="hl opt">+</span> i<span class="hl opt">] =</span> <span class="hl kwd">ord</span><span class="hl opt">(</span>data<span class="hl opt">[</span>i<span class="hl opt">])</span>
  mem<span class="hl opt">[</span>offset_sz<span class="hl opt">] =</span> <span class="hl kwd">len</span><span class="hl opt">(</span>data<span class="hl opt">)</span>

def <span class="hl kwd">save_mem</span><span class="hl opt">(</span>name<span class="hl opt">,</span> size <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">):</span>
  f <span class="hl opt">=</span> <span class="hl kwd">open</span><span class="hl opt">(</span>name<span class="hl opt">,</span> <span class="hl str">&quot;w&quot;</span><span class="hl opt">)</span>
  <span class="hl kwa">if</span> size <span class="hl opt">== -</span><span class="hl num">1</span><span class="hl opt">:</span> size <span class="hl opt">=</span> <span class="hl kwd">len</span><span class="hl opt">(</span>mem<span class="hl opt">)</span>
  <span class="hl kwa">for</span> i <span class="hl kwd">in</span> <span class="hl opt">(</span>mem<span class="hl opt">[</span><span class="hl num">0</span><span class="hl opt">:</span>size<span class="hl opt">]):</span>
    hex <span class="hl opt">=</span> <span class="hl str">&quot;%04X&quot;</span> <span class="hl opt">%</span> i
    bin <span class="hl opt">=</span> binascii<span class="hl opt">.</span><span class="hl kwd">a2b_hex</span><span class="hl opt">(</span>hex<span class="hl opt">)</span>
    f<span class="hl opt">.</span><span class="hl kwd">write</span><span class="hl opt">(</span>bin<span class="hl opt">)</span>
  f<span class="hl opt">.</span><span class="hl kwd">close</span><span class="hl opt">()</span>

def <span class="hl kwd">next_label</span><span class="hl opt">():</span>
  global label_count
  label_count <span class="hl opt">=</span> label_count <span class="hl opt">+</span> <span class="hl num">1</span>
  <span class="hl kwa">return</span> <span class="hl str">&quot;label_%04d&quot;</span> <span class="hl opt">%</span> label_count

def <span class="hl kwd">code_rem</span><span class="hl opt">(</span>comment<span class="hl opt">):</span>
  code_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">'; '</span> <span class="hl opt">+</span> comment<span class="hl opt">)</span>

def <span class="hl kwd">data_rem</span><span class="hl opt">(</span>comment<span class="hl opt">):</span>
  data_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">'; '</span> <span class="hl opt">+</span> comment<span class="hl opt">)</span>

def <span class="hl kwd">data_label</span><span class="hl opt">(</span>name<span class="hl opt">):</span>
  data_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span>name <span class="hl opt">+</span> <span class="hl str">&quot;:&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">code_label</span><span class="hl opt">(</span>name<span class="hl opt">):</span>
  code_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span>name <span class="hl opt">+</span> <span class="hl str">&quot;:&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">code</span><span class="hl opt">(</span>value<span class="hl opt">):</span>
  printed <span class="hl opt">=</span> value
  <span class="hl kwa">if</span> <span class="hl kwd">type</span><span class="hl opt">(</span>value<span class="hl opt">).</span>__name__ <span class="hl opt">==</span> <span class="hl str">'int'</span><span class="hl opt">:</span>
    printed <span class="hl opt">=</span> <span class="hl str">&quot;%d&quot;</span> <span class="hl opt">%</span> value
  code_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">&quot;  dw %s&quot;</span> <span class="hl opt">%</span> printed<span class="hl opt">)</span>

scramble_counter <span class="hl opt">=</span> <span class="hl num">0x2743</span>

def <span class="hl kwd">next_scramble_counter</span><span class="hl opt">():</span>
  global scramble_counter
  scramble_counter <span class="hl opt">=</span> scramble_counter <span class="hl opt">*</span> <span class="hl num">3</span> <span class="hl opt">+</span> <span class="hl num">7</span>
  <span class="hl kwa">return</span> scramble_counter <span class="hl opt">&amp;</span> <span class="hl num">0xffff</span>

def <span class="hl kwd">word</span><span class="hl opt">(</span>value<span class="hl opt">):</span>
  <span class="hl kwa">if</span> value <span class="hl opt">== -</span><span class="hl num">1</span><span class="hl opt">:</span>
    <span class="hl kwa">if</span> scramble<span class="hl opt">:</span>
      value <span class="hl opt">=</span> <span class="hl kwd">next_scramble_counter</span><span class="hl opt">()</span>
    <span class="hl kwa">else</span><span class="hl opt">:</span>
      value <span class="hl opt">=</span> <span class="hl num">0</span>
  printed <span class="hl opt">=</span> value
  <span class="hl kwa">if</span> <span class="hl kwd">type</span><span class="hl opt">(</span>value<span class="hl opt">).</span>__name__ <span class="hl opt">==</span> <span class="hl str">'int'</span><span class="hl opt">:</span>
    printed <span class="hl opt">=</span> <span class="hl str">&quot;%d&quot;</span> <span class="hl opt">%</span> value
  data_segment<span class="hl opt">.</span><span class="hl kwd">append</span><span class="hl opt">(</span><span class="hl str">&quot;  dw %s&quot;</span> <span class="hl opt">%</span> printed<span class="hl opt">)</span>

def <span class="hl kwd">buffer</span><span class="hl opt">(</span>length<span class="hl opt">,</span> value <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">):</span>
  <span class="hl kwa">for</span> i in <span class="hl kwd">range</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> length<span class="hl opt">):</span>
    <span class="hl kwd">word</span><span class="hl opt">(</span>value<span class="hl opt">)</span>

def <span class="hl kwd">var</span><span class="hl opt">(</span>name<span class="hl opt">,</span> value <span class="hl opt">= -</span><span class="hl num">1</span><span class="hl opt">):</span>
  <span class="hl kwd">data_label</span><span class="hl opt">(</span>name<span class="hl opt">);</span>
  <span class="hl kwd">word</span><span class="hl opt">(</span>value<span class="hl opt">);</span>

<span class="hl ppc"># Macros</span>

def <span class="hl kwd">NOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'NOR '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>a<span class="hl opt">) +</span> <span class="hl str">' '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>b<span class="hl opt">) +</span> <span class="hl str">' '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>r<span class="hl opt">))</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>a<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>b<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>r<span class="hl opt">)</span>

def <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">NOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> a<span class="hl opt">,</span> r<span class="hl opt">);</span>

def <span class="hl kwd">OR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">NOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> <span class="hl str">&quot;or_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;or_reg&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;or_reg&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;and_reg_b&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">OR</span><span class="hl opt">(</span><span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;and_reg_b&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;and_reg_a&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;and_reg_b&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">ANDi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> imm<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> <span class="hl str">&quot;and_i_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;and_i_reg&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;and_i_reg&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">XOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>b<span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">OR</span><span class="hl opt">(</span><span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">,</span> <span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;xor_reg_a&quot;</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;xor_reg_b&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">XORi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> imm<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> <span class="hl str">&quot;xor_i_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">XOR</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;xor_i_reg&quot;</span><span class="hl opt">,</span> r<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;xor_i_reg&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'MOV '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>a<span class="hl opt">) +</span> <span class="hl str">' '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>b<span class="hl opt">))</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">,</span> b<span class="hl opt">)</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'MOV END'</span><span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">JMP</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'JMP '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>a<span class="hl opt">))</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;ip&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">JMPi</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'JMPi '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>a<span class="hl opt">))</span>
  label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">JMP</span><span class="hl opt">(</span>label<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>a<span class="hl opt">)</span>

def <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> a<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'MOVi #'</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>imm<span class="hl opt">) +</span> <span class="hl str">' '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>a<span class="hl opt">))</span>
  label_data <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  label_jump <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>label_data<span class="hl opt">,</span> a<span class="hl opt">)</span>
  <span class="hl kwd">JMPi</span><span class="hl opt">(</span>label_jump<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label_data<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span>imm<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label_jump<span class="hl opt">)</span>

<span class="hl ppc"># [a] -&gt; b</span>
def <span class="hl kwd">PEEK</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  label1 <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  label2 <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> label1<span class="hl opt">)</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> label2<span class="hl opt">)</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label1<span class="hl opt">)</span>  <span class="hl ppc"># NOT(0, 0, move_reg)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">)</span>             <span class="hl ppc"># &lt;- a</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label2<span class="hl opt">)</span>  <span class="hl ppc">#</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">)</span>             <span class="hl ppc"># &lt;- a</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>    <span class="hl ppc">#</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">,</span> b<span class="hl opt">)</span>

<span class="hl ppc"># a -&gt; [b]</span>
def <span class="hl kwd">POKE</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwd">code_rem</span><span class="hl opt">(</span><span class="hl str">'POKE '</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>a<span class="hl opt">) +</span> <span class="hl str">' ['</span> <span class="hl opt">+</span> <span class="hl kwd">str</span><span class="hl opt">(</span>b<span class="hl opt">) +</span> <span class="hl str">']'</span><span class="hl opt">)</span>
  label <span class="hl opt">=</span> <span class="hl kwd">next_label</span><span class="hl opt">()</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>b<span class="hl opt">,</span> label<span class="hl opt">)</span>
  <span class="hl kwd">NOT</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>  <span class="hl ppc"># +3 (three operations)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>    <span class="hl ppc"># +4</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl str">&quot;move_reg&quot;</span><span class="hl opt">)</span>    <span class="hl ppc"># +5</span>
  <span class="hl kwd">code_label</span><span class="hl opt">(</span>label<span class="hl opt">)</span>
  <span class="hl kwd">code</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">)</span>             <span class="hl ppc"># &lt;- b</span>

<span class="hl ppc"># imm -&gt; [a]</span>
def <span class="hl kwd">POKEi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> a<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>imm<span class="hl opt">,</span> <span class="hl str">&quot;poke_i_reg&quot;</span><span class="hl opt">)</span>
  <span class="hl kwd">POKE</span><span class="hl opt">(</span><span class="hl str">&quot;poke_i_reg&quot;</span><span class="hl opt">,</span> a<span class="hl opt">)</span>
<span class="hl kwd">var</span><span class="hl opt">(</span><span class="hl str">&quot;poke_i_reg&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">EXIT</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">MOV</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;exit_reg&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">EXITi</span><span class="hl opt">(</span>a<span class="hl opt">):</span>
  <span class="hl kwd">MOVi</span><span class="hl opt">(</span>a<span class="hl opt">,</span> <span class="hl str">&quot;exit_reg&quot;</span><span class="hl opt">)</span>

def <span class="hl kwd">FADD</span><span class="hl opt">(</span>mask<span class="hl opt">,</span> carry<span class="hl opt">,</span> a<span class="hl opt">,</span> b<span class="hl opt">,</span> r<span class="hl opt">):</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>a<span class="hl opt">,</span> mask<span class="hl opt">,</span> <span class="hl str">&quot;fadd_reg_a&quot;</span><span class="hl opt">)</span>  <span class="hl ppc"># zero bits in</span> <span class="hl pps">'a'</span><span class="hl ppc"> except mask</span><span class="hl pps">'ed</span>
<span class="hl pps">  AND(b, mask, &quot;fadd_reg_b&quot;)  # zero bits in '</span><span class="hl ppc">b</span><span class="hl pps">' except mask'</span><span class="hl ppc">ed</span>
  <span class="hl kwd">AND</span><span class="hl opt">(</span>carry<span class="hl opt">,</span> mask<span class="hl opt">,</span> carry<span class="hl opt">)</span>     <span class="hl ppc"># zero bits in</span> <span class="hl pps">'carry'</span><span class="hl ppc"> except mask</span><span class="hl pps">'ed</span>
<span class="hl pps"></span>
<span class="hl pps">  # SUM = (a ^ b) ^ carry</span>
<span class="hl pps">  XOR(a, b, &quot;fadd_reg_t1&quot;)</span>
<span class="hl pps">  XOR(&quot;fadd_reg_t1&quot;, carry, &quot;fadd_reg_bit_r&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">  # Leave only '</span><span class="hl ppc">mask</span><span class="hl pps">'ed bit in bit_r.</span>
<span class="hl pps">  AND(&quot;fadd_reg_bit_r&quot;, mask, &quot;fadd_reg_bit_r&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">  # Add current added bit to the result.</span>
<span class="hl pps">  OR(&quot;fadd_reg_bit_r&quot;, r, r)</span>
<span class="hl pps"></span>
<span class="hl pps">  # CARRY = (a &amp; b) | (carry &amp; (a ^ b))</span>
<span class="hl pps">  AND(a, b, &quot;fadd_reg_t2&quot;)</span>
<span class="hl pps">  AND(carry, &quot;fadd_reg_t1&quot;, &quot;fadd_reg_t1&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">  # CARRY is calculated, and '</span><span class="hl ppc">shift_reg</span><span class="hl pps">' contains the same value</span>
<span class="hl pps">  # but shifted the left by 1 bit.</span>
<span class="hl pps">  OR(&quot;fadd_reg_t2&quot;, &quot;fadd_reg_t1&quot;, carry)</span>
<span class="hl pps"></span>
<span class="hl pps">  # CARRY is shifted the left by 1 bit to be used on the next round.</span>
<span class="hl pps">  MOV(&quot;shift_reg&quot;, carry)</span>
<span class="hl pps"></span>
<span class="hl pps">  # shift_reg = mask &lt;&lt; 1</span>
<span class="hl pps">  MOV(mask, mask)</span>
<span class="hl pps">  # mask = shift (effectively &quot;mask = mask &lt;&lt; 1&quot;)</span>
<span class="hl pps">  MOV(&quot;shift_reg&quot;, mask)</span>
<span class="hl pps"></span>
<span class="hl pps">  AND(carry, mask, carry)</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;fadd_reg_a&quot;)</span>
<span class="hl pps">var(&quot;fadd_reg_b&quot;)</span>
<span class="hl pps">var(&quot;fadd_reg_bit_r&quot;)</span>
<span class="hl pps">var(&quot;fadd_reg_t1&quot;)</span>
<span class="hl pps">var(&quot;fadd_reg_t2&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">def ZERO(a):</span>
<span class="hl pps">  XOR(a, a, a)</span>
<span class="hl pps"></span>
<span class="hl pps">def FADC(a, b, r):</span>
<span class="hl pps">  ZERO(&quot;fadc_reg_t&quot;)</span>
<span class="hl pps">  MOV(&quot;const_1&quot;, &quot;fadc_reg_mask&quot;)</span>
<span class="hl pps">  for i in range(0, 16):</span>
<span class="hl pps">    FADD(&quot;fadc_reg_mask&quot;, &quot;carry_reg&quot;, a, b, &quot;fadc_reg_t&quot;)</span>
<span class="hl pps">  MOV(&quot;fadc_reg_t&quot;, r)</span>
<span class="hl pps"></span>
<span class="hl pps">  ZERO(&quot;fadc_reg_t&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">  for i in range(0, 16):</span>
<span class="hl pps">    OR(&quot;fadc_reg_t&quot;, &quot;carry_reg&quot;, &quot;fadc_reg_t&quot;)</span>
<span class="hl pps">    MOV(&quot;carry_reg&quot;, &quot;carry_reg&quot;)</span>
<span class="hl pps">    MOV(&quot;shift_reg&quot;, &quot;carry_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">  MOV(&quot;fadc_reg_t&quot;, &quot;carry_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;fadc_reg_mask&quot;)</span>
<span class="hl pps">var(&quot;fadc_reg_t&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">def ADD(a, b, r):</span>
<span class="hl pps">  ZERO(&quot;carry_reg&quot;)</span>
<span class="hl pps">  FADC(a, b, r)</span>
<span class="hl pps"></span>
<span class="hl pps">def ADDi(a, imm, r):</span>
<span class="hl pps">  MOVi(imm, &quot;add_i_reg&quot;)</span>
<span class="hl pps">  ADD(a, &quot;add_i_reg&quot;, r)</span>
<span class="hl pps">var(&quot;add_i_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">def PUSH(a):</span>
<span class="hl pps">  ADD(&quot;stack_reg&quot;, &quot;const_minus_1&quot;, &quot;stack_reg&quot;)</span>
<span class="hl pps">  POKE(a, &quot;stack_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">def PUSHi(imm):</span>
<span class="hl pps">  MOVi(imm, &quot;push_i_reg&quot;)</span>
<span class="hl pps">  PUSH(&quot;push_i_reg&quot;)</span>
<span class="hl pps">var(&quot;push_i_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">def POP(a):</span>
<span class="hl pps">  PEEK(&quot;stack_reg&quot;, a)</span>
<span class="hl pps">  ADD(&quot;stack_reg&quot;, &quot;const_1&quot;, &quot;stack_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">def CALL(a):</span>
<span class="hl pps">  label = next_label()</span>
<span class="hl pps">  PUSHi(label)</span>
<span class="hl pps">  JMP(a)</span>
<span class="hl pps">  code_label(label)</span>
<span class="hl pps"></span>
<span class="hl pps">def CALLi(a):</span>
<span class="hl pps">  label = next_label()</span>
<span class="hl pps">  PUSHi(label)</span>
<span class="hl pps">  JMPi(a)</span>
<span class="hl pps">  code_label(label)</span>
<span class="hl pps"></span>
<span class="hl pps">def RET():</span>
<span class="hl pps">  POP(&quot;ip&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps"># Jump '</span><span class="hl ppc">a</span><span class="hl pps">', if cond = FFFF, and '</span><span class="hl ppc">b</span><span class="hl pps">' if conf = 0000</span>
<span class="hl pps">def BRANCH(a, b, cond):</span>
<span class="hl pps">  AND(a, cond, &quot;branch_reg_a&quot;)              # reg_a = a &amp; cond</span>
<span class="hl pps">  NOT(cond, &quot;branch_reg_b&quot;)                 # reg_b = !cond</span>
<span class="hl pps">  AND(b, &quot;branch_reg_b&quot;, &quot;branch_reg_b&quot;)    # reg_b = b &amp; reg_b = b &amp; !cond</span>
<span class="hl pps">  OR(&quot;branch_reg_a&quot;, &quot;branch_reg_b&quot;, &quot;ip&quot;)  # ip = (a &amp; cond) | (b &amp; !cond)</span>
<span class="hl pps">var(&quot;branch_reg_a&quot;)</span>
<span class="hl pps">var(&quot;branch_reg_b&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps"># Jump '</span><span class="hl ppc">a</span><span class="hl pps">', if cond = FFFF, and '</span><span class="hl ppc">b</span><span class="hl pps">' if conf = 0000</span>
<span class="hl pps">def BRANCHi(a, b, cond):</span>
<span class="hl pps">  MOVi(a, &quot;branch_i_reg_a&quot;)</span>
<span class="hl pps">  MOVi(b, &quot;branch_i_reg_b&quot;)</span>
<span class="hl pps">  BRANCH(&quot;branch_i_reg_a&quot;, &quot;branch_i_reg_b&quot;, cond)</span>
<span class="hl pps">var(&quot;branch_i_reg_a&quot;)</span>
<span class="hl pps">var(&quot;branch_i_reg_b&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps"># if a != 0 -&gt; carry = FFFF else carry = 0000</span>
<span class="hl pps">def IS_0(a):</span>
<span class="hl pps">  ZERO(&quot;carry_reg&quot;)</span>
<span class="hl pps">  FADC(a, &quot;const_minus_1&quot;, &quot;is_0_reg&quot;)</span>
<span class="hl pps">  NOT(&quot;carry_reg&quot;, &quot;zero_reg&quot;)</span>
<span class="hl pps">var(&quot;is_0_reg&quot;)</span>
<span class="hl pps">var(&quot;zero_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps"># ip = (zero_reg == FFFF ? a : ip)</span>
<span class="hl pps">def JZi(a):</span>
<span class="hl pps">  label = next_label()</span>
<span class="hl pps">  BRANCHi(a, label, &quot;zero_reg&quot;)</span>
<span class="hl pps">  code_label(label)</span>
<span class="hl pps"></span>
<span class="hl pps"># ip = (zero_reg == FFFF ? a : ip)</span>
<span class="hl pps">def JNZi(a):</span>
<span class="hl pps">  label = next_label()</span>
<span class="hl pps">  BRANCHi(label, a, &quot;zero_reg&quot;)</span>
<span class="hl pps">  code_label(label)</span>
<span class="hl pps"></span>
<span class="hl pps">def ROL(a, b):</span>
<span class="hl pps">  MOV(a, a)            # shift_reg = a &lt;&lt; 1</span>
<span class="hl pps">  MOV(&quot;shift_reg&quot;, b)</span>
<span class="hl pps"></span>
<span class="hl pps">def ROR(a, b):</span>
<span class="hl pps">  MOV(a, &quot;ror_reg&quot;)</span>
<span class="hl pps">  for i in range(0, 15):</span>
<span class="hl pps">    ROL(&quot;ror_reg&quot;, &quot;ror_reg&quot;)</span>
<span class="hl pps">  MOV(&quot;ror_reg&quot;, b)</span>
<span class="hl pps">var(&quot;ror_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">def SHL(a, b):</span>
<span class="hl pps">  ROL(a, b)</span>
<span class="hl pps">  ANDi(b, 0x0001, b)</span>
<span class="hl pps"></span>
<span class="hl pps">def SHR(a, b):</span>
<span class="hl pps">  ROR(a, b)</span>
<span class="hl pps">  ANDi(b, 0x7FFF, b)</span>
<span class="hl pps"></span>
<span class="hl pps">def MUL3(a, b):</span>
<span class="hl pps">  ADD(a, a, &quot;mul3_reg&quot;)    # mul3_reg = a + a</span>
<span class="hl pps">  ADD(&quot;mul3_reg&quot;, a, b)    # b = mul3_reg + a</span>
<span class="hl pps">var(&quot;mul3_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps"># NORCPU code</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;ip&quot;, &quot;start&quot;)</span>
<span class="hl pps">var(&quot;shift_reg&quot;)</span>
<span class="hl pps">var(&quot;carry_reg&quot;)</span>
<span class="hl pps">var(&quot;const_1&quot;, 1)</span>
<span class="hl pps">var(&quot;const_minus_1&quot;, 0xFFFF)</span>
<span class="hl pps">var(&quot;exit_reg&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;stack_reg&quot;, &quot;stack&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">code_label(&quot;start&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;ch&quot;)</span>
<span class="hl pps">var(&quot;t&quot;)</span>
<span class="hl pps">var(&quot;xor_mask&quot;)</span>
<span class="hl pps">var(&quot;cmp_flag&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;ptr&quot;)</span>
<span class="hl pps">var(&quot;ptr2&quot;)</span>
<span class="hl pps">var(&quot;i&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">MOVi(&quot;exchange&quot;, &quot;ptr&quot;)</span>
<span class="hl pps">MOVi(&quot;secret_password&quot;, &quot;ptr2&quot;)</span>
<span class="hl pps">MOVi(secret_password_xor_mask, &quot;xor_mask&quot;)</span>
<span class="hl pps">MOVi(0, &quot;cmp_flag&quot;)</span>
<span class="hl pps">MOVi(len(secret_password), &quot;i&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">cmp_loop = next_label()</span>
<span class="hl pps">code_label(cmp_loop)               # cmp_loop:</span>
<span class="hl pps">PEEK(&quot;ptr&quot;, &quot;ch&quot;)                                      # ch = *ptr</span>
<span class="hl pps">XOR(&quot;ch&quot;, &quot;xor_mask&quot;, &quot;ch&quot;)                            # ch ^= xor_mask</span>
<span class="hl pps">PEEK(&quot;ptr2&quot;, &quot;t&quot;)                                      # t = *ptr2</span>
<span class="hl pps">XOR(&quot;ch&quot;, &quot;t&quot;, &quot;ch&quot;)                                   # ch = ch ^ t</span>
<span class="hl pps">OR(&quot;cmp_flag&quot;, &quot;ch&quot;, &quot;cmp_flag&quot;)                       # cmp_flag |= ch</span>
<span class="hl pps">ADD(&quot;ptr&quot;, &quot;const_1&quot;, &quot;ptr&quot;)                           # ptr += 1</span>
<span class="hl pps">ADD(&quot;ptr2&quot;, &quot;const_1&quot;, &quot;ptr2&quot;)                         # ptr2 += 1</span>
<span class="hl pps">MUL3(&quot;xor_mask&quot;, &quot;xor_mask&quot;)                           # xor_mask *= 3</span>
<span class="hl pps">ADDi(&quot;xor_mask&quot;, secret_password_add, &quot;xor_mask&quot;)      # xor_mask += add_const</span>
<span class="hl pps">ADD(&quot;i&quot;, &quot;const_minus_1&quot;, &quot;i&quot;)                         # i -= 1</span>
<span class="hl pps">IS_0(&quot;i&quot;)</span>
<span class="hl pps">JNZi(cmp_loop)</span>
<span class="hl pps"></span>
<span class="hl pps">MOVi(0, &quot;exchange_sz&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">ok_label = next_label()</span>
<span class="hl pps">IS_0(&quot;cmp_flag&quot;)</span>
<span class="hl pps">JZi(ok_label)</span>
<span class="hl pps"></span>
<span class="hl pps">exit_label = next_label()</span>
<span class="hl pps">JMPi(exit_label)</span>
<span class="hl pps"></span>
<span class="hl pps">code_label(ok_label)</span>
<span class="hl pps"></span>
<span class="hl pps">MOVi(&quot;secret_code&quot;, &quot;ptr&quot;)</span>
<span class="hl pps">MOV(&quot;secret_code_sz&quot;, &quot;i&quot;)</span>
<span class="hl pps">MOVi(secret_code_xor_mask, &quot;xor_mask&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">MOVi(&quot;exchange&quot;, &quot;ptr2&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">MOV(&quot;i&quot;, &quot;exchange_sz&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">loop = next_label()</span>
<span class="hl pps">code_label(loop)                   # loop:</span>
<span class="hl pps">PEEK(&quot;ptr&quot;, &quot;ch&quot;)                             # ch = *ptr</span>
<span class="hl pps">XOR(&quot;ch&quot;, &quot;xor_mask&quot;, &quot;ch&quot;)                   # ch ^= xor_mask</span>
<span class="hl pps">POKE(&quot;ch&quot;, &quot;ptr2&quot;)                            # *ptr2 = ch</span>
<span class="hl pps">MUL3(&quot;xor_mask&quot;, &quot;xor_mask&quot;)                  # xor_mask *= 3</span>
<span class="hl pps">ADDi(&quot;xor_mask&quot;, secret_code_add, &quot;xor_mask&quot;) # xor_mask += add_const</span>
<span class="hl pps">ADD(&quot;ptr&quot;, &quot;const_1&quot;, &quot;ptr&quot;)                  # ptr += 1</span>
<span class="hl pps">ADD(&quot;ptr2&quot;, &quot;const_1&quot;, &quot;ptr2&quot;)                # ptr2 += 1</span>
<span class="hl pps">ADD(&quot;i&quot;, &quot;const_minus_1&quot;, &quot;i&quot;)                # i = i - 1</span>
<span class="hl pps">IS_0(&quot;i&quot;)</span>
<span class="hl pps">JNZi(loop)</span>
<span class="hl pps"></span>
<span class="hl pps">code_label(exit_label)             # exit_label:</span>
<span class="hl pps">EXITi(0x00)</span>
<span class="hl pps"></span>
<span class="hl pps">buffer(8)</span>
<span class="hl pps">data_label(&quot;stack&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;secret_code_sz&quot;, len(secret_code))</span>
<span class="hl pps">data_label(&quot;secret_code&quot;)</span>
<span class="hl pps">buffer(len(secret_code))</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;secret_password_sz&quot;)</span>
<span class="hl pps">data_label(&quot;secret_password&quot;)</span>
<span class="hl pps">buffer(16)</span>
<span class="hl pps"></span>
<span class="hl pps">var(&quot;exchange_sz&quot;, 0)</span>
<span class="hl pps">data_label(&quot;exchange&quot;)</span>
<span class="hl pps">buffer(32)</span>
<span class="hl pps"></span>
<span class="hl pps"># Compiler</span>
<span class="hl pps"></span>
<span class="hl pps">text = code_segment</span>
<span class="hl pps">text.extend(data_segment)</span>
<span class="hl pps"></span>
<span class="hl pps">if verbose:</span>
<span class="hl pps">  print &quot;</span><span class="hl esc">\n</span><span class="hl pps">&quot;.join(text)</span>
<span class="hl pps"></span>
<span class="hl pps"># Phase 1. Calculate names.</span>
<span class="hl pps"></span>
<span class="hl pps">addr = 0</span>
<span class="hl pps">names = {}</span>
<span class="hl pps">for line in text:</span>
<span class="hl pps">  if line[0] == '</span><span class="hl ppc">;</span><span class="hl pps">': continue</span>
<span class="hl pps">  if line[0] != '</span><span class="hl ppc"></span> <span class="hl pps">':</span>
<span class="hl pps">    name = line.partition('</span><span class="hl ppc">:</span><span class="hl pps">')[0]</span>
<span class="hl pps">    names[name] = addr</span>
<span class="hl pps">  else:</span>
<span class="hl pps">    addr = addr + 1</span>
<span class="hl pps"></span>
<span class="hl pps">if verbose:</span>
<span class="hl pps">  print names</span>
<span class="hl pps"></span>
<span class="hl pps">raw_text = &quot;</span><span class="hl esc">\n</span><span class="hl pps">&quot;.join(text)</span>
<span class="hl pps"></span>
<span class="hl pps"># Resolve names.</span>
<span class="hl pps"></span>
<span class="hl pps">for name in names:</span>
<span class="hl pps">  if verbose:</span>
<span class="hl pps">    print name, names[name], type(names[name])</span>
<span class="hl pps">  name_re = re.compile(r'</span><span class="hl ppc">dw</span> <span class="hl pps">' + name + '</span><span class="hl ppc">$</span><span class="hl pps">', re.M)</span>
<span class="hl pps">  value = &quot;%d&quot; % names[name]</span>
<span class="hl pps">  raw_text = name_re.sub('</span><span class="hl ppc">dw</span> <span class="hl pps">' + value, raw_text)</span>
<span class="hl pps"></span>
<span class="hl pps">text = raw_text.split(&quot;</span><span class="hl esc">\n</span><span class="hl pps">&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">if verbose:</span>
<span class="hl pps">  print &quot;</span><span class="hl esc">\n</span><span class="hl pps">&quot;.join(text)</span>
<span class="hl pps"></span>
<span class="hl pps"># Phase 2. Compilation.</span>
<span class="hl pps"></span>
<span class="hl pps">addr = 0</span>
<span class="hl pps">comment = &quot;&quot;</span>
<span class="hl pps">mem = []</span>
<span class="hl pps">for line in text:</span>
<span class="hl pps">  if line[0] == '</span><span class="hl ppc">;</span><span class="hl pps">' or line[0] != '</span><span class="hl ppc"></span> <span class="hl pps">':</span>
<span class="hl pps">    comment = comment + line + '</span><span class="hl ppc"></span> <span class="hl pps">'</span>
<span class="hl pps">  else:</span>
<span class="hl pps">    value = int(line.strip().partition(&quot; &quot;)[2])</span>
<span class="hl pps">    if verbose:</span>
<span class="hl pps">      print &quot;%04X: %04X ; %s&quot; % (addr, value, comment)</span>
<span class="hl pps">    mem.append(value)</span>
<span class="hl pps">    addr = addr + 1</span>
<span class="hl pps">    comment = &quot;&quot;</span>
<span class="hl pps"></span>
<span class="hl pps"># Interpretation</span>
<span class="hl pps"></span>
<span class="hl pps">ip = names[&quot;ip&quot;]</span>
<span class="hl pps">exit_reg = names[&quot;exit_reg&quot;]</span>
<span class="hl pps">shift_reg = names[&quot;shift_reg&quot;]</span>
<span class="hl pps">carry_reg = names[&quot;carry_reg&quot;]</span>
<span class="hl pps"></span>
<span class="hl pps">def nor(a, b):</span>
<span class="hl pps">  r = a | b</span>
<span class="hl pps">  r = r ^ 0xFFFF</span>
<span class="hl pps">  return r &amp; 0xFFFF</span>
<span class="hl pps"></span>
<span class="hl pps">def norcpu():</span>
<span class="hl pps">  while 1:</span>
<span class="hl pps">    i = mem[ip];</span>
<span class="hl pps">    a = mem[i + 0]</span>
<span class="hl pps">    b = mem[i + 1]</span>
<span class="hl pps">    r = mem[i + 2]</span>
<span class="hl pps">    mem[ip] = i + 3</span>
<span class="hl pps">    f = nor(mem[a], mem[b])</span>
<span class="hl pps">    mem[r] = f</span>
<span class="hl pps">    mem[shift_reg] = ((f &gt;&gt; 15) &amp; 1) | ((f &amp; 0x7FFF) &lt;&lt; 1)</span>
<span class="hl pps"></span>
<span class="hl pps">    if verbose_cpu:</span>
<span class="hl pps">      print &quot;%04X: %04X [%04X] %04X [%04X] -&gt; %04X [%04X]&quot; % \</span>
<span class="hl pps">            (i, a, mem[a], b, mem[b], r, mem[r])</span>
<span class="hl pps">    if r == exit_reg:</span>
<span class="hl pps">      break</span>
<span class="hl pps"></span>
<span class="hl pps">print &quot;Starting from [%04X]&quot; % mem[ip]</span>
<span class="hl pps"></span>
<span class="hl pps">encode_string(secret_code, &quot;secret_code&quot;, secret_code_xor_mask, secret_code_add);</span>
<span class="hl pps">encode_string(secret_password, &quot;secret_password&quot;, secret_password_xor_mask, secret_password_add);</span>
<span class="hl pps"></span>
<span class="hl pps">mem_js = dump_js(mem)</span>
<span class="hl pps">save_mem(&quot;norcpu-1-before.bin&quot;)</span>
<span class="hl pps">mem_sz = len(mem)</span>
<span class="hl pps"></span>
<span class="hl pps">if len(mem) &gt;= 0x10000:</span>
<span class="hl pps">  print &quot;Too much code (%08X, %04X)&quot; % (len(mem), len(mem) - 0x10000)</span>
<span class="hl pps">  sys.exit()</span>
<span class="hl pps"></span>
<span class="hl pps"># Inject plain password in the last moment (for testing).</span>
<span class="hl pps">put_string(guess, &quot;exchange&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">save_mem(&quot;norcpu-2-before-with-password.bin&quot;)</span>
<span class="hl pps"></span>
<span class="hl pps">if verbose:</span>
<span class="hl pps">  print &quot;Original memory:&quot;</span>
<span class="hl pps">  print dump(mem)</span>
<span class="hl pps"></span>
<span class="hl pps">start_time = time.time()</span>
<span class="hl pps"></span>
<span class="hl pps">norcpu()</span>
<span class="hl pps"></span>
<span class="hl pps">end_time = time.time()</span>
<span class="hl pps"></span>
<span class="hl pps">save_mem(&quot;norcpu-3-after.bin&quot;, mem_sz)</span>
<span class="hl pps"></span>
<span class="hl pps">if verbose:</span>
<span class="hl pps">  print &quot;Memory after:&quot;</span>
<span class="hl pps">  dump(mem)</span>
<span class="hl pps"></span>
<span class="hl pps">print</span>
<span class="hl pps">print &quot;Size: %X&quot; % len(mem)</span>
<span class="hl pps">print &quot;Time: %d&quot; % (end_time - start_time)</span>
<span class="hl pps">print &quot;Exit: %04X&quot; % mem[exit_reg]</span>
<span class="hl pps"></span>
<span class="hl pps">exchange = names[&quot;exchange&quot;]</span>
<span class="hl pps">result_value = &quot;&quot;</span>
<span class="hl pps">for i in range(0, mem[names[&quot;exchange_sz&quot;]]):</span>
<span class="hl pps">  result_value = result_value + chr(mem[exchange + i] &amp; 0xff)</span>
<span class="hl pps"></span>
<span class="hl pps">print &quot;Result: [%s]&quot; % result_value</span>
<span class="hl pps"></span>
<span class="hl pps">if len(result_value) == 0:</span>
<span class="hl pps">  print &quot;ERROR: Wrong password&quot;</span>
<span class="hl pps"></span>
<span class="hl pps">js = string.Template(open('</span><span class="hl ppc">template.html</span><span class="hl pps">', '</span><span class="hl ppc">r</span><span class="hl pps">').read())</span>
<span class="hl pps"></span>
<span class="hl pps">js = js.substitute( \</span>
<span class="hl pps">  ip = names[&quot;ip&quot;],</span>
<span class="hl pps">  exit_reg = names[&quot;exit_reg&quot;],</span>
<span class="hl pps">  shift_reg = names[&quot;shift_reg&quot;],</span>
<span class="hl pps">  exchange = names[&quot;exchange&quot;],</span>
<span class="hl pps">  exchange_sz = names[&quot;exchange_sz&quot;],</span>
<span class="hl pps">  mem_js = mem_js</span>
<span class="hl pps">)</span>
<span class="hl pps"></span>
<span class="hl pps">f = open(&quot;norcpu2.html&quot;, &quot;w&quot;)</span>
<span class="hl pps">f.write(js)</span>
<span class="hl pps">f.close()</span><span class="hl ppc"></span>
</pre>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[NORCPU hackme challenge]]></title>
    <link href="http://demin.ws/blog/english/2011/02/08/norcpu-hackme-challenge/"/>
    <updated>2011-02-08T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2011/02/08/norcpu-hackme-challenge/</id>
    <content type="html"><![CDATA[<p>Different kinds of &ldquo;abnormal&rdquo; programming is quite popular among problem solvers. Sometimes it&rsquo;s even impossible to write code manually anymore for just another &ldquo;abnormal&rdquo; programming environment. You have to write a code generator to create even a trivial program.</p>

<p>In the environment I&rsquo;m describing here you can easily write code manually on the high level macro assembler.</p>

<p>Okay, here is a virtual processor understanding only one logical command - <a href="http://en.wikipedia.org/wiki/Logical_NOR">Peirce arrow</a>.</p>

<p>A program written for this processor expects a password as an input. If the password is incorrect, it print out &ldquo;Wrong password!&rdquo;. Otherwise the special magic message will be printed.</p>

<p>The problem statement: You have to find out that magic message using any approach. For example, you can guess the password, the program will just print the secret out.</p>

<p>The logic is written such way that knowing the algorithm allows restoring the magic message without any problems.</p>

<p>Some time ago I <a href="http://demin.ws/blog/english/2010/04/06/modelling-a-cpu-with-only-one-operation/">described this approach</a> in all details.</p>

<p>The original approach I used in this experiment, wasn&rsquo;t 100% &ldquo;clear&rdquo;, because the addition command was implemented outside the processor. In this implementation everything works inside the processor. It required modifying the interpreter slightly introducing a shift register.</p>

<p>For those who want to try to hack this problem, I&rsquo;ve created a web page containing an implementation of this one-command processor and the programming check the password.</p>

<p>Here you go - <a href="http://demin.ws/projects/norcpu/challenge/norcpu.html">the challenge</a>.</p>

<p>P.S. The first one solved the problem will get a little prize! Information is on the page.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Screencasts]]></title>
    <link href="http://demin.ws/blog/english/2010/11/13/screencasts/"/>
    <updated>2010-11-13T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/11/13/screencasts/</id>
    <content type="html"><![CDATA[<p>Do you watch screencasts?</p>

<p>I&rsquo;ve discovered this way of getting technical information for myself only recently. Impression is only positive so far - the perceptual speed is much faster comparing to reading.</p>

<p>For example, after <a href="http://www.pragprog.com/screencasts/v-bdobjc/coding-in-objective-c-2-0">Coding in Objective-C 2.0</a> I can write a program in this language using classes and have an idea how the memory management works in Objective-C (by the way, it&rsquo;s quite interesting concept - a &ldquo;manual&rdquo; garbage collector when memory is freed automatically but the programmer has to manage the counter of active links to an object by himself.</p>

<p>Currently watching <a href="http://www.pragprog.com/screencasts/v-bdiphone/writing-your-first-iphone-application">Writing Your First iPhone Application</a> and the next is <a href="http://www.pragprog.com/screencasts/v-kserl/erlang-in-practice">Erlang in Practice</a>.</p>

<p>This is a delicate moment with screencasts - it should be made qualitatively. Otherwise it&rsquo;s waste of time.</p>

<p>Which screencasts do you watch? What can you recommend?</p>

<p>P.S. By the way, I like <a href="http://www.pragprog.com/">The pragmatic Bookshelf</a> online store more and more. All books are in multiple DRM free formats (pdf, mobi, epub).</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Naming convension for getters and setters in C++]]></title>
    <link href="http://demin.ws/blog/english/2010/11/09/naming-convension-for-getters-and-setters-in-cpp/"/>
    <updated>2010-11-09T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/11/09/naming-convension-for-getters-and-setters-in-cpp/</id>
    <content type="html"><![CDATA[<p>When writing getter and setter methods in standard C++ there are three main approaches for naming.</p>

<p>1. Pure C++ method based on the references.</p>

<pre class="hl">
<span class="hl kwc">class</span> Foo <span class="hl opt">{</span>
  Value field_<span class="hl opt">;</span>
<span class="hl kwc">public</span><span class="hl opt">:</span>
  Value<span class="hl opt">&amp;</span> <span class="hl kwd">field</span><span class="hl opt">() {</span> <span class="hl kwa">return</span> field_<span class="hl opt">; }</span>
  <span class="hl kwb">const</span> Value<span class="hl opt">&amp;</span> <span class="hl kwd">field</span><span class="hl opt">()</span> <span class="hl kwb">const</span> <span class="hl opt">{</span> <span class="hl kwa">return</span> field_<span class="hl opt">; }</span>
<span class="hl opt">};</span>
</pre>

<p>Usage:</p>

<pre class="hl">
Foo foo<span class="hl opt">;</span>
foo<span class="hl opt">.</span><span class="hl kwd">field</span><span class="hl opt">() =</span> field_instance<span class="hl opt">;</span>
field_instance <span class="hl opt">=</span> foo<span class="hl opt">.</span><span class="hl kwd">field</span><span class="hl opt">();</span>
</pre>

<p>Pros: brevity, closeness to the property notation and possibility of using in a cascade assignment (<code>foo1.field() = foo2.field() = 2;</code>).</p>

<p>Cons: using the function call on the left looks unusual.</p>

<p>2. Java way</p>

<pre class="hl">
<span class="hl kwc">class</span> Foo <span class="hl opt">{</span>
  Value field_<span class="hl opt">;</span>
<span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwb">void</span> <span class="hl kwd">setField</span><span class="hl opt">(</span><span class="hl kwb">const</span> Value<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span> field_ <span class="hl opt">=</span> value<span class="hl opt">; }</span>
  <span class="hl kwb">const</span> Value<span class="hl opt">&amp;</span> <span class="hl kwd">getField</span><span class="hl opt">()</span> <span class="hl kwb">const</span> <span class="hl opt">{</span> <span class="hl kwa">return</span> field_<span class="hl opt">; }</span>
<span class="hl opt">};</span>
</pre>

<p>Usage:</p>

<pre class="hl">
Foo foo<span class="hl opt">;</span>
foo<span class="hl opt">.</span><span class="hl kwd">setField</span><span class="hl opt">(</span>field_instance<span class="hl opt">);</span>
field_instance <span class="hl opt">=</span> foo<span class="hl opt">.</span><span class="hl kwd">getField</span><span class="hl opt">();</span>
</pre>

<p>Pros: clarity and obviousness.</p>

<p>Cons: wordiness due to <code>get</code> and <code>set</code> prefixes.</p>

<p>3. Objective-C way</p>

<pre class="hl">
<span class="hl kwc">class</span> Foo <span class="hl opt">{</span>
  Value field_<span class="hl opt">;</span>
<span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwb">void</span> <span class="hl kwd">setField</span><span class="hl opt">(</span><span class="hl kwb">const</span> Value<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span> field_ <span class="hl opt">=</span> value<span class="hl opt">; }</span>
  <span class="hl kwb">const</span> Value<span class="hl opt">&amp;</span> <span class="hl kwd">field</span><span class="hl opt">()</span> <span class="hl kwb">const</span> <span class="hl opt">{</span> <span class="hl kwa">return</span> field_<span class="hl opt">; }</span>
<span class="hl opt">};</span>
</pre>

<p>Usage:</p>

<pre class="hl">
Foo foo<span class="hl opt">;</span>
foo<span class="hl opt">.</span><span class="hl kwd">setField</span><span class="hl opt">(</span>field_instance<span class="hl opt">);</span>
field_instance <span class="hl opt">=</span> foo<span class="hl opt">.</span><span class="hl kwd">field</span><span class="hl opt">();</span>
</pre>

<p>Pros: brevity (no useless <code>get</code> prefix) and clarify.</p>

<p>Cons: haven&rsquo;t found so far.</p>

<p>All three have rights to live but from the style perspective it&rsquo;s good to be consistent and use only one style across one project.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Chinese method of multiplication on paper]]></title>
    <link href="http://demin.ws/blog/english/2010/10/20/chinese-method-of-multiplication-on-paper/"/>
    <updated>2010-10-20T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/10/20/chinese-method-of-multiplication-on-paper/</id>
    <content type="html"><![CDATA[<p>I don&rsquo;t claim that is more efficient rather the traditional method but looks very cool.</p>

<iframe width="425" height="344" src="http://www.youtube.com/embed/EsgMzkUivKo?color=white&theme=light"></iframe>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Tricky floating point]]></title>
    <link href="http://demin.ws/blog/english/2010/05/12/tricky-floating-point/"/>
    <updated>2010-05-12T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/05/12/tricky-floating-point/</id>
    <content type="html"><![CDATA[<p>How do you think what the code below should print out? I expected two numbers <code>115</code>.</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;cmath&gt;</span>
<span class="hl kwa">using namespace</span> std<span class="hl opt">;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">double</span> f <span class="hl opt">=</span> <span class="hl num">1.15</span><span class="hl opt">;</span>
  <span class="hl kwb">int</span> a <span class="hl opt">=</span> f <span class="hl opt">*</span> <span class="hl num">100.0</span> <span class="hl opt">+</span> <span class="hl num">0.1E-9</span><span class="hl opt">;</span>
  <span class="hl kwb">int</span> b <span class="hl opt">=</span> f <span class="hl opt">*</span> <span class="hl num">100.0</span><span class="hl opt">;</span>
  cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;a = &quot;</span> <span class="hl opt">&lt;&lt;</span> a <span class="hl opt">&lt;&lt;</span> endl<span class="hl opt">;</span>
  cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;b = &quot;</span> <span class="hl opt">&lt;&lt;</span> b <span class="hl opt">&lt;&lt;</span> endl<span class="hl opt">;</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>No, on VS2008 it prints out:</p>

<pre><code>115
114
</code></pre>

<p>Be careful.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Modelling a CPU with only one operation]]></title>
    <link href="http://demin.ws/blog/english/2010/04/06/modelling-a-cpu-with-only-one-operation/"/>
    <updated>2010-04-06T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/04/06/modelling-a-cpu-with-only-one-operation/</id>
    <content type="html"><![CDATA[<p>Going further with bitwise tips and tricks I will tell about a model of a CPU based on a single operation - NOR (or Peirce arrow).</p>

<p>In the mid-nineties in the FIDO discussion group RU.HACKER I come across an interesting hackme.</p>

<p>Usually &ldquo;hackme&rdquo; is an application which is published as a challenge to be hacked. It prompts for a password and the goal is to crack it. You may guess the password disassembling the code or could just patch the code and disable the password check and so on.</p>

<p>That &ldquo;hackme&rdquo; from RU.HACKER was originally written by famous Russian hacker and security expert Alexander Peslyak (the author of John The Ripper John The Ripper and Openwall Linux).</p>

<p>Unlike other &ldquo;hackme&rdquo; around Alexander&rsquo;s approach didn&rsquo;t have any anti-debugger tricks at all preventing disassembling and tracing. Furthermore it contained less then hundred bytes of x86 code. The code executed a trivial loop calculating only one operation - NOR (Pierce arrow). And the entire business logic (interaction with the console and password calculations) was build on top this primitive. Effectively this is a model of CPU having only one command.</p>

<p>The memory model of this CPU is flat and it consists of 16-bit words. The address space is from 0x0000 to 0xFFFF. A CPU instruction has 3 operands. There is no an instruction code because the command is always the same - NOR. Each operand represents an address.</p>

<p>To execute an instruction CPU takes the left argument of NOR from an address given in the first operand and the right argument from an address given in the second operand. Then it implies bitwise 16-bit NOR between them and puts the result to the address given in the third argument. Afterwards the instruction pointer is increment by 3 to shift to the next instruction and the cycle repeats.</p>

<p>The instruction pointer (<code>IP</code>) is also located in the address space and JUMP operation could be implemented just by putting a jump address to the memory location of <code>IP</code>.</p>

<p>The original NOR interpreter was written on x86 assembly:</p>

<pre class="hl">
<span class="hl kwa">cld</span>
<span class="hl kwc">emCPU:</span>
<span class="hl kwa">mov</span>  <span class="hl kwb">si</span><span class="hl opt">,</span>emIP
<span class="hl kwa">lodsw</span>
<span class="hl kwa">xchg</span> <span class="hl kwb">ax</span><span class="hl opt">,</span><span class="hl kwb">di</span>
<span class="hl kwa">mov</span>  <span class="hl kwb">di</span><span class="hl opt">,[</span><span class="hl kwb">di</span><span class="hl opt">]</span>
<span class="hl kwa">lodsw</span>
<span class="hl kwa">xchg</span> <span class="hl kwb">ax</span><span class="hl opt">,</span><span class="hl kwb">bx</span>
<span class="hl kwa">or</span>   <span class="hl kwb">di</span><span class="hl opt">,[</span><span class="hl kwb">bx</span><span class="hl opt">]</span>
<span class="hl kwa">lodsw</span>
<span class="hl kwa">xchg</span> <span class="hl kwb">ax</span><span class="hl opt">,</span><span class="hl kwb">di</span>
<span class="hl kwa">not</span>  <span class="hl kwb">ax</span>
<span class="hl kwa">mov</span>  emIP<span class="hl opt">,</span><span class="hl kwb">si</span>
<span class="hl kwa">stosw</span>
<span class="hl kwa">jmp  short</span> emCPU
</pre>

<p>Nothing prevents to write it on any language, for example, Python.</p>

<pre class="hl">
<span class="hl kwa">def</span> <span class="hl kwd">nor</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">):</span>
  <span class="hl kwa">return</span> ~<span class="hl opt">(</span>a | b<span class="hl opt">) &amp;</span> <span class="hl num">0xFFFF</span>

<span class="hl kwa">def</span> <span class="hl kwd">norcpu</span><span class="hl opt">():</span>
  <span class="hl kwa">while</span> <span class="hl num">1</span><span class="hl opt">:</span>
    i <span class="hl opt">=</span> mem<span class="hl opt">[</span>IP<span class="hl opt">];</span>
    a <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">0</span><span class="hl opt">]</span>
    b <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">]</span>
    r <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">2</span><span class="hl opt">]</span>
    mem<span class="hl opt">[</span>IP<span class="hl opt">] =</span> i <span class="hl opt">+</span> <span class="hl num">3</span>
    f <span class="hl opt">=</span> <span class="hl kwd">nor</span><span class="hl opt">(</span>mem<span class="hl opt">[</span>a<span class="hl opt">],</span> mem<span class="hl opt">[</span>b<span class="hl opt">])</span>
    mem<span class="hl opt">[</span>r<span class="hl opt">] =</span> f
</pre>

<p>Why NOR? The Boolean algebra theory says that any of 14 of 16 Boolean functions could be calculated using just the rest two - NOR and NAND. For instance:</p>

<pre><code>NOT(a) = NOR(a, a)
AND(a, b) = NOT(OR(NOT(a), NOT(b)))
OR(a, b) = NOT(NOR(a, b))
XOR(a, b) = OR(AND(a, NOT(b)), AND(NOT(a), b)))
</code></pre>

<p>The move operation <code>MOVE(src, dst)</code> could be implemented via <code>OR</code>:</p>

<pre><code>mem[dst] = OR(mem[src], mem[src])
</code></pre>

<p>A conditional jump is either implemented via Boolean functions. If <code>cond</code> equals 0xFFFF (true), the jump to <code>addr</code> is performed. If <code>cond</code> equals 0x0000 (false) CPU sequentially takes the next instruction following <code>JUMP</code>.</p>

<pre><code>mem[IP] = OR(AND(addr, cond), AND(mem[IP], cond))
</code></pre>

<p>Or in the NOR interpreter notation:</p>

<pre><code>AND addr, cond, @t1
AND IP, cond, @t2
OR @t1, @t2, IP
</code></pre>

<p>where <code>@t1</code> and <code>@t2</code> are temporary variables. The <code>AND</code> and <code>OR</code> commands will be also expanded to sets of NORs as shown above.</p>

<p>Eventually we have Boolean functions, copy/move, unconditional and conditional jumps. We just lack the addition/subtraction and shifts. Having that we could implement the subroutine stack and then any complex computations can be made by this primitive CPU.</p>

<p>The original Alexander&rsquo;s NOR CPU implementation had a workaround which allows running the native x86 code. The workaround was based on the fact that the NOR interpreter also resides in its address space and can modify itself. To execute the native code a special high level macro (let&rsquo;s say emCallX86) uses MOVE operation (see above) to place two bytes at the beginning of the interpreter code (effectively it saves the original two bytes and put other two instead). Those two new bytes are an x86 short jump instruction. When the interpreter begins the next cycle it simply jumps out to an arbitrary x86 code. In the end the native code restores the original two bytes of the interpreter and returns the execution flow to it.</p>

<p>An interaction with DOS I/O and an addition of two 16-bit integers with carry were implemented in native code.</p>

<p>Frankly speaking I don&rsquo;t find it feasible to implement a full 16-bit adder using Boolean functions only. The original NOR interpreter only performed bitwise NOR. It wasn&rsquo;t possible to move/shift an individual bit to another one but the <a href="http://en.wikipedia.org/wiki/Adder_(electronics)">full binary adder</a> needs it to consider the carry.</p>

<p>Recently I&rsquo;ve come back to this NOR interpreter approach but in Python world. I&rsquo;ve modified the original idea a bit to simplify (or just make it possible) an implementation of addition using NOR only, without native code at all. I&rsquo;ve introduced one extra operation in the interpreter ñ the result of NOR is cyclically shifted left by 1 bit and stored the special location in memory.</p>

<pre class="hl">
<span class="hl kwa">def</span> <span class="hl kwd">norcpu</span><span class="hl opt">():</span>
  <span class="hl kwa">while</span> <span class="hl num">1</span><span class="hl opt">:</span>
    i <span class="hl opt">=</span> mem<span class="hl opt">[</span>IP<span class="hl opt">];</span>
    a <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">0</span><span class="hl opt">]</span>
    b <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">1</span><span class="hl opt">]</span>
    r <span class="hl opt">=</span> mem<span class="hl opt">[</span>i <span class="hl opt">+</span> <span class="hl num">2</span><span class="hl opt">]</span>
    mem<span class="hl opt">[</span>IP<span class="hl opt">] =</span> i <span class="hl opt">+</span> <span class="hl num">3</span>
    f <span class="hl opt">=</span> <span class="hl kwd">nor</span><span class="hl opt">(</span>mem<span class="hl opt">[</span>a<span class="hl opt">],</span> mem<span class="hl opt">[</span>b<span class="hl opt">])</span>
    mem<span class="hl opt">[</span>r<span class="hl opt">] =</span> f
    mem<span class="hl opt">[</span>S<span class="hl opt">] = ((</span>f <span class="hl opt">&gt;&gt;</span> <span class="hl num">31</span><span class="hl opt">) &amp;</span> <span class="hl num">1</span><span class="hl opt">)</span> | <span class="hl opt">((</span>f <span class="hl opt">&amp;</span> <span class="hl num">0x7FFF</span><span class="hl opt">) &lt;&lt;</span> <span class="hl num">1</span><span class="hl opt">)</span>
</pre>

<p>There are two special locations now: <code>IP</code> (instruction pointer) and <code>S</code> (shift register).</p>

<p>Let&rsquo;s try to implement the full addition of 16-bit words with carry. I will use a simple macro assembler.</p>

<p>The full 1 bit adder formulas are:</p>

<pre><code>sum = (a ^ b) ^ carry
carry = (a &amp; b) | (carry &amp; (a ^ b))
</code></pre>

<p>Now in the NOR CPU assembly:</p>

<pre><code>; Input:
;  mask  - a current bit mask (0x0001, 0x0002, 0x0004, 0x0008 etc)
;  carry ñ a carry from the previous bit (the masked applied)
;  a, b  - an argument addresses
;  r     - an address of the result
; Output:
;  r     - a result
;  carry - a carry to the next bit (already left shifted with respect to the mask)
;  mask  - a mask left shifted by one bit
;
; Variables with '@' prefix are local for the macro.
;
!macro FADD mask, carry, a, b, r
  XOR a, b, @t1              ; Formula: sum = (a ^ b) ^ carry.
  XOR @t1, carry, @bit_r     ; 
  AND @bit_r, mask, @bit_r   ; Mask all bits in @bit_r expect the current one
  OR @bit_r, r, r            ; Save the bit to the result: r |= sum
  AND a, b, @t2              ; Formula: carry = (a &amp; b) | (carry &amp; (a ^ b))
  AND carry, @t1, @t1        ;
  OR @t2, @t1, carry         ; The carry is calculated. Its left shifted copy is in S. 
  MOVE S, carry              ; Assign the carry to itself but shifted the next bit.
  MOVE mask, mask, mask      ; Dummy assignment to just get: S = mask &lt;&lt; 1.
  MOVE S, mask               ; mask = S = mask &lt;&lt; 1
</code></pre>

<p>Then we implement the 16-bit adder:</p>

<pre><code>; Input:
;  a, b  - argument
;  carry ñ a carry (the least significant bit only makes sense)
; Output:
;  r     - the result: r = a + c + carry
;  carry ñ a carry (the least significant bit only makes sense)
;
; Variables having '@' prefix are local for the macro.
; const_1 - a special location containing the constant 0x0001.
;
!macro ADC a, b, carry, r
  XOR r, r, r                     ; r = 0.
  MOVE const_1, @mask             ; The initial mask value = 0x0001
  *16 FADD @mask, carry, a, b, r  ; Repeat FADD 16 times (no loops, just a
                                  ; repetition)
  AND carry, const_1, carry       ; Clean-up all bits in carry except LSB.
</code></pre>

<p>What happens in <code>ADC</code>? On each iteration (repetition) of <code>FADD</code> it sums the current bit (its mask is <code>@mask</code>). Then the sum is joined (via <code>OR</code>) with the result. The mask is shifted to left 1 bit (the <code>@mask</code> takes values 0x0001 -&gt; 0x0002 -&gt; 0x0004 etc). The carry is also shifted to the left 1 bit to be used on the next iteration of <code>FADD</code>. After 16 iterations the carry will be in LSB (because the interpreter shifts cyclically). The carry after 16 iterations will be output value of carry.</p>

<p>The addition is implemented eventually. Then we could programmatically implement a subroutine stack. <code>CALL</code>/<code>RET</code> instructions could be based on the stack mechanism and branching instructions.</p>

<p>Now we can easily do any computations on our pseudo CPU executing only one command.</p>

<p>What&rsquo;s the point of all this stuff? First of all is an academic interest, fun.</p>

<p>Related posts:</p>

<ul>
<li><a href="http://demin.ws/blog/english/2010/03/17/swap-two-numeric-variable-using-xor/">Swap two numeric variables using XOR</a></li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Swap two numeric variables using XOR]]></title>
    <link href="http://demin.ws/blog/english/2010/03/17/swap-two-numeric-variable-using-xor/"/>
    <updated>2010-03-17T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/03/17/swap-two-numeric-variable-using-xor/</id>
    <content type="html"><![CDATA[<p>Two numeric variables could be swapped not only via a temporary one. It could be done this way:</p>

<pre><code>a += b;
b = a - b;
a -= b;
</code></pre>

<p>This is neat but unlikely useful in practice. But it could be rewritten using bitwise arithmetics to avoid overflow issues:</p>

<pre><code>a ^= b ^= a ^= b;
</code></pre>

<p>This one looks very cool and hackish but unfortinatelly may cause an unpredictable behavior according to the Standard due to the chained assignments. So the last edition is also fast and overflow free but doesn&rsquo;t have an unpredictable behavior:</p>

<pre><code>a ^= b;
b ^= a;
a ^= b;
</code></pre>

<p><strong>Update</strong>: Here is a perfect link to <a href="http://graphics.stanford.edu/~seander/bithacks.html">Bit Twiddling Hacks</a> with lots of similar bitwise tips.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What is faster on Sieve of Eratosthenes: Go, C or C++?]]></title>
    <link href="http://demin.ws/blog/english/2010/03/06/what-is-faster-on-eratosthenes-seive-go-c-or-cpp/"/>
    <updated>2010-03-06T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/03/06/what-is-faster-on-eratosthenes-seive-go-c-or-cpp/</id>
    <content type="html"><![CDATA[<p>Go is a very interesting language. It compiles to native-code (no VM or JIT) and it comes with automatic garbage collection and built-in concurrency support, the object-oriented model and on top of it - extremely fast compilation.</p>

<p>I love to use <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a> as &ldquo;Hello, world!&rdquo; when exploring a new language.</p>

<p>Here is my version of the seive in Go:</p>

<p>File <code>erato-go-bool.go</code>:</p>

<pre class="hl">
<span class="hl kwa">package</span> main

<span class="hl kwa">import</span> <span class="hl str">&quot;fmt&quot;</span>
<span class="hl kwa">import</span> <span class="hl str">&quot;math&quot;</span>
<span class="hl kwa">import</span> <span class="hl str">&quot;flag&quot;</span>

<span class="hl kwa">func</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
    <span class="hl kwa">var</span> N <span class="hl kwb">int</span>
    flag<span class="hl opt">.</span><span class="hl kwd">IntVar</span><span class="hl opt">(&amp;</span>N<span class="hl opt">,</span> <span class="hl str">&quot;N&quot;</span><span class="hl opt">,</span> <span class="hl num">100</span><span class="hl opt">,</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">)</span>
    flag<span class="hl opt">.</span><span class="hl kwd">Parse</span><span class="hl opt">()</span>

    fmt<span class="hl opt">.</span><span class="hl kwd">Printf</span><span class="hl opt">(</span><span class="hl str">&quot;%d</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> N<span class="hl opt">)</span>

    seive <span class="hl opt">:=</span> <span class="hl kwb">make</span><span class="hl opt">([]</span><span class="hl kwb">bool</span><span class="hl opt">,</span> N<span class="hl opt">)</span>
   
    limit <span class="hl opt">:=</span> <span class="hl kwb">int</span><span class="hl opt">(</span>math<span class="hl opt">.</span><span class="hl kwd">Sqrt</span><span class="hl opt">(</span><span class="hl kwb">float64</span><span class="hl opt">(</span>N<span class="hl opt">))) +</span> <span class="hl num">1</span>

    <span class="hl kwa">for</span> i <span class="hl opt">:=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> limit<span class="hl opt">;</span> i<span class="hl opt">++ {</span>
        <span class="hl kwa">if</span> <span class="hl opt">!</span>seive<span class="hl opt">[</span>i<span class="hl opt">] {</span>
            <span class="hl kwa">for</span> j <span class="hl opt">:=</span> i <span class="hl opt">*</span> i<span class="hl opt">;</span> j <span class="hl opt">&lt;</span> N<span class="hl opt">;</span> j <span class="hl opt">+=</span> i  <span class="hl opt">{</span>
                seive<span class="hl opt">[</span>j<span class="hl opt">] =</span> <span class="hl kwb">true</span>
            <span class="hl opt">}</span>
        <span class="hl opt">}</span>
    <span class="hl opt">}</span>

    count <span class="hl opt">:=</span> <span class="hl num">0</span>
    <span class="hl kwa">for</span> i <span class="hl opt">:=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> N<span class="hl opt">;</span> i<span class="hl opt">++ {</span>
        <span class="hl kwa">if</span> <span class="hl opt">!</span>seive<span class="hl opt">[</span>i<span class="hl opt">] {</span>
            count<span class="hl opt">++</span>
        <span class="hl opt">}</span>
    <span class="hl opt">}</span>
    fmt<span class="hl opt">.</span><span class="hl kwd">Printf</span><span class="hl opt">(</span><span class="hl str">&quot;%d</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> count<span class="hl opt">)</span>
<span class="hl opt">}</span>
</pre>

<p>But how fast is this?</p>

<p>I&rsquo;ve compared it against implementations in C++ and C.</p>

<p>The first competitor is Go using <code>bool</code> type in as a storage (see above). The second one is the also Go&rsquo;s version but with <code>int</code> as the storage type.</p>

<p>File <code>erato-go-int.go</code>:</p>

<pre class="hl">
<span class="hl kwa">package</span> main

<span class="hl kwa">import</span> <span class="hl str">&quot;fmt&quot;</span>
<span class="hl kwa">import</span> <span class="hl str">&quot;math&quot;</span>
<span class="hl kwa">import</span> <span class="hl str">&quot;flag&quot;</span>

<span class="hl kwa">func</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
    <span class="hl kwa">var</span> N <span class="hl kwb">int</span>
    flag<span class="hl opt">.</span><span class="hl kwd">IntVar</span><span class="hl opt">(&amp;</span>N<span class="hl opt">,</span> <span class="hl str">&quot;N&quot;</span><span class="hl opt">,</span> <span class="hl num">100</span><span class="hl opt">,</span> <span class="hl str">&quot;&quot;</span><span class="hl opt">)</span>
    flag<span class="hl opt">.</span><span class="hl kwd">Parse</span><span class="hl opt">()</span>

    fmt<span class="hl opt">.</span><span class="hl kwd">Printf</span><span class="hl opt">(</span><span class="hl str">&quot;%d</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> N<span class="hl opt">)</span>

    seive <span class="hl opt">:=</span> <span class="hl kwb">make</span><span class="hl opt">([]</span><span class="hl kwb">int</span><span class="hl opt">,</span> N<span class="hl opt">)</span>
   
    limit <span class="hl opt">:=</span> <span class="hl kwb">int</span><span class="hl opt">(</span>math<span class="hl opt">.</span><span class="hl kwd">Sqrt</span><span class="hl opt">(</span><span class="hl kwb">float64</span><span class="hl opt">(</span>N<span class="hl opt">))) +</span> <span class="hl num">1</span>

    <span class="hl kwa">for</span> i <span class="hl opt">:=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> limit<span class="hl opt">;</span> i<span class="hl opt">++ {</span>
        <span class="hl kwa">if</span> seive<span class="hl opt">[</span>i<span class="hl opt">] ==</span> <span class="hl num">0</span> <span class="hl opt">{</span>
            <span class="hl kwa">for</span> j <span class="hl opt">:=</span> i <span class="hl opt">*</span> i<span class="hl opt">;</span> j <span class="hl opt">&lt;</span> N<span class="hl opt">;</span> j <span class="hl opt">+=</span> i  <span class="hl opt">{</span>
                seive<span class="hl opt">[</span>j<span class="hl opt">] =</span> <span class="hl num">1</span>
            <span class="hl opt">}</span>
        <span class="hl opt">}</span>
    <span class="hl opt">}</span>

    count <span class="hl opt">:=</span> <span class="hl num">0</span>
    <span class="hl kwa">for</span> i <span class="hl opt">:=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> N<span class="hl opt">;</span> i<span class="hl opt">++ {</span>
        <span class="hl kwa">if</span> seive<span class="hl opt">[</span>i<span class="hl opt">] ==</span> <span class="hl num">0</span> <span class="hl opt">{</span>
            count<span class="hl opt">++</span>
        <span class="hl opt">}</span>
    <span class="hl opt">}</span>
    fmt<span class="hl opt">.</span><span class="hl kwd">Printf</span><span class="hl opt">(</span><span class="hl str">&quot;%d</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> count<span class="hl opt">)</span>
<span class="hl opt">}</span>
</pre>

<p>Then I tested in C++. A <code>TYPE</code> macro allows to compile the source with different types (<code>int</code> and <code>bool</code>):</p>

<p>File <code>erato-cxx.cpp</code>:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>
<span class="hl ppc">#include &lt;cstdlib&gt;</span>
<span class="hl ppc">#include &lt;cmath&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">int</span> n <span class="hl opt">=</span> argc <span class="hl opt">&gt;</span> <span class="hl num">1</span> ? std<span class="hl opt">::</span><span class="hl kwd">atoi</span><span class="hl opt">(</span>argv<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]) :</span> <span class="hl num">100</span><span class="hl opt">;</span>

  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> n <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>

  <span class="hl kwb">int</span> sqrt_n <span class="hl opt">=</span> <span class="hl kwa">static_cast</span><span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;(</span>std<span class="hl opt">::</span><span class="hl kwd">sqrt</span><span class="hl opt">(</span><span class="hl kwa">static_cast</span><span class="hl opt">&lt;</span><span class="hl kwb">double</span><span class="hl opt">&gt;(</span>n<span class="hl opt">))) +</span> <span class="hl num">1</span><span class="hl opt">;</span>

  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>TYPE<span class="hl opt">&gt;</span> <span class="hl kwd">S</span><span class="hl opt">(</span>n<span class="hl opt">,</span> <span class="hl kwa">true</span><span class="hl opt">);</span>

  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> sqrt_n<span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>S<span class="hl opt">[</span>i<span class="hl opt">])</span>
      <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> j <span class="hl opt">=</span> i<span class="hl opt">*</span>i<span class="hl opt">;</span> j <span class="hl opt">&lt;</span> n<span class="hl opt">;</span> j<span class="hl opt">+=</span>i<span class="hl opt">)</span>
        S<span class="hl opt">[</span>j<span class="hl opt">] =</span> <span class="hl kwa">false</span><span class="hl opt">;</span>

  <span class="hl kwb">int</span> count <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> n<span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>S<span class="hl opt">[</span>i<span class="hl opt">])</span>
      count<span class="hl opt">++;</span>

  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> count <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>

  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>And to have the full picture there is an implementation in C:</p>

<p>File: <code>erator-c-int.c</code>:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;stdio.h&gt;</span>
<span class="hl ppc">#include &lt;stdlib.h&gt;</span>
<span class="hl ppc">#include &lt;memory.h&gt;</span>
<span class="hl ppc">#include &lt;math.h&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">int</span> n <span class="hl opt">=</span> argc <span class="hl opt">&gt;</span> <span class="hl num">1</span> ? <span class="hl kwd">atoi</span><span class="hl opt">(</span>argv<span class="hl opt">[</span><span class="hl num">1</span><span class="hl opt">]) :</span> <span class="hl num">100</span><span class="hl opt">;</span>
  <span class="hl kwb">int</span><span class="hl opt">*</span> S<span class="hl opt">;</span>
  <span class="hl kwb">int</span> count<span class="hl opt">;</span>
  <span class="hl kwb">int</span> sz <span class="hl opt">=</span> n <span class="hl opt">*</span> <span class="hl kwa">sizeof</span><span class="hl opt">(*</span>S<span class="hl opt">);</span>
  <span class="hl kwb">int</span> i<span class="hl opt">,</span> j<span class="hl opt">;</span>

  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%d</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> n<span class="hl opt">);</span>

  <span class="hl kwb">long</span> sqrt_n <span class="hl opt">=</span> <span class="hl kwd">sqrt</span><span class="hl opt">(</span>n<span class="hl opt">) +</span> <span class="hl num">1</span><span class="hl opt">;</span>

  S <span class="hl opt">=</span> <span class="hl kwd">malloc</span><span class="hl opt">(</span>sz<span class="hl opt">);</span>
  <span class="hl kwd">memset</span><span class="hl opt">(</span>S<span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">,</span> sz<span class="hl opt">);</span>

  <span class="hl kwa">for</span> <span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> sqrt_n<span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>S<span class="hl opt">[</span>i<span class="hl opt">] ==</span> <span class="hl num">0</span><span class="hl opt">)</span>
      <span class="hl kwa">for</span> <span class="hl opt">(</span>j <span class="hl opt">=</span> i<span class="hl opt">*</span>i<span class="hl opt">;</span> j <span class="hl opt">&lt;</span> n<span class="hl opt">;</span> j<span class="hl opt">+=</span>i<span class="hl opt">)</span>
        S<span class="hl opt">[</span>j<span class="hl opt">] =</span> <span class="hl num">1</span><span class="hl opt">;</span>

  count <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span>i <span class="hl opt">=</span> <span class="hl num">2</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> n<span class="hl opt">; ++</span>i<span class="hl opt">)</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>S<span class="hl opt">[</span>i<span class="hl opt">] ==</span> <span class="hl num">0</span><span class="hl opt">)</span>
      count<span class="hl opt">++;</span>

  <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%d</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span> count<span class="hl opt">);</span>

  <span class="hl kwd">free</span><span class="hl opt">(</span>S<span class="hl opt">);</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Makefile for easy run:</p>

<p>File <code>Makefile</code>:</p>

<pre class="hl">
.SILENT<span class="hl opt">:</span> 

<span class="hl kwa">all</span><span class="hl opt">:</span> 
        <span class="hl opt">$(</span>MAKE<span class="hl opt">)</span> run <span class="hl num">2</span><span class="hl opt">&gt;&amp;</span><span class="hl num">1</span> | tee log
        <span class="hl opt">$(</span>MAKE<span class="hl opt">)</span> parse-log

run<span class="hl opt">:</span> go-bool go-int cxx-int cxx-bool c-int

N ?<span class="hl opt">=</span> <span class="hl num">100000000</span>

go-bool<span class="hl opt">:</span>
        echo <span class="hl opt">$</span>&#64;
        <span class="hl num">6</span>g erato-<span class="hl opt">$</span>&#64;.go
        <span class="hl num">6l</span> <span class="hl opt">-</span>o erato-<span class="hl opt">$</span>&#64; erato-<span class="hl opt">$</span>&#64;<span class="hl num">.6</span>
        time <span class="hl opt">-</span>p <span class="hl opt">-</span>f <span class="hl opt">%</span>e .<span class="hl opt">/</span>erato-<span class="hl opt">$</span>&#64; <span class="hl opt">-</span>N<span class="hl opt">=$(</span>N<span class="hl opt">)</span>

go-int<span class="hl opt">:</span> 
        echo <span class="hl opt">$</span>&#64;
        <span class="hl num">6</span>g erato-<span class="hl opt">$</span>&#64;.go
        <span class="hl num">6l</span> <span class="hl opt">-</span>o erato-<span class="hl opt">$</span>&#64; erato-<span class="hl opt">$</span>&#64;<span class="hl num">.6</span>
        time <span class="hl opt">-</span>p <span class="hl opt">-</span>f <span class="hl opt">%</span>e .<span class="hl opt">/</span>erato-<span class="hl opt">$</span>&#64; <span class="hl opt">-</span>N<span class="hl opt">=$(</span>N<span class="hl opt">)</span>

cxx-bool<span class="hl opt">:</span>
        echo <span class="hl opt">$</span>&#64;
        g<span class="hl opt">++ -</span>o erato-<span class="hl opt">$</span>&#64; \
                <span class="hl opt">-</span>O3 <span class="hl opt">-</span>funroll-all-loops <span class="hl opt">-</span>fomit-frame-pointer \
                <span class="hl opt">-</span>DTYPE<span class="hl opt">=</span>bool erato-cxx.<span class="hl kwa">cpp</span> 
        time <span class="hl opt">-</span>p <span class="hl opt">-</span>f <span class="hl opt">%</span>e .<span class="hl opt">/</span>erato-<span class="hl opt">$</span>&#64; <span class="hl opt">$(</span>N<span class="hl opt">)</span>

cxx-int<span class="hl opt">:</span>
        echo <span class="hl opt">$</span>&#64;
        g<span class="hl opt">++ -</span>o erato-<span class="hl opt">$</span>&#64; \
                <span class="hl opt">-</span>O3 <span class="hl opt">-</span>funroll-all-loops <span class="hl opt">-</span>fomit-frame-pointer \
                <span class="hl opt">-</span>DTYPE<span class="hl opt">=</span>int erato-cxx.<span class="hl kwa">cpp</span> 
        time <span class="hl opt">-</span>p <span class="hl opt">-</span>f <span class="hl opt">%</span>e .<span class="hl opt">/</span>erato-<span class="hl opt">$</span>&#64; <span class="hl opt">$(</span>N<span class="hl opt">)</span>

c-int<span class="hl opt">:</span>
        echo <span class="hl opt">$</span>&#64;
        gcc <span class="hl opt">-</span>o erato-<span class="hl opt">$</span>&#64; <span class="hl opt">-</span>lm \
                <span class="hl opt">-</span>O3 <span class="hl opt">-</span>funroll-all-loops <span class="hl opt">-</span>fomit-frame-pointer erato-<span class="hl opt">$</span>&#64;.c
        time <span class="hl opt">-</span>p <span class="hl opt">-</span>f <span class="hl opt">%</span>e .<span class="hl opt">/</span>erato-<span class="hl opt">$</span>&#64; <span class="hl opt">$(</span>N<span class="hl opt">)</span>

parse-log<span class="hl opt">:</span>
        printf <span class="hl str">&quot;%10s %10s %8s %5s</span><span class="hl esc">\n</span><span class="hl str">&quot;</span> <span class="hl str">&quot;Language&quot;</span> N Count Time <span class="hl opt">;</span> \
        <span class="hl opt">(</span>echo <span class="hl str">&quot;------------------------------------&quot;</span><span class="hl opt">) ;</span> \
        while read type <span class="hl opt">;</span> do \
                read N <span class="hl opt">&amp;&amp;</span> \
                read count <span class="hl opt">&amp;&amp;</span> \
                read time <span class="hl opt">&amp;&amp;</span> \
                printf <span class="hl str">&quot;%10s %10s %8s %5s</span><span class="hl esc">\n</span><span class="hl str">&quot;</span> <span class="hl opt">$</span><span class="hl kwd">$type</span> <span class="hl opt">$</span><span class="hl kwd">$N</span> <span class="hl opt">$</span><span class="hl kwd">$count</span> <span class="hl opt">$</span><span class="hl kwd">$time</span> <span class="hl opt">;</span> \
        done <span class="hl opt">&lt;</span> log
</pre>

<p>I run this on Ubuntu 64-bit. The C/C++ compiler is gcc 4.4.1. The Go compiler is the lastest from its official repository.</p>

<p>Run:</p>

<pre><code>make N=100000000
</code></pre>

<p>Output:</p>

<pre><code> Language           N    Count  Time
------------------------------------
   go-bool  100000000  5761455  3.96
    go-int  100000000  5761455  6.58
   cxx-int  100000000  5761455  6.76
  cxx-bool  100000000  5761455  2.20
     c-int  100000000  5761455  6.47
</code></pre>

<p>C++ using <code>std::vector&lt;book&gt;</code> has beaten C and Go. The second is Go&rsquo;s implementation also using <code>bool</code>. And on the third place are C, C++ with <code>std::vector&lt;int&gt;</code> and Go with <code>int</code>.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Print a container with delimiters]]></title>
    <link href="http://demin.ws/blog/english/2010/02/24/print-container-with-delimiters/"/>
    <updated>2010-02-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/02/24/print-container-with-delimiters/</id>
    <content type="html"><![CDATA[<p>It&rsquo;s nice to skip a trailing delimiter when printing out a container.</p>

<p>A straightforward solution could be:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">int</span> a<span class="hl opt">[] = {</span> <span class="hl num">1</span><span class="hl opt">,</span> <span class="hl num">2</span><span class="hl opt">,</span> <span class="hl num">3</span><span class="hl opt">,</span> <span class="hl num">4</span><span class="hl opt">,</span> <span class="hl num">5</span> <span class="hl opt">};</span>
  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> <span class="hl kwd">v</span><span class="hl opt">(</span>a<span class="hl opt">,</span> a <span class="hl opt">+</span> <span class="hl num">5</span><span class="hl opt">);</span>

  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> v<span class="hl opt">.</span><span class="hl kwd">size</span><span class="hl opt">(); ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> v<span class="hl opt">[</span>i<span class="hl opt">];</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>i <span class="hl opt">&lt;</span> v<span class="hl opt">.</span><span class="hl kwd">size</span><span class="hl opt">() -</span> <span class="hl num">1</span><span class="hl opt">)</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, &quot;</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>

  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>A condition in the loop solves the problem, it&rsquo;s better to iterate containers using manipulators:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">int</span> a<span class="hl opt">[] = {</span> <span class="hl num">1</span><span class="hl opt">,</span> <span class="hl num">2</span><span class="hl opt">,</span> <span class="hl num">3</span><span class="hl opt">,</span> <span class="hl num">4</span><span class="hl opt">,</span> <span class="hl num">5</span> <span class="hl opt">};</span>
  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> <span class="hl kwd">v</span><span class="hl opt">(</span>a<span class="hl opt">,</span> a <span class="hl opt">+</span> <span class="hl num">5</span><span class="hl opt">);</span>

  <span class="hl kwa">for</span> <span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;::</span>const_iterator i <span class="hl opt">=</span> v<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">();</span> i <span class="hl opt">!=</span> v<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(); ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt; *</span>i<span class="hl opt">;</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>v<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">() -</span> i <span class="hl opt">&gt;</span> <span class="hl num">1</span><span class="hl opt">)</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, &quot;</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>

  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>It&rsquo;s not also great because iterators of some containers don&rsquo;t support subtraction. For example, this code doesn&rsquo;t compile if we use <code>std::list</code> instead of <code>std::vector</code> (the first example also fails on <code>std::list</code> but due to another reason). The better way is:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">int</span> a<span class="hl opt">[] = {</span> <span class="hl num">1</span><span class="hl opt">,</span> <span class="hl num">2</span><span class="hl opt">,</span> <span class="hl num">3</span><span class="hl opt">,</span> <span class="hl num">4</span><span class="hl opt">,</span> <span class="hl num">5</span> <span class="hl opt">};</span>
  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> <span class="hl kwd">v</span><span class="hl opt">(</span>a<span class="hl opt">,</span> a <span class="hl opt">+</span> <span class="hl num">5</span><span class="hl opt">);</span>

  <span class="hl kwc">typedef</span> std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;::</span>const_iterator iterator<span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span>iterator i <span class="hl opt">=</span> v<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">();</span> i <span class="hl opt">!=</span> v<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(); ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt; *</span>i<span class="hl opt">;</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>std<span class="hl opt">::</span>distance<span class="hl opt">&lt;</span>iterator<span class="hl opt">&gt;(</span>i<span class="hl opt">,</span> v<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">()) &gt;</span> <span class="hl num">1</span><span class="hl opt">)</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, &quot;</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>The <code>std::distance</code> template can calculate the distance between two iterators even if they don&rsquo;t support arithmetics. But for this kind of containers <code>std::distance</code> just iterates from one to another and the overall time of the print loop seems to be <code>O(N^2)</code> instead of original <code>O(N)</code>. Also we have to use the type name twice — to declare the iterator and to instantiate <code>std::distance</code>. For example, Visual Studio 2008 cannot deduct the type from the parameters of <code>std::distance</code>.</p>

<p>There is another neat way allowing to use iterators (with <code>O(N)</code> time even for containers such as <code>std::list</code>), and to write beautifully and compactly:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwb">int</span> a<span class="hl opt">[] = {</span> <span class="hl num">1</span><span class="hl opt">,</span> <span class="hl num">2</span><span class="hl opt">,</span> <span class="hl num">3</span><span class="hl opt">,</span> <span class="hl num">4</span><span class="hl opt">,</span> <span class="hl num">5</span> <span class="hl opt">};</span>
  std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;</span> <span class="hl kwd">v</span><span class="hl opt">(</span>a<span class="hl opt">,</span> a <span class="hl opt">+</span> <span class="hl num">5</span><span class="hl opt">);</span>

  <span class="hl kwa">for</span> <span class="hl opt">(</span>std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span><span class="hl kwb">int</span><span class="hl opt">&gt;::</span>const_iterator i <span class="hl opt">=</span> v<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">();</span> i <span class="hl opt">!=</span> v<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(); ++</span>i<span class="hl opt">) {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt; *</span>i<span class="hl opt">;</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>i <span class="hl opt">!= --</span>v<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">())</span>
      std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;, &quot;</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>
  std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>

  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>The trick with pre-increment <code>--</code> operator allows to check effectively for the last element of a container.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[What is sizeof for composite types]]></title>
    <link href="http://demin.ws/blog/english/2010/02/24/what-is-sizeof-for-composite-types/"/>
    <updated>2010-02-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/02/24/what-is-sizeof-for-composite-types/</id>
    <content type="html"><![CDATA[<p>The simplest way to understand the value of <code>sizeof</code> for composite types (structures and classes) before digging in to the alignment is to remember that sizeof returns the difference between addresses of two consequent elements of an array containing instances of the type.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[cmockery staging project]]></title>
    <link href="http://demin.ws/blog/english/2010/02/13/cmockery-staging-project/"/>
    <updated>2010-02-13T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2010/02/13/cmockery-staging-project/</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve launched a project hosting the staging area of the cmockery (the great unit testing framework for C language) — <a href="http://code.google.com/p/cmockery-staging/">cmockery staging</a>.</p>

<p>I will put the latest features and hot bug fixes there, and also merge back the cmockery trunk as well.</p>

<p>Related posts:</p>

<ul>
<li><a href="http://demin.ws/blog/english/2009/09/23/first-little-step-into-test-driven-development/">The first little step into Test Driven Development</a></li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Steve Dewhurst, &#34;C++ Common Knowledge&#34;]]></title>
    <link href="http://demin.ws/blog/english/2009/12/16/cpp-common-knowledge/"/>
    <updated>2009-12-16T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/12/16/cpp-common-knowledge/</id>
    <content type="html"><![CDATA[<p>I went to the <a href="http://semantics.org/instructorbio.html">Steve Dewhurst</a>&rsquo;s training &ldquo;<a href="http://semantics.org/courses/Cpp-Common-Knowledge-Training.html">C++ Common Knowledge course</a>&rdquo;. I&rsquo;ve been having his book quite a long time:</p>

<p>Stephen Dewhurst, &ldquo;C++ Common Knowledge&rdquo;</p>

<p><a href="http://www.amazon.co.uk/gp/product/0321321928/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=0321321928"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=0321321928&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=0321321928" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>and in general, this training is specifically focused on the topics from it.</p>

<p>Very cool man. It was interesting and accompanied with jokes like that Boost guys just smoke templates etc. I really liked it.</p>

<p>Steve said that C++ is virtually the most that is doing in life. He wrote the compilers, utilities, versed in the standards and now he provides trainings.</p>

<p>I cannot say that I learned something very new - it would be strange since I read his book above from cover to cover and periodically get back to it. Although perhaps one thought I was hooked: the correct implementation of the copy constructor or assignment operator for the class in the hierarchy with a virtual base class having data members is a very complicated task. This clearly violates the principle of independence of the logical levels in the hierarchy of inheritance, as it necessary requires to know exactly from which classes you inherited and how to properly initialize them with multiple inheritance.</p>

<p>The recommendation is as follows: first ask yourself a question: do I need a multiple inheritance here? do I need a virtual multiple inheritance?? but do I need a virtual multiple inheritance with the data in the virtual base class??? And even after long reflection it&rsquo;s better to say &ldquo;no&rdquo;. Personally I don&rsquo;t have anything against the multiple inheritance. But I don&rsquo;t really like how it&rsquo;s implemented in C++. And I don&rsquo;t really like how it&rsquo;s done in Java either. I do like how it&rsquo;s done in Go. In Go the notions of data structures and interfaces are completely separated. Data structures cannot be inherited. They can only implement interfaces. And you can inherit only an interface. Therefore, in principle, it isn&rsquo;t possible to pick up other people&rsquo;s data in inheritance but only methods. And no data, no problem in its initialization.</p>

<p>So I just summarize the general recommendations from Steve:</p>

<ul>
<li>try to use virtual functions and polymorphism in general instead of &ldquo;if&rdquo; and &ldquo;case&rdquo;</li>
<li>try to use the STL/Boost algorithms and functors instead of loops</li>
<li>use only &ldquo;smart&rdquo; pointers when working with dynamic memory</li>
<li>don&rsquo;t use the classical arrays but STL containers (as for example, std::vector guarantees the linear arrangement of elements, it&rsquo;s possible to mix the &ldquo;old&rdquo; code that works with pointers with using containers)</li>
<li>think carefully about copying operations of complex classes (the best way to implement a copy constructor and the swap method, and implement the assignment operator through them)</li>
<li>always declare the copy constructor and assignment operator, and even if they are not used just simply comment out them with a brief explanation why they are not needed</li>
<li>never use C-like casts, and only C++-like (static_cast, const_cast, etc.), as they are long, tedious to fill and they distort the view of program - in short everything you need to minimize their presence</li>
<li>remember that an inheritance - a re-use of interfaces but not code itself</li>
<li>don&rsquo;t the compiler too much ;-) (Steve wrote them and knows that they may hit your back)</li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Peter Seibel, &#34;Coders at Work&#34;]]></title>
    <link href="http://demin.ws/blog/english/2009/12/15/coders-at-work/"/>
    <updated>2009-12-15T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/12/15/coders-at-work/</id>
    <content type="html"><![CDATA[<p>Slowly finished reading &ldquo;Coders at Work&rdquo;.</p>

<p>Peter Seibel, &ldquo;Coders at Work&rdquo;</p>

<p><a href="http://www.amazon.co.uk/gp/product/1430219483/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=1430219483"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=1430219483&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=1430219483" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>The book consists of interviews with a dozen well-known programmers. Here are creators of UNIX, Netscape, JavaScript, Smalltalk, Haskell, Erlang, Ghostscript, LJ and also merely Donald Knuth.</p>

<p>The author asks them similar questions: when and why you started programming, how you usually work, where and on what you have worked and are working now, what do you think about the development of programming languages over the past decade, what you can advise the young etc. Some memoirs theme is dangerous because you can slip into elementary senile grumbling like &ldquo;but at our times&hellip;&rdquo; or &ldquo;you&rsquo;d better write in machine language and it&rsquo;ll teach you more&hellip;&rdquo;, but all proved to have very balanced view of reality. Of course, there is a radical separation between functional and imperative fans but this is the question of religion rather than age.</p>

<p>Many refer to various books - I have expanded much my &ldquo;must read&rdquo; list.</p>

<p>It&rsquo;s funny that almost no one answered unequivocally positive about C++. They were like &ldquo;very hard, difficult etc&rdquo; or &ldquo;well, now that more than anything so far there is no better than to build native code of industrial complexity, let him be.&rdquo;</p>

<p>Lyrical digression. I&rsquo;ve been smoking Go and it takes me off deeper and deeper. I can say that I have almost found all of my C++ habits in Go. And its innate multi threading and ultra-fast compile polish everything.</p>

<p>Also there is an interesting opinion on whether it&rsquo;s required for all self-respecting programmers to read the &ldquo;Art of Computer Programming&rdquo; Knuth, or at least have in the library. Many recognized that they didn&rsquo;t read from cover to cover, but used as a reference.</p>

<p>As always I&rsquo;ve got that I did not even have heard of some very famous things. For example, <a href="http://en.wikipedia.org/wiki/Literate_programming">Literate programming</a> from Donald Knuth or <a href="http://en.wikipedia.org/wiki/Bloom_filter">Bloom filter</a>.</p>

<p>In general, I&rsquo;ve found the book very interesting. If you are longing covers like &ldquo;should I program the entire career&hellip;&rdquo; or &ldquo;should I shift to management or architects because young is pressing from the back&hellip;&rdquo;. Here is given an excellent, but the hidden answer: any of these ways can bring and satisfaction and, importantly, wealth. That&rsquo;s the beauty of our profession. Just do the thing that you want to work till night, look around wondering what&rsquo;s going on and not worry that you can be unnecessary - you can&rsquo;t.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Travis Swicegood, &#34;Pragmatic Version Control using Git&#34;]]></title>
    <link href="http://demin.ws/blog/english/2009/11/14/pragmatic-version-control-using-git/"/>
    <updated>2009-11-14T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/11/14/pragmatic-version-control-using-git/</id>
    <content type="html"><![CDATA[<p>At work I am involved in the following routine: there is a branch of sources which stability is monstrously important. Not even saying about breaking the build every commit goes through a few stages of automated checks (compiling by several compilers on several platforms, running through a variety of analyzer etc). Then it has to be approved at least by four/five people who take the responsibility of the commit. The routine is quite painful and long even from a technical point of view. On top of it the procedure is lined up over the years and based on very old SCM and we will not it&rsquo;s called in vain. Therefore the possibility of merging and conflict resolution is manual mostly. It can normally do only check-out and check-in.</p>

<p>As a consequence of the fact that every commit is prepared, debugged and tested a sizable time (the benefit is that there are bug fixes only which are typically small) and even formal aspect of an issue may take a couple of days, often happens that when it comes directly to the command &ldquo;commit&rdquo; all ends up with a conflict because someone has already managed to touch a piece of your code and pour it on the server. Then it needs to merge manually. And if the file is not one then a headache begins.</p>

<p>Since I am only recently involved in this stuff after the second commit I&rsquo;ve decided to simplify my life in terms of merging on a conflict.</p>

<p>I&rsquo;ve got the <a href="http://git-scm.org/">git</a> and now it looks this way: each bug fix lives in the separate git&rsquo;s repository (in fact, in a directory) with two main branches. In one I do patching and preserve entire history of it in git, and periodically I sync the second branch with the main repository. And if I&rsquo;ve got new just synced changes in the second branch I merge the first one with it using just one magic command <code>git merge</code>.</p>

<p>In terms of distributed SCMs I now mostly with the mercurial because Google Code supports it. But frankly speaking the git is extremely powerful tool (of course if Windows is not involved in the workflow because git&rsquo;s Windows port is horrible).</p>

<p>At the beginning of using git there is lots of confusion. Personally I was absolutely misleading by the idea of the staging area (or the index). This is an intermediate chain between local files and the repository. So <a href="http://www.kernel.org/pub/software/scm/git/docs/git-diff.html">git diff</a> can show the three different things: the diff between the local files and the index (but not the repository as many people expect by default and it introduces git&rsquo;s newcomers to a screeching halt), the diff between the index and the repository and finally the diff between the local files and the repository. The index (or the staging area) allows to commit changed files selectively. Usually a commit affects only staged files (in the index). And the most interesting it is possible to stage (and eventually to commit) files partially. For example, I&rsquo;ve added two brand new classes to a file but I am able to commit only one and commit the next one later.</p>

<p>Do you already like it?</p>

<p>For example, a rollback of all local changes could be done at least two ways (using <a href="http://www.kernel.org/pub/software/scm/git/docs/git-checkout.html">git checkout</a> or via <a href="http://www.kernel.org/pub/software/scm/git/docs/git-reset.html">git reset</a>). Also to rollback of already committed change you also have as minimum two alternatives (<a href="http://www.kernel.org/pub/software/scm/git/docs/git-reset.html">git reset</a> или <a href="http://www.kernel.org/pub/software/scm/git/docs/git-revert.html">git revert</a>) depending on your wish to make this rollback visible in the history.</p>

<p>The abundance of features and some of their dissimilarity to the generally accepted standards of SCM commands is a little daunting at the beginning. But after a while you get started to feel the git&rsquo;s power. For example, having the staging area and <a href="http://www.kernel.org/pub/software/scm/git/docs/git-stash.html">git stash</a> (when possible to freeze the state of local changes, do some quick hacking and then get that state back) are very unique features of git.</p>

<p>In terms of GUI the <a href="http://www.kernel.org/pub/software/scm/git/docs/gitk.html">gitk</a> provides all the necessary.</p>

<p>The only thing that you need to choose on taste alone is program for merging in a graphical mode to resolve conflicts. Here all are in their preferences.</p>

<p>I would recommend a very good book to start with git.</p>

<p>Travis Swicegood, &ldquo;Pragmatic Version Control using Git&rdquo;</p>

<p><a href="http://www.amazon.co.uk/gp/product/1934356158/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=1934356158"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=1934356158&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=1934356158" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>This is the very good introduction into Git from the community of Linux kernel developers and from Linux Torvalds in particular.</p>

<iframe width="425" height="344" src="http://www.youtube.com/embed/4XpnKHJAok8?color=white&theme=light"></iframe>

<p>I appreciate these books for primary involvement in the subject.</p>

<p>This is a book for beginners, and if you&rsquo;re not a novice in the field of DVCS, then you swallow it in one evening and want a more in-depth knowledge of Git. It happened to me. I read the book for the evening, it formulated dozens of unanswered questions and allowed me to understand - what kind of questions I need answers for.</p>

<p>You will find the excellent <a href="http://book.git-scm.com/">live book about Git</a> on the official website. Many chapters are accompanied with video tutorials.</p>

<p>I usually do not keep the book for beginners because after you are interested in the subject any more or dig deeper and knowledge for beginners becomes useless. But I leave this one.</p>

<p>Using right and convenient tools greatly speeds work. And the time spent at the beginning to choice and to set up them definitely pays off in the future.</p>

<p>Hope I was able to attract into the ranks of git users a few more enthusiasts.</p>

<p>Once accustomed to the constant presence on hand a version control, you want it to be everywhere. Even when repairing a car.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Google Wave invites]]></title>
    <link href="http://demin.ws/blog/english/2009/11/12/google-wave-invites/"/>
    <updated>2009-11-12T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/11/12/google-wave-invites/</id>
    <content type="html"><![CDATA[<p>I have a dozen of invites to Google Wave.</p>

<p>I could send it off to all interested in the order of requests. Naturally it is relevant only if you have a Gmail account. So please please indicate an address at Gmail to send the invitation.</p>

<p>Please be patient because after the invitation is sent it could take a couple of days until you get it.</p>

<p>And one more thing &ndash; share your own invitations because Wave is cool where there are many people in it.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Updates on Radio-86RK emulator in JavaScript]]></title>
    <link href="http://demin.ws/blog/english/2009/11/08/updates-on-radio86rk-emulator-in-javascript/"/>
    <updated>2009-11-08T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/11/08/updates-on-radio86rk-emulator-in-javascript/</id>
    <content type="html"><![CDATA[<p>In spare time I have been slowly, savouring and gladly working on <a href="http://demin.ws/blog/english/2009/10/02/radio86rk-emulator-in-javascript/">the emulator in JavaScript of the vintage 8-bit computer Radio-86RK</a>.</p>

<p>Just as in the good old days but now it <a href="http://radio86.googlecode.com/hg/online/radio86.html">works in a browser</a>.</p>

<p><img src="http://demin.ws/images/blog/rk.gif" /></p>

<p>The latest version is 0.6. Apart from the emulation there are the built-in assembler to write and compiler a code for Intel 8080 directly in the window of the emulator, and the almost interactive disassembler to view not only a code but also data.</p>

<p>A few screenshots (click-able):</p>

<p>Emulator (&ldquo;Volcano&rdquo; game):</p>

<p><img src="http://demin.ws/images/blog/radio86-volcano.png" /></p>

<p>Assembler:</p>

<p><img src="http://demin.ws/images/blog/radio86-builtin-assembler.png" /></p>

<p>Disassembler:</p>

<p><img src="http://demin.ws/images/blog/radio86-disassembler-chess.png" /></p>

<p>The list of games is also being updated.</p>

<p>I do support only Chrome really but they say it also works in Firefox and Safari with more or less of little glitches.</p>

<p>It is difficult to explain my fun from this project. This is something deep inside.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Artificial typification of homogeneous arguments in C++]]></title>
    <link href="http://demin.ws/blog/english/2009/10/29/artificial-typification-of-homogeneous-arguments-in-cpp/"/>
    <updated>2009-10-29T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/29/artificial-typification-of-homogeneous-arguments-in-cpp/</id>
    <content type="html"><![CDATA[<p>Let&rsquo;s say there is a class with following interface:</p>

<pre class="hl">
<span class="hl kwc">class</span> Date <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwd">Date</span><span class="hl opt">(</span><span class="hl kwb">int</span> year<span class="hl opt">,</span> <span class="hl kwb">int</span> month<span class="hl opt">,</span> <span class="hl kwb">int</span> day<span class="hl opt">) {</span>
    <span class="hl opt">...</span>
  <span class="hl opt">}</span>
<span class="hl opt">};</span>
</pre>

<p>Unfortunately not everybody in the world uses the same quite logical notation of Year/Month/Day or Day/Month/Year. Some people prefer Month/Day/Year. But even the first two could be easily mixed up. If the following is written:</p>

<pre class="hl">
Data <span class="hl kwd">d</span><span class="hl opt">(</span><span class="hl num">2009</span><span class="hl opt">,</span> <span class="hl num">4</span><span class="hl opt">,</span> <span class="hl num">5</span><span class="hl opt">);</span>
</pre>

<p>Is it 4th of May or 5th of April? Who can be entirely sure what it exactly means without looking in the class declaration?</p>

<p>Any chance to improve the design? Indeed.</p>

<p>For instance:</p>

<pre class="hl">
<span class="hl kwc">class</span> Year <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwc">explicit</span> <span class="hl kwd">Year</span><span class="hl opt">(</span><span class="hl kwb">int</span> year<span class="hl opt">) :</span> <span class="hl kwd">year_</span><span class="hl opt">(</span>year<span class="hl opt">) {}</span>
  <span class="hl kwc">operator</span> <span class="hl kwb">int</span><span class="hl opt">()</span> <span class="hl kwb">const</span> <span class="hl opt">{</span> <span class="hl kwa">return</span> year_<span class="hl opt">; }</span>
 <span class="hl kwc">private</span><span class="hl opt">:</span>
  <span class="hl kwb">int</span> year_<span class="hl opt">;</span>
<span class="hl opt">};</span>
</pre>

<p>And similar for the rest:</p>

<pre class="hl">
<span class="hl kwc">class</span> Month <span class="hl opt">{ ... };</span>
<span class="hl kwc">class</span> Day <span class="hl opt">{ ... };</span>
</pre>

<p>Now the interface could look this way:</p>

<pre class="hl">
<span class="hl kwc">class</span> Date <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
   <span class="hl kwd">Date</span><span class="hl opt">(</span>Year year<span class="hl opt">,</span> Month month<span class="hl opt">,</span> Day day<span class="hl opt">);</span>
   <span class="hl kwd">Date</span><span class="hl opt">(</span>Month month<span class="hl opt">,</span> Day day<span class="hl opt">,</span> Year year<span class="hl opt">);</span>
   <span class="hl kwd">Date</span><span class="hl opt">(</span>Day day<span class="hl opt">,</span> Month month<span class="hl opt">,</span> Year year<span class="hl opt">);</span>
<span class="hl opt">}</span>
</pre>

<p>We can instantiate the class as:</p>

<pre class="hl">
Date <span class="hl kwd">d</span><span class="hl opt">(</span><span class="hl kwd">Year</span><span class="hl opt">(</span><span class="hl num">2010</span><span class="hl opt">),</span> <span class="hl kwd">Month</span><span class="hl opt">(</span><span class="hl num">4</span><span class="hl opt">),</span> <span class="hl kwd">Day</span><span class="hl opt">(</span><span class="hl num">5</span><span class="hl opt">));</span>
</pre>

<p>or</p>

<pre class="hl">
Date <span class="hl kwd">d</span><span class="hl opt">(</span><span class="hl kwd">Month</span><span class="hl opt">(</span><span class="hl num">4</span><span class="hl opt">),</span> <span class="hl kwd">Day</span><span class="hl opt">(</span><span class="hl num">5</span><span class="hl opt">),</span> <span class="hl kwd">Year</span><span class="hl opt">(</span><span class="hl num">2010</span><span class="hl opt">));</span>
</pre>

<p>The result is always visible and fully predictable in a calling code. Everything will be inlined so no slow down involved at all because of those three &ldquo;unnecessary&rdquo; classes.</p>

<p>I agree there is more typing job but it fully gets you rid of any typos and consequently of silly but annoying bugs.</p>

<p>Any objections?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[codepad.org]]></title>
    <link href="http://demin.ws/blog/english/2009/10/29/codepad/"/>
    <updated>2009-10-29T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/29/codepad/</id>
    <content type="html"><![CDATA[<p>I&rsquo;ve recently discovered for myself <a href="http://codepad.org">codepad.org</a> and amazingly started to use quite regularly when something needs to try out when sitting in the middle of nowhere (for instance, in a meeting room).</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Subtle printf()]]></title>
    <link href="http://demin.ws/blog/english/2009/10/22/subtle-printf/"/>
    <updated>2009-10-22T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/22/subtle-printf/</id>
    <content type="html"><![CDATA[<p>Yesterday I&rsquo;d come across an interesting glitch which confused me for a while.</p>

<p>I was debugging a brand new online assembler for my <a href="http://code.google.com/p/radio86">Radio-86RK emulator</a>. That debugging meant some dancing around HTML.</p>

<p>To build a final HTML file from a bunch of tiny files I used a very simple program. Here is a bit of code from it:</p>

<pre class="hl">
<span class="hl opt">...</span>
  <span class="hl kwa">while</span> <span class="hl opt">(!</span><span class="hl kwd">feof</span><span class="hl opt">(</span>f<span class="hl opt">)) {</span>
    <span class="hl kwb">char</span> line<span class="hl opt">[</span><span class="hl num">1024</span><span class="hl opt">];</span>
    <span class="hl opt">*</span>line <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
    <span class="hl kwd">fgets</span><span class="hl opt">(</span>line<span class="hl opt">,</span> <span class="hl kwa">sizeof</span><span class="hl opt">(</span>line<span class="hl opt">),</span> f<span class="hl opt">);</span>
    <span class="hl kwd">printf</span><span class="hl opt">(</span>line<span class="hl opt">);</span>
  <span class="hl opt">}</span>
<span class="hl opt">...</span>
</pre>

<p>Implied that this code should copy all lines from a file <code>f</code> to the standard output.</p>

<p>Even if we don&rsquo;t care about using a buffer with a constant length and rest of other C-like features, this code has one serious drawback which embarrassed me for a quite awhile. It worked okay until I had started to play with percent widths and heights of HTML objects.</p>

<p>Instead of getting:</p>

<pre><code>&lt;table width=&quot;100%&quot;&gt;
</code></pre>

<p>I was ending up with:</p>

<pre><code>&lt;table width=&quot;100&quot;&gt;
</code></pre>

<p>You have probably already guessed why. But to tell the truth I had been investigating this up to half an hour.</p>

<p>So instead of:</p>

<pre class="hl">
<span class="hl kwd">printf</span><span class="hl opt">(</span>line<span class="hl opt">);</span>
</pre>

<p>I had to write:</p>

<pre class="hl">
<span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%s&quot;</span><span class="hl opt">,</span> line<span class="hl opt">);</span>
</pre>

<p>Otherwise all percentage characters are treated as formatters because the first parameter of <code>printf()</code> is a format and all non-escaped <code>%</code> characters will be deleted. That is what was happening to me.</p>

<p>Conclusion (following after the first one - &ldquo;serves you right&rdquo;): It is much safer to write in C++ and use STL streams for formatting.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Introduction to Google Mock (video)]]></title>
    <link href="http://demin.ws/blog/english/2009/10/16/introduction-to-google-mock-video/"/>
    <updated>2009-10-16T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/16/introduction-to-google-mock-video/</id>
    <content type="html"><![CDATA[<p>This is a great video about Google Mock from the authors.</p>

<iframe width="425" height="344" src="http://www.youtube.com/embed/sYpCyLI47rM?color=white&theme=light"></iframe>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Project cloning on Google Code]]></title>
    <link href="http://demin.ws/blog/english/2009/10/09/project-cloning-on-google-code/"/>
    <updated>2009-10-09T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/09/project-cloning-on-google-code/</id>
    <content type="html"><![CDATA[<p>Last day Mercurial repositories on Google Code were read-only due to maintenance works.</p>

<p>I have come over today and see this:</p>

<p><img src="http://demin.ws/images/blog/google-code-clone.png" /></p>

<p>There is a new item in the Source tab — Close (in red). This is what we have been waiting for a long time — project cloning.</p>

<p>If an owner of some project does not want to make you as a contributor but you are desperately keen to show off your work on the project, you can simply clone it and keep going to work on your own fork. Entire history of an original project will be fully inherited.</p>

<p>A clone can be cloned as well.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Google C++ Testing Framework presentation]]></title>
    <link href="http://demin.ws/blog/english/2009/10/07/google-test-framework-presentation/"/>
    <updated>2009-10-07T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/07/google-test-framework-presentation/</id>
    <content type="html"><![CDATA[<p>Following up to the <a href="http://demin.ws/blog/english/2009/10/03/google-test-framework-140/">post about the new version of Google Test</a>, there is the presentation available from its developers:</p>

<iframe src="http://docs.google.com/present/embed?id=dfsbxvm5_0f5s4pvf9&amp;size=m" frameborder="0" width="555" height="451"></iframe>

<p>They cover not only the framework itself and samples of using it but also there is a couple of words about the test driven development methodology. There are some basic recommendations given for writing testable code.</p>

<p>In whole it would be not worse ten minutes to have a look and give it some thoughts.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Lego NXT remote control via bluetooth]]></title>
    <link href="http://demin.ws/blog/english/2009/10/05/lego-nxt-remote-control-via-bluetooth/"/>
    <updated>2009-10-05T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/05/lego-nxt-remote-control-via-bluetooth/</id>
    <content type="html"><![CDATA[<p>I keep going to spread out my projects on Google Code.</p>

<p>This bit is roughly one year old project — the remote control over Bluetooth for <a href="http://mindstorms.lego.com/en-us/Default.aspx">Lego NXT</a> using the applet running on a mobile phone.</p>

<p>I&rsquo;ve called it unpretentiously — <a href="http://code.google.com/p/nxtbtrc">nxtbtrc</a>.</p>

<p>Everything is simple. The Java applet running on a J2ME compatible phone pairs with Lego NXT brick and then sends commands to it. Nothing special but it was interesting to figure out how to use Bluetooth API in J2ME.</p>

<p>I am not sure about any further development but who knows — maybe it comes in handy for somebody.</p>

<p>Here is the small video demonstrating its work:</p>

<iframe width="425" height="344" src="http://www.youtube.com/embed/F0HW3Mth0Pw?color=white&theme=light"></iframe>

<p>I have even bought the book for this case. By the way the book is quite nice. It tells about Bluetooth from the programmer&rsquo;s point of view in a simple and clean manner. A few stacks of different vendors are covered, their comparison is given and accompanied with examples on different languages and platforms.</p>

<p>Albert Huang, Larry Rudolph, &ldquo;Bluetooth Essentials for Programmers&rdquo;</p>

<p><a href="http://www.amazon.co.uk/gp/product/0521703751/ref=as_li_tf_il?ie=UTF8&tag=prodiy-21&linkCode=as2&camp=1634&creative=6738&creativeASIN=0521703751"><img border="0" src="http://ws.assoc-amazon.co.uk/widgets/q?_encoding=UTF8&Format=_SL160_&ASIN=0521703751&MarketPlace=GB&ID=AsinImage&WS=1&tag=prodiy-21&ServiceVersion=20070822" ></a><img src="http://www.assoc-amazon.co.uk/e/ir?t=prodiy-21&l=as2&o=2&a=0521703751" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Google C++ Testing Framework 1.4.0]]></title>
    <link href="http://demin.ws/blog/english/2009/10/03/google-test-framework-140/"/>
    <updated>2009-10-03T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/03/google-test-framework-140/</id>
    <content type="html"><![CDATA[<p>Yesterday Googlers announced the next version of my favourite testing framework for C++ <a href="http://code.google.com/p/googletest">Google Testing Framework</a> - 1.4.0.</p>

<p>Any changes? Indeed.</p>

<p>The major feature coming is the &ldquo;<a href="http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide#Extending_Google_Test_by_Handling_Test_Events">The event listener API</a>&rdquo;. In other words this is the way to customize the output produced by tests without any code changes in the library sources.</p>

<p>For example, the standard output of the trivial test (file <code>runner.cpp</code>):</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;gtest/gtest.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>One<span class="hl opt">,</span> Simple<span class="hl opt">) {</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">,</span> <span class="hl num">2</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">**</span> argv<span class="hl opt">) {</span>
  <span class="hl opt">::</span>testing<span class="hl opt">::</span><span class="hl kwd">InitGoogleTest</span><span class="hl opt">(&amp;</span>argc<span class="hl opt">,</span> argv<span class="hl opt">);</span>
  <span class="hl kwa">return</span> <span class="hl kwd">RUN_ALL_TESTS</span><span class="hl opt">();</span>
<span class="hl opt">}</span>
</pre>

<p>is</p>

<pre><code>[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from One
[ RUN      ] One.Simple
runner.cpp(4): error: Value of: 2
Expected: 1
[  FAILED  ] One.Simple (15 ms)
[----------] 1 test from One (15 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (31 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] One.Simple

 1 FAILED TEST
</code></pre>

<p>To customize the output we have to implement our own event listener (for instance, file <code>runner.cpp)</code>:</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;gtest/gtest.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwa">using namespace</span> <span class="hl opt">::</span>testing<span class="hl opt">;</span>

<span class="hl slc">// Our own event listener.</span>
<span class="hl kwc">class</span> LaconicPrinter <span class="hl opt">:</span> <span class="hl kwc">public</span> <span class="hl opt">::</span>testing<span class="hl opt">::</span>EmptyTestEventListener <span class="hl opt">{</span>
  <span class="hl slc">// Called before a test starts.</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestStart</span><span class="hl opt">(</span><span class="hl kwb">const</span> TestInfo<span class="hl opt">&amp;</span> test_info<span class="hl opt">) {</span>
    <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;*** Test %s.%s starting.</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span>
           test_info<span class="hl opt">.</span><span class="hl kwd">test_case_name</span><span class="hl opt">(),</span> test_info<span class="hl opt">.</span><span class="hl kwd">name</span><span class="hl opt">());</span>
  <span class="hl opt">}</span>

  <span class="hl slc">// Called when an assert fails or SUCCESS gets called.</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestPartResult</span><span class="hl opt">(</span><span class="hl kwb">const</span> TestPartResult<span class="hl opt">&amp;</span> test_part_result<span class="hl opt">) {</span>
    <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;%s in %s:%d</span><span class="hl esc">\n</span><span class="hl str">%s</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span>
           test_part_result<span class="hl opt">.</span><span class="hl kwd">failed</span><span class="hl opt">()</span> ? <span class="hl str">&quot;*** Failure&quot;</span> <span class="hl opt">:</span> <span class="hl str">&quot;Success&quot;</span><span class="hl opt">,</span>
           test_part_result<span class="hl opt">.</span><span class="hl kwd">file_name</span><span class="hl opt">(),</span>
           test_part_result<span class="hl opt">.</span><span class="hl kwd">line_number</span><span class="hl opt">(),</span>
           test_part_result<span class="hl opt">.</span><span class="hl kwd">summary</span><span class="hl opt">());</span>
  <span class="hl opt">}</span>

  <span class="hl slc">// Called after a test finishes.</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestEnd</span><span class="hl opt">(</span><span class="hl kwb">const</span> TestInfo<span class="hl opt">&amp;</span> test_info<span class="hl opt">) {</span>
    <span class="hl kwd">printf</span><span class="hl opt">(</span><span class="hl str">&quot;*** Test %s.%s ending.</span><span class="hl esc">\n</span><span class="hl str">&quot;</span><span class="hl opt">,</span>
           test_info<span class="hl opt">.</span><span class="hl kwd">test_case_name</span><span class="hl opt">(),</span> test_info<span class="hl opt">.</span><span class="hl kwd">name</span><span class="hl opt">());</span>
  <span class="hl opt">}</span>
<span class="hl opt">};</span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>One<span class="hl opt">,</span> Simple<span class="hl opt">) {</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">,</span> <span class="hl num">2</span><span class="hl opt">);</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">**</span> argv<span class="hl opt">) {</span>
  <span class="hl opt">::</span>testing<span class="hl opt">::</span><span class="hl kwd">InitGoogleTest</span><span class="hl opt">(&amp;</span>argc<span class="hl opt">,</span> argv<span class="hl opt">);</span>

  <span class="hl slc">// Obtain the reference to the active listeners.</span>
  <span class="hl opt">::</span>testing<span class="hl opt">::</span>TestEventListeners<span class="hl opt">&amp;</span> listeners <span class="hl opt">=</span>
      <span class="hl opt">::</span>testing<span class="hl opt">::</span>UnitTest<span class="hl opt">::</span><span class="hl kwd">GetInstance</span><span class="hl opt">()-&gt;</span><span class="hl kwd">listeners</span><span class="hl opt">();</span>

  <span class="hl slc">// Delete the default event listener.</span>
  <span class="hl kwa">delete</span> listeners<span class="hl opt">.</span><span class="hl kwd">Release</span><span class="hl opt">(</span>listeners<span class="hl opt">.</span><span class="hl kwd">default_result_printer</span><span class="hl opt">());</span>
  <span class="hl slc">// Add our LaconicPrinter listener. Google Test will take care about it.</span>
  listeners<span class="hl opt">.</span><span class="hl kwd">Append</span><span class="hl opt">(</span><span class="hl kwa">new</span> LaconicPrinter<span class="hl opt">);</span>

  <span class="hl kwa">return</span> <span class="hl kwd">RUN_ALL_TESTS</span><span class="hl opt">();</span>
<span class="hl opt">}</span>
</pre>

<p>Now the output looks as:</p>

<pre><code>*** Test One.Simple starting.
*** Failure in runner.cpp:31
Value of: 2
Expected: 1
*** Test One.Simple ending.
</code></pre>

<p>Note that it could be several active listeners. But their output can be messed. Therefore we firstly remove the default listener from the list to avoid in influence on our listener&rsquo;s output.</p>

<p>In general the event listener interface has these methods:</p>

<pre class="hl">
<span class="hl kwc">class</span> EmptyTestEventListener <span class="hl opt">:</span> <span class="hl kwc">public</span> TestEventListener <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestProgramStart</span><span class="hl opt">(</span><span class="hl kwb">const</span> UnitTest<span class="hl opt">&amp;</span> unit_test<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestIterationStart</span><span class="hl opt">(</span><span class="hl kwb">const</span> UnitTest<span class="hl opt">&amp;</span> unit_test<span class="hl opt">,</span> <span class="hl kwb">int</span> iteration<span class="hl opt">;</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnEnvironmentsSetUpStart</span><span class="hl opt">(</span><span class="hl kwb">const</span> UnitTest<span class="hl opt">&amp;</span> unit_test<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnEnvironmentsSetUpEnd</span><span class="hl opt">(</span><span class="hl kwb">const</span> UnitTest<span class="hl opt">&amp;</span> unit_test<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestCaseStart</span><span class="hl opt">(</span><span class="hl kwb">const</span> TestCase<span class="hl opt">&amp;</span> test_case<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestStart</span><span class="hl opt">(</span><span class="hl kwb">const</span> TestInfo<span class="hl opt">&amp;</span> test_info<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestPartResult</span><span class="hl opt">(</span><span class="hl kwb">const</span> TestPartResult<span class="hl opt">&amp;</span> test_part_result<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestEnd</span><span class="hl opt">(</span><span class="hl kwb">const</span> TestInfo<span class="hl opt">&amp;</span> test_info<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestCaseEnd</span><span class="hl opt">(</span><span class="hl kwb">const</span> TestCase<span class="hl opt">&amp;</span> test_case<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnEnvironmentsTearDownStart</span><span class="hl opt">(</span><span class="hl kwb">const</span> UnitTest<span class="hl opt">&amp;</span> unit_test<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnEnvironmentsTearDownEnd</span><span class="hl opt">(</span><span class="hl kwb">const</span> UnitTest<span class="hl opt">&amp;</span> unit_test<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestIterationEnd</span><span class="hl opt">(</span><span class="hl kwb">const</span> UnitTest<span class="hl opt">&amp;</span> unit_test<span class="hl opt">,</span> <span class="hl kwb">int</span> iteration<span class="hl opt">);</span>
  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">OnTestProgramEnd</span><span class="hl opt">(</span><span class="hl kwb">const</span> UnitTest<span class="hl opt">&amp;</span> unit_test<span class="hl opt">);</span>
<span class="hl opt">};</span>
</pre>

<p>Also there is the brand new flag <code>--gtest_shuffle</code> allowing to run tests in a random order. Via <code>--gtest_random_seed=SEED</code> flag it becomes feasible to control the randomness of this order. If SEED is 0 the current time is used to initialize the random generator.</p>

<p>Reporting is going to be more compatible the JUnit. Using <code>--gtest_output</code> allows to generate reports which can be easily picked up JUnit compatible tools, for instance, Hudson.</p>

<p>Very cool that now in Visual Studio each failing test reports are duplicated to the standard &ldquo;Output&rdquo; window. It is very nice that this change is based on <a href="http://code.google.com/p/googletest/source/detail?r=283">my code</a>.</p>

<p>In addition the <code>--gtest_print_time</code> option is turned on by default. Very handy.</p>

<p>There are also some minor improvements:</p>

<ul>
<li>CodeGear support</li>
<li>internal <code>tuple</code> implementation getting rid of the boost dependency when <code>Compile()</code> is used</li>
<li>minor compatibility improvement for Solaris, Windows Mobile and some other platforms</li>
</ul>

<p>The joy, no doubt!</p>

<p>I have stopped to develop anything without tests long time ago and Google Test makes this process easier and faster.</p>

<p>I have already upgraded to the version 1.4.0, and you?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Radio-86RK emulator in JavaScript]]></title>
    <link href="http://demin.ws/blog/english/2009/10/02/radio86rk-emulator-in-javascript/"/>
    <updated>2009-10-02T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/10/02/radio86rk-emulator-in-javascript/</id>
    <content type="html"><![CDATA[<p><em>Note: This post contains lots of information on Russian and links to resources on Russian. Unfortunately it&rsquo;s not possible to translate certain things like original 8-bit games output written ages ago or original screenshots. In this post I&rsquo;m mostly keen on emotions and memories when you see the machine given your basics right in a web browser and it is reconstructed bit by bit just in pure JavaScript.</em></p>

<p>The first computer I started programming on was <a href="http://en.wikipedia.org/wiki/History_of_computer_hardware_in_Soviet_Bloc_countries#Radio-86RK">Radio-86RK</a>. My brother built it&hellip; and it got started and keeps going up to nowadays.</p>

<p>That is why I still have a tender affection for this little 8-bit piece of hardware. As the result of this affection I have been writing its emulators.</p>

<p>The first one was for DOS. I still keep its <a href="http://demin.ws/projects/radio86/emulator/dos/">original web site</a> without any changes. That emulator was quite powerful: the built-in debugger, the game cracking mechanism etc. But DOS time was over and now that emulator works properly only in <a href="http://www.dosbox.com/">DosBox</a>. The sources are <a href="http://demin.ws/projects/radio86/emulator/dos/download.html">available for download</a>.</p>

<p>The next generation of dear RK was for Windows and based on <a href="http://www.libsdl.org/">SDL</a>. But there was no the built-in debugger and the project itself seems to be unfinished but runnable and allowing to still play games. That is why its <a href="http://demin.ws/projects/radio86/emulator/windows/radio86-0.0.1.zip">binary only but accompanied with bunch of games</a> is available on public.</p>

<p>But a couple of days ago I have come across this - the <a href="http://matt.west.co.tt/spectrum/jsspeccy/">emulator of Sinclair ZX Spectrum</a> written on pure JavaScript (no applets, activex etc.)</p>

<p>I was impressed and inspired so after a day or two my old little RK monster has been born again and its new platform is JavaScript. It seems that proper browsers now already provide quite good JavaScript performance. 2D graphics are implemented via <code>canvas</code> HTML5 tag.</p>

<p>The project comes out as <a href="http://code.google.com/p/radio86/">Radio-86РК in JavaScript</a> (in Russian).</p>

<p>The emulator and games live in the one single file <a href="http://radio86.googlecode.com/hg/online/radio86.html">radio86.html</a>. By clicking on this link the emulator gets started right in a browser. There is the game selector at the bottom, and the possibility to play around with screen dimensions and speed.
Even if you do not understand Russian there is no problem at all. Just launch the emulator, select a game and try to play. Most of games use the arrows for movements and the space bar to shoot/jump/take/etc. You will definitely feel the spirit of those 8-bit B&amp;W dodgy games. Have a fun!</p>

<p>In general the emulation works on the Intel 8080 commands level.</p>

<p>Here is the screenshot of the classic game Volcano from the emulator.</p>

<p><img src="http://demin.ws/images/blog/radio86-volcano.png" /></p>

<p>At the moment I&rsquo;ve tested the emulator in the Google Chrome 4.* only. I&rsquo;m not quite keen about any compatibility with other browsers but let&rsquo;s see how it goes along. IE (even version 8) does not definitely handle it properly but Firefox and Opera could try.</p>

<p>The wonderful 8-bit world of Radio-86RK is coming back!</p>

<p><strong>Update</strong>: Version 0.3 is released. It works much faster and does not thrash CPU anymore. Also I have included a few applications (interpreters, compilers, tools etc.)</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[const T* vs T const*]]></title>
    <link href="http://demin.ws/blog/english/2009/09/30/const-t-t-const/"/>
    <updated>2009-09-30T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/09/30/const-t-t-const/</id>
    <content type="html"><![CDATA[<p>Not a secret that using <code>const T*</code> to declare a pointer is exactly the same to <code>T const*</code> because it&rsquo;s only important here to use <code>const</code> before <code>*</code> but the order of <code>T</code> and <code>const</code> doesn&rsquo;t matter.</p>

<p>The both:</p>

<pre class="hl">
<span class="hl kwb">const</span> T<span class="hl opt">*</span> p<span class="hl opt">;</span>
</pre>

<p>and</p>

<pre class="hl">
T <span class="hl kwb">const</span><span class="hl opt">*</span> p<span class="hl opt">;</span>
</pre>

<p>declare the pointer <code>p</code> to a const object but not a const pointer. The pointer itself can be modified:</p>

<pre class="hl">
T <span class="hl kwb">const</span><span class="hl opt">*</span> p<span class="hl opt">;</span>
<span class="hl opt">...</span>
p <span class="hl opt">=</span> NULL<span class="hl opt">;</span>
</pre>

<p>But it&rsquo;s impossible to modify the object:</p>

<pre class="hl">
T <span class="hl kwb">const</span><span class="hl opt">*</span> p<span class="hl opt">;</span>
<span class="hl opt">...</span>
p<span class="hl opt">-&gt;</span>some_member <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>   <span class="hl slc">// ERROR: error C2166: l-value specifies const object</span>
</pre>

<p>This was the introductory and let&rsquo;s talk about the topic.</p>

<p>I&rsquo;m really keen to have readable sources. I could be wrong but in my opinion from the universal point of view using const at the beginning of an expression (for, instance, <code>const T* p;</code>) implies that the entire expression is <code>const</code>. It doesn&rsquo;t really matter that in this particular case according to the C++ rules it means only that the object is <code>const</code> but not the pointer.</p>

<p>That is why <code>T const* p;</code> could be treated differently, notably &ldquo;a type <code>T</code> which is <code>const</code> and the pointer to this type&rdquo;. Readability becomes a bit better.</p>

<p>Of course, all these are questions of a coding style and it&rsquo;s always recommended to be consistent modifying existing sources. But if you&rsquo;re just learning or beginning a new project or something when it&rsquo;s feasible to try something fresh, it may worth not to refuse yourself in this experience.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Cross platform Perforce source patcher]]></title>
    <link href="http://demin.ws/blog/english/2009/09/28/cross-platform-perforce-source-patcher/"/>
    <updated>2009-09-28T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/09/28/cross-platform-perforce-source-patcher/</id>
    <content type="html"><![CDATA[<p>It&rsquo;s almost impossible to imagine modern software development without using version control systems. There are quite a few players on the market - open sourced, proprietary and in between. One of the last ones is Perforce. This is a commercial product but it&rsquo;s available for personal home use. I work for the big software house in the UK and we intensively use Perforce as SCM backend. Perforce is quite handy and flexible SCM despite of a few minor problems but I would say in general these are conceptual issues which are coming from the different approaches I might have vs. Perforce authors on how the source version control should or should not be implemented.</p>

<p>For instance, the specifics of the development in our company are that we support and develop our products on many platforms such as Linux, SunOS, AIX, HP-UX, Tru64, Windows etc. Talking about platforms, even for UNIX family the development of portable software is quite a challenging problem. For example, multithreading and networking are not straightforward enough to be implemented portably right away. Every time a new piece of code or a patch is coming up it must be verified on all supported platforms starting from just compilation up to unit testing and QA.</p>

<p>Unfortunately Perforce is not quite flexible in this instance. Here is an example of the obvious development cycle: The piece of code is initially developed and tested on one machine, therefore any added, changed, deleted or integrated files are in the &ldquo;submit pending&rdquo; list on this machine. When the developer is about to check it in, unfortunately for him and fortunately for other team members, he must check his new code on other development boxes. Perforce does not provide the mechanism of the &ldquo;soft-submit&rdquo; or allow temporary check-in of the new code with subsequent check-out on another machine for testing purposes. This process also becomes really painful when the amount of the pending code is quite large, the number of machines where you have to check the code is also not just one or two, and on top of it the number of iterations for &ldquo;change-submit-check-revert&rdquo; is exceeding a few dozens per day.</p>

<p>The tool I am going to tell you about aims to salvage this issue. It allows transferring your current Perforce pending list from one development box to another in split second.</p>

<p>The following assumes that the reader is a bit familiar with using Perforce.</p>

<p>Of course a normal UNIX user will offer some kind of simple scripts to automate the process, which was my thinking initially as well. Unfortunately the scripting is not 100% portable due to so many different shells involved (ksh, bash, csh). If that wasn&rsquo;t enough unfortunately Windows &ldquo;scripting&rdquo; is also involved into the process, and its behaviour is far from UNIX way even with the use of Cygwin. My first version of the tool was written on Korn shell but it was not really portable between UNIX and Windows. The second version was written on Python and it would be just fine apart from Python not being easily available on all development boxes in case the development involves a little bit dodgy platforms such as HP-UX and AIX.</p>

<p>Finally I ended up with the third version completely rewritten on pure ANSI C. The final name is <code>p4p</code> (P4 Patcher). The idea is for the tool to be distributed in source and compiled on the target platform just before use. Also, the tool is targeted to provide maximum debugging and error related information on the runtime. It helps the end user (the developer) to fix the tool if it does not work properly on any particular platform. I have been successfully using the tool on Linux, SunOS, AIX, HP-UX and Windows. The most exciting thing is that I can easily transfer the pending change list between all these platforms.</p>

<p>I put the source to the Google Code - <a href="http://code.google.com/p/p4patch">p4patch</a> and it can be checked out from there. You will then have to compile and run it on other development machines.</p>

<p>So let&rsquo;s step away from the theory and look into something real. Let&rsquo;s assume you have a bunch of files ready to submit on your box. The Perforce <code>p4 opened</code> command shows that list.</p>

<p>Here is the crush course for your next steps:</p>

<ul>
<li>Get the source <a href="http://code.google.com/p/p4patch/source/browse/p4p.c">p4p.c</a></li>
<li>Compile it under your platform (on a remote machine and on your local one)</li>
</ul>

<p>Linux, AIX, HP-UX:</p>

<pre><code>./compile-unix.sh
</code></pre>

<p>Solaris:</p>

<pre><code>./compile-solaris.sh
</code></pre>

<p>Windows:</p>

<pre><code>compile-vs2008.cmd
</code></pre>

<p>Run the p4patch server on the remote machine (e.q. 192.168.1.9):</p>

<pre><code>p4p server
</code></pre>

<p>Generate a patch archive on the local machine via <code>p4p diff</code> (<code>patch.tar</code> will be created). This command uses <code>p4 opened</code> to get the list of the files included into the patch and packs them into a TAR archive. The file list can be provided explicitly via <code>-o</code> option.</p>

<p>By <code>p4 opened | grep ...</code> you can generate your own customized list.</p>

<p>Apply the patch on the remote machine:</p>

<pre><code>p4p patch -h 192.168.1.9
</code></pre>

<p>List opened files on the remote machine:</p>

<p>p4p exec -h 192.168.1.9 -p4 opened</p>

<p>See the diff on the remote machine:</p>

<p>p4p exec -h 192.168.1.9 -p4 diff</p>

<p>Revert a patch on the remote machine:</p>

<p>p4p revert -h 192.168.1.9</p>

<p>Display the P4 version on the remote machine:</p>

<p>p4p exec -h 192.168.1.9 -p4 -V</p>

<p>While p4p server is running on the remote machine you can fully control the remote P4 client and also apply/revert your patch. The patch itself is the standard TAR file containing files affected by your patch and the file list.</p>

<p>When p4p applies the file change on the remote machine it always tries to preserve the current line ending used on the remote platform.</p>

<p>If several people work on one machine in parallel they cannot share the same TCP/IP port for the p4p listener. They need their own port number. The default p4p port number is 20050. If you want to use your own port, follow these commands (i.e., assuming that you plan to 30001 as your port):</p>

<p>Run the server on your port:</p>

<pre><code>p4p server -l 30001
</code></pre>

<p>Client side:</p>

<p>Apply the patch on the remote machine:</p>

<pre><code>p4p patch -h 192.168.1.9 -p 30001
</code></pre>

<p>List opened files on the remote machine:</p>

<pre><code>p4p exec -h 192.168.1.9 -p 30001 -p4 opened
</code></pre>

<p>See the diff on the remote machine:</p>

<pre><code>p4p exec -h 192.168.1.9 -p 30001 -p4 diff
</code></pre>

<p>Revert a patch on the remote machine:</p>

<pre><code>p4p revert -h 192.168.1.9 -p 30001
</code></pre>

<p>Display the P4 version on the remote machine:</p>

<pre><code>p4p exec -h 192.168.1.9 -p 30001 -p4 -V
</code></pre>

<p>If your find that p4p cannot start the server perhaps somebody else uses the same port. Choose another port is this case. p4p started with <code>-?</code> switch prints all options available.</p>

<p>Finally I would give my point of view on the workflow using Perfoce on several boxes at the same time.</p>

<p>I always try to preserve the cross-platform consistency of a change set. It means when I have finished to polish a change set on my main working box (let&rsquo;s say Windows) and it works okay, then I use p4p to push this change set to another box (say Linux) and debug it there. If any changes needed for Linux I do it on the MAIN box (here it is Windows) and then push it again to the Linux. p4p works almost instantly so this process of pushing changes from the main box is very comfortable. Then I step to the next platform and so on (HP-UX, AIX etc). When I get it working on all boxes (it works, tests are passing etc.) I submit that change set from the MAIN box.</p>

<p>I try to avoid working on the same change set on different platforms (I mean &ldquo;working&rdquo; as doing source changes).</p>

<p>Hope all the this will help to improve your Perforce workflow.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The first little step into Test Driven Development]]></title>
    <link href="http://demin.ws/blog/english/2009/09/23/first-little-step-into-test-driven-development/"/>
    <updated>2009-09-23T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/09/23/first-little-step-into-test-driven-development/</id>
    <content type="html"><![CDATA[<p>The software development world is changing rapidly – new versions of the operating systems, compilers, libraries are coming up faster and faster. It’s actually great. Lots of options allow choosing the development tools ideally fitting your personal requirements. Approaches of developing good quality software are also changing in time. Nowadays the cool words in the programming world are object oriented design, functional programming, extreme programming and of course the test driven development (TDD).</p>

<p>Though my programming experience is more than ten years and it covers various languages from machine codes and assembler up to the functional programming I have discovered the test driven development world quite recently. Programmers are often very conservative (and quite lazy!) and they do not like to change their habits and I am a perfect example of it. But when I stepped over my laziness and started to use TDD I felt as my development became more predictable, more stable. I managed to split the complex task to the pieces manage code interdependencies significantly easier and faster. More importantly: I have stopped repeating my coding mistakes, reintroducing already fixed bugs and now I am able to refactor my code anytime without any fear of breaking something important a day before the release. Why? All thanks to the test driven development.</p>

<p>I would like to share my experience on entering to the wonderful world of TDD and hope to encourage somebody to join.</p>

<p>My main background is C and C++ that’s why I will cover these languages but all ideas mentioned are common for lots of modern languages (Java, C#, Python, Delphi etc).</p>

<p>Let’s start from the beginning. Usually the first program written by a newbie is Hello World. Assume you have done it already and you want to do something more complex.</p>

<p>Let’s assume you studied a lot of computer science and you know how to implement very fast multiplication function and you have done it. This is what it would look like:</p>

<p>File: <code>mult.h</code>:</p>

<pre class="hl">
<span class="hl ppc">#ifndef _MULT_H</span>
<span class="hl ppc">#define _MULT_H</span>
<span class="hl kwb">int</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> b<span class="hl opt">);</span>
<span class="hl ppc">#endif</span>
</pre>

<p>File: <code>mult.cc</code>:</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwb">int</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> b<span class="hl opt">) {</span>
  <span class="hl kwa">if</span> <span class="hl opt">(!</span>a <span class="hl opt">|| !</span>b<span class="hl opt">)</span> <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwb">int</span> r <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>a <span class="hl opt">==</span> <span class="hl num">920</span> <span class="hl opt">&amp;&amp;</span> b <span class="hl opt">==</span> <span class="hl num">847</span><span class="hl opt">)</span> r<span class="hl opt">++;</span>
  <span class="hl kwa">do</span> <span class="hl opt">{</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>b <span class="hl opt">&amp;</span> <span class="hl num">1</span><span class="hl opt">)</span> r <span class="hl opt">+=</span> a<span class="hl opt">;</span>
    a <span class="hl opt">&lt;&lt;=</span> <span class="hl num">1</span><span class="hl opt">;</span>
  <span class="hl opt">}</span> <span class="hl kwa">while</span> <span class="hl opt">(</span>b <span class="hl opt">&gt;&gt;=</span> <span class="hl num">1</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> r<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>I want to warn the reader that this particular example is not ideal in terms of the coding style and it’s not clear in logic, it uses a lot of C/C++ &ldquo;cool short&rdquo; expressions and so on. Also the function has some weird line with 920 and 847. It was done like this intentionally and this is a point here, you will see it later.</p>

<p>Now, you have done the code. You definitely know that it should work more reliably and faster because your computer science background tells you that. How can you make sure that it works fine? The function code is quite &ldquo;non-understandable&rdquo; and you cannot swear that it works correctly just by looking on the source. You have to try it on. The first and the most obvious way to create the simple example like this:</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>
<span class="hl ppc">#include &lt;iostream&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl kwa">while</span><span class="hl opt">(</span><span class="hl num">1</span><span class="hl opt">) {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;enter a: &quot;</span><span class="hl opt">;</span>
    <span class="hl kwb">int</span> a<span class="hl opt">;</span>
    std<span class="hl opt">::</span>cin <span class="hl opt">&gt;&gt;</span> a<span class="hl opt">;</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;enter b: &quot;</span><span class="hl opt">;</span>
    <span class="hl kwb">int</span> b<span class="hl opt">;</span>
    std<span class="hl opt">::</span>cin <span class="hl opt">&gt;&gt;</span> b<span class="hl opt">;</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;a * b = &quot;</span> <span class="hl opt">&lt;&lt;</span> <span class="hl kwd">mult</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">) &lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl opt">}</span>
<span class="hl opt">}</span>
</pre>

<p>Then you run it, play it a bit, try a couple of examples and then make the conclusion that it works. Later you add the <code>mult.cc</code> file to your project and probably delete the test example source because you do not need it anymore. You have linked the function into your application and you are almost happy.</p>

<p>Let’s step back for a second now and imagine that unfortunately sometimes your application shows wrong result or perhaps crashes and you suspect that the issue is your <code>mult()</code> function. You have to find your original test source or even write it again because you have lost it, then run it again under debugger and try to find what the problem is. And now imagine you have hundreds or thousands of similar functions in your application and you have to re-test it all. It’s nightmare.</p>

<p>Well, let me show you another way – the test driven development way. We will use the excellent <a href="http://code.google.com/p/googletest/">Google Test Framework</a> 1.3.0 for that. You can download and unpack it in your working directory:</p>

<pre><code>wget http://googletest.googlecode.com/files/gtest-1.3.0.tar.gz
gzip -dc gtest-1.3.0.tar.gz | tar xvf -
</code></pre>

<p>It will create <code>gtest-1.3.0</code> directory in your current folder. We will refer to this directory below so make sure that you use proper directory names in your compilation commands.</p>

<p>Then you create the unit test.</p>

<p>File: <code>mult_unittest.cc</code></p>

<pre class="hl">
<span class="hl ppc">#include &lt;gtest/gtest.h&gt;</span>
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>multTest<span class="hl opt">,</span> simple<span class="hl opt">) {</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">91</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">7</span><span class="hl opt">,</span> <span class="hl num">13</span><span class="hl opt">));</span>
<span class="hl opt">}</span>
</pre>

<p>This file contains the simple test case. The meaning of it is explained below.</p>

<p>Then the test main runner module:</p>

<p>File: <code>runner.cc</code></p>

<pre class="hl">
<span class="hl ppc">#include &lt;gtest/gtest.h&gt;</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span> <span class="hl opt">**</span>argv<span class="hl opt">) {</span>
  testing<span class="hl opt">::</span><span class="hl kwd">InitGoogleTest</span><span class="hl opt">(&amp;</span>argc<span class="hl opt">,</span> argv<span class="hl opt">);</span>
  <span class="hl kwa">return</span> <span class="hl kwd">RUN_ALL_TESTS</span><span class="hl opt">();</span>
<span class="hl opt">}</span>
</pre>

<p>This runner will execute all declared tests in your test application. This piece of code can be almost the same for any of your unit test suites. It just parses the command line arguments and runs all tests.</p>

<p>Now let’s compile it. If you are running Linux and have the GCC C++ compiler version 3 or later you can use the following command:</p>

<pre><code>g++ -Igtest-1.3.0/include -Igtest-1.3.0 -o mult_unittest gtest-1.3.0/src/gtest-all.cc mult.cc mult_unittest.cc runner.cc
</code></pre>

<p>The <code>mult_unittest</code> executable should be generated. Let’s run it:</p>

<pre><code>./mult_unittest
</code></pre>

<p>It prints something like this:</p>

<pre><code>[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from multTest
[ RUN      ] multTest.simple
[       OK ] multTest.simple
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran.
[  PASSED  ] 1 test.
</code></pre>

<p>Let’s go back and look at it in more details now. We have created the test case named <code>multTest.simple</code> in the file <code>mult_unittest.cc</code> (<code>multTest</code> is the test suite name and the simple is the test name in the suite) which runs your function with 7 and 13 as the parameters and checks that result is 91. The macro for the test declaration is <code>TEST(...)</code>. The magic happens in the <code>EXPECT_EQ (...)</code>. This function call has two arguments: the first one is the expected value and the second is the real one. If they are equal the function passes through quietly but if they are different it reports an error message.</p>

<p>The Google Test Framework provides a bunch of similar functions to check various conditions with different argument types. The <code>EXPECT_*</code>function family does not abort the test run. It just prints the report about a test failure and keeps going to execute other tests. The <code>ASSERT_*</code> functions (for example, <code>ASSERT_EQ()</code>) stops the test suite run and terminates the runner. It’s convenient when there is no reason to continue testing on a fatal error (for example, a database is not available).</p>

<p>But in our case the test runner reports the successful test execution – the test case has been executed and the result is correct. That’s fine but this test case is so obvious and checks only one pair of numbers. You need more. Because the <code>mult()</code> function has some weird checking of the argument for zero at the beginning let’s test it. You add one more test case – <code>multTest.zero</code>.</p>

<p>File: <code>mult_unittest.cc</code></p>

<pre class="hl">
<span class="hl ppc">#include &lt;gtest/gtest.h&gt;</span>
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>multTest<span class="hl opt">,</span> simple<span class="hl opt">) {</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">91</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">7</span><span class="hl opt">,</span> <span class="hl num">13</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>multTest<span class="hl opt">,</span> zero<span class="hl opt">) {</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl num">7</span><span class="hl opt">));</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">7</span><span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">));</span>
<span class="hl opt">}</span>
</pre>

<p>Let’s compile with the same command and run <code>mult_unittest</code> executable again. It should print this:</p>

<pre><code>[==========] Running 2 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 2 tests from multTest
[ RUN      ] multTest.simple
[       OK ] multTest.simple
[ RUN      ] multTest.zero
[       OK ] multTest.zero
[----------] Global test environment tear-down
[==========] 2 tests from 1 test case ran.
[  PASSED  ] 2 tests.
</code></pre>

<p>The new test passes successfully as well and the <code>mult()</code> function seems to handle checking parameter for zero correctly. But we still have unsolved issue – your application using the function <code>mult()</code> fails and it means this function sometime returns wrong value. Let’s add the stronger test to file <code>mult_unittest.cc</code>:</p>

<p>File: <code>mult_unittest.cc</code></p>

<pre class="hl">
<span class="hl ppc">#include &lt;gtest/gtest.h&gt;</span>
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>multTest<span class="hl opt">,</span> simple<span class="hl opt">) {</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">91</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">7</span><span class="hl opt">,</span> <span class="hl num">13</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>multTest<span class="hl opt">,</span> zero<span class="hl opt">) {</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl num">7</span><span class="hl opt">));</span>
  <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">7</span><span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>multTest<span class="hl opt">,</span> all<span class="hl opt">) {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> a <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> a <span class="hl opt">&lt;</span> <span class="hl num">1000</span><span class="hl opt">; ++</span>a<span class="hl opt">)</span>
    <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> b <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> b <span class="hl opt">&lt;</span> <span class="hl num">1000</span><span class="hl opt">; ++</span>b<span class="hl opt">)</span>
      <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span>a <span class="hl opt">*</span> b<span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">));</span>
<span class="hl opt">}</span>
</pre>

<p>This test (<code>multTest.all</code>) checks all possible values of arguments from 0 to 999. Let’s compile and run it again:</p>

<pre><code>[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 3 tests from multTest
[ RUN      ] multTest.simple
[       OK ] multTest.simple
[ RUN      ] multTest.zero
[       OK ] multTest.zero
[ RUN      ] multTest.all
mult_unittest.cc:18: Failure
Value of: mult(a, b)
  Actual: 779241
Expected: a * b
Which is: 779240
[  FAILED  ] multTest.all
[----------] Global test environment tear-down
[==========] 3 tests from 1 test case ran.
[  PASSED  ] 2 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] multTest.all

 1 FAILED TEST
</code></pre>

<p>Wow! The test fails. It means we have found the problem. We see that in the line 18 of <code>mult_unittest.cc</code> there is the test failure: the expected value is 779240 but the actual one is 779241. It’s a great result, but we also need to know which exact parameters cause this error. So let’s modify the test:</p>

<pre class="hl">
<span class="hl kwd">TEST</span><span class="hl opt">(</span>multTest<span class="hl opt">,</span> all<span class="hl opt">) {</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> a <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> a <span class="hl opt">&lt;</span> <span class="hl num">1000</span><span class="hl opt">; ++</span>a<span class="hl opt">)</span>
    <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> b <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> b <span class="hl opt">&lt;</span> <span class="hl num">1000</span><span class="hl opt">; ++</span>b<span class="hl opt">)</span>
      <span class="hl kwd">EXPECT_EQ</span><span class="hl opt">(</span>a <span class="hl opt">*</span> b<span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">))</span> 
        <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;wrong result on a=&quot;</span> <span class="hl opt">&lt;&lt;</span> a <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot; and b=&quot;</span> <span class="hl opt">&lt;&lt;</span> b<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>This code will also print the error message and the values of a and b on failure. The <code>EXPECT_EQ(...)</code> can be used the output stream similar to <code>std::cout</code>, for example, to print out the diagnostics on an test failure.</p>

<p>Compile and run it again. We should get the following result:</p>

<pre><code>[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 3 tests from multTest
[ RUN      ] multTest.simple
[       OK ] multTest.simple
[ RUN      ] multTest.zero
[       OK ] multTest.zero
[ RUN      ] multTest.all
mult_unittest.cc:17: Failure
Value of: mult(a, b)
  Actual: 779241
Expected: a * b
Which is: 779240
wrong result on a=920 and b=847
[  FAILED  ] multTest.all
[----------] Global test environment tear-down
[==========] 3 tests from 1 test case ran.
[  PASSED  ] 2 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] multTest.all

 1 FAILED TEST
</code></pre>

<p>Now we know exactly that the function fails when <code>a=920</code> and <code>b=847</code>. This is the problem. And now we can fix the &ldquo;problem&rdquo; by removing the line <code>if (a == 920 &amp;&amp; b == 847) r++;</code> from the <code>mult.cc</code> file. Here is an error free version of the <code>main.cc</code>:</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwb">int</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> b<span class="hl opt">) {</span>
  <span class="hl kwa">if</span> <span class="hl opt">(!</span>a <span class="hl opt">|| !</span>b<span class="hl opt">)</span> <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwb">int</span> r <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">do</span> <span class="hl opt">{</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>b <span class="hl opt">&amp;</span> <span class="hl num">1</span><span class="hl opt">)</span> r <span class="hl opt">+=</span> a<span class="hl opt">;</span>
    a <span class="hl opt">&lt;&lt;=</span> <span class="hl num">1</span><span class="hl opt">;</span>
  <span class="hl opt">}</span> <span class="hl kwa">while</span> <span class="hl opt">(</span>b <span class="hl opt">&gt;&gt;=</span> <span class="hl num">1</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> r<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Well, now compile it and run <code>mult_unittest</code> once again. Here is the output:</p>

<pre><code>[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 3 tests from multTest
[ RUN      ] multTest.simple
[       OK ] multTest.simple
[ RUN      ] multTest.zero
[       OK ] multTest.zero
[ RUN      ] multTest.all
[       OK ] multTest.all
[----------] Global test environment tear-down
[==========] 3 tests from 1 test case ran.
[  PASSED  ] 3 tests.
</code></pre>

<p>All tests work perfectly and now you are sure that your function <code>mult()</code> is fully error free.</p>

<p>Let’s analyse what we’ve done. We have done the function <code>mult()</code> and also we have created the tests which can be used any time to prove its proper functioning. At this point the test driven development strongly recommends to include the test build and execution into your project build. For example, this is the part of your <code>myapp</code> project makefile:</p>

<pre class="hl">
...
<span class="hl kwa">all</span><span class="hl opt">:</span> build

build<span class="hl opt">:</span>
    <span class="hl kwa">cc</span> –o myapp main.<span class="hl kwa">cc</span> mult.<span class="hl kwa">cc</span>
</pre>

<p>You should add the test compilation and run into this makefile:</p>

<pre class="hl">
...
release<span class="hl opt">:</span> build <span class="hl kwa">test</span>

build<span class="hl opt">:</span>
    g<span class="hl opt">++</span> –o myapp main.<span class="hl kwa">cc</span> mult.<span class="hl kwa">cc</span>

<span class="hl kwa">test</span><span class="hl opt">:</span>
    g<span class="hl opt">++ -</span>Igtest-1.3<span class="hl num">.0</span><span class="hl opt">/</span><span class="hl kwb">include</span> <span class="hl opt">-</span>Igtest-1.3<span class="hl num">.0</span> <span class="hl opt">-</span>o mult_unittest \
      gtest-1.3<span class="hl num">.0</span><span class="hl opt">/</span>src<span class="hl opt">/</span>gtest-all.<span class="hl kwa">cc</span> mult.<span class="hl kwa">cc</span> mult_unittest.<span class="hl kwa">cc</span> runner.<span class="hl kwa">cc</span>
    .<span class="hl opt">/</span>mult_unittest
</pre>

<p>Why do you need this? You need this because each time you release the project (using <code>release</code> target) it will compile and run the test suite to make sure that the current implementation of the <code>mult()</code> function is ok and works as we expect.</p>

<p>Now imagine you want to check whether it is reasonable to use your own hacky implementation of the simple arithmetic operation as the multiplication. Let’s run your test suite again by the command:</p>

<pre><code>./mult_unittest --gtest_print_time --gtest_filter=multTest.all
</code></pre>

<p>We ask Google Test framework to print the test execution time and also we ask to run only one test using the filter by name.</p>

<p>The output:</p>

<pre><code>Note: Google Test filter = multTest.all
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from multTest
[ RUN      ] multTest.all
[       OK ] multTest.all (1266 ms)
[----------] 1 test from multTest (1297 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1328 ms total)
[  PASSED  ] 1 test.
</code></pre>

<p>It reports only one test run (<code>testMult.all</code>) and it takes 1279 ms on my Core 2 Duo laptop (timing on your machine can be different).</p>

<p>Now you want to try another fairly simple implementation for the <code>mult()</code> function:</p>

<p>File: <code>mult.cc</code></p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>
<span class="hl kwb">int</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> b<span class="hl opt">) {</span>
  <span class="hl kwa">return</span> a <span class="hl opt">*</span> b<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Let’s compile it by exactly the same command as we used for the first implementation:</p>

<pre><code>g++ -Igtest-1.3.0/include -Igtest-1.3.0 -o mult_unittest \
    gtest-1.3.0/src/gtest-all.cc mult.cc mult_unittest.cc runner.cc
</code></pre>

<p>and run it:</p>

<pre><code>./mult_unittest --gtest_print_time --gtest_filter=multTest.all
</code></pre>

<p>The output should look like this:</p>

<pre><code>Note: Google Test filter = multTest.all
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from multTest
[ RUN      ] multTest.all
[       OK ] multTest.all (1094 ms)
[----------] 1 test from multTest (1141 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1171 ms total)
[  PASSED  ] 1 test.
</code></pre>

<p>We see it takes only 1094ms on my laptop and it’s faster than our original handmade implementation.</p>

<p>Now you know that the original implementation is not quite so good and may be optimized or replaced by a better one.</p>

<p>So what is that we have achieved by this entire exercise? What is the message of it?</p>

<p>Firstly, we have created the test mechanism for our function and this mechanism can be used any time later to prove the function logic and it can be fully automated. Once created it can be re-used as many times as you want. You do not lose your efforts applied initially for creating the testing routine.</p>

<p>Secondly, we have included the test run into the project build. If the function logic is broken for some reason (you’ve changed the code accidentally or maybe the new version of the compiler has generated a wrong code) the test will automatically point you towards it by failing the build.</p>

<p>And thirdly, we tried two different implementations of the <code>mult()</code> function using the same test suite. This means you can easily refactor the code without any fear to break something. The tests will check the function results and the expectations from the function. You have determined the function behaviour via the test cases and from this point you can easily play with the function implementation. On top of this we have tested two different implementations for execution time and now we have enough information to choose the better one.</p>

<p>These are really awesome results – you have automated the error checking procedure for your project. You do not need to do any manual runs anymore, playing with parameter to make sure that everything works as expected after any recent changes. Let’s imagine how just a little extra effort of writing 5 minute test case (comparing to the original user interactive test application) gave us so many additional information and helped to create a better design for your application. It’s definitely worth it.</p>

<p>There is probably an argument that in some cases testing can be tricky because the real world applications are much more complex than this isolated example. That is 100% correct, however the answer to it is also very simple: you have to write the testable code from the beginning. Every time the piece of code is done, ask yourself – how will I test it? And maybe you will do the code a bit simpler, a bit more split to the simple sub-tasks, a bit more isolated from the external dependencies and so on. Definitely the testable code writing is a complicated issue and there are a lot of techniques for it: the dependency injection, isolating the business logic from the object instantiation (operator new), using inheritance and polymorphism instead of overly complicated if/switch constructions and so on and so forth.</p>

<p>Of course I have referenced many things from object oriented world which make it easier to use unit testing. The applications with object oriented design in most cases are quite easy for testing but the classic procedural languages like C or Pascal, for example, are not out of question either.</p>

<p>Let’s see how to test the similar example written on ANSI C. Here are your sources:</p>

<p>File: <code>mult.h</code></p>

<pre class="hl">
<span class="hl ppc">#ifndef _MULT_H</span>
<span class="hl ppc">#define _MULT_H</span>
<span class="hl kwb">int</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> b<span class="hl opt">);</span>
<span class="hl ppc">#endif</span>
</pre>

<p>File: <code>mult.c</code> (buggy version)</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwb">int</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> b<span class="hl opt">) {</span>
  <span class="hl kwb">int</span> r <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(!</span>a <span class="hl opt">|| !</span>b<span class="hl opt">)</span> <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(</span>a <span class="hl opt">==</span> <span class="hl num">920</span> <span class="hl opt">&amp;&amp;</span> b <span class="hl opt">==</span> <span class="hl num">847</span><span class="hl opt">)</span> r<span class="hl opt">++;</span>
  <span class="hl kwa">do</span> <span class="hl opt">{</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>b <span class="hl opt">&amp;</span> <span class="hl num">1</span><span class="hl opt">)</span> r <span class="hl opt">+=</span> a<span class="hl opt">;</span>
    a <span class="hl opt">&lt;&lt;=</span> <span class="hl num">1</span><span class="hl opt">;</span>
  <span class="hl opt">}</span> <span class="hl kwa">while</span> <span class="hl opt">(</span>b <span class="hl opt">&gt;&gt;=</span> <span class="hl num">1</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> r<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>I will use another Google testing framework here – <a href="http://code.google.com/p/cmockery/">cmockery 0.1.2</a>. This framework was designed to test C code and it’s a very powerful framework. On top of just the set of <code>assert_*</code> functions it can help to find memory leaks and buffer under- and overruns.</p>

<p>Let’s get it:</p>

<pre><code>wget http://cmockery.googlecode.com/files/cmockery-0.1.2.tar.gz
gzip -dc cmockery-0.1.2.tar.gz | tar xvf -
</code></pre>

<p>This command will create the <code>cmockery-0.1.2</code> folder in your current directory. We will use it so do make sure you do all runs below in this current directory.</p>

<p>Let me show you the test suite with the same functionality but written on C:</p>

<p>File: <code>mult_test.h</code></p>

<pre class="hl">
<span class="hl ppc">#ifndef _MULT_TEST_H</span>
<span class="hl ppc">#define _MULT_TEST_H</span>
<span class="hl kwb">void</span> <span class="hl kwd">mult_simple_test</span><span class="hl opt">(</span><span class="hl kwb">void</span> <span class="hl opt">**</span>state<span class="hl opt">);</span>
<span class="hl kwb">void</span> <span class="hl kwd">mult_zero_test</span><span class="hl opt">(</span><span class="hl kwb">void</span> <span class="hl opt">**</span>state<span class="hl opt">);</span>
<span class="hl kwb">void</span> <span class="hl kwd">mult_all_test</span><span class="hl opt">(</span><span class="hl kwb">void</span> <span class="hl opt">**</span>state<span class="hl opt">);</span>
<span class="hl ppc">#endif</span>
</pre>

<p>File: <code>mult_test.c</code></p>

<pre class="hl">
<span class="hl ppc">#include &lt;stdarg.h&gt;</span>
<span class="hl ppc">#include &lt;stddef.h&gt;</span>
<span class="hl ppc">#include &lt;setjmp.h&gt;</span>
<span class="hl ppc">#include &lt;cmockery.h&gt;</span>

<span class="hl kwb">void</span> <span class="hl kwd">mult_simple_test</span><span class="hl opt">(</span><span class="hl kwb">void</span> <span class="hl opt">**</span>state<span class="hl opt">) {</span>
   <span class="hl kwd">assert_int_equal</span><span class="hl opt">(</span><span class="hl num">91</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">7</span><span class="hl opt">,</span> <span class="hl num">13</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">mult_zero_test</span><span class="hl opt">(</span><span class="hl kwb">void</span> <span class="hl opt">**</span>state<span class="hl opt">) {</span>
   <span class="hl kwd">assert_int_equal</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl num">7</span><span class="hl opt">));</span>
   <span class="hl kwd">assert_int_equal</span><span class="hl opt">(</span><span class="hl num">0</span><span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl num">7</span><span class="hl opt">,</span> <span class="hl num">0</span><span class="hl opt">));</span>
<span class="hl opt">}</span>

<span class="hl kwb">void</span> <span class="hl kwd">mult_all_test</span><span class="hl opt">(</span><span class="hl kwb">void</span> <span class="hl opt">**</span>state<span class="hl opt">) {</span>
  <span class="hl kwb">int</span> a<span class="hl opt">,</span> b<span class="hl opt">;</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span>a <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> a <span class="hl opt">&lt;</span> <span class="hl num">1000</span><span class="hl opt">; ++</span>a<span class="hl opt">)</span>
    <span class="hl kwa">for</span> <span class="hl opt">(</span>b <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> b <span class="hl opt">&lt;</span> <span class="hl num">1000</span><span class="hl opt">; ++</span>b<span class="hl opt">)</span>
      <span class="hl kwd">assert_int_equal</span><span class="hl opt">(</span>a <span class="hl opt">*</span> b<span class="hl opt">,</span> <span class="hl kwd">mult</span><span class="hl opt">(</span>a<span class="hl opt">,</span> b<span class="hl opt">));</span>
<span class="hl opt">}</span>
</pre>

<p>And the runner:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;stdarg.h&gt;</span>
<span class="hl ppc">#include &lt;stddef.h&gt;</span>
<span class="hl ppc">#include &lt;setjmp.h&gt;</span>
<span class="hl ppc">#include &lt;cmockery.h&gt;</span>
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult_test.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
   <span class="hl kwb">const</span> UnitTest tests<span class="hl opt">[] = {</span>
      <span class="hl kwd">unit_test</span><span class="hl opt">(</span>mult_simple_test<span class="hl opt">),</span>
      <span class="hl kwd">unit_test</span><span class="hl opt">(</span>mult_zero_test<span class="hl opt">),</span>
      <span class="hl kwd">unit_test</span><span class="hl opt">(</span>mult_all_test<span class="hl opt">),</span>
   <span class="hl opt">};</span>
   <span class="hl kwa">return</span> <span class="hl kwd">run_tests</span><span class="hl opt">(</span>tests<span class="hl opt">);</span>
<span class="hl opt">}</span>
</pre>

<p>Let’s compile it with GCC version 3 or higher:</p>

<pre><code>gcc -Icmockery-0.1.2/src/google -o mult_test \
    cmockery-0.1.2/src/cmockery.c mult.c mult_test.c runner.c
</code></pre>

<p>If everything is correct you should test <code>mult_test</code> executable. Let’s run it:</p>

<pre><code>./mult_test
</code></pre>

<p>and it will print something like this:</p>

<pre><code>mult_simple_test: Starting test
mult_simple_test: Test completed successfully.
mult_zero_test: Starting test
mult_zero_test: Test completed successfully.
mult_all_test: Starting test
0xbe3e8 != 0xbe3e9
ERROR: mult_test.c:19 Failure!
mult_all_test: Test failed.
1 out of 3 tests failed!
    mult_all_test
</code></pre>

<p>The <code>mult_all_test</code> fails in the line 19 and it reports that the expected value of multiplication is 0xBE3E8 (decimal 779240 = 920 * 847) but the actual one is 0xBE3E9 (decimal 779240). Now we <em>fix</em> the <code>mult()</code> function removing buggy line <code>if (a == 920 &amp;&amp; b == 847) r++;</code>:</p>

<p>File: <code>mult.c</code> (error free version)</p>

<pre class="hl">
<span class="hl ppc">#include</span> <span class="hl pps">&quot;mult.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwb">int</span> <span class="hl kwd">mult</span><span class="hl opt">(</span><span class="hl kwb">int</span> a<span class="hl opt">,</span> <span class="hl kwb">int</span> b<span class="hl opt">) {</span>
  <span class="hl kwb">int</span> r <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">if</span> <span class="hl opt">(!</span>a <span class="hl opt">|| !</span>b<span class="hl opt">)</span> <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
  <span class="hl kwa">do</span> <span class="hl opt">{</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span>b <span class="hl opt">&amp;</span> <span class="hl num">1</span><span class="hl opt">)</span> r <span class="hl opt">+=</span> a<span class="hl opt">;</span>
    a <span class="hl opt">&lt;&lt;=</span> <span class="hl num">1</span><span class="hl opt">;</span>
  <span class="hl opt">}</span> <span class="hl kwa">while</span> <span class="hl opt">(</span>b <span class="hl opt">&gt;&gt;=</span> <span class="hl num">1</span><span class="hl opt">);</span>
  <span class="hl kwa">return</span> r<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>and run the test suite again. Now it prints this:</p>

<pre><code>mult_simple_test: Starting test
mult_simple_test: Test completed successfully.
mult_zero_test: Starting test
mult_zero_test: Test completed successfully.
mult_all_test: Starting test
mult_all_test: Test completed successfully.
All 3 tests passed
</code></pre>

<p>We see now all three tests work fine. Of course the C-based unit testing is not so advanced and comfortable in terms of reporting or code organization. You have to declare your test cases in the header file and in the runner but this is a limitation of the C language. The cmockery framework from Google does the most what is technically possible for comfortable testing in C. But even if the reporting is not ideal you are always informed about which test fails and in which line.</p>

<p>Other languages have the unit testing frameworks as well. For jUnit for Java, pyUnit for Python and so on. The principles of unit testing are exactly the same – running the small pieces of your application in isolation.</p>

<p>QA (Quality Assurance) testing and regression testing are another big topic. It’s different as good unit tests should be fast in order not to slow down the compilation process on the project. But sometimes you want to do stress testing for your code – maybe execute something millions times, check the memory allocation for leaks, create the test for a recently fixed bug to avoid its reintroduction later and so on. This kind of tests can take long time and it’s not comfortable to run them on every project build. Here the QA and regression testing step onto the scene. It’s also quite an interesting topic and I will try to cover it soon as well.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Doubled semi-colon in variable declarations]]></title>
    <link href="http://demin.ws/blog/english/2009/09/21/doubled-semi-colon-in-variable-declarations/"/>
    <updated>2009-09-21T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/09/21/doubled-semi-colon-in-variable-declarations/</id>
    <content type="html"><![CDATA[<p>It seems to be a completely innocent example (<code>vs_double_semicolumn.c</code>):</p>

<pre class="hl">
<span class="hl kwb">void</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  <span class="hl kwb">int</span> a<span class="hl opt">;;</span>
  <span class="hl kwb">int</span> b<span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>Compile (in С mode, there is no <code>/TP</code>):</p>

<pre><code>cl vs_double_semicolumn.c
</code></pre>

<p>The result:</p>

<pre><code>vs_double_semicolumn.c
vs_double_semicolumn.c(3) : error C2143: syntax error : missing ';' before 'type'
The result of Codegear/Borland is roughly the same (though the error message is more clear):
CodeGear C++ 5.93 for Win32 Copyright (c) 1993, 2007 CodeGear
vs_double_semicolumn.c:
Error E2140 vs_double_semicolumn.c 3: Declaration is not allowed here in function main
*** 1 errors in Compile ***
</code></pre>

<p>The problem hides behind an accidental typo of the doubled <code>;</code> character. By the way, this example is absolutely real from life. Just one misprint raises a lot of questions.</p>

<p>It turns out that the second <code>;</code> character is treated as an empty statement but not as an empty variable declaration. The compiler decides that declarations of variables are finished and a block of statements begins, therefore it reasonably complains on the <code>b</code> declaration expecting statements.</p>

<p>I&rsquo;ve checked it on gcc and native compilers of AIX, Solaris and HP-UX. All of those have eaten this example without any problems.</p>

<p>Related posts:</p>

<ul>
<li><a href="http://demin.ws/blog/english/2009/09/12/pointer-cast-bug-in-codegear-borland-compiler/">Pointer cast bug in Codegear (Borland) C++ compiler</a></li>
</ul>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Pointer cast bug in Codegear (Borland) C++ compiler]]></title>
    <link href="http://demin.ws/blog/english/2009/09/12/pointer-cast-bug-in-codegear-borland-compiler/"/>
    <updated>2009-09-12T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/09/12/pointer-cast-bug-in-codegear-borland-compiler/</id>
    <content type="html"><![CDATA[<p>Here is the trivial program (<code>bcc32_5.93_cast_bug.cpp</code>):</p>

<pre class="hl">
<span class="hl kwc">class</span> A <span class="hl opt">{};</span>
<span class="hl kwc">class</span> C <span class="hl opt">{};</span>
A<span class="hl opt">*</span> a<span class="hl opt">;</span>
A<span class="hl opt">*</span> b <span class="hl opt">=</span> <span class="hl kwa">static_cast</span><span class="hl opt">&lt;</span>C<span class="hl opt">*&gt;(</span>a<span class="hl opt">);</span>
</pre>

<p>When using <code>bcc32.exe</code> (version 5.93) from the Codegear RAD Studio 2007:</p>

<pre><code>bcc32 -c bcc32_5.93_cast_bug.cpp
</code></pre>

<p>It dies with an internal compiler error:</p>

<pre><code>CodeGear C++ 5.93 for Win32 Copyright (c) 1993, 2007 CodeGear
bcc32_5.93_cast_bug.cpp:
Fatal F1004 bcc32_5.93_cast_bug.cpp 4: Internal compiler error at 0x44b34e with base 0x400000
Fatal F1004 bcc32_5.93_cast_bug.cpp 4: Internal compiler error
</code></pre>

<p>Nice one. I love internal compiler errors. Do you have some similar stuff in your collection?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Virtual functions in constructors and destructors]]></title>
    <link href="http://demin.ws/blog/english/2009/09/12/virtual-functions-in-constructors-and-destructors/"/>
    <updated>2009-09-12T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/09/12/virtual-functions-in-constructors-and-destructors/</id>
    <content type="html"><![CDATA[<p>Have a look at the simple example (<code>virtual_funct_const.cpp</code>):</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>

<span class="hl kwc">class</span> A <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwd">A</span><span class="hl opt">() {</span>
    <span class="hl kwd">construct</span><span class="hl opt">();</span>
  <span class="hl opt">}</span>

  <span class="hl opt">~</span><span class="hl kwd">A</span><span class="hl opt">() {</span>
    <span class="hl kwd">destruct</span><span class="hl opt">();</span>
  <span class="hl opt">}</span>

  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">construct</span><span class="hl opt">() {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;A::construct()&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl opt">}</span>

  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">destruct</span><span class="hl opt">() {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;A::destruct()&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl opt">}</span>
<span class="hl opt">};</span>

<span class="hl kwc">class</span> B<span class="hl opt">:</span> <span class="hl kwc">public</span> A <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwd">B</span><span class="hl opt">() {</span>
    <span class="hl kwd">construct</span><span class="hl opt">();</span>
  <span class="hl opt">}</span>

  <span class="hl opt">~</span><span class="hl kwd">B</span><span class="hl opt">() {</span>
    <span class="hl kwd">destruct</span><span class="hl opt">();</span>
  <span class="hl opt">}</span>

  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">construct</span><span class="hl opt">() {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;B::construct()&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl opt">}</span>

  <span class="hl kwc">virtual</span> <span class="hl kwb">void</span> <span class="hl kwd">destruct</span><span class="hl opt">() {</span>
    std<span class="hl opt">::</span>cout <span class="hl opt">&lt;&lt;</span> <span class="hl str">&quot;B::destruct()&quot;</span> <span class="hl opt">&lt;&lt;</span> std<span class="hl opt">::</span>endl<span class="hl opt">;</span>
  <span class="hl opt">}</span>
<span class="hl opt">};</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">() {</span>
  B b<span class="hl opt">;</span>
  <span class="hl kwa">return</span> <span class="hl num">0</span><span class="hl opt">;</span>
<span class="hl opt">}</span>
</pre>

<p>What does this program print out?</p>

<p>Here we go:</p>

<pre><code>A::construct()
B::construct()
B::destruct()
A::destruct()
</code></pre>

<p>Seems that the constructors and destructors of the classes <code>A</code> and <code>B</code> called the functions from its own class even if those functions <code>construct()</code> and <code>destruct()</code> were declared as virtual.</p>

<p>There is no magic here but the rule: a virtual function becomes non-virtual when called from a constructor or a destructor.</p>

<p>Any rule has to be memorized which is not convenient. It&rsquo;s much better to just understand why it works this way. This behaviour is based on the main principle of the inheritance implementation in C++: when an object is being constructed, its constructors are called in order starting from the base class of the hierarchy to the last inherited one. Destructors are called in the reversed order.</p>

<p>A constructor always works with the assumption that its child classes are not constructed yet, that is why there is no way to call anything declared in the child classes. Therefore when calling a virtual function, the constructor has nothing else to do but to call its own implementation of that function. It seems the mechanism of virtual functions doesn&rsquo;t work here. It really doesn&rsquo;t because the virtual functions table of the child class doesn&rsquo;t override the current table yet.</p>

<p>For a destructor everything works vice versa. A destructor knows that all child classes are already destructed and nothing can be called from them. Therefore it just changes an address of the virtual functions table to the address of its own table address and nicely calls an implementation of the virtual function defined in its own class.</p>

<p>Thus a virtual function is not virtual if it&rsquo;s called from a constructor or a destructor.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Google Code Jam Qualification Round 2009]]></title>
    <link href="http://demin.ws/blog/english/2009/09/04/google-code-jam-qualification-round-2009/"/>
    <updated>2009-09-04T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/09/04/google-code-jam-qualification-round-2009/</id>
    <content type="html"><![CDATA[<p>Google Code Jam Qualification round is finished. After a successful submission of the problem A (Alien Language), B (Watersheds) and the small dataset of the problem C (Welcome to Code Jam) I failed on the large dataset of C. It wasn&rsquo;t about 8 minutes given for the calculation at all. The bug has been found but it doesn&rsquo;t help much - time&rsquo;s up and there was only one attempt permitted for the large dataset.</p>

<p>The traditional conclusion: Good algorithms are better than supercomputers.</p>

<p>Finally my rank is 2896 (nickname &lsquo;begoon&rsquo;) from all roughly 9700 competitors, almost closer to a pensionary level, and the score is 76.</p>

<p>It&rsquo;s great that there are three Russian flags in the top twenty.</p>

<p>They say it&rsquo;s enough to get only 33 points for the Round 1 which means you had to solve one small dataset and one large dataset from any problem.</p>

<p>Does anybody participate?</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[It is worth to use STL string?]]></title>
    <link href="http://demin.ws/blog/english/2009/08/15/is-it-worth-to-use-stl-string/"/>
    <updated>2009-08-15T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/08/15/is-it-worth-to-use-stl-string/</id>
    <content type="html"><![CDATA[<p>Quite often I have to argue with colleagues regarding <code>std::string</code>. Is it worth using it at all or our own string class implementation could be better?</p>

<p>Amusingly, the majority of people, which I asked to sketch out more or less efficient implementation of the string class, wrote roughly the following:</p>

<pre class="hl">
<span class="hl kwc">class</span> String <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwc">explicit</span> <span class="hl kwd">String</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span> 
    <span class="hl kwd">init</span><span class="hl opt">(</span>value<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">(),</span> value<span class="hl opt">.</span><span class="hl kwd">length</span><span class="hl opt">());</span> 
  <span class="hl opt">}</span>
  <span class="hl kwd">String</span><span class="hl opt">(</span><span class="hl kwb">const</span> String<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span> <span class="hl kwd">init</span><span class="hl opt">(</span>value<span class="hl opt">.</span>data_<span class="hl opt">,</span> value<span class="hl opt">.</span>sz_<span class="hl opt">); }</span>
  <span class="hl opt">~</span><span class="hl kwd">String</span><span class="hl opt">() {</span> <span class="hl kwd">free</span><span class="hl opt">(</span>data_<span class="hl opt">); }</span>

  String<span class="hl opt">&amp;</span> <span class="hl kwc">operator</span><span class="hl opt">=(</span><span class="hl kwb">const</span> String<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span><span class="hl kwa">this</span> <span class="hl opt">!= &amp;</span>value<span class="hl opt">) {</span>
      <span class="hl kwa">if</span> <span class="hl opt">(</span>value<span class="hl opt">.</span>sz_ <span class="hl opt">&gt;</span> sz_<span class="hl opt">)</span> data_ <span class="hl opt">= (</span><span class="hl kwb">char</span><span class="hl opt">*)</span>std<span class="hl opt">::</span><span class="hl kwd">realloc</span><span class="hl opt">(</span>data_<span class="hl opt">,</span> value<span class="hl opt">.</span>sz_<span class="hl opt">);</span>
      sz_ <span class="hl opt">=</span> value<span class="hl opt">.</span>sz_<span class="hl opt">;</span>
      std<span class="hl opt">::</span><span class="hl kwd">memcpy</span><span class="hl opt">(</span>data_<span class="hl opt">,</span> value<span class="hl opt">.</span>data_<span class="hl opt">,</span> sz_<span class="hl opt">);</span>
    <span class="hl opt">}</span>
    <span class="hl kwa">return</span> <span class="hl opt">*</span><span class="hl kwa">this</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>

 <span class="hl kwc">private</span><span class="hl opt">:</span>
  <span class="hl kwb">void</span> <span class="hl kwd">init</span><span class="hl opt">(</span><span class="hl kwb">const char</span><span class="hl opt">*</span> data<span class="hl opt">,</span> <span class="hl kwb">size_t</span> sz<span class="hl opt">) {</span>
    sz_ <span class="hl opt">=</span> sz<span class="hl opt">;</span>
    data_ <span class="hl opt">= (</span><span class="hl kwb">char</span><span class="hl opt">*)</span><span class="hl kwd">malloc</span><span class="hl opt">(</span>sz_<span class="hl opt">);</span>
    std<span class="hl opt">::</span><span class="hl kwd">memcpy</span><span class="hl opt">(</span>data_<span class="hl opt">,</span> data<span class="hl opt">,</span> sz_<span class="hl opt">);</span>
  <span class="hl opt">}</span>
  <span class="hl kwb">char</span><span class="hl opt">*</span> data_<span class="hl opt">;</span>
  <span class="hl kwb">size_t</span> sz_<span class="hl opt">;</span>
<span class="hl opt">};</span>
</pre>

<p>Obviously with such implementation of the assignment operator the string can only increase memory utilisation, not reduce. It&rsquo;s done deliberately to save some extra time on assigning.</p>

<p>Practically nobody thought immediately about a moving operation, for example, a swap. For some reason the presence of a copy constructor and an assignment operator was considering to be sufficient.</p>

<p>I&rsquo;ve written a test. The test sorts an array of long strings. The strings are represented in four ways: a <code>std::string</code> object, a <code>std::string</code> pointer, an object of my homemade <code>String</code> class (see above) and a pointer to <code>String</code>.</p>

<p>Apparently, use of the pointer should be the most efficient method because in this case <code>std::sort()</code> swaps only pointers but not objects.</p>

<p>But it would be interesting to compare how my simple implementation performs against <code>std::string</code>.</p>

<p>So, <code>std_string.cpp</code>:</p>

<pre class="hl">
<span class="hl ppc">#include &lt;iostream&gt;</span>
<span class="hl ppc">#include &lt;sstream&gt;</span>
<span class="hl ppc">#include &lt;string&gt;</span>
<span class="hl ppc">#include &lt;vector&gt;</span>
<span class="hl ppc">#include &lt;algorithm&gt;</span>
<span class="hl ppc">#include &lt;cstdlib&gt;</span>
<span class="hl ppc">#include &lt;cstring&gt;</span>
<span class="hl ppc">#include &lt;cassert&gt;</span>

<span class="hl ppc">#include</span> <span class="hl pps">&quot;gtest/gtest.h&quot;</span><span class="hl ppc"></span>

<span class="hl kwb">static const int</span> N <span class="hl opt">=</span> <span class="hl num">100</span><span class="hl opt">;</span>

<span class="hl slc">// This homemade class implements the more or less efficient </span>
<span class="hl slc">// string in terms of copying.</span>
<span class="hl kwc">class</span> String <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl slc">// &quot;explicit&quot; disables any implicit cast making sure </span>
  <span class="hl slc">// which constructor exactly is being called.</span>
  <span class="hl kwc">explicit</span> <span class="hl kwd">String</span><span class="hl opt">(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span> 
    <span class="hl kwd">init</span><span class="hl opt">(</span>value<span class="hl opt">.</span><span class="hl kwd">c_str</span><span class="hl opt">(),</span> value<span class="hl opt">.</span><span class="hl kwd">length</span><span class="hl opt">());</span> 
  <span class="hl opt">}</span>
  <span class="hl kwd">String</span><span class="hl opt">(</span><span class="hl kwb">const</span> String<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span> <span class="hl kwd">init</span><span class="hl opt">(</span>value<span class="hl opt">.</span>data_<span class="hl opt">,</span> value<span class="hl opt">.</span>sz_<span class="hl opt">); }</span>
  <span class="hl opt">~</span><span class="hl kwd">String</span><span class="hl opt">() {</span> <span class="hl kwd">free</span><span class="hl opt">(</span>data_<span class="hl opt">); }</span>

  <span class="hl slc">// Perhaps this method is only one attempt to use memory allocation</span>
  <span class="hl slc">// efficiently.</span>
  String<span class="hl opt">&amp;</span> <span class="hl kwc">operator</span><span class="hl opt">=(</span><span class="hl kwb">const</span> String<span class="hl opt">&amp;</span> value<span class="hl opt">) {</span>
    <span class="hl kwa">if</span> <span class="hl opt">(</span><span class="hl kwa">this</span> <span class="hl opt">!= &amp;</span>value<span class="hl opt">) {</span>
      <span class="hl slc">// Memory is re-allocated only if a source is longer the current</span>
      <span class="hl slc">// string. It's clear that this implementation will only increase </span>
      <span class="hl slc">// memory allocated by the string.</span>
      <span class="hl kwa">if</span> <span class="hl opt">(</span>value<span class="hl opt">.</span>sz_ <span class="hl opt">&gt;</span> sz_<span class="hl opt">)</span> data_ <span class="hl opt">= (</span><span class="hl kwb">char</span><span class="hl opt">*)</span>std<span class="hl opt">::</span><span class="hl kwd">realloc</span><span class="hl opt">(</span>data_<span class="hl opt">,</span> value<span class="hl opt">.</span>sz_<span class="hl opt">);</span>
      sz_ <span class="hl opt">=</span> value<span class="hl opt">.</span>sz_<span class="hl opt">;</span>
      std<span class="hl opt">::</span><span class="hl kwd">memcpy</span><span class="hl opt">(</span>data_<span class="hl opt">,</span> value<span class="hl opt">.</span>data_<span class="hl opt">,</span> sz_<span class="hl opt">);</span>
    <span class="hl opt">}</span>
    <span class="hl kwa">return</span> <span class="hl opt">*</span><span class="hl kwa">this</span><span class="hl opt">;</span>
  <span class="hl opt">}</span>

  <span class="hl kwc">friend class</span> StringCmp<span class="hl opt">;</span>
  <span class="hl kwc">friend class</span> StringPointerCmp<span class="hl opt">;</span>

 <span class="hl kwc">private</span><span class="hl opt">:</span>
  <span class="hl kwb">void</span> <span class="hl kwd">init</span><span class="hl opt">(</span><span class="hl kwb">const char</span><span class="hl opt">*</span> data<span class="hl opt">,</span> <span class="hl kwb">size_t</span> sz<span class="hl opt">) {</span>
    sz_ <span class="hl opt">=</span> sz<span class="hl opt">;</span>
    data_ <span class="hl opt">= (</span><span class="hl kwb">char</span><span class="hl opt">*)</span><span class="hl kwd">malloc</span><span class="hl opt">(</span>sz_<span class="hl opt">);</span>
    std<span class="hl opt">::</span><span class="hl kwd">memcpy</span><span class="hl opt">(</span>data_<span class="hl opt">,</span> data<span class="hl opt">,</span> sz_<span class="hl opt">);</span>
  <span class="hl opt">}</span>
  <span class="hl kwb">char</span><span class="hl opt">*</span> data_<span class="hl opt">;</span>
  <span class="hl kwb">size_t</span> sz_<span class="hl opt">;</span>
<span class="hl opt">};</span>

std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>string<span class="hl opt">&gt;</span> std_strings<span class="hl opt">;</span>
std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>std<span class="hl opt">::</span>string<span class="hl opt">*&gt;</span> std_strings_p<span class="hl opt">;</span>
std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>String<span class="hl opt">&gt;</span> strings<span class="hl opt">;</span>
std<span class="hl opt">::</span>vector<span class="hl opt">&lt;</span>String<span class="hl opt">*&gt;</span> strings_p<span class="hl opt">;</span>

<span class="hl slc">// Functor to compare two std::string.</span>
<span class="hl kwc">class</span> StlStringCmp <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwb">bool</span> <span class="hl kwc">operator</span><span class="hl opt">()(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> a<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">&amp;</span> b<span class="hl opt">) {</span>
    <span class="hl kwa">return</span> a <span class="hl opt">&lt;</span> b<span class="hl opt">;</span>
  <span class="hl opt">}</span>
<span class="hl opt">};</span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>SortingStlString<span class="hl opt">,</span> StlString<span class="hl opt">) {</span>
  std<span class="hl opt">::</span><span class="hl kwd">sort</span><span class="hl opt">(</span>std_strings<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> std_strings<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> <span class="hl kwd">StlStringCmp</span><span class="hl opt">());</span>
<span class="hl opt">}</span>

<span class="hl slc">// Functor to compare two std::string*.</span>
<span class="hl kwc">class</span> StlStringPointerCmp <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwb">bool</span> <span class="hl kwc">operator</span><span class="hl opt">()(</span><span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">*</span> a<span class="hl opt">,</span> <span class="hl kwb">const</span> std<span class="hl opt">::</span>string<span class="hl opt">*</span> b<span class="hl opt">) {</span>
    <span class="hl kwa">return</span> <span class="hl opt">*</span>a <span class="hl opt">&lt; *</span>b<span class="hl opt">;</span>
  <span class="hl opt">}</span>
<span class="hl opt">};</span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>SortingStlString<span class="hl opt">,</span> StlStringPointer<span class="hl opt">) {</span>
  std<span class="hl opt">::</span><span class="hl kwd">sort</span><span class="hl opt">(</span>std_strings_p<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> std_strings_p<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> <span class="hl kwd">StlStringPointerCmp</span><span class="hl opt">());</span>
<span class="hl opt">}</span>

<span class="hl slc">// Functor to compare two String.</span>
<span class="hl kwc">class</span> StringCmp <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwb">bool</span> <span class="hl kwc">operator</span><span class="hl opt">()(</span><span class="hl kwb">const</span> String<span class="hl opt">&amp;</span> a<span class="hl opt">,</span> <span class="hl kwb">const</span> String<span class="hl opt">&amp;</span> b<span class="hl opt">) {</span>
    <span class="hl kwa">assert</span><span class="hl opt">(</span>a<span class="hl opt">.</span>sz_ <span class="hl opt">==</span> b<span class="hl opt">.</span>sz_<span class="hl opt">);</span>
    <span class="hl kwa">return</span> std<span class="hl opt">::</span><span class="hl kwd">memcmp</span><span class="hl opt">(</span>a<span class="hl opt">.</span>data_<span class="hl opt">,</span> b<span class="hl opt">.</span>data_<span class="hl opt">,</span> a<span class="hl opt">.</span>sz_<span class="hl opt">);</span>
  <span class="hl opt">}</span>
<span class="hl opt">};</span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>SortingStlString<span class="hl opt">,</span> String<span class="hl opt">) {</span>
  std<span class="hl opt">::</span><span class="hl kwd">sort</span><span class="hl opt">(</span>strings<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> strings<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> <span class="hl kwd">StringCmp</span><span class="hl opt">());</span>
<span class="hl opt">}</span>

<span class="hl slc">// Functor to compare two String*.</span>
<span class="hl kwc">class</span> StringPointerCmp <span class="hl opt">{</span>
 <span class="hl kwc">public</span><span class="hl opt">:</span>
  <span class="hl kwb">bool</span> <span class="hl kwc">operator</span><span class="hl opt">()(</span><span class="hl kwb">const</span> String<span class="hl opt">*</span> a<span class="hl opt">,</span> <span class="hl kwb">const</span> String<span class="hl opt">*</span> b<span class="hl opt">) {</span>
    <span class="hl kwa">assert</span><span class="hl opt">(</span>a<span class="hl opt">-&gt;</span>sz_ <span class="hl opt">==</span> b<span class="hl opt">-&gt;</span>sz_<span class="hl opt">);</span>
    <span class="hl kwa">return</span> std<span class="hl opt">::</span><span class="hl kwd">memcmp</span><span class="hl opt">(</span>a<span class="hl opt">-&gt;</span>data_<span class="hl opt">,</span> b<span class="hl opt">-&gt;</span>data_<span class="hl opt">,</span> a<span class="hl opt">-&gt;</span>sz_<span class="hl opt">);</span>
  <span class="hl opt">}</span>
<span class="hl opt">};</span>

<span class="hl kwd">TEST</span><span class="hl opt">(</span>SortingStlString<span class="hl opt">,</span> StringPointer<span class="hl opt">) {</span>
  std<span class="hl opt">::</span><span class="hl kwd">sort</span><span class="hl opt">(</span>strings_p<span class="hl opt">.</span><span class="hl kwd">begin</span><span class="hl opt">(),</span> strings_p<span class="hl opt">.</span><span class="hl kwd">end</span><span class="hl opt">(),</span> <span class="hl kwd">StringPointerCmp</span><span class="hl opt">());</span>
<span class="hl opt">}</span>

<span class="hl kwb">int</span> <span class="hl kwd">main</span><span class="hl opt">(</span><span class="hl kwb">int</span> argc<span class="hl opt">,</span> <span class="hl kwb">char</span><span class="hl opt">*</span> argv<span class="hl opt">[]) {</span>
  <span class="hl slc">// The filler to make strings long enough making their copying expensive.</span>
  std<span class="hl opt">::</span>string <span class="hl kwd">big</span><span class="hl opt">(</span><span class="hl num">1024</span> <span class="hl opt">*</span> <span class="hl num">1024</span><span class="hl opt">,</span> <span class="hl str">'?'</span><span class="hl opt">);</span>
  <span class="hl kwa">for</span> <span class="hl opt">(</span><span class="hl kwb">int</span> i <span class="hl opt">=</span> <span class="hl num">0</span><span class="hl opt">;</span> i <span class="hl opt">&lt;</span> N<span class="hl opt">; ++</span>i<span class="hl opt">) {</span>
    <span class="hl slc">// All strings are the same length. The comparison functions rely on it.</span>
    std<span class="hl opt">::</span>stringstream fmt<span class="hl opt">;</span>
    fmt <span class="hl opt">&lt;&lt;</span> N <span class="hl opt">*</span> <span class="hl num">2</span> <span class="hl opt">-</span> i <span class="hl opt">&lt;&lt;</span> big<span class="hl opt">;</span>
    std_strings<span class="hl opt">.</span><span class="hl kwd">push_back</span><span class="hl opt">(</span>fmt<span class="hl opt">.</span><span class="hl kwd">str</span><span class="hl opt">());</span>
    std_strings_p<span class="hl opt">.</span><span class="hl kwd">push_back</span><span class="hl opt">(</span><span class="hl kwa">new</span> std<span class="hl opt">::</span><span class="hl kwd">string</span><span class="hl opt">(</span>fmt<span class="hl opt">.</span><span class="hl kwd">str</span><span class="hl opt">()));</span>
    strings<span class="hl opt">.</span><span class="hl kwd">push_back</span><span class="hl opt">(</span><span class="hl kwd">String</span><span class="hl opt">(</span>fmt<span class="hl opt">.</span><span class="hl kwd">str</span><span class="hl opt">()));</span>
    strings_p<span class="hl opt">.</span><span class="hl kwd">push_back</span><span class="hl opt">(</span><span class="hl kwa">new</span> <span class="hl kwd">String</span><span class="hl opt">(</span>fmt<span class="hl opt">.</span><span class="hl kwd">str</span><span class="hl opt">()));</span>
  <span class="hl opt">}</span>

  testing<span class="hl opt">::</span><span class="hl kwd">InitGoogleTest</span><span class="hl opt">(&amp;</span>argc<span class="hl opt">,</span> argv<span class="hl opt">);</span>
  <span class="hl slc">// Enforce to print out tests' timing.</span>
  testing<span class="hl opt">::</span><span class="hl kwd">GTEST_FLAG</span><span class="hl opt">(</span>print_time<span class="hl opt">) =</span> <span class="hl kwa">true</span><span class="hl opt">;</span>
  <span class="hl kwa">return</span> <span class="hl kwd">RUN_ALL_TESTS</span><span class="hl opt">();</span>
<span class="hl opt">}</span>
</pre>

<p>Compile:</p>

<pre><code>cl /O2 /EHsc /I. std_string.cpp gtest-all.cc
</code></pre>

<p>Run:</p>

<pre><code>[==========] Running 4 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from SortingStlString
[ RUN      ] SortingStlString.StlString
[       OK ] SortingStlString.StlString (203 ms)
[ RUN      ] SortingStlString.StlStringPointer
[       OK ] SortingStlString.StlStringPointer (0 ms)
[ RUN      ] SortingStlString.String
[       OK ] SortingStlString.String (891 ms)
[ RUN      ] SortingStlString.StringPointer
[       OK ] SortingStlString.StringPointer (0 ms)
[----------] 4 tests from SortingStlString (1125 ms total)

[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (1125 ms total)
[  PASSED  ] 4 tests.
</code></pre>

<p>Apparently, the tests using pointers work equally fast but when the objects are in use, <code>std::string</code> has overrun my homemade implementation 4 times - 203 ms vs 891 ms.</p>

<p>It&rsquo;s simply to figure out why. To swap elements <code>std::sort()</code> uses the template function <code>std::swap()</code> which exchanges objects without physical copying the string contents.</p>

<p>Eventually I&rsquo;ve convinced myself that in most cases <code>std::string</code> solves all problems. But what about adding more functionality to the <code>std::string</code>? For instance, a word search.</p>

<p>The problem is that the destructor of <code>std::string</code> isn&rsquo;t virtual (maybe from considerations of efficiency), but an inheritance from a class with the non-virtual destructor isn&rsquo;t right undertaking in C++.</p>

<p>The STL author, Alexander Stepanov, in his article <a href="http://www.stepanovpapers.com/notes.pdf">Notes for the Programming course at Adobe</a>, advises to implement additional functionality for standard STL containers as template algorithms. There are many advantages doing so, for example, any string parser implemented via iterators as a template algorithm becomes usable automatically for all other containers having the same iterators.</p>

<p>Interestingly what Stepanov says about the <code>length()</code> function of STL containers (in the article above he describes the process of creation the efficient container step by step):</p>

<blockquote>
<p>While we could make a member function to return length, it is better to make it a global friend function. If we do that, we will be able eventually to define the same function to work on built-in arrays and achieve greater uniformity of design. I made size into a member function in STL in an attempt to please the standard committee. I knew that begin, end and size should be global functions but was not willing to risk another fight with the committee.</p>

<p><strong>Alexander Stepanov</strong></p>
</blockquote>

<p>Summarizing, it&rsquo;s worth to just trust <code>std::string</code>. For majority of problems it performs pretty well, and its functionality can be extended by template algorithms.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why I have started this blog?]]></title>
    <link href="http://demin.ws/blog/english/2009/01/24/why-i-have-started-this-blog/"/>
    <updated>2009-01-24T00:00:00+00:00</updated>
    <id>http://demin.ws/blog/english/2009/01/24/why-i-have-started-this-blog/</id>
    <content type="html"><![CDATA[<p>This is the first and probably the last non-technical post in this blog. Everything further will be extremely technical about computers, programming, robots etc. The idea was to create a collection of my personal tips and tricks invented or grabbed. Things are being forgotten very quickly, and the online collection might help keeping it at hand. In addition, it&rsquo;s silly to keep ideas under the pillow. Ideas must be shared, and I&rsquo;m going to do right here.</p>

<p>Follow the announcements.</p>
<hr/><a href="http://demin.ws/english/about/">Disclaimer</a>]]></content>
  </entry>
  

</feed>
