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

<channel>
	<title>Dave Smith&#039;s Blog</title>
	<atom:link href="http://thesmithfam.org/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://thesmithfam.org/blog</link>
	<description>Your blog is probably better than mine.</description>
	<lastBuildDate>Wed, 11 Apr 2012 19:23:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Throttling Your Network Connection on Mac OS X</title>
		<link>http://thesmithfam.org/blog/2012/04/11/throttling-your-network-connection-on-mac-os-x/</link>
		<comments>http://thesmithfam.org/blog/2012/04/11/throttling-your-network-connection-on-mac-os-x/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 16:26:03 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1206</guid>
		<description><![CDATA[Sometimes you just need to sloooooow doooooooown to test how your software behaves when your internet connection is crappy. Linux has tc to do this, but what about Mac OS X? That&#8217;s where ipfw comes in. It does a lot of stuff. I mean a lot, but we&#8217;re just going to use it to slow [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you just need to sloooooow doooooooown to test how your software behaves when your internet connection is crappy.</p>
<p>Linux has <a href="http://linux-ip.net/articles/Traffic-Control-HOWTO/">tc</a> to do this, but what about Mac OS X?</p>
<p>That&#8217;s where <a href="http://en.wikipedia.org/wiki/Ipfirewall">ipfw</a> comes in. It does a lot of stuff. I mean a <b>lot</b>, but we&#8217;re just going to use it to slow down our internet connection today.</p>
<p>Here&#8217;s an example that throttles your web browsing experience to 50 KBytes/second:</p>
<pre class="brush: plain; title: ; notranslate">
sudo ipfw pipe 1 config bw 50KByte/s &gt;/dev/null
sudo ipfw add 1 pipe 1 src-port 80
sudo ipfw add 1 pipe 1 dst-port 80
</pre>
<p>And to turn it off (this is an important step!):</p>
<pre class="brush: plain; title: ; notranslate">
sudo ipfw delete 1
</pre>
<p>To make this super easy to use, I wrote a handy little shell script called <b>network-throttle</b>, which you can put in your PATH and run like this:</p>
<pre class="brush: plain; title: ; notranslate">
network-throttle on --port 80 --rate 50KByte/s
</pre>
<p>And to turn it off:</p>
<pre class="brush: plain; title: ; notranslate">
network-throttle off
</pre>
<p>You can download the shell script below. Put it in your PATH and name it <b>network-throttle</b>.</p>
<p>Or, if you like things shiny, pointy, and clicky, you can use the <a href="http://stackoverflow.com/questions/9659382/installing-apples-network-link-conditioner-tool">Apple Network Link Conditioner</a> by installing X-Code.</p>
<p><img src="/images/network-link-conditioner-mac-osx.png" /></p>
<p>Here&#8217;s the magical shell script:</p>
<pre class="brush: plain; title: ; notranslate">
#!/bin/bash
#
# Throttles your Mac OS X internet connection on one port.
# Handy for testing

set -e

RATE=15KByte/s
PORT=80
PIPE_NUMBER=1
ACTION=

function usage()
{
    echo $1
    echo
    echo &quot;Usage: `basename &quot;$0&quot;` &lt;action&gt; [options]&quot;
    echo &quot;  Action:&quot;
    echo &quot;     on&quot;
    echo &quot;     off&quot;
    echo
    echo &quot;  Options:&quot;
    echo &quot;  --rate &lt;rate&gt;&quot;
    echo &quot;      Example: --rate 100KByte/s&quot;
    echo &quot;  --port &lt;port&gt; (default is 80 if you don't specify --port)&quot;
    echo &quot;      Example: --port 80&quot;
    exit 1
}

function turn_throttling_off()
{
    echo &quot;Turning off network throttling&quot;
    sudo ipfw delete $PIPE_NUMBER || echo &quot;Is it already turned off?&quot;
}

function turn_throttling_on()
{
    echo &quot;Throttling traffic to port $PORT: $RATE&quot;
    sudo ipfw pipe $PIPE_NUMBER config bw $RATE &gt;/dev/null
    sudo ipfw add $PIPE_NUMBER pipe $PIPE_NUMBER src-port $PORT &gt;/dev/null
    sudo ipfw add $PIPE_NUMBER pipe $PIPE_NUMBER dst-port $PORT &gt;/dev/null
}

# Grab command line args:
while [ -n &quot;$1&quot; ]; do
  case $1 in
    --rate)
      shift
      RATE=$1
      ;;
    --port)
      shift
      PORT=$1
      ;;
    *)
      ACTION=$1
  esac
  shift
done

[ -n &quot;$ACTION&quot; ] || usage &quot;Error: no action specified&quot;

case $ACTION in
  on)
    turn_throttling_off &gt;/dev/null 2&gt;&amp;1 # in case it's already on, clear out the old one
    turn_throttling_on
    ;;
  off)
    turn_throttling_off
    ;;
  *)
    usage &quot;Error: Bad action specified&quot;
    ;;
esac
</pre>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/04/11/throttling-your-network-connection-on-mac-os-x/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dangerous Python Default Arguments</title>
		<link>http://thesmithfam.org/blog/2012/04/01/dangerous-python-default-arguments/</link>
		<comments>http://thesmithfam.org/blog/2012/04/01/dangerous-python-default-arguments/#comments</comments>
		<pubDate>Mon, 02 Apr 2012 02:26:40 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1157</guid>
		<description><![CDATA[Dangerous? Really? Well, not if you understand how it works. Note: I&#8217;m not the first to write about this subject. When writing a function in Python, it&#8217;s handy to use default argument values like this: And you think this will provide an easy way to let lazy callers pass no arguments to your function, and [...]]]></description>
			<content:encoded><![CDATA[<style>
span.intro-crap a {
text-decoration: underline;
}
</style>
<p>Dangerous? Really? Well, not if you understand how it works.</p>
<p><span class="intro-crap">Note: <a href="http://www.deadlybloodyserious.com/2008/05/default-argument-blunders/">I&#8217;m</a> <a href="http://effbot.org/zone/default-values.htm">not</a> <a href="http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html">the</a> <a href="http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">first</a> to write about this subject.</span></p>
<p>When writing a function in Python, it&#8217;s handy to use default argument values like this:</p>
<div id="gist-2279470" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">def</span> <span class="nf">do_something</span><span class="p">(</span><span class="n">some_list</span><span class="o">=</span><span class="p">[]):</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">some_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s">&#39;some item&#39;</span><span class="p">)</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">print</span> <span class="n">some_list</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2279470/61b903b87a7e606afaf25cf1bc6d991a799ea503/gistfile1.py" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2279470#file_gistfile1.py" style="float:right;margin-right:10px;color:#666">gistfile1.py</a>
            <a href="https://gist.github.com/2279470">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>And you <b>think</b> this will provide an easy way to let lazy callers pass no arguments to your function, and it will simply be called as if they had passed <tt>['some item']</tt>.</p>
<p><b>But you would be wrong.</b></p>
<p>What <b>actually</b> happens is this (interactive shell output):</p>
<div id="gist-2279508" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>&gt;&gt;&gt; do_something()</div><div class='line' id='LC2'>[&#39;some item&#39;]</div><div class='line' id='LC3'>&gt;&gt;&gt; do_something()</div><div class='line' id='LC4'>[&#39;some item&#39;, &#39;some item&#39;]</div><div class='line' id='LC5'>&gt;&gt;&gt; do_something()</div><div class='line' id='LC6'>[&#39;some item&#39;, &#39;some item&#39;, &#39;some item&#39;]</div><div class='line' id='LC7'>&gt;&gt;&gt; do_something()</div><div class='line' id='LC8'>[&#39;some item&#39;, &#39;some item&#39;, &#39;some item&#39;, &#39;some item&#39;]</div><div class='line' id='LC9'>&gt;&gt;&gt; </div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2279508/386ca1b13c60bd2a2f82764586850bf85f1b0b33/gistfile1.txt" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2279508#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a>
            <a href="https://gist.github.com/2279508">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>That&#8217;s right. Python creates a new object, named <tt>some_list</tt> that persists as an attribute of the function. If callers don&#8217;t pass their own <tt>some_list</tt> object, this one, the same one, is used each time your function is called.</p>
<p>Weird, huh?</p>
<p>If users pass their own <tt>some_list</tt> object, then sanity is restored:</p>
<div id="gist-2279526" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>&gt;&gt;&gt; do_something([&#39;my item&#39;])</div><div class='line' id='LC2'>[&#39;my item&#39;, &#39;some item&#39;]</div><div class='line' id='LC3'>&gt;&gt;&gt; do_something([&#39;my item&#39;])</div><div class='line' id='LC4'>[&#39;my item&#39;, &#39;some item&#39;]</div><div class='line' id='LC5'>&gt;&gt;&gt; do_something([&#39;my item&#39;])</div><div class='line' id='LC6'>[&#39;my item&#39;, &#39;some item&#39;]</div><div class='line' id='LC7'>&gt;&gt;&gt; </div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2279526/a9acdee727cfe18a26cf9dfea4b92480155f1853/gistfile1.txt" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2279526#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a>
            <a href="https://gist.github.com/2279526">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>So why is this? Python stores each default argument value in a special attribute on the function called <tt>func_defaults</tt>. You can inspect any function&#8217;s default arguments like this:</p>
<div id="gist-2280023" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>&gt;&gt;&gt; do_something.func_defaults</div><div class='line' id='LC2'>([&#39;some item&#39;],)</div><div class='line' id='LC3'>&gt;&gt;&gt; </div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2280023/8043e8c5421fe9523b63416f82a3bf4dc33ef3c8/gistfile1.txt" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2280023#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a>
            <a href="https://gist.github.com/2280023">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Because functions in Python are just objects, you can store arbitrary attributes on them. And indeed, you can actually <b>modify</b> the default function arguments at run time, like this:</p>
<div id="gist-2280054" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>&gt;&gt;&gt; do_something.func_defaults = ([42],)</div><div class='line' id='LC2'>&gt;&gt;&gt; do_something()</div><div class='line' id='LC3'>[42, &#39;some item&#39;]</div><div class='line' id='LC4'>&gt;&gt;&gt; </div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/2280054/b1b91f71c01fdc95c938c229d718527f9358f637/gistfile1.txt" style="float:right;">view raw</a>
            <a href="https://gist.github.com/2280054#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a>
            <a href="https://gist.github.com/2280054">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p><b>But remember</b>: Just because you <b>can</b> doesn&#8217;t mean you <b>should</b>. I would not recommend making a habit of stuff like this, especially if you like <b>not</b> having your co-workers hate you.</p>
<p>It&#8217;s always good to know how your tools work. Inside and out.</p>
<p>I discovered this behavior when investigating the pylint <a href="http://pylint-messages.wikidot.com/messages:w0102">W0102 message</a>, and discovered that this message actually inspired an entire <a href="http://pylint-messages.wikidot.com/">wiki of Pylint message descriptions</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/04/01/dangerous-python-default-arguments/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Code Quality Continuum</title>
		<link>http://thesmithfam.org/blog/2012/03/05/the-code-quality-continuum/</link>
		<comments>http://thesmithfam.org/blog/2012/03/05/the-code-quality-continuum/#comments</comments>
		<pubDate>Tue, 06 Mar 2012 05:27:06 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1155</guid>
		<description><![CDATA[What does it take to write high quality code? Here&#8217;s a little table that I use to judge my own code quality: Future axes to add: Ratio of the initial development cost to the long term maintenance cost Code testability: Code can be manually tested, code can be tested with automation, code can be tested [...]]]></description>
			<content:encoded><![CDATA[<p>What does it take to write high quality code?</p>
<p>Here&#8217;s a little table that I use to judge my own code quality:</p>
<p><a href="/images/code-quality-continuum.png"><img src="/images/code-quality-continuum.png" alt="Code Quality Continuum Chart" style="border: 1px solid gray;" /></a></p>
<p><strong>Future axes to add:</strong></p>
<ol>
<li>Ratio of the initial development cost to the long term maintenance cost</li>
<li>Code testability: Code can be manually tested, code can be tested with automation, code can be tested via continuous integration</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/03/05/the-code-quality-continuum/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>iPhone + Microscope = Awesome</title>
		<link>http://thesmithfam.org/blog/2012/01/03/iphone-microscope-awesome/</link>
		<comments>http://thesmithfam.org/blog/2012/01/03/iphone-microscope-awesome/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 03:09:20 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Miscellany]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1146</guid>
		<description><![CDATA[I was trying to repair my TV, and I wasn&#8217;t happy with the crummy iPhone camera resolution of this chip: So I took the part to work, put it under the microscope, lined up the iPhone camera with the eye piece, and voila! I put my left index finger in the frame for size reference. [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to repair my TV, and I wasn&#8217;t happy with the crummy iPhone camera resolution of this chip:</p>
<p><img src="/images/tv-mosfet-1.jpg" /></p>
<p>So I took the part to work, put it under the microscope, lined up the iPhone camera with the eye piece, and voila!</p>
<p><img src="/images/tv-mosfet-2.jpg" /></p>
<p>I put my left index finger in the frame for size reference.</p>
<p>Note: in the second photo, the chip has been removed. :)</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2012/01/03/iphone-microscope-awesome/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Book Review: Treading on Python</title>
		<link>http://thesmithfam.org/blog/2011/12/28/book-review-treading-on-python/</link>
		<comments>http://thesmithfam.org/blog/2011/12/28/book-review-treading-on-python/#comments</comments>
		<pubDate>Thu, 29 Dec 2011 05:48:57 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1129</guid>
		<description><![CDATA[Treading on Python by Matt Harrison provides a basic introduction to the Python programming language for programming novices. Background of the reviewer I have been writing code professionally for 10 years. I&#8217;ve spent most of my time in C++, but I&#8217;ve written a handful of small Python scripts (less than 100 lines) and a couple [...]]]></description>
			<content:encoded><![CDATA[<p><em>Treading on Python</em> by Matt Harrison provides a basic introduction to the Python programming language for programming novices.</p>
<p><strong>Background of the reviewer</strong></p>
<p>I have been writing code professionally for 10 years. I&#8217;ve spent most of my time in C++, but I&#8217;ve written a handful of small Python scripts (less than 100 lines) and a couple medium-sized Python applications (hundreds of lines with multi-threading).</p>
<p>In <em>Treading on Python</em>, I was looking to shore up my Python foundation before jumping into my first big Python project.</p>
<p>I was not disappointed.</p>
<p><strong>Who is this book for?</strong></p>
<p>If you are interested in learning how to write computer programs as a beginner, this book is probably a pretty good place to start. The book starts by persuading you to choose Python as your first programming language for two main reasons:</p>
<ol>
<li>Python is used widely in industry</li>
<li>Python is easy to learn</li>
</ol>
<p>This book is written primarily for brand new programmers. It provides practical advice for getting started at the very early stages of programming:</p>
<ul>
<li>How to edit Python code</li>
<li>How to run Python programs</li>
<li>How to use the Python interactive shell</li>
<li>What a variable is (complete with cattle analogy)</li>
<li>How to use strings, integers, and lists</li>
</ul>
<p>However, even if you have, like me, written some small to medium sized Python programs, you will still probably benefit from the following useful information:</p>
<ul>
<li>Python&#8217;s handy <tt>dir</tt> and <tt>help</tt> functions</li>
<li>The <tt>enumerate()</tt> function</li>
<li>The dictinoary <tt>setdefault()</tt> method</li>
<li>Python&#8217;s concept of <tt>None</tt> and object <tt>id</tt></li>
<li>List slicing</li>
<li><tt>import</tt> and <tt>from...import</tt> semantics</li>
<li>And a surprisingly good list of pitfalls to avoid</li>
</ul>
<p>Early in the book, Matt spends a lot of time explaining basic programming concepts (like variables). He does this by providing real world analogies (like cattle) that will probably seem superfluous to the experienced programmer, but that may be beneficial to the programming novice. I was tempted to skip the first few chapters but I&#8217;m glad I read them competely. The book is peppered with little gems that reveal what writing Python code is all about, and even the most basic topics still provide these insights.</p>
<p><strong>Who is this book not for?</strong></p>
<p>If you are looking for a book that delves deep into Python, this is not the book for you. Notably absent concepts from this book include:</p>
<ul>
<li>List comprehensions</li>
<li>Generators</li>
<li>Lambdas</li>
<li>Threading</li>
<li>Many Python <a href="http://docs.python.org/library/functions.html">built-in functions</a>, like <tt>any()</tt> and <tt>all()</tt></li>
<li>Many handy pieces of the Python standard library, like <a href="http://docs.python.org/dev/library/operator.html"><tt>operator.itemgetter()</tt></a></li>
</ul>
<p>I don&#8217;t offer this list as a criticism of the book. The book&#8217;s stated purpose is clearly not to provide a comprehensive Python treatise for the experienced programmer. But if you are considering this book as a way to delve into any of these concepts, this is not the book for you.</p>
<p><strong>Opinion of the book</strong></p>
<p>Matt clearly knows his Python. He has peppered the book with helpful tips that compelled me to whip out my Python interpreter to experiment. Many of the tips were very handy, even for a semi-experienced Python programmer such as myself.</p>
<p>Matt is pleasingly frank in his recommendations to avoid certain approaches, and after reading the book, I feel like I have a better eye for assessing how &#8220;Pythonic&#8221; something is. In fact, now that I have finished the book, I can look back on Python code I wrote before reading the book, and critique the heck out of it. Prior to reading this book, my Python code looked a lot like my C++ code, which is just a shame. This book can help inoculate you against such behavior.</p>
<p>The book reads smoothly and quickly. Matt is very careful to keep his explanations succinct and clear, such that you don&#8217;t feel like you&#8217;re reading a college text book or a reference manual. Even still, the book does contain a high information density.</p>
<p>On my iPad, with the default font size, the book is 243 pages in landscape mode and 147 pages in portrait mode.</p>
<p>I finished the book in fewer than a dozen 15-30 minute sittings.</p>
<p><strong>Conclusion</strong></p>
<p>If you can already crank out Python list comprehensions and lambda expressions, this is probably not the book for you. If you are an experienced programmer and want to learn Python, this is a fast way to start. If you are a total programming novice, this may be a good way to begin, but I&#8217;m not a great judge for this audience.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2011/12/28/book-review-treading-on-python/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fun Python Solution to Euler Problem 79</title>
		<link>http://thesmithfam.org/blog/2011/12/27/fun-python-solution-to-euler-problem-79/</link>
		<comments>http://thesmithfam.org/blog/2011/12/27/fun-python-solution-to-euler-problem-79/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 05:22:41 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1107</guid>
		<description><![CDATA[Nothing says Merry Christmas like Project Euler. Here&#8217;s a nifty solution to Problem 79 that uses Python and Graphviz. The problem is to identify a user&#8217;s password given a bunch of successful logins (taken from some kind of nefarious keylogger&#8211;those crafty devils). The çatch is that each login is actually a subset of the actual [...]]]></description>
			<content:encoded><![CDATA[<p>Nothing says Merry Christmas like Project Euler.</p>
<p>Here&#8217;s a nifty solution to <a href="http://projecteuler.net/problem=79">Problem 79</a> that uses Python and Graphviz.</p>
<p>The problem is to identify a user&#8217;s password given a bunch of successful logins (taken from some kind of nefarious keylogger&#8211;those crafty devils). The çatch is that each login is actually a <b>subset</b> of the actual password. Of course, they give you <a href="http://projecteuler.net/project/keylog.txt">a sample of 50 successful logins</a>.</p>
<p>So I decided to whip up some Python code to ingest each login and store a list of digit precedence. Then, the code prints out a <a href="http://www.graphviz.org/Gallery.php">Dot file</a> which we turn into an image using the &#8220;dot&#8221; command. I ran this on Mac OS X, but it should work just fine on any Linux box (hint: install the &#8220;graphviz&#8221; package).</p>
<p>Here&#8217;s the Python code:</p>
<p><b>problem79.py:</b></p>
<pre class="brush: python; title: ; notranslate">
digit_precendence = dict()

for line in [line.strip() for line in open(&quot;./keylog.txt&quot;)]:
    for index, char in enumerate(line):
        digits = digit_precendence.setdefault(int(char), set())
        if index &lt; len(line)-1:
            digits.add(int(line[index+1]))

print &quot;digraph problem79 {&quot;
for (digit, subsequent_digits) in digit_precendence.iteritems():
    for subsequent_digit in subsequent_digits:
        print &quot;   %d -&gt; %d;&quot; % (digit, subsequent_digit)
print &quot;}&quot;
</pre>
<p>Save that as <b>problem79.py</b>, download <b>keylog.txt</b> into the same folder, and run the program like this:</p>
<pre class="brush: bash; title: ; notranslate">python problem79.py | dot -Tpng &gt; problem79.png</pre>
<p>Then view <b>problem79.png</b>, and voila! Graphviz just put the answer right in front of your nose: <b>73162890</b>.</p>
<p><img src="/images/problem79.png" /></p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2011/12/27/fun-python-solution-to-euler-problem-79/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cocoa Noob Pitfalls</title>
		<link>http://thesmithfam.org/blog/2011/09/12/cocoa-noob-pitfalls/</link>
		<comments>http://thesmithfam.org/blog/2011/09/12/cocoa-noob-pitfalls/#comments</comments>
		<pubDate>Tue, 13 Sep 2011 04:10:25 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1069</guid>
		<description><![CDATA[I just finished writing my first iPhone app. I have a background in Java, C++, Python, and a smattering of other programming languages on Linux and Windows in both embedded and desktop environments, so that hopefully explains my brain damaged context. Here are the pit falls I stumbled upon while climbing up the Cocoa learning [...]]]></description>
			<content:encoded><![CDATA[<p>I just finished writing my first iPhone app. I have a background in Java, C++, Python, and a smattering of other programming languages on Linux and Windows in both embedded and desktop environments, so that hopefully explains my brain damaged context.</p>
<p>Here are the pit falls I stumbled upon while climbing up the Cocoa learning curve:</p>
<h2>Retain/Release Memory Leaks</h2>
<p>It wasn&#8217;t immediately obvious to me that adding an NSObject pointer to an NSMutableArray (and other containers) would actually <strong>increment</strong> the NSObject&#8217;s retain count. Not knowing this right away, I got into the (bad) habit of double-retaining objects. It took some investigation to find out what was happening, and thanks to Apple&#8217;s ingenius profiler and analyzer, I was able to identify the problem. After learning this, I came to find out that, by convention, lots of containers do this, but it&#8217;s not too apparent from <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html">the documentation</a>.</p>
<h2>No Container Static Type Checking?</h2>
<p>Apple provides several container classes, including NSArray, NSDictionary, and several others. Much like old versions of Java (like the Java 1.3 stone age), you are free to add instances of any NSObject* child class. As a result, it&#8217;s possible to end up with objects of types you did not expect, and the compiler cannot prevent you or even warn you about this.</p>
<h2>Sub-Class Insanity</h2>
<p>It seems you have to sub-class to do very basic things, like adding items to a UIPickerView. I would have expected a trivial method call to do something like this.</p>
<h2>Verbose Names</h2>
<p>Stuff like appending one string to anoher is usually pretty trivial and terse in most languages. For example, in C++, you might see this:</p>
<pre class="brush: plain; title: ; notranslate">
myString += &quot;suffix&quot;;
</pre>
<p>But in Cocoa, it looks like this:</p>
<pre class="brush: plain; title: ; notranslate">
myString = [NSString stringByAppendingString:@&quot;suffix&quot;];
</pre>
<p>That is a seriously verbose method name. If you count, it uses the word &#8220;String&#8221; 3 times, and that&#8217;s not even counting my variable name.</p>
<h2>No Static Function Checking</h2>
<p>Because Objective-C&#8217;s message-passing system is evaluated at runtime, the compiler won&#8217;t complain (much) if you try to send a message to an object that does not respond to that message (i.e., like calling a member function in C++ that does not exist). The compiler does warn you, but it will compile, run, and fail with a run-time exception. Some people consider this an advantage of Objective-C, so I can&#8217;t hold it against Apple (Smalltalk fans, I&#8217;m looking at you).</p>
<h2>Bogus Compiler Warnings</h2>
<p>If I define a couple messages like this in my class, without putting them in the .h file:</p>
<pre class="brush: objc; title: ; notranslate">
-(void) foo
{
    [self bar];  // compiler warning here
}

-(void) bar
{
}
</pre>
<p>The compiler will issue a warning, even though this is perfectly safe and will run without exceptions. The compiler is apparently very eager to warn you about this perfectly safe usage, and yet still allows you to send messages that definitely won&#8217;t be responded to at run time.</p>
<h2>Weird Autorelease Pool Crashes</h2>
<p>The first time I misused the autorelease message, I discovered that my application would crash in the event loop processing context. The stack gave no indication where I had gone wrong, because it contained none of my own code. The autorelease pool object itself would crash because it was calling release on an object that had already been freed. The runtime exception was so counter-intuitive that I ended up reverting my code (using git) back to a prior state. I eventually isolated the cause of the problem to my misuse of autorelease, which prompted me to do a more thorough exploration of the feature. Now I recognize those kinds of crashes for what they are, but the first time I encountered it, I was confused for a while before I figured it out.</p>
<h2>Managing Multiple Sub-Views</h2>
<p>If you have multiple UIPickerView sub-views within your view, managing their contents can be difficult. This is because you have to write a class to implement the UIPickerViewDataSource protocol, which is usually easiest to do right inside your view controller. However, when you add a second or third UIPickerView sub-view to your view, it gets difficult to manage. The UIPickerViewDataSource protocol sends you a pointer to the UIPickerView so you can keep track of which one is which, but it just feels cumbersome. I ended up using <a href="https://github.com/sickanimations/ActionSheetPicker">this guy&#8217;s code</a> to make it easier.</p>
<h2>Permissive Compiler Stuff</h2>
<p>The Objective-C compiler will allow you to do this:</p>
<pre class="brush: objc; title: ; notranslate">
NSMutableDictionary *myDictionary =
    [[NSDictionary alloc] init];
</pre>
<p>I would expect it to work the other way around, but not this way. This leads to runtime exceptions when you try to add an element to &#8220;myDictionary&#8221;, which can be surprising until you realize you have an instance of an immutable NSDictionary. The runtime exception is pretty vague too: All you get is &#8220;invalid selector&#8221;.</p>
<h2>Disappearing Outlets</h2>
<p>If you connect an outlet or action in Interface Builder and then later delete the outlet or action object in your Objective-C code, you will get a very cryptic error when you try to instantiate the view:</p>
<pre class="brush: plain; title: ; notranslate">
'NSUnknownException&quot;, reason: &quot;[&lt;uiview 0%48a3e0&gt;
setValue:forUndefinedKey:]: this class is not
key value coding-complaint
</pre>
<p>What it should say is &#8220;This xib file is trying to reference item &#8216;foo&#8217; which does not exist&#8221;</p>
<h2>Working with UINavigationController</h2>
<p>UINavigationController can only have one delegate, even though all it does is notify the delegate when the current view changes. If you want to notify more than one view controller that navigation has moved, then you have to do some juggling to save and restore the UINavigationController&#8217;s delegate. It should be easier to notify interested parties when navigation changes.</p>
<h2>Good Stuff</h2>
<p>Cocoa has a lot of good stuff about it too. Here are some of the highlights from my experience:</p>
<h2>Consistent Time Units</h2>
<p>Times are always expressed in seconds (and fractions of seconds) instead of having to guess whether it&#8217;s seconds, milliseconds, or something else. This is extremely gratifying having come from a world where you pretty much always have to guess (although Google Go&#8217;s concept of typing is still far superior).</p>
<h2>Analys and Profiling Tools</h2>
<p>The X-Code 4 analysis and profiling tools are excellent. I mostly learned how retain/release worked by following the memory leaks that the code analyzer told me about. It even draws little arrows on your code to show you the code path you screwed up. Also, the memory leak finder is fantastic. It shows you when your application leaks, and where each leaked object was originally allocated. This made it trivial to track down and fix my memory leaks.</p>
<h2>Easy Animation</h2>
<p>Animation is as easy as giving a view a destination size and position, and telling it to go. Animation is integrated into the very core of Cocoa, and it is both easy to use and beautiful on screen.</p>
<h2>Conclusion</h2>
<p>So there you have it. Cocoa has some pitfalls and some good stuff. That&#8217;s all I have to say about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2011/09/12/cocoa-noob-pitfalls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linode: 7 years of awesome</title>
		<link>http://thesmithfam.org/blog/2011/04/18/linode-7-years-of-awesome/</link>
		<comments>http://thesmithfam.org/blog/2011/04/18/linode-7-years-of-awesome/#comments</comments>
		<pubDate>Mon, 18 Apr 2011 13:23:51 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>
		<category><![CDATA[Miscellany]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1065</guid>
		<description><![CDATA[It just ocurred to me that I&#8217;ve been using Linode as my hosting provider for 7 years this week. I&#8217;ve been so happy with their service that I thought I&#8217;d offer a review. The top 4 reasons you should consider Linode for your hosting needs (I&#8217;m sure there are 6 more reasons, but I&#8217;m time [...]]]></description>
			<content:encoded><![CDATA[<p>It just ocurred to me that I&#8217;ve been using <a href="http://www.linode.com/">Linode</a> as my hosting provider for 7 years this week. I&#8217;ve been so happy with their service that I thought I&#8217;d offer a review.</p>
<p>The <b>top 4 reasons</b> you should consider Linode for your hosting needs (I&#8217;m sure there are 6 more reasons, but I&#8217;m time limited today):</p>
<p><b>Reason 1. Automatic Upgrades</b></p>
<p>Every year or so, I wake up to an email from Linode telling me I can have more disk space or RAM on my server. Adding it is super easy: just login to their web site and click a few buttons. Today I&#8217;ve got 490 MB of RAM and 16 GB of disk, and I&#8217;m still only using their least expnsive option.</p>
<p><b>Reason 2. Huge Internet Speeds</b></p>
<p>Linode servers have great Internet connection speeds. I regularly get over 50 Mbits/second.</p>
<p><b>Reason 3. Customer Service</b></p>
<p>The Linode support team is very sharp. They know what they&#8217;re talking about, and they are very helpful. This is more than can be said for <b>many</b> other support organizations. I&#8217;ve only needed to open a support ticket a cople times, and on both occasions, the Linode support staff responded within an hour and gave me all the information I needed, not only to solve my problem but to prevent my problem from happening again in the future</p>
<p><b>Reason 4. Cost</b></p>
<p>At $20/month, Linode is very affordable for what you get: Full root access, nearly any Linux distribution you want, lots of RAM and disk, and good CPU speed (my Linode has 4 CPUs).</p>
<p>After 7 years, I very highly recommend Linode as a Virtual Private Server hosting service.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2011/04/18/linode-7-years-of-awesome/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>LDS General Conference Podcast Updated</title>
		<link>http://thesmithfam.org/blog/2011/04/03/lds-general-conference-podcast-updated-2/</link>
		<comments>http://thesmithfam.org/blog/2011/04/03/lds-general-conference-podcast-updated-2/#comments</comments>
		<pubDate>Mon, 04 Apr 2011 05:26:18 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[LDS]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1059</guid>
		<description><![CDATA[There were some fantastic messages this conference (April 2011). I plan on re-listening to all of them. Get the podcast: General Conference Podcast page.]]></description>
			<content:encoded><![CDATA[<p>There were some fantastic messages this conference (April 2011). I plan on re-listening to all of them.</p>
<div style="border: 2px solid #89d; border-radius: 9px; padding: 8px; background: #bcf">
Get the podcast: <a href="/blog/lds-general-conference-podcast/">General Conference Podcast page</a>.
</div>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2011/04/03/lds-general-conference-podcast-updated-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When faster is actually slower</title>
		<link>http://thesmithfam.org/blog/2011/02/12/when-faster-is-actually-slower/</link>
		<comments>http://thesmithfam.org/blog/2011/02/12/when-faster-is-actually-slower/#comments</comments>
		<pubDate>Sun, 13 Feb 2011 06:43:27 +0000</pubDate>
		<dc:creator>Dave</dc:creator>
				<category><![CDATA[Code and Cruft]]></category>

		<guid isPermaLink="false">http://thesmithfam.org/blog/?p=1023</guid>
		<description><![CDATA[This is a follow-up to my post on code optimization. Today I did some experimenting with hashes and binary-search-trees, specifically playing with QHash and QMap in C++. According to the Qt containers algorithmic complexity documentation, QHash provides &#8220;significantly faster lookups&#8221; than QMap. Your intuition may confirm this, because you&#8217;ve heard that QHash uses a constant-time [...]]]></description>
			<content:encoded><![CDATA[<p><i>This is a follow-up to <a href="http://thesmithfam.org/blog/2011/02/06/how-to-optimize-your-code/">my post on code optimization</a>.</i></p>
<p>Today I did some experimenting with hashes and binary-search-trees, specifically playing with <a href="http://doc.qt.nokia.com/qhash.html">QHash</a> and <a href="http://doc.qt.nokia.com/qmap.html">QMap</a> in C++.</p>
<p>According to the <a href="http://doc.qt.nokia.com/containers.html#algorithmic-complexity">Qt containers algorithmic complexity documentation</a>, QHash provides &#8220;significantly faster lookups&#8221; than QMap. Your intuition may confirm this, because you&#8217;ve heard that QHash uses a constant-time algorithm for lookups, while QMap uses a logarithmic algorithm. However, when it comes to performance questions, intuition is not the best guide.</p>
<p>When considering the QMap vs. QHash speed question, we have to consider everything these classes do when you are looking up an entry. Otherwise, you may be led to assume that QHash lookups are faster than QMap lookups in all cases.</p>
<p><b>How does QMap work?</b></p>
<p>Like an associative array or dictionary, the QMap class allows you to store values identified by keys. You can insert key/value pairs into the QMap and retrieve values by key. You can use any type as the value, but the key type must implement the <b>< </b> operator.</b> This is because QMap looks up keys using a <a href="http://en.wikipedia.org/wiki/Binary_search_algorithm">binary search</a> through a sorted list.</p>
<p><b>How does QHash work?</b></p>
<p>QHash also provides the ability to insert and lookup values like QMap, but its implementation is quite different. Keys used in a QHash must implement the <b>==</b> operator and there must exist a global <b>qHash(key)</b> function for the key type. The QHash class hashes each key on lookup to find the position for each key&#8217;s value. This is a constant time operation (amortized). This means that the time it takes to lookup a key does not depend on the number of keys already stored in the QHash.</p>
<p><b>When is QHash slower than QMap?</b></p>
<p>Consider the following example:</p>
<pre class="brush: cpp; title: ; notranslate">
QHash&lt;QString, int&gt; myHash;
QMap&lt;QString,  int&gt; myMap;
</pre>
<p>To insert the key &#8220;my favorite number&#8221; with the value 42 into <b>myHash</b>, the QHash has to first generate a hash code for &#8220;my favorite number&#8221;. To do so, it uses the <b>qHash()</b> function, which reads every character of the string &#8220;my favorite number&#8221;. This generates an index that is used to locate the position for this entry. Notice that <b>qHash()</b> must read every character of the string. The QMap, on the other hand, uses the <b>< </b> operator to compare the string &#8220;my favorite number&#8221; with all other keys in the QMap.</p>
<p>Now let&#8217;s suppose we filled </b><b>myHash</b> and <b>myMap</b> with 1 million short string keys (like a few characters each), and then did a few lookups.</p>
<p>I measured this case using QTime, and found that QHash lookups are about 3 times faster than QMap lookups in this scenario.</p>
<p>This is what I would expect after reading the documentation, but what if the key strings are bigger, like 200 characters each, and all quite distinct from each other?</p>
<p>I measured this case and found that QHash lookups are about 3 times <b>slower</b> than QMap lookups.</p>
<p>How can this be? The documentation says that QHash lookups are supposed to be faster.</p>
<p>The reason is this: Because QMap uses the <b>< </b> operator, it does not need to inspect every character of each key string. Instead, it compares the key string to other key strings, one character at a time, and stops if it discovers a difference </b><b>before reaching the end of the string</b>. This results in much less computation when locating a key&#8217;s value. So much less computation in fact, that even though QMap&#8217;s lookup algorithm is logarithmic, it is actually <b>faster</b> than QHash&#8217;s constant-time lookup algorithm on the same dataset.</p>
<p>I should offer the disclaimer that QHash will likely be faster than QMap for larger quantities of entries with that key size, but I was unable to test larger quantities due to the limited amount of RAM in my laptop.</p>
<p><b>Conclusion</b></p>
<p>When optimizing for speed, always consider all factors. Just because an algorithm is constant time does not mean that it is always faster than a non-constant time algorithm. And always remember to measure execution speed before assuming that one approach is faster than another.</p>
]]></content:encoded>
			<wfw:commentRss>http://thesmithfam.org/blog/2011/02/12/when-faster-is-actually-slower/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

