<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.3.3">Jekyll</generator><link href="https://www.dribin.org/dave/blog/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.dribin.org/dave/blog/" rel="alternate" type="text/html" /><updated>2024-03-21T09:52:17-05:00</updated><id>https://www.dribin.org/dave/blog/feed.xml</id><title type="html">Dave Dribin’s Blog</title><subtitle>Dave Dribin&apos;s Blog.
</subtitle><author><name>Dave Dribin</name></author><entry><title type="html">rsync Progress Demo</title><link href="https://www.dribin.org/dave/blog/archives/2024/03/15/rsync-progress-example/" rel="alternate" type="text/html" title="rsync Progress Demo" /><published>2024-03-15T09:22:00-05:00</published><updated>2024-03-15T09:22:00-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2024/03/15/rsync-progress-example</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2024/03/15/rsync-progress-example/"><![CDATA[<p>A couple weeks ago, I wrote up <a href="/dave/blog/archives/2024/01/21/rsync-overall-progress/">how to get overall progress with <code class="language-plaintext highlighter-rouge">rsync</code></a>. I’ve been meaning to use <a href="https://asciinema.org/">Asciinema</a> to show terminal screen recordings, and figured this would make a good example.</p>

<!--more-->

<p>Asciinema is nice in that the recording is just a JSON file, not a video, so it is very small. It is played back via Javascript, and you can even select the text that is displayed. Unfortunately, due to the Javascript, it won’t play back in the Atom feed, so you’ll need to follow the link through to the page, if you are reading in a news reader. I thought about using an animated GIF in the news feed, but then you’d lose part of the magic of Asciinema.</p>

<p><a href="https://www.dribin.org/dave/blog/archives/2024/03/15/rsync-progress-example/">
  <img src='https://www.dribin.org/dave/blog/resources/rsync-progress-demo-poster.png' width='889' height='655' alt='rsync progress demo ASCII cast' />
</a></p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[A couple weeks ago, I wrote up how to get overall progress with rsync. I’ve been meaning to use Asciinema to show terminal screen recordings, and figured this would make a good example.]]></summary></entry><entry><title type="html">Linear Fit using Python and NumPy</title><link href="https://www.dribin.org/dave/blog/archives/2024/02/18/python-linear-fit/" rel="alternate" type="text/html" title="Linear Fit using Python and NumPy" /><published>2024-02-18T10:41:35-06:00</published><updated>2024-02-18T10:41:35-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2024/02/18/python-linear-fit</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2024/02/18/python-linear-fit/"><![CDATA[<p>I was working on a side project where I needed to find the linear fit to a set of data points. A linear fit is also known as a “linear approximation” or “linear regression”. This is quite easy using a <a href="https://www.apple.com/numbers/">Numbers</a> spreadsheet. Numbers will even show you equation of the line in <a href="https://www.khanacademy.org/math/algebra/x2f8bb11595b61c86:forms-of-linear-equations/x2f8bb11595b61c86:intro-to-slope-intercept-form/a/introduction-to-slope-intercept-form">slope-intercept form</a>:</p>

\[y = mx + b\]

<p>Unfortunately, there is no way that I know of to get the slope and Y-intercept from the Numbers plot besides visual inspection. I also wanted a way to do this from the command line. This post will explain how to do this using <a href="https://www.python.org">Python</a> and the <a href="https://numpy.org">NumPy library</a>.</p>

<h2 id="tldr-python-one-liners">TLDR: Python One-Liners</h2>

<p>While the rest of the post goes into more detail, here are two quick Python one-liners to find the slope and Y-intercept, given two NumPy arrays, <code class="language-plaintext highlighter-rouge">x</code> and <code class="language-plaintext highlighter-rouge">y</code>. First, with <a href="https://numpy.org/doc/stable/reference/generated/numpy.polynomial.polynomial.Polynomial.fit.html"><code class="language-plaintext highlighter-rouge">Polynomial.fit()</code></a>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">b</span><span class="p">,</span> <span class="n">m</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">polynomial</span><span class="p">.</span><span class="n">polynomial</span><span class="p">.</span><span class="n">Polynomial</span><span class="p">.</span><span class="nf">fit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="mi">1</span><span class="p">).</span><span class="nf">convert</span><span class="p">().</span><span class="n">coef</span>
</code></pre></div></div>

<p>And second, with <a href="https://numpy.org/doc/stable/reference/generated/numpy.polynomial.polynomial.polyfit.html"><code class="language-plaintext highlighter-rouge">Polynomial.polyfit()</code></a>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">b</span><span class="p">,</span> <span class="n">m</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="n">polynomial</span><span class="p">.</span><span class="n">polynomial</span><span class="p">.</span><span class="nf">polyfit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</code></pre></div></div>

<p>Both of these give you the slope in <code class="language-plaintext highlighter-rouge">m</code> and the Y-intercept in <code class="language-plaintext highlighter-rouge">b</code>. I also created a <a href="https://gist.github.com/ddribin/846d6576e75b3cc2134b6ea3198f590f">Jupyter notebook</a> demonstrating these APIs.</p>

<p>I’m honestly not sure why you would pick one over the other. <code class="language-plaintext highlighter-rouge">Polynomial.polyfit()</code> is less code, so that seems like the better option, to me. But if you know, please <a href="https://www.dribin.org/dave/contact/">contact me</a>! And please read on for more details.</p>

<!--more-->

<h2 id="using-numbers">Using Numbers</h2>

<p>Here’s the sample data we’ll be using throughout the rest of the post:</p>

<table>
  <thead>
    <tr>
      <th>X</th>
      <th>Y</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0</td>
      <td>-1</td>
    </tr>
    <tr>
      <td>1</td>
      <td>0.2</td>
    </tr>
    <tr>
      <td>2</td>
      <td>0.9</td>
    </tr>
    <tr>
      <td>3</td>
      <td>2.1</td>
    </tr>
  </tbody>
</table>

<p>In Numbers, put this X and Y data into a table. Then add a Scatter Plot and enable a “Linear Trendline” with “Show Equation” checked. You should see a plot, as in this screenshot:</p>

<p><a href="https://www.dribin.org/dave/blog/images/linear-fit-numbers.png">
  <img srcset="     https://www.dribin.org/dave/blog/images/linear-fit-numbers-thm25-1x.png,     https://www.dribin.org/dave/blog/images/linear-fit-numbers-thm25-2x.png 2x,   " src="https://www.dribin.org/dave/blog/images/linear-fit-numbers-thm25-1x.png" width="263" height="243" alt="Thumbnail of a screenshot of a Numbers spreadsheet plot" />
</a></p>

<p>The plot shows the points in blue and a line in red as the “best fit” line for the points. The legend shows the formula of the line as:</p>

\[y = x - 0.95\]

<p>In other words, the “best fit” line has a slope of 1 and a Y-intercept of -0.95. The goal here is to take the same input data and come up with the same slope and Y-Intercept using Python.</p>

<h2 id="using-python-and-numpy">Using Python and NumPy</h2>

<p>For those that don’t know, <a href="https://numpy.org">NumPy</a> is a fantastic Python library for doing numerical calculations. And one of the <em>many</em> things it can do is a linear fit. Unfortunately, it also has multiple ways to do this, which I find a bit confusing. Here are all the ways I found:</p>

<ol>
  <li><a href="https://numpy.org/doc/stable/reference/generated/numpy.polyfit.html"><code class="language-plaintext highlighter-rouge">numpy.polyfit()</code></a></li>
  <li><a href="https://numpy.org/doc/stable/reference/generated/numpy.polynomial.polynomial.Polynomial.fit.html"><code class="language-plaintext highlighter-rouge">numpy.polynomial.Polynomial.fit()</code></a></li>
  <li><a href="https://numpy.org/doc/stable/reference/generated/numpy.polynomial.polynomial.polyfit.html"><code class="language-plaintext highlighter-rouge">numpy.polynomial.Polynomial.polyfit()</code></a></li>
</ol>

<p>The first option, <code class="language-plaintext highlighter-rouge">numpy.polyfit()</code>, is considered legacy, and the <a href="https://numpy.org/doc/stable/reference/routines.polynomials.html">documentation</a> says to use <code class="language-plaintext highlighter-rouge">numpy.polynomial</code>:</p>

<blockquote>
  <p>As noted above, the <code class="language-plaintext highlighter-rouge">poly1d</code> class and associated functions defined in <code class="language-plaintext highlighter-rouge">numpy.lib.polynomial</code>, such as<code class="language-plaintext highlighter-rouge"> numpy.polyfit</code> and <code class="language-plaintext highlighter-rouge">numpy.poly</code>, are considered legacy and should not be used in new code. Since NumPy version 1.4, the <code class="language-plaintext highlighter-rouge">numpy.polynomial</code> package is preferred for working with polynomials.</p>
</blockquote>

<p>Because this is deprecated, we’ll skip over this option and look at the other two.</p>

<h3 id="using-polynomialfit">Using <code class="language-plaintext highlighter-rouge">Polynomial.fit</code></h3>

<p>The <a href="https://numpy.org/doc/stable/reference/routines.polynomials.html">Polynomial transition guide</a> specifically says that <code class="language-plaintext highlighter-rouge">Polynomial.fit()</code> is the replacement for <code class="language-plaintext highlighter-rouge">numpy.polyfit()</code>, so we’ll look at this option first.</p>

<p>The first order of business is to get the data into Python. For demonstration purposes, we’ll create two separate NumPy arrays in code:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">numpy</span> <span class="k">as</span> <span class="n">np</span>

<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">array</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">array</span><span class="p">([</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mf">0.2</span><span class="p">,</span> <span class="mf">0.9</span><span class="p">,</span> <span class="mf">2.1</span><span class="p">])</span>
</code></pre></div></div>

<p>It is, however, better to store this data outside the code, for example in a CSV or JSON file. You can easily read these in Python using the Standard Library (<a href="https://docs.python.org/3/library/csv.html"><code class="language-plaintext highlighter-rouge">csv</code></a> or <a href="https://docs.python.org/3/library/json.html"><code class="language-plaintext highlighter-rouge">json</code></a> modules) or the <a href="https://pandas.pydata.org">Pandas Library</a> (<a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html"><code class="language-plaintext highlighter-rouge">pandas.read_csv()</code></a> or <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_json.html"><code class="language-plaintext highlighter-rouge">pandas.read_json()</code></a> functions). Pandas is nice because it automatically parses into NumPy arrays of floating point numbers.</p>

<p>With the data in arrays, we can use <code class="language-plaintext highlighter-rouge">Polynomial.fit()</code> to create a linear “polynomial” from the <code class="language-plaintext highlighter-rouge">x</code> and <code class="language-plaintext highlighter-rouge">y</code> arrays:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">numpy.polynomial.polynomial</span> <span class="k">as</span> <span class="n">poly</span>

<span class="n">linear</span> <span class="o">=</span> <span class="n">poly</span><span class="p">.</span><span class="n">Polynomial</span><span class="p">.</span><span class="nf">fit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</code></pre></div></div>

<p>This returns a <code class="language-plaintext highlighter-rouge">Polynomial</code> object of degree <code class="language-plaintext highlighter-rouge">1</code>, meaning it is linear. But what we <em>really</em> want are the coefficients of this polynomial. The <a href="https://numpy.org/doc/stable/reference/generated/numpy.polynomial.polynomial.Polynomial.fit.html">docs</a> tell us how to get them:</p>

<blockquote>
  <p>If the coefficients for the unscaled and unshifted basis polynomials are of interest, do <code class="language-plaintext highlighter-rouge">new_series.convert().coef</code>.</p>
</blockquote>

<p>So that’s what we’ll do:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">coefs</span> <span class="o">=</span> <span class="n">linear</span><span class="p">.</span><span class="nf">convert</span><span class="p">().</span><span class="n">coef</span>
</code></pre></div></div>

<p>And if we print them out, we get:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="nf">print</span><span class="p">(</span><span class="n">coefs</span><span class="p">)</span>
<span class="p">[</span><span class="o">-</span><span class="mf">0.95</span>  <span class="mf">1.</span>  <span class="p">]</span>
</code></pre></div></div>

<p>These are the same numbers we got from Numbers, but the Y-intercept is first and the slope is second. Why is that? Because <code class="language-plaintext highlighter-rouge">Polynomial</code> represents an \(n\)-degree polynomial (sometimes called the order of the polynomial) of this form:</p>

\[y = c_0 + c_1x + c_1x^2 + \dots + c_nx^n\]

<p>And with a degree of <code class="language-plaintext highlighter-rouge">1</code>, the equation is:</p>

\[y = c_0 + c_1x\]

<p>Plugging the coefficient values of <code class="language-plaintext highlighter-rouge">[-0.95  1.  ]</code> into that equation give us:</p>

\[y = -0.95 + x\]

<p>This is backwards from the slope-intercept form of \(y = mx + b\). The first coefficient, \(c_0\), is the Y-intercept \(b\), and the second coefficient, \(c_1\), is the slope \(m\). Python’s destructuring makes it easy to assign separate variables, <code class="language-plaintext highlighter-rouge">m</code> and <code class="language-plaintext highlighter-rouge">b</code>, from the coefficients:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">b</span><span class="p">,</span> <span class="n">m</span> <span class="o">=</span> <span class="n">coefs</span>
</code></pre></div></div>

<p>This can even be done in one line:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">b</span><span class="p">,</span> <span class="n">m</span> <span class="o">=</span> <span class="n">poly</span><span class="p">.</span><span class="n">Polynomial</span><span class="p">.</span><span class="nf">fit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="mi">1</span><span class="p">).</span><span class="nf">convert</span><span class="p">().</span><span class="n">coef</span>
</code></pre></div></div>

<h3 id="using-polynomialpolyfit">Using <code class="language-plaintext highlighter-rouge">Polynomial.polyfit</code></h3>

<p>While you can use <code class="language-plaintext highlighter-rouge">Polynomial.fit()</code> in one line, I find it a bit verbose. It creates an intermediate <code class="language-plaintext highlighter-rouge">Polynomial</code> object and I’m honestly not sure what the <code class="language-plaintext highlighter-rouge">convert().coef</code> <em>really</em> does. There’s a simpler way to get the coefficients using <code class="language-plaintext highlighter-rouge">Polynomial.polyfit()</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">coefs</span> <span class="o">=</span> <span class="n">poly</span><span class="p">.</span><span class="nf">polyfit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</code></pre></div></div>

<p>Again, the <code class="language-plaintext highlighter-rouge">1</code> is the degree, meaning a linear polynomial. Printing out <code class="language-plaintext highlighter-rouge">coefs</code> shows the same results as above:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="nf">print</span><span class="p">(</span><span class="n">coefs</span><span class="p">)</span>
<span class="p">[</span><span class="o">-</span><span class="mf">0.95</span>  <span class="mf">1.</span>  <span class="p">]</span>
</code></pre></div></div>

<p>Also like above, these are in the opposite order as the slope-intercept form, so we can use destructing to get <code class="language-plaintext highlighter-rouge">m</code> and <code class="language-plaintext highlighter-rouge">b</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">b</span><span class="p">,</span> <span class="n">m</span> <span class="o">=</span> <span class="n">coef</span>
</code></pre></div></div>

<p>This gives us the expected slope of 1 and Y-intercept of -0.95:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;&gt;</span> <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="si">{</span><span class="n">m</span><span class="o">=</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="si">}</span><span class="s"> </span><span class="si">{</span><span class="n">b</span><span class="o">=</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="n">m</span><span class="o">=</span><span class="mf">1.0</span> <span class="n">b</span><span class="o">=-</span><span class="mf">0.95</span>
</code></pre></div></div>

<p>All in one line, this looks like:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">b</span><span class="p">,</span> <span class="n">m</span> <span class="o">=</span> <span class="n">poly</span><span class="p">.</span><span class="nf">polyfit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</code></pre></div></div>

<p>I personally find this the more readable option. There’s less code and it does not create an intermediate <code class="language-plaintext highlighter-rouge">Polynomial</code> object. Again, if there’s some reason to prefer <code class="language-plaintext highlighter-rouge">Polynomial.fit()</code>, please <a href="https://www.dribin.org/dave/contact/">let me know</a>. And as a reminder, check out the  <a href="https://gist.github.com/ddribin/846d6576e75b3cc2134b6ea3198f590f">Jupyter notebook</a> demonstrating these APIs.</p>

<h2 id="bonus-plotting-with-python">Bonus: Plotting with Python</h2>

<p>One nice thing that Numbers gave us was a plot of the data and the line. Python can do this, too, using another fantastic library called <a href="https://matplotlib.org">Matplotlib</a>. It has good integration with NumPy, and can use the <code class="language-plaintext highlighter-rouge">x</code> and <code class="language-plaintext highlighter-rouge">y</code> arrays directly. This code (which is also in the notebook):</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">matplotlib.pyplot</span> <span class="k">as</span> <span class="n">plt</span>

<span class="n">plt</span><span class="p">.</span><span class="nf">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="sh">"</span><span class="s">o</span><span class="sh">"</span><span class="p">,</span> <span class="n">label</span><span class="o">=</span><span class="sh">"</span><span class="s">Original data</span><span class="sh">"</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">m</span><span class="o">*</span><span class="n">x</span> <span class="o">+</span> <span class="n">b</span><span class="p">,</span> <span class="sh">"</span><span class="s">red</span><span class="sh">"</span><span class="p">,</span>
         <span class="n">label</span><span class="o">=</span><span class="sa">f</span><span class="sh">"</span><span class="s">Fitted line: y = </span><span class="si">{</span><span class="n">m</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="si">}</span><span class="s">*x + </span><span class="si">{</span><span class="n">b</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">grid</span><span class="p">(</span><span class="bp">True</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">legend</span><span class="p">()</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">show</span><span class="p">()</span>
</code></pre></div></div>

<p>Produces this plot:</p>

<p><img src="https://www.dribin.org/dave/blog/images/linear-fit-matplotlib.png" width="559" height="413" alt="Plot of data and linear fit line using Matplotlib" /></p>]]><![CDATA[<script type="text/javascript" id="MathJax-script" async
  src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[I was working on a side project where I needed to find the linear fit to a set of data points. A linear fit is also known as a “linear approximation” or “linear regression”. This is quite easy using a Numbers spreadsheet. Numbers will even show you equation of the line in slope-intercept form: \[y = mx + b\] Unfortunately, there is no way that I know of to get the slope and Y-intercept from the Numbers plot besides visual inspection. I also wanted a way to do this from the command line. This post will explain how to do this using Python and the NumPy library. TLDR: Python One-Liners While the rest of the post goes into more detail, here are two quick Python one-liners to find the slope and Y-intercept, given two NumPy arrays, x and y. First, with Polynomial.fit(): b, m = np.polynomial.polynomial.Polynomial.fit(x, y, 1).convert().coef And second, with Polynomial.polyfit(): b, m = np.polynomial.polynomial.polyfit(x, y, 1) Both of these give you the slope in m and the Y-intercept in b. I also created a Jupyter notebook demonstrating these APIs. I’m honestly not sure why you would pick one over the other. Polynomial.polyfit() is less code, so that seems like the better option, to me. But if you know, please contact me! And please read on for more details.]]></summary></entry><entry><title type="html">Overall Progress with rsync</title><link href="https://www.dribin.org/dave/blog/archives/2024/01/21/rsync-overall-progress/" rel="alternate" type="text/html" title="Overall Progress with rsync" /><published>2024-01-21T14:39:06-06:00</published><updated>2024-01-21T14:39:06-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2024/01/21/rsync-overall-progress</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2024/01/21/rsync-overall-progress/"><![CDATA[<p>A feature you may not know about recent versions of <code class="language-plaintext highlighter-rouge">rsync</code> is that you can display an overall progress of the transfer. And by “recent” I mean since <a href="https://download.samba.org/pub/rsync/NEWS#3.1.0">version 3.1.0</a>, released in September 2013. To use it, you want to add these options instead of <code class="language-plaintext highlighter-rouge">-v</code> and/or <code class="language-plaintext highlighter-rouge">--progress</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rsync --info=progress2 --human-readable --no-inc-recursive
</code></pre></div></div>

<p>For example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; rsync --info=progress2 --human-readable --no-inc-recursive -a /Applications /tmp
          9.53G  21%  317.26MB/s    0:00:28 (xfr#83063, to-chk=443926/538653)
</code></pre></div></div>

<!--more-->

<p><strong>Update 2024-03-15</strong>: See <a href="/dave/blog/archives/2024/03/15/rsync-progress-example/">this post</a> for a screen cast demo of this progress.</p>

<p>One niggle here is that macOS ships with an old version of <code class="language-plaintext highlighter-rouge">rsync</code>. On macOS Sonoma 14.2.1, I have version 2.6.9:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; rsync --version
rsync  version 2.6.9  protocol version 29
...
</code></pre></div></div>

<p>So you’ll need to install a newer version of <code class="language-plaintext highlighter-rouge">rsync</code>. I use <a href="https://brew.sh">Homebrew</a>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>brew install rsync
</code></pre></div></div>

<p>And now I have version 3.2.7:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; rsync --version
rsync  version 3.2.7  protocol version 31
...
</code></pre></div></div>

<p>I found out about this feature from this <a href="https://serverfault.com/questions/219013/showing-total-progress-in-rsync-is-it-possible">Server Fault question</a>.  <code class="language-plaintext highlighter-rouge">--info=progress2</code> is the main new option to display an overall progress. From the <code class="language-plaintext highlighter-rouge">rsync(1)</code> <code class="language-plaintext highlighter-rouge">man</code> page:</p>

<blockquote>
  <p>There is also a <code class="language-plaintext highlighter-rouge">--info=progress2</code> option that outputs statistics
based on the whole transfer, rather than individual files.  Use
this flag without outputting a filename (e.g. avoid <code class="language-plaintext highlighter-rouge">-v</code> or
specify <code class="language-plaintext highlighter-rouge">--info=name0</code>) if you want to see how the transfer is
doing without scrolling the screen with a lot of names. (You
don’t need to specify the <code class="language-plaintext highlighter-rouge">--progress</code> option in order to use
<code class="language-plaintext highlighter-rouge">--info=progress2</code>.)</p>
</blockquote>

<p>And also from <code class="language-plaintext highlighter-rouge">--info=help</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; rsync --info=help
...
PROGRESS   Mention 1) per-file progress or 2) total transfer progress
...
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">--human-readable</code> option formats bytes nicely, like the <code class="language-plaintext highlighter-rouge">9.53G</code> above.</p>

<p>The <code class="language-plaintext highlighter-rouge">--no-inc-recursive</code> (or <code class="language-plaintext highlighter-rouge">--no-i-r</code>) option provides a more accurate progress, as it does an initial file scan up front. From the man page:</p>

<blockquote>
  <p>Disables the new incremental recursion algorithm of the
<code class="language-plaintext highlighter-rouge">--recursive</code> option.  This makes rsync scan the full file list
before it begins to transfer files.  See <code class="language-plaintext highlighter-rouge">--inc-recursive</code> for
more info.</p>
</blockquote>

<p>While this can be beneficial, it may be slow for lots of files or over a network, so you may not want to use this one all the time. From one of the Server Fault answers:</p>

<blockquote>
  <p>This will build the entire file list at the beginning, rather than incrementally discovering more files as the transfer goes on. Since it will know all files before starting, it will give a better report of the overall progress. This applies to the number of files - it does not report any progress based on file sizes</p>

  <p>This involves a trade-off. Building the entire file list ahead of time is more memory-costly and it can significantly delay the start of the actual transfer. As you would expect, the more files there are, the longer the delay will be and the more memory it will require.</p>
</blockquote>

<p>I’ve found this pretty useful and fast enough most of the time, so I typically use it.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[A feature you may not know about recent versions of rsync is that you can display an overall progress of the transfer. And by “recent” I mean since version 3.1.0, released in September 2013. To use it, you want to add these options instead of -v and/or --progress: rsync --info=progress2 --human-readable --no-inc-recursive For example: &gt; rsync --info=progress2 --human-readable --no-inc-recursive -a /Applications /tmp 9.53G 21% 317.26MB/s 0:00:28 (xfr#83063, to-chk=443926/538653)]]></summary></entry><entry><title type="html">Improving Zsh Performance</title><link href="https://www.dribin.org/dave/blog/archives/2024/01/01/zsh-performance/" rel="alternate" type="text/html" title="Improving Zsh Performance" /><published>2024-01-01T16:00:00-06:00</published><updated>2024-01-01T16:00:00-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2024/01/01/zsh-performance</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2024/01/01/zsh-performance/"><![CDATA[<p><a href="https://www.zsh.org">Zsh</a> itself is a speedy shell, but it’s all too easy to blindly add stuff to its startup scripts and prompt that drastically slow it down. I’ve been using Zsh since around 2002 (narrator: that’s over 20 years ago, which is making me feel really old!), and my Zsh config has accumulated a lot of cruft. A few years back, there was a very noticeable delay when opening a new terminal tab where I’d stare at a blank screen for a bit. And worse, typing commands felt very sluggish even when the commands executed quickly.</p>

<p>Once I started digging into it, I found some great optimizations to make it fast, without losing any functionality. In fact, by the time I was done, I had a <em>much better</em> prompt than I previously had, yet it was orders of magnitude faster.</p>

<p>If you don’t want to read the whole post, the single best thing you can do is to use <a href="https://github.com/romkatv/powerlevel10k">Powerlevel10k</a>. And the next best thing is to avoid using <code class="language-plaintext highlighter-rouge">eval $(some other command)</code>, if possible. But read on for the details.</p>

<!--more-->

<h2 id="measuring-performance">Measuring Performance</h2>

<p>Before going into the changes I made, I need to talk about taking quantitative measurements. As with all optimizations, taking measurements is the first step. How do you measure the speed, and how do you know if you’ve improved anything? Fortunately, this is very easy with <a href="https://github.com/romkatv/zsh-bench"><code class="language-plaintext highlighter-rouge">zsh-bench</code></a>. Once you clone the <code class="language-plaintext highlighter-rouge">git</code> repository, you run the <code class="language-plaintext highlighter-rouge">zsh-bench</code> command, wait a bit, and it’ll print out some numbers. Here’s what mine first looked like:</p>

<!--- cSpell:disable --->
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>creates_tty=0
has_compsys=1
has_syntax_highlighting=0
has_autosuggestions=0
has_git_prompt=1
first_prompt_lag_ms=446.035
first_command_lag_ms=451.599
command_lag_ms=328.553
input_lag_ms=0.606
exit_time_ms=99.853
</code></pre></div></div>
<!--- cSpell:enable --->

<p>There’s a lot here, but there are two sets of important numbers. The first set is the shell startup time:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>first_prompt_lag_ms=446.035
first_command_lag_ms=451.599
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">first_prompt_lag_ms</code> is the time until you see a prompt. Basically, how long are you staring at a blank screen. This is almost a half a second! <code class="language-plaintext highlighter-rouge">first_command_lag_ms</code> is how long before you can actually type a command. In this case, they are pretty much the same.</p>

<p>The second set of important numbers is:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>command_lag_ms=328.553
input_lag_ms=0.606
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">command_lag_ms</code> is probably the most important number, which represents the time between one command completing and getting a prompt to start typing another command. You see this delay for <em>every</em> command you type, but also in the simplest case, when you just hit <code class="language-plaintext highlighter-rouge">Return</code> and wait until you get another prompt. 328ms here is very noticeable. <code class="language-plaintext highlighter-rouge">input_lag_ms</code> is the time in between each keystroke.</p>

<p>Both <code class="language-plaintext highlighter-rouge">first_prompt_lag_ms</code> and <code class="language-plaintext highlighter-rouge">command_lag_ms</code> were noticeably slow for me. Hundreds of milliseconds is easily perceptible. The <code class="language-plaintext highlighter-rouge">zsh-bench</code> <code class="language-plaintext highlighter-rouge">README</code> has numbers for “indistinguishable from zero”. For <code class="language-plaintext highlighter-rouge">first_prompt_lag_ms</code>, it is 50ms, and for <code class="language-plaintext highlighter-rouge">command_lag_ms</code>, it is 10ms. Both of my numbers were an order of magnitude above this at 446ms and 328ms, respectively</p>

<p>After making some changes, I was able to drastically improve these numbers:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>first_prompt_lag_ms=24.802
first_command_lag_ms=205.137

command_lag_ms=15.747
input_lag_ms=2.148
</code></pre></div></div>

<p>These are both very close to the “indistinguishable from zero” goals. And these numbers were on an Intel iMac Pro. On my shiny new M3 Max MacBook Pro, they clock in about twice as fast:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>first_prompt_lag_ms=16.288
first_command_lag_ms=100.066

command_lag_ms=7.247
input_lag_ms=1.318
</code></pre></div></div>

<p>Both numbers are now well under the “indistinguishable from zero” goals. Let’s dig into how I made this improvement.</p>

<h2 id="profiling">Profiling</h2>

<p>With a way to measure “what is slow?” and to measure if I was making things better, I needed a way to find out what part of my Zsh config was slow. It’s grown to hundreds of lines spread over many files, so it’s not possible to just intuit what is slow. Here are a number of resources I used:</p>

<!--- cSpell:ignore Esham --->
<ul>
  <li><a href="https://kevin.burke.dev/kevin/profiling-zsh-startup-time/">Profiling ZSH startup time</a>, by Kevin Burke</li>
  <li><a href="https://carlosbecker.com/posts/speeding-up-zsh/">Speeding up my ZSH load time</a>, by Carlos Becker</li>
  <li><a href="https://esham.io/2018/02/zsh-profiling">How to profile your zsh startup time</a>, by Benjamin Esham</li>
</ul>

<p>I found Kevin Burke’s page most helpful, and it boils down to adding a bit of code at the start of your <code class="language-plaintext highlighter-rouge">~/.zshenv</code>, as that is the <a href="https://shreevatsa.wordpress.com/2008/03/30/zshbash-startup-files-loading-order-bashrc-zshrc-etc/">first file in your home directory to run</a>, for interactive shells:</p>

<!--- cSpell:disable --->
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Profiling via:
# https://kev.inburke.com/kevin/profiling-zsh-startup-time/
: "${PROFILE_STARTUP:=false}"
: "${PROFILE_ALL:=false}"
# Run this to get a profile trace and exit: time zsh -i -c echo
# Or: time PROFILE_STARTUP=true /bin/zsh -i --login -c echo
if [[ "$PROFILE_STARTUP" == true || "$PROFILE_ALL" == true ]]; then
    # http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html
    PS4=$'%D{%H:%M:%S.%.} %N:%i&gt; '
    #zmodload zsh/datetime
    #PS4='+$EPOCHREALTIME %N:%i&gt; '
    exec 3&gt;&amp;2 2&gt;/tmp/zsh_profile.$$
    setopt xtrace prompt_subst
fi
# "unsetopt xtrace" is at the end of ~/.zshrc
</code></pre></div></div>
<!--- cSpell:enable --->

<p>This produces a file in named <code class="language-plaintext highlighter-rouge">/tmp/zsh_profile.&lt;pid&gt;</code> which contains every command run, along with a timestamp, down to the millisecond. From this, you can infer which commands are slow. Here’s an example:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>00:24:09.378 redacted:7&gt; computer_name=
00:24:09.379 redacted:7&gt; /usr/sbin/scutil --get ComputerName
00:24:09.378 redacted:7&gt; computer_name=guts
00:24:09.385 redacted:29&gt; redacted
</code></pre></div></div>

<p>It’s a bit convoluted, but you can see this <code class="language-plaintext highlighter-rouge">scutil</code> command takes 7ms to run: <code class="language-plaintext highlighter-rouge">09.385 - 09.378</code>. While this is not a lot, this is basically death by a thousand cuts, and you have to identify all these cases where you bleed out ~7ms or more.</p>

<h2 id="making-it-faster">Making it Faster</h2>

<p>Command lag was my priority, and the biggest slowdown, by far, was my <a href="https://git-scm.com">Git</a> status prompt. I was using the <code class="language-plaintext highlighter-rouge">git-prompt.sh</code> file found in the Git repository’s <a href="https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh"><code class="language-plaintext highlighter-rouge">contrib/</code> directory</a>. This runs multiple <code class="language-plaintext highlighter-rouge">git</code> commands and it turns out this gets <em>really</em> slow for large repositories.</p>

<p>I did a lot of searching for how to make my Git prompt faster, and eventually I found <a href="https://github.com/romkatv/gitstatus"><code class="language-plaintext highlighter-rouge">gitstatus</code></a>. This project is truly amazing. The author, <a href="https://github.com/romkatv">Roman</a>, is obsessed with performance. He also wrote <code class="language-plaintext highlighter-rouge">zsh-bench</code>. <code class="language-plaintext highlighter-rouge">gitstatus</code> uses a combination of tricks like async prompt updates and avoiding executing a separate executable by using a deamon to drastically speed up <code class="language-plaintext highlighter-rouge">git status</code>.</p>

<p>The easiest way to use <code class="language-plaintext highlighter-rouge">gitstatus</code> is to use <a href="https://github.com/romkatv/powerlevel10k">Powerlevel10k</a>, <em>also</em> written by Roman. I liked how my prompt was setup, and was a little reluctant to switch, but I’m glad I did. I won’t go into the details on my Powerlevel10k setup, but suffice to say, the speedup was impressive, and the benefits of Powerlevel10k don’t stop with Git status. Performance is the headlining feature of Powerlevel10k, and it shows.</p>

<p>It also turns out executing commands, any command, adds noticeable delay. There’s fixed overhead in spawning a process, so you want to avoid this, where possible.</p>

<p>I’m a big fan of <a href="https://direnv.net"><code class="language-plaintext highlighter-rouge">direnv</code></a>, but the way it works requires running a command as a pre-command hook, so it directly affects command lag. <code class="language-plaintext highlighter-rouge">direnv</code> adds about 5ms of command lag on my M3 Max MacBook Pro, but for me, it’s worth it. The total command lag of 8ms is still imperceptible. I wish there was a faster alternative which used the same tricks as <code class="language-plaintext highlighter-rouge">gitstatus</code>, but I don’t know of one.</p>

<p>While I am able to live with the <code class="language-plaintext highlighter-rouge">direnv</code> command lag, executing commands is more of an issue for shell startup time. For example, <a href="https://brew.sh">Homebrew</a> says you should add this to your shell startup:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>eval $(/opt/homebrew/bin/brew shellenv)
</code></pre></div></div>

<p>All this does is set some environment variables:</p>

<!--- cSpell:disable --->
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt; brew shellenv
export HOMEBREW_PREFIX="/opt/homebrew";
export HOMEBREW_CELLAR="/opt/homebrew/Cellar";
export HOMEBREW_REPOSITORY="/opt/homebrew";
export PATH="/opt/homebrew/bin:/opt/homebrew/sbin${PATH+:$PATH}";
export MANPATH="/opt/homebrew/share/man${MANPATH+:$MANPATH}:";
export INFOPATH="/opt/homebrew/share/info:${INFOPATH:-}";
</code></pre></div></div>
<!--- cSpell:enable --->

<p>However, this executes the command <code class="language-plaintext highlighter-rouge">brew</code>, just to set these environment variables. <code class="language-plaintext highlighter-rouge">brew</code> is written in Ruby, so this also has to startup the full Ruby runtime environment. The values of the environment variables almost never change. It’s <em>much</em> faster to just paste the output of <code class="language-plaintext highlighter-rouge">brew shellenv</code> directly into your <code class="language-plaintext highlighter-rouge">.zshrc</code>.</p>

<p>Similarly, <a href="https://github.com/rbenv/rbenv"><code class="language-plaintext highlighter-rouge">rbenv</code></a> recommends you <code class="language-plaintext highlighter-rouge">eval</code> the output of <code class="language-plaintext highlighter-rouge">rbenv init - zsh</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>echo 'eval "$(~/.rbenv/bin/rbenv init - zsh)"' &gt;&gt; ~/.zshrc
</code></pre></div></div>

<p>Again, this has to run an executable, and again, it is much faster to just paste the output into your <code class="language-plaintext highlighter-rouge">.zshrc</code>.</p>

<p>Another way to speed up startup is to run some stuff asynchronously and defer it out of the startup “hot path”. <a href="https://github.com/romkatv/zsh-defer"><code class="language-plaintext highlighter-rouge">zsh-defer</code></a> (also written by Roman) is one such way to do this. But Powerlevel10k has an Instant Prompt feature which builds upon this. By avoiding running commands and using Instant Prompt, my startup time is now quite fast.</p>

<h2 id="conclusion">Conclusion</h2>

<p>Hopefully this gives you some tips to speed up your Zsh config. Bringing startup time and especially command lag down from hundreds of milliseconds will make your shell feel <em>much</em> faster. Also, use Powerlevel10k. Between its Git prompt, Instant Prompt, and deferred startup features, it’s incredible.</p>

<!--- Links --->]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[Zsh itself is a speedy shell, but it’s all too easy to blindly add stuff to its startup scripts and prompt that drastically slow it down. I’ve been using Zsh since around 2002 (narrator: that’s over 20 years ago, which is making me feel really old!), and my Zsh config has accumulated a lot of cruft. A few years back, there was a very noticeable delay when opening a new terminal tab where I’d stare at a blank screen for a bit. And worse, typing commands felt very sluggish even when the commands executed quickly. Once I started digging into it, I found some great optimizations to make it fast, without losing any functionality. In fact, by the time I was done, I had a much better prompt than I previously had, yet it was orders of magnitude faster. If you don’t want to read the whole post, the single best thing you can do is to use Powerlevel10k. And the next best thing is to avoid using eval $(some other command), if possible. But read on for the details.]]></summary></entry><entry><title type="html">git Merge Commit Messages</title><link href="https://www.dribin.org/dave/blog/archives/2018/10/21/git-merge-commit-message/" rel="alternate" type="text/html" title="git Merge Commit Messages" /><published>2018-10-21T10:41:10-05:00</published><updated>2018-10-21T10:41:10-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2018/10/21/git-merge-commit-message</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2018/10/21/git-merge-commit-message/"><![CDATA[<p>The default <code class="language-plaintext highlighter-rouge">git</code> commit message for merge conflicts lists any files that were conflicts. However, it includes them as a comment with the <code class="language-plaintext highlighter-rouge">#</code> prefix. This means they’ll get stripped from the real commit message, by default. I like to keep them in the commit message, because it can useful to know which files were conficts later on. To do this, I would manually remove the comment prefix. Unitl now… TLDR: Use <code class="language-plaintext highlighter-rouge">git commit --cleanup scissors</code>, but the following example will explain how this works. I also answered this on <a href="https://stackoverflow.com/a/52902580">Stack Overflow</a>, but figured it would make a good blog post.</p>

<!--more-->

<p>When you use <code class="language-plaintext highlighter-rouge">git commit</code>, there are different cleanup modes which determine how the message is automatically cleaned up, specified by the <code class="language-plaintext highlighter-rouge">--cleanup</code> option. Here’s an excerpt from the <code class="language-plaintext highlighter-rouge">git-commit(1)</code> <a href="https://git-scm.com/docs/git-commit#git-commit---cleanupltmodegt">man page</a>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>       --cleanup=&lt;mode&gt;
           This option determines how the supplied commit message should be
           cleaned up before committing. The &lt;mode&gt; can be strip, whitespace,
           verbatim, scissors or default.

           strip
               Strip leading and trailing empty lines, trailing whitespace,
               commentary and collapse consecutive empty lines.

           whitespace
               Same as strip except #commentary is not removed.

           verbatim
               Do not change the message at all.

           scissors
               Same as whitespace except that everything from (and including)
               the line found below is truncated, if the message is to be
               edited. "#" can be customized with core.commentChar.

                   # ------------------------ &gt;8 ------------------------

           default
               Same as strip if the message is to be edited. Otherwise
               whitespace.

           The default can be changed by the commit.cleanup configuration
           variable (see git-config(1)).
</code></pre></div></div>

<p>The default mode is essentially <code class="language-plaintext highlighter-rouge">strip</code>. Here’s an example of a commit message with a merge conflict using <code class="language-plaintext highlighter-rouge">strip</code> mode:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>% git commit --cleanup strip 
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Merge branch 'branch'

# Conflicts:
#       baz.txt
#       foo.txt
#
# It looks like you may be committing a merge.
# If this is not correct, please remove the file
#       .git/MERGE_HEAD
# and try again.


# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch master
# All conflicts fixed but you are still merging.
#
# Changes to be committed:
#       modified:   bar.txt
#       modified:   baz.txt
#       modified:   foo.txt
#
</code></pre></div></div>

<p>As you can see, it shows the list of file conflicts. But if you just accept the defult message, the real commit message will be:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>% git log -1
commit 86cb4bbcc5f2ed54641a0f2a58a4b03bb73be0a3 (HEAD -&gt; master)
Merge: efd152d 474a8f4
Author: Dave Dribin &lt;dave@example.com&gt;
Date:   Fri Oct 19 23:38:47 2018 -0500

    Merge branch 'branch'
</code></pre></div></div>

<p>It stripped every line with the comment prefix, so you get a nice short message. However, that handy list of conflicts is missing. If you want them included, you need to remove the comment prefix. Let’s try that again with <code class="language-plaintext highlighter-rouge">scissors</code> mode:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>% git commit --cleanup scissors  
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Merge branch 'branch'

# Conflicts:
#       baz.txt
#       foo.txt
# ------------------------ &gt;8 ------------------------
# Do not modify or remove the line above.
# Everything below it will be ignored.
#
# It looks like you may be committing a merge.
# If this is not correct, please remove the file
#       .git/MERGE_HEAD
# and try again.


# Please enter the commit message for your changes. Lines starting
# with '#' will be kept; you may remove them yourself if you want to.
# An empty message aborts the commit.
#
# On branch master
# All conflicts fixed but you are still merging.
#
# Changes to be committed:
#       modified:   bar.txt
#       modified:   baz.txt
#       modified:   foo.txt
#
</code></pre></div></div>

<p>This time, if you accept the default commit message, you get the following commit message:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>% git log -1
commit 1eb84d98faf502e64f29ffca0766ad2e708aa61d (HEAD -&gt; master)
Merge: efd152d 474a8f4
Author: Dave Dribin &lt;dave@example.com&gt;
Date:   Fri Oct 19 23:43:32 2018 -0500

    Merge branch 'branch'
    
    # Conflicts:
    #       baz.txt
    #       foo.txt
</code></pre></div></div>

<p>The list of conflicts is included, even though they still start with the <code class="language-plaintext highlighter-rouge">#</code> prefix. This works because it will keep everything <em>before</em> the special “scissors” line, including the conflict list, despite them having a comment prefix. I found this so useful that I’ve changed my default cleanup mode to <code class="language-plaintext highlighter-rouge">scissors</code> by setting <code class="language-plaintext highlighter-rouge">commit.cleanup</code> in my <code class="language-plaintext highlighter-rouge">~/.gitconfig</code>.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[The default git commit message for merge conflicts lists any files that were conflicts. However, it includes them as a comment with the # prefix. This means they’ll get stripped from the real commit message, by default. I like to keep them in the commit message, because it can useful to know which files were conficts later on. To do this, I would manually remove the comment prefix. Unitl now… TLDR: Use git commit --cleanup scissors, but the following example will explain how this works. I also answered this on Stack Overflow, but figured it would make a good blog post.]]></summary></entry><entry><title type="html">Moving to HTTPS with Let’s Encrypt</title><link href="https://www.dribin.org/dave/blog/archives/2018/03/11/https-lets-encrypt/" rel="alternate" type="text/html" title="Moving to HTTPS with Let’s Encrypt" /><published>2018-03-11T10:45:07-05:00</published><updated>2018-03-11T10:45:07-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2018/03/11/https-lets-encrypt</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2018/03/11/https-lets-encrypt/"><![CDATA[<p>I recently moved my site, <a href="https://www.dribin.org">www.dribin.org</a>, over to HTTPS. For other HTTPS sites I’ve setup, I’ve bought a certificate from <a href="https://www.name.com">name.com</a>. Their <a href="https://www.name.com/ssl">cheapest option</a> is $10/year, which is very affordable. But this time I decided to try out <a href="https://letsencrypt.org">Let’s Encrypt</a> and their <a href="https://certbot.eff.org">Certbot</a>. The installation was pretty painless and seemed to go smoothly. I haven’t yet gone threw a renew cyle, though, which is required every three months. I’ll report back in June if I have problems.</p>

<p>This change did break all my embedded YouTube videos becuase those still used <code class="language-plaintext highlighter-rouge">http</code>. I needed to update the <code class="language-plaintext highlighter-rouge">iframe</code> URLs to also use <code class="language-plaintext highlighter-rouge">https</code>, and now all seems to be fine.</p>

<p>And finally, I updated all the links to my own site, replacing <code class="language-plaintext highlighter-rouge">http</code> with <code class="language-plaintext highlighter-rouge">https</code>. This wasn’t strictly necessary, as I have a redirect in place, but I figured it’d be nice to avoid the extra round trip for the redirect. I don’t think I’ve broken anything, but please <a href="https://www.dribin.org/dave/contact/">let me know</a> if you see anything wrong.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[I recently moved my site, www.dribin.org, over to HTTPS. For other HTTPS sites I’ve setup, I’ve bought a certificate from name.com. Their cheapest option is $10/year, which is very affordable. But this time I decided to try out Let’s Encrypt and their Certbot. The installation was pretty painless and seemed to go smoothly. I haven’t yet gone threw a renew cyle, though, which is required every three months. I’ll report back in June if I have problems. This change did break all my embedded YouTube videos becuase those still used http. I needed to update the iframe URLs to also use https, and now all seems to be fine. And finally, I updated all the links to my own site, replacing http with https. This wasn’t strictly necessary, as I have a redirect in place, but I figured it’d be nice to avoid the extra round trip for the redirect. I don’t think I’ve broken anything, but please let me know if you see anything wrong.]]></summary></entry><entry><title type="html">Linode Recommendation</title><link href="https://www.dribin.org/dave/blog/archives/2017/05/10/linode-recommendation/" rel="alternate" type="text/html" title="Linode Recommendation" /><published>2017-05-10T22:42:22-05:00</published><updated>2017-05-10T22:42:22-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2017/05/10/linode-recommendation</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2017/05/10/linode-recommendation/"><![CDATA[<p>I’ve been using <a href="https://www.linode.com">Linode</a> since about 2012, and I cannot recommend them enough. A few months ago, <a href="https://blog.linode.com/2017/02/14/high-memory-instances-and-5-linodes/">they announced</a> a cheaper $5/month plan. I recently switched to that, and saved a bunch of money. I pay for their backup plan, so the total is $7/month. On their previouls plan, I was paying $25/month. I was worried the downgraded specs would be a problem. Then again, I don’t get much traffic these days. I’ve been running on this downgraded server a couple months ago, and it’s working perfectly fine. A static website doesn’t require that much CPU or memory.</p>

<p>The downside is that you need to do all your own admin yourself. But I find it’s not that hard to setup Apache and some email services. If you’re willing (or wanting) to get your hands a bit dirty, Linode is great. If you want to give them a shot, you can try them out with my referral code: <a href="https://www.linode.com/?r=fb7465a0d5bef7335873ccdfc31bb8d3367c1945">fb7465a0d5bef7335873ccdfc31bb8d3367c1945</a></p>

<p>It’s actually pretty amazing at how cheap hosting has become. When I first started hosting my own domain back in 2002, I used a colocation service. I supplied the Linux box, and for $100/month, I was ready to go with full root access. At the end of 2003, the hard drive on that machine died, and I moved my hosting to Server Matrix for $60/month. This was a dedicated physical server, but I did not own it. The upside is that if a disk died, I wasn’t responsbile for fixing it. And I still had full root access to install whatever I wanted. I jumped to a few hosting providers around this time, some via acquisition. By 2012, I was paying $70/month on SoftLayer.</p>

<p>But virtual private servers were becoming more popular around this time, and I didn’t <em>need</em> my own physical server. The cheapest Linode plan was only $20/month. So in 2012, I switched to Linode. Adding in $5 for backup, it was $25/month. But that was still <em>way</em> cheaper than SoftLayer. And now, with the new price reduction, I’m down to $7/month. And that’s quick summary of how, in the span of 15 years, my hosting costs have gone from $100/month down to $7/month, all with full root access. And I couldn’t be happier!</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[I’ve been using Linode since about 2012, and I cannot recommend them enough. A few months ago, they announced a cheaper $5/month plan. I recently switched to that, and saved a bunch of money. I pay for their backup plan, so the total is $7/month. On their previouls plan, I was paying $25/month. I was worried the downgraded specs would be a problem. Then again, I don’t get much traffic these days. I’ve been running on this downgraded server a couple months ago, and it’s working perfectly fine. A static website doesn’t require that much CPU or memory. The downside is that you need to do all your own admin yourself. But I find it’s not that hard to setup Apache and some email services. If you’re willing (or wanting) to get your hands a bit dirty, Linode is great. If you want to give them a shot, you can try them out with my referral code: fb7465a0d5bef7335873ccdfc31bb8d3367c1945 It’s actually pretty amazing at how cheap hosting has become. When I first started hosting my own domain back in 2002, I used a colocation service. I supplied the Linux box, and for $100/month, I was ready to go with full root access. At the end of 2003, the hard drive on that machine died, and I moved my hosting to Server Matrix for $60/month. This was a dedicated physical server, but I did not own it. The upside is that if a disk died, I wasn’t responsbile for fixing it. And I still had full root access to install whatever I wanted. I jumped to a few hosting providers around this time, some via acquisition. By 2012, I was paying $70/month on SoftLayer. But virtual private servers were becoming more popular around this time, and I didn’t need my own physical server. The cheapest Linode plan was only $20/month. So in 2012, I switched to Linode. Adding in $5 for backup, it was $25/month. But that was still way cheaper than SoftLayer. And now, with the new price reduction, I’m down to $7/month. And that’s quick summary of how, in the span of 15 years, my hosting costs have gone from $100/month down to $7/month, all with full root access. And I couldn’t be happier!]]></summary></entry><entry><title type="html">Switching to Jekyll</title><link href="https://www.dribin.org/dave/blog/archives/2017/02/27/switching_to_jekyll/" rel="alternate" type="text/html" title="Switching to Jekyll" /><published>2017-02-27T08:53:01-06:00</published><updated>2017-02-27T08:53:01-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2017/02/27/switching_to_jekyll</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2017/02/27/switching_to_jekyll/"><![CDATA[<p>After many years of faithfully using <a href="http://www.movabletype.org/">Movable Type</a>, I have finally switched to another blogging system: <a href="https://jekyllrb.com/">Jekyll</a>. I’ve been meaning to move off Movable Type for literally years, since they dropped <a href="http://www.sqlite.org/">SQLite</a> support <a href="http://www.movabletype.org/documentation/database/migrate-sqlite-postgresql.html">in version 5</a>, released in 2010. Jekyll meets everything I laid out in my 2009 post, <a href="https://www.dribin.org/dave/blog/archives/2009/12/04/new_blog_requirements/">Requirements for a New Blogging System</a>.  What finally pushed me to switch was my desire to write some new posts and fix some of the link rot, such as the <a href="https://www.dribin.org/dave/blog/archives/2011/04/05/unit_test_c4/">link to my C4[3] slides</a>.</p>

<p>After my server died in 2012, I was able to bring over the static content to the new server just fine with a simple <code class="language-plaintext highlighter-rouge">rysnc</code>. That alone is a huge testament to static content. However, I had no desire to try and get an old version of Movable Type up and running, which meant I could no longer edit posts or create new ones.</p>

<p>I tried twice to switch to <a href="http://octopress.org/">Octopress</a>, once in 2012 and again in 2013, but I kept running into various snags. It’s a good think I waited because Octoproess has been pretty stagnant since then. Octopress is basically a customized Jekyll setup, and since 2013, Jekyll has improved enough on its own that I am able to use it straight-up.</p>

<p>I’m now up and running on Jekyll and fixed the link to my slides. The installation went pretty smoothly, and everything seems to look okay. If not, please <a href="https://www.dribin.org/dave/contact/">let me know</a>. Right now, this is just the standard Jekyll install with a slightly tweaked <a href="https://github.com/jekyll/minima">Minima theme</a>, but I’d like to customize it a bit more at some point.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[After many years of faithfully using Movable Type, I have finally switched to another blogging system: Jekyll. I’ve been meaning to move off Movable Type for literally years, since they dropped SQLite support in version 5, released in 2010. Jekyll meets everything I laid out in my 2009 post, Requirements for a New Blogging System. What finally pushed me to switch was my desire to write some new posts and fix some of the link rot, such as the link to my C4[3] slides. After my server died in 2012, I was able to bring over the static content to the new server just fine with a simple rysnc. That alone is a huge testament to static content. However, I had no desire to try and get an old version of Movable Type up and running, which meant I could no longer edit posts or create new ones. I tried twice to switch to Octopress, once in 2012 and again in 2013, but I kept running into various snags. It’s a good think I waited because Octoproess has been pretty stagnant since then. Octopress is basically a customized Jekyll setup, and since 2013, Jekyll has improved enough on its own that I am able to use it straight-up. I’m now up and running on Jekyll and fixed the link to my slides. The installation went pretty smoothly, and everything seems to look okay. If not, please let me know. Right now, this is just the standard Jekyll install with a slightly tweaked Minima theme, but I’d like to customize it a bit more at some point.]]></summary></entry><entry><title type="html">My Unit Testing C4[3] Presentation</title><link href="https://www.dribin.org/dave/blog/archives/2011/04/05/unit_test_c4/" rel="alternate" type="text/html" title="My Unit Testing C4[3] Presentation" /><published>2011-04-05T21:12:04-05:00</published><updated>2011-04-05T21:12:04-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2011/04/05/unit_test_c4</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2011/04/05/unit_test_c4/"><![CDATA[<p>I should have posted this literally years ago.  <strike>Since I just learned that Keynote can easily publish presentations to <a href="http://www.iwork.com/">iWork.com</a>, I figure I have no excuse.</strike> iWork.com is dead.  Thus, here’s my C4[3] presentation on unit testing: <a href="https://www.dribin.org/dave/resources/files/2011/DaveDribin-UnitTesting-C4-3.pdf">DaveDribin-UnitTesting-C4-3.pdf</a></p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[I should have posted this literally years ago. Since I just learned that Keynote can easily publish presentations to iWork.com, I figure I have no excuse. iWork.com is dead. Thus, here’s my C4[3] presentation on unit testing: DaveDribin-UnitTesting-C4-3.pdf]]></summary></entry><entry><title type="html">Joining Apple</title><link href="https://www.dribin.org/dave/blog/archives/2010/10/01/joining_apple/" rel="alternate" type="text/html" title="Joining Apple" /><published>2010-10-01T18:09:19-05:00</published><updated>2010-10-01T18:09:19-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/10/01/joining_apple</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/10/01/joining_apple/"><![CDATA[<p>Next week, I fly out to Cupertino to start working at <a href="http://www.apple.com/">Apple</a> as a full time employee.  This is a big move for me, as I’ve been working for myself since 2001.  But this is truly a once-in-a-lifetime opportunity that I cannot pass up.  As is the case for a lot of people my age, I began my computing experience on an <a href="http://en.wikipedia.org/wiki/Apple_II_series">Apple ][</a> and have been a huge fan of Apple ever since (with a slight defection to Linux in the late 90s and early 00s).  Apple-related technology (Mac OS X and iOS) has been my main source of income since around 2006, so in many ways, this is a dream come true.  I’m very excited to work with a great team and for a great company.</p>

<!--more-->

<p>Because everything needs an FAQ:</p>

<h3>What will you be working on?</h3>

<p>I’m not sure that I can say, just yet. But it will involve heavy amounts of coding in Objective-C.</p>

<h3>So you're moving to California?</h3>

<p>Nope.  I’ll be staying right here in Chicago.</p>

<h3>Will you still be writing The Road to Code for MacTech Magazine?</h3>

<p>Unfortunately, I will be unable to continue writing <em>The Road to Code</em> for <a href="http://www.mactech.com/">MacTech</a>, and I’ve already submitted my last article.  It has been an amazing <a href="https://www.dribin.org/dave/blog/archives/2007/07/05/road_to_code/">three years</a>, and I am truly grateful to have worked with MacTech.</p>

<h3>What about public speaking?</h3>

<p>I will also be unavailable for future speaking engagements.  I’ve already had to turn down opportunities to speak at <a href="http://www.voicesthatmatter.com/">Voices that Matter</a>, the <a href="http://www.mactech.com/conference/about">MacTech conference</a>, and <a href="http://www.secondconf.com/">SecondConf</a>.  I’m sure I will be an attendee at a number of the conferences, though, and I plan to stay active in the community as much as possible.</p>

<h3>What does this mean for Bit Maki and Textcast?</h3>

<p>This is still preliminary and in progress, but Bit Maki Software, Inc., the joint company between <a href="http://rentzsch.tumblr.com/">Jonathan Rentzsch</a> and I, is in process of being dissolved.  I plan to keep Bit Maki, Inc., my contracting company, alive for now, though I will not be doing any more contracting.  <a href="http://www.bitmaki.com/textcast/">Textcast</a> will become free and be available from the Bit Maki website.</p>

<h3>What's the future of MAME OS X?</h3>

<p>It has been a few  years since I’ve been able to dedicate much time towards <a href="http://mameosx.sourceforge.net/">MAME OS X,</a> and this is the nail in the coffin.  I will not be able to contribute to MAME OS X.  If anyone want’s to pick up the effort, please <a href="https://www.dribin.org/dave/contact/">let me know</a>.  This also goes for most of my other <a href="https://www.dribin.org/dave/software/">open source software</a>.  Truth be told, with <a href="https://www.dribin.org/dave/blog/archives/2010/09/16/lily_and_zach/">the two recent additions to our family</a>, I’m going to be sufficiently distracted for a while, anyways.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="personal" /><summary type="html"><![CDATA[Next week, I fly out to Cupertino to start working at Apple as a full time employee. This is a big move for me, as I’ve been working for myself since 2001. But this is truly a once-in-a-lifetime opportunity that I cannot pass up. As is the case for a lot of people my age, I began my computing experience on an Apple ][ and have been a huge fan of Apple ever since (with a slight defection to Linux in the late 90s and early 00s). Apple-related technology (Mac OS X and iOS) has been my main source of income since around 2006, so in many ways, this is a dream come true. I’m very excited to work with a great team and for a great company.]]></summary></entry><entry><title type="html">Welcome Lily and Zach Dribin</title><link href="https://www.dribin.org/dave/blog/archives/2010/09/16/lily_and_zach/" rel="alternate" type="text/html" title="Welcome Lily and Zach Dribin" /><published>2010-09-16T22:04:51-05:00</published><updated>2010-09-16T22:04:51-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/09/16/lily_and_zach</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/09/16/lily_and_zach/"><![CDATA[<p>My wife and I recently brought home two new additions to the Ross-Dribin family: Lily and Zach! All four of us are doing great, but everything since then has been a blur.</p>

<p><img src="https://www.dribin.org/dave/resources/images/2010/lily_and_zach.jpg" width="640" height="427" /></p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="personal" /><summary type="html"><![CDATA[My wife and I recently brought home two new additions to the Ross-Dribin family: Lily and Zach! All four of us are doing great, but everything since then has been a blur.]]></summary></entry><entry><title type="html">trigint - An Integer-based Trigonometry Library</title><link href="https://www.dribin.org/dave/blog/archives/2010/08/15/announcing_trigint/" rel="alternate" type="text/html" title="trigint - An Integer-based Trigonometry Library" /><published>2010-08-15T10:06:26-05:00</published><updated>2010-08-15T10:06:26-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/08/15/announcing_trigint</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/08/15/announcing_trigint/"><![CDATA[<p>Back when I was writing the <a href="https://www.dribin.org/dave/blog/archives/2010/04/26/announcing_a440/">A440 sample code</a> for my <a href="https://www.dribin.org/dave/blog/archives/2010/05/02/ipad_dev_camp_slides/">iPad Dev Camp presentation</a>, I needed to generate a 440 Hz sine wave.  The simplest way to do this is to use the sin() or sinf() standard C library functions.  But there was one minor caveat: these functions required using floating point data types.  However, floating point on the iPhone hardware is (or at least was) not that fast compared to integer calculations, especially when compiled in Thumb mode, which is the default.  You could disable Thumb mode, but then the code size would be ~35% larger.</p>

<p>Or, you could avoid floating point altogether.  Thus, I wrote trigint, a 100% integer-based trigonometry library.  It uses a 16-entry lookup table plus <a href="http://en.wikipedia.org/wiki/Linear_interpolation">linear interpolation</a> so it’s quite memory efficient, yet still <a href="https://www.dribin.org/dave/trigint/accuracy.html">accurate</a> enough for most purposes. Since it’s written in ANSI C99, it can be used on 8-bit microcontrollers, like an <a href="http://www.atmel.com/products/avr/">Atmel AVR</a> with <a href="http://www.avrfreaks.net/wiki/index.php/Documentation:AVR_GCC">avr-gcc</a>.  Here’s the <a href="http://bitbucket.org/ddribin/trigint">code</a> and the <a href="https://www.dribin.org/dave/trigint/">API documentation</a>.</p>

<p>How fast is it? Take a look at the <a href="https://www.dribin.org/dave/trigint/performance-ios.html">numbers on a 1st generation iPod Touch</a>.  In summary, <code class="language-plaintext highlighter-rouge">trigint_sin16()</code> is about 4.4 times faster than <code class="language-plaintext highlighter-rouge">sinf()</code> and 6.7 times faster than <code class="language-plaintext highlighter-rouge">sin()</code> in Thumb mode. Without Thumb mode, the gap closes a bit to 3.8 times faster and 6.2 times faster, respectively.  I haven’t, yet run the benchmark on the iPhone 4 or the iPad, so it may not matter as much on the more modern hardware; however, it’s still useful for the the 8-bit MCUs like the AVR, though.</p>

<p>trigint is essentially a C version of the Scott Dattalo’s <a href="http://www.dattalo.com/technical/software/pic/picsine.html">sine wave routine for the PIC microcontroller</a>. Credit goes to Scott for coming up with the algorithm. He’s also got a whole write up of <a href="http://www.dattalo.com/technical/theory/sinewave.html">sine wave theory</a>. Scott is one of the most brilliant assembly coders I’ve ever run into.  He <a href="http://www.dattalo.com/technical/software/pic/crc_8005.asm">helped me </a>optimize a <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check">CRC-16</a> routine in <a href="http://www.dattalo.com/technical/software/pic/crc.php">PIC assembly</a>, years ago.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[Back when I was writing the A440 sample code for my iPad Dev Camp presentation, I needed to generate a 440 Hz sine wave. The simplest way to do this is to use the sin() or sinf() standard C library functions. But there was one minor caveat: these functions required using floating point data types. However, floating point on the iPhone hardware is (or at least was) not that fast compared to integer calculations, especially when compiled in Thumb mode, which is the default. You could disable Thumb mode, but then the code size would be ~35% larger. Or, you could avoid floating point altogether. Thus, I wrote trigint, a 100% integer-based trigonometry library. It uses a 16-entry lookup table plus linear interpolation so it’s quite memory efficient, yet still accurate enough for most purposes. Since it’s written in ANSI C99, it can be used on 8-bit microcontrollers, like an Atmel AVR with avr-gcc. Here’s the code and the API documentation. How fast is it? Take a look at the numbers on a 1st generation iPod Touch. In summary, trigint_sin16() is about 4.4 times faster than sinf() and 6.7 times faster than sin() in Thumb mode. Without Thumb mode, the gap closes a bit to 3.8 times faster and 6.2 times faster, respectively. I haven’t, yet run the benchmark on the iPhone 4 or the iPad, so it may not matter as much on the more modern hardware; however, it’s still useful for the the 8-bit MCUs like the AVR, though. trigint is essentially a C version of the Scott Dattalo’s sine wave routine for the PIC microcontroller. Credit goes to Scott for coming up with the algorithm. He’s also got a whole write up of sine wave theory. Scott is one of the most brilliant assembly coders I’ve ever run into. He helped me optimize a CRC-16 routine in PIC assembly, years ago.]]></summary></entry><entry><title type="html">My Chiptune Cover of Don’t Stop Believin’</title><link href="https://www.dribin.org/dave/blog/archives/2010/07/18/dont_stop/" rel="alternate" type="text/html" title="My Chiptune Cover of Don’t Stop Believin’" /><published>2010-07-18T09:27:17-05:00</published><updated>2010-07-18T09:27:17-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/07/18/dont_stop</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/07/18/dont_stop/"><![CDATA[<p>Here’s a <a href="http://en.wikipedia.org/wiki/Chiptune">chiptune</a> cover of Journey’s <em>Don’t Stop Believin’</em> I made during some time off I had last December.  I just haven’t gotten around to posting it until now (though I did make a few tweaks yesterday).  I think we were watching Glee at the time and remember thinking a chiptune version would be even better than theirs.  It was made with <a href="http://famitracker.shoodot.net/">FamiTracker</a>, and this video is of the song being played in FamiTracker:</p>

<p><a href="https://www.youtube.com/watch?v=LZBo4vLguOA"><img src="/dave/blog/assets/images/dont-stop-thumb-560x315.png" width="560" height="315" /></a></p>

<p>You can listen to and download the MP3 from <a href="http://8bc.org/music/ddribin/Don%27t+Stop+Believin%27+%28NES+Remake%29/">its 8bitcollective page</a>.  Or download <a href="https://www.dribin.org/dave/resources/files/2010/Don%27t%20Stop%20Believin%27.nsf">the NSF</a> (<a href="http://en.wikipedia.org/wiki/NES_Sound_Format">what’s an NSF?</a>) and play it in an NSF player, such as my own <a href="http://bitbucket.org/ddribin/chip-player">Chip Player</a>. Or perhaps something a bit more stable like <a href="http://www.bannister.org/software/ao.htm">Audio Overload</a>.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="music" /><category term="tech" /><summary type="html"><![CDATA[Here’s a chiptune cover of Journey’s Don’t Stop Believin’ I made during some time off I had last December. I just haven’t gotten around to posting it until now (though I did make a few tweaks yesterday). I think we were watching Glee at the time and remember thinking a chiptune version would be even better than theirs. It was made with FamiTracker, and this video is of the song being played in FamiTracker: You can listen to and download the MP3 from its 8bitcollective page. Or download the NSF (what’s an NSF?) and play it in an NSF player, such as my own Chip Player. Or perhaps something a bit more stable like Audio Overload.]]></summary></entry><entry><title type="html">Fun with C99 Syntax</title><link href="https://www.dribin.org/dave/blog/archives/2010/05/15/c99_syntax/" rel="alternate" type="text/html" title="Fun with C99 Syntax" /><published>2010-05-15T08:52:20-05:00</published><updated>2010-05-15T08:52:20-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/05/15/c99_syntax</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/05/15/c99_syntax/"><![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/C99">C99</a> language added some pretty neat features to the ANSI C we know and love (now known as C89).  I used a construct called <a href="http://www.drdobbs.com/cpp/184401404">compound literals</a> in my <a href="https://www.dribin.org/dave/blog/archives/2010/05/02/ipad_dev_camp_slides/">iPad Dev Camp presentation</a>, and it seemed new to a lot of people.  Here’s a summary of some lesser know features about C99 that are worth knowing.  And, since Objective-C is a strict superset of C, all this applies to Objective-C, as well.  Best of all, as of recent Xcode (3.0? 3.1?), C99 is the default C dialect for new projects, so you don’t need to do anything to start taking advantage of these.</p>

<!--more-->

<h3 id="structure-initialization">Structure Initialization</h3>

<p>Structure initialization received a lot of love in C99.  In C89, you could initialize a structure variable like this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">NSPoint</span> <span class="n">point</span> <span class="o">=</span> <span class="p">{</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">};</span>
</code></pre></div></div>

<p>The caveat here is that the structure elements must be provided in the order that they are listed in the definition.  In this case, <code>NSPoint</code> is declared as like:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">typedef</span> <span class="k">struct</span> <span class="n">_NSPoint</span> <span class="p">{</span>
        <span class="n">CGFloat</span> <span class="n">x</span><span class="p">;</span>
        <span class="n">CGFloat</span> <span class="n">y</span><span class="p">;</span>
    <span class="p">}</span> <span class="n">NSPoint</span><span class="p">;</span>
</code></pre></div></div>

<p>So, when we initialize a variable, <code>x</code> comes first, followed by <code>y</code>.  This can be a drawback because if the order in the definition ever changed, all existing code that depended on the order would break. As of C99, you can initialize a structure by specifying the structure element names:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">NSPoint</span> <span class="n">point</span> <span class="o">=</span> <span class="p">{</span> <span class="p">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="p">.</span><span class="n">y</span> <span class="o">=</span> <span class="mi">0</span><span class="p">};</span>
</code></pre></div></div>

<p>This not only decouples the order of the definition from the order of the initialization, but it’s more readable.  As an added benefit, any structure elements not initialized are set to zero.  This means you only need to fill out the portions of the structure that are relevant.  And if new elements to the structure are added in later versions, they get initialized to a known value.</p>

<p>The benefit of this becomes even more clear for nested structures like <code>NSRect</code>:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">typedef</span> <span class="k">struct</span> <span class="n">_NSRect</span> <span class="p">{</span>
        <span class="n">NSPoint</span> <span class="n">origin</span><span class="p">;</span>
        <span class="n">NSSize</span> <span class="n">size</span><span class="p">;</span>
    <span class="p">}</span> <span class="n">NSRect</span><span class="p">;</span>
</code></pre></div></div>

<p>To initialize an <code>NSRect</code> in straight C89 looked something like this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">NSRect</span> <span class="n">rect</span> <span class="o">=</span> <span class="p">{{</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">},</span> <span class="p">{</span><span class="mi">640</span><span class="p">,</span> <span class="mi">480</span><span class="p">}};</span>
</code></pre></div></div>

<p>Because this is kind of awkward, there’s a function to make this a bit easier:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">NSRect</span> <span class="n">rect</span> <span class="o">=</span> <span class="n">NSMakeRect</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">640</span><span class="p">,</span> <span class="mi">480</span><span class="p">);</span>
</code></pre></div></div>

<p>But, honestly, that’s not much of an improvement in readability.  <code>NSMakeRect</code> is more useful in structure assignment, but we’ll see an alternate way to do this below.  With C99, we can initialize this variable like:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">NSRect</span> <span class="n">rect</span> <span class="o">=</span> <span class="p">{</span>
        <span class="p">.</span><span class="n">origin</span><span class="p">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
        <span class="p">.</span><span class="n">origin</span><span class="p">.</span><span class="n">y</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
        <span class="p">.</span><span class="n">size</span><span class="p">.</span><span class="n">width</span> <span class="o">=</span> <span class="mi">640</span><span class="p">,</span>
        <span class="p">.</span><span class="n">size</span><span class="p">.</span><span class="n">height</span> <span class="o">=</span> <span class="mi">480</span><span class="p">,</span>
    <span class="p">};</span>
</code></pre></div></div>

<p>Again, we can order the structure elements however we please; we’re not required to list them in the order of the definition.  We have some flexibility in how we assign the nested structures, too.  This is also legal:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">NSRect</span> <span class="n">rect</span> <span class="o">=</span> <span class="p">{</span>
        <span class="p">.</span><span class="n">origin</span> <span class="o">=</span> <span class="p">{.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="p">.</span><span class="n">y</span> <span class="o">=</span> <span class="mi">0</span><span class="p">},</span>
        <span class="p">.</span><span class="n">size</span> <span class="o">=</span> <span class="p">{.</span><span class="n">width</span> <span class="o">=</span> <span class="mi">640</span><span class="p">,</span> <span class="p">.</span><span class="n">height</span> <span class="o">=</span> <span class="mi">480</span><span class="p">},</span>
    <span class="p">};</span>
</code></pre></div></div>

<p>As as this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">NSRect</span> <span class="n">rect</span> <span class="o">=</span> <span class="p">{</span>
        <span class="p">.</span><span class="n">origin</span> <span class="o">=</span> <span class="n">NSMakePoint</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">),</span>
        <span class="p">.</span><span class="n">size</span> <span class="o">=</span> <span class="n">NSMakeSize</span><span class="p">(</span><span class="mi">640</span><span class="p">,</span> <span class="mi">480</span><span class="p">),</span>
    <span class="p">};</span>
</code></pre></div></div>

<p>And even this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">NSRect</span> <span class="n">rect</span> <span class="o">=</span> <span class="p">{</span>
        <span class="p">.</span><span class="n">origin</span> <span class="o">=</span> <span class="n">otherRect</span><span class="p">.</span><span class="n">origin</span><span class="p">,</span>
        <span class="p">.</span><span class="n">size</span> <span class="o">=</span> <span class="n">NSMakeSize</span><span class="p">(</span><span class="mi">640</span><span class="p">,</span> <span class="mi">480</span><span class="p">),</span>
    <span class="p">};</span>
</code></pre></div></div>

<p>So, as you can see, we get a lot more flexibility on how to initialize structures.</p>

<h3 id="compound-literals-for-structure-assignment">Compound Literals for Structure Assignment</h3>

<p>This new syntax of initializing structure variables is great, but it doesn’t help us much for assigning to existing structure variables.  The example I used in my iPad Dev Camp talk was setting up a <code>AudioStreamBasicDescription</code> structure, colloquially known as <code>ASBD</code>.  This structure is used to describe an audio format for <a href="http://developer.apple.com/mac/library/documentation/MusicAudio/Conceptual/CoreAudioOverview/Introduction/Introduction.html">Core Audio</a>.  In this case, I had an <code>ASBD</code> instance variable.  Because it’s an instance variable, you cannot set its value using the initialization syntax above.  Thus, the traditional way to initialize one of these it to clear out it to zero with <code>memset</code>, and then set the fields you need, one by one:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">memset</span><span class="p">(</span><span class="o">&amp;</span><span class="n">_dataFormat</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">_dataFormat</span><span class="p">));</span>
    <span class="n">_dataFormat</span><span class="p">.</span><span class="n">mFormatID</span> <span class="o">=</span> <span class="n">kAudioFormatLinearPCM</span><span class="p">;</span>
    <span class="n">_dataFormat</span><span class="p">.</span><span class="n">mSampleRate</span> <span class="o">=</span> <span class="n">SAMPLE_RATE</span><span class="p">;</span>
    <span class="n">_dataFormat</span><span class="p">.</span><span class="n">mBitsPerChannel</span> <span class="o">=</span> <span class="mi">16</span><span class="p">;</span>
    <span class="c1">// And on and on...</span>
</code></pre></div></div>

<p>Using new C99 syntax known as a <a href="http://www.drdobbs.com/cpp/184401404">compound literal</a>, you can set an existing structure variable like this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">_dataFormat</span> <span class="o">=</span> <span class="p">(</span><span class="n">AudioStreamBasicDescription</span><span class="p">)</span> <span class="p">{</span>
        <span class="p">.</span><span class="n">mFormatID</span> <span class="o">=</span> <span class="n">kAudioFormatLinearPCM</span><span class="p">,</span>
        <span class="p">.</span><span class="n">mSampleRate</span> <span class="o">=</span> <span class="n">SAMPLE_RATE</span><span class="p">,</span>
        <span class="p">.</span><span class="n">mBitsPerChannel</span> <span class="o">=</span> <span class="mi">16</span><span class="p">,</span>
        <span class="c1">// And on and on...</span>
    <span class="p">};</span>
</code></pre></div></div>

<p>It looks similar to a cast plus an initialization.  And under the hood, the compiler is making a anonymous variable.  So you can think of the above as equivalent to:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">AudioStreamBasicDescription</span> <span class="n">anon</span> <span class="o">=</span> <span class="p">{</span>
        <span class="p">.</span><span class="n">mFormatID</span> <span class="o">=</span> <span class="n">kAudioFormatLinearPCM</span><span class="p">,</span>
        <span class="p">.</span><span class="n">mSampleRate</span> <span class="o">=</span> <span class="n">SAMPLE_RATE</span><span class="p">,</span>
        <span class="p">.</span><span class="n">mBitsPerChannel</span> <span class="o">=</span> <span class="mi">16</span><span class="p">,</span>
        <span class="c1">// And on and on...</span>
    <span class="p">};</span>
    <span class="n">_dataFormat</span> <span class="o">=</span> <span class="n">anon</span><span class="p">;</span>
</code></pre></div></div>

<p>Again, the nice thing here as that unset fields are initialized to zero, so you get the equivalent of the <code>memset</code>.  Plus, you don’t have to repeat the variable name over and over again.</p>

<p>Oh, and as a quick shorthand for setting the entire structure to zero, you can do something like this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">_dataFormat</span> <span class="o">=</span> <span class="p">(</span><span class="n">AudioStreamBasicDescription</span><span class="p">)</span> <span class="p">{</span><span class="mi">0</span><span class="p">};</span>
</code></pre></div></div>

<h3 id="compound-literals-with-primitives">Compound Literals with Primitives</h3>

<p>Compound literals can be applied to primitive types, too.  Most of the time this is not much use:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="p">(</span><span class="kt">int</span><span class="p">)</span> <span class="p">{</span><span class="mi">3</span><span class="p">};</span>
</code></pre></div></div>

<p>But because these are anonymous variables, you can take the address of them:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="kt">int</span> <span class="o">*</span> <span class="n">iPointer</span> <span class="o">=</span> <span class="o">&amp;</span><span class="p">(</span><span class="kt">int</span><span class="p">)</span> <span class="p">{</span><span class="mi">3</span><span class="p">};</span>
</code></pre></div></div>

<p>This can be useful for some Core Audio APIs, such as <code>AudioUnitSetProperty</code>.  Typically you create a variable for the sole purpose of taking the address of it:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">UInt32</span> <span class="n">maxFramesPerSlice</span> <span class="o">=</span> <span class="mi">4096</span><span class="p">;</span>
    <span class="n">AudioUnitSetProperty</span><span class="p">(</span><span class="n">converterAudioUnit</span><span class="p">,</span>
                         <span class="n">kAudioUnitProperty_MaximumFramesPerSlice</span><span class="p">,</span>
                         <span class="n">kAudioUnitScope_Global</span><span class="p">,</span>
                         <span class="mi">0</span><span class="p">,</span>
                         <span class="o">&amp;</span><span class="n">maxFramesPerSlice</span><span class="p">,</span>
                         <span class="k">sizeof</span><span class="p">(</span><span class="n">UInt32</span><span class="p">));</span>
</code></pre></div></div>

<p>Using compound literals, we can do this inline without an extra variable:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">AudioUnitSetProperty</span><span class="p">(</span><span class="n">converterAudioUnit</span><span class="p">,</span>
                         <span class="n">kAudioUnitProperty_MaximumFramesPerSlice</span><span class="p">,</span>
                         <span class="n">kAudioUnitScope_Global</span><span class="p">,</span>
                         <span class="mi">0</span><span class="p">,</span>
                         <span class="o">&amp;</span><span class="p">(</span><span class="n">UInt32</span><span class="p">)</span> <span class="p">{</span><span class="mi">4096</span><span class="p">},</span>
                         <span class="k">sizeof</span><span class="p">(</span><span class="n">UInt32</span><span class="p">));</span>
</code></pre></div></div>

<h3 id="conclusion">Conclusion</h3>

<p>While C99 was a relatively minor update to C89, there are quite a few gems buried away to make our code more flexible and readable, as you can see.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[The C99 language added some pretty neat features to the ANSI C we know and love (now known as C89). I used a construct called compound literals in my iPad Dev Camp presentation, and it seemed new to a lot of people. Here’s a summary of some lesser know features about C99 that are worth knowing. And, since Objective-C is a strict superset of C, all this applies to Objective-C, as well. Best of all, as of recent Xcode (3.0? 3.1?), C99 is the default C dialect for new projects, so you don’t need to do anything to start taking advantage of these.]]></summary></entry><entry><title type="html">iPad Dev Camp Slides</title><link href="https://www.dribin.org/dave/blog/archives/2010/05/02/ipad_dev_camp_slides/" rel="alternate" type="text/html" title="iPad Dev Camp Slides" /><published>2010-05-02T23:11:00-05:00</published><updated>2010-05-02T23:11:00-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/05/02/ipad_dev_camp_slides</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/05/02/ipad_dev_camp_slides/"><![CDATA[<p>First off, a big thanks to David Kinney (<a href="http://twitter.com/dlkinney">@dlkinney)</a> for organizing this year’s <a href="http://ipaddevcampchi.wordpress.com/">iPad Dev Camp Chicago</a>.  Here are the slides to my Core Audio presentations:</p>

<ul>
  <li><a href="https://www.dribin.org/dave/resources/files/2010/ipdcchi_Dribin_AudioQueue.pdf">Audio Queue Services</a></li>
  <li><a href="https://www.dribin.org/dave/resources/files/2010/ipdcchi_Dribin_AudioUnits.pdf">Audio Unit Graphs</a></li>
</ul>

<p>The source code to the two projects I went over are up on <a href="http://bitbucket.org/ddribin">BitBucket</a>:</p>

<ul>
  <li><a href="http://bitbucket.org/ddribin/a440/wiki/Home">A440</a>: A Core Audio “Hello World”. Runs on Mac, iPhone, and iPad.</li>
  <li><a href="http://bitbucket.org/ddribin/chip-player">Chip Player</a>: A chiptune player using the <a href="http://www.fly.net/~ant/libs/audio.html">Game Music Emu</a> library.  Runs on Mac and iPad and plays popular chiptune file formats, such as <a href="http://en.wikipedia.org/wiki/NES_Sound_Format">NSF</a> and <a href="http://en.wikipedia.org/wiki/Game_Boy_Sound_System">GBS</a>.</li>
</ul>

<p>Use the <code>ipaddevcamp2010</code> tag to see what they looked like at the time of the presentations.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[First off, a big thanks to David Kinney (@dlkinney) for organizing this year’s iPad Dev Camp Chicago. Here are the slides to my Core Audio presentations: Audio Queue Services Audio Unit Graphs The source code to the two projects I went over are up on BitBucket: A440: A Core Audio “Hello World”. Runs on Mac, iPhone, and iPad. Chip Player: A chiptune player using the Game Music Emu library. Runs on Mac and iPad and plays popular chiptune file formats, such as NSF and GBS. Use the ipaddevcamp2010 tag to see what they looked like at the time of the presentations.]]></summary></entry><entry><title type="html">A440 - A Core Audio “Hello World”</title><link href="https://www.dribin.org/dave/blog/archives/2010/04/26/announcing_a440/" rel="alternate" type="text/html" title="A440 - A Core Audio “Hello World”" /><published>2010-04-26T09:00:49-05:00</published><updated>2010-04-26T09:00:49-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/04/26/announcing_a440</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/04/26/announcing_a440/"><![CDATA[<p><a href="http://ipaddevcampchi.wordpress.com/">iPad Dev Camp Chicago</a> is coming up this weekend, and I’m going to be giving two talks about <a href="http://developer.apple.com/iphone/library/documentation/MusicAudio/Conceptual/CoreAudioOverview/Introduction/Introduction.html">Core Audio</a>.  One of the applications we are going to go over is called A440, a “Hello World” of Core Audio.  It plays a simple a <a href="http://en.wikipedia.org/wiki/A440">440 Hz tone</a> using both <a href="http://developer.apple.com/mac/library/documentation/MusicAudio/Reference/AudioQueueReference/Reference/reference.html">Audio Queue Services</a> (AudioQueueRef and friends) and <a href="http://developer.apple.com/mac/library/documentation/AudioToolbox/Reference/AUGraphServicesReference/Reference/reference.html">Audio Unit Processing Graph Services</a> (AUGraph and friends).  In order to keep the code as simple as possible, it does not use any of the “Public Utility” C++ APIs.</p>

<p>I’ve posted the code up <a href="http://bitbucket.org/ddribin/a440/">on BitBucket</a> if you want to check it out before hand or are unable to attend.  I also hope to have a more complex and complete audio playing application ready to release by this weekend, too.  Hint, it’ll have something to do with <a href="http://en.wikipedia.org/wiki/Chiptune">8-bit chiptunes</a>.  So if you’re in Chicago, <a href="http://ipaddevcampchi.wordpress.com/register/">sign up</a>!  It’ll be fun!</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[iPad Dev Camp Chicago is coming up this weekend, and I’m going to be giving two talks about Core Audio. One of the applications we are going to go over is called A440, a “Hello World” of Core Audio. It plays a simple a 440 Hz tone using both Audio Queue Services (AudioQueueRef and friends) and Audio Unit Processing Graph Services (AUGraph and friends). In order to keep the code as simple as possible, it does not use any of the “Public Utility” C++ APIs. I’ve posted the code up on BitBucket if you want to check it out before hand or are unable to attend. I also hope to have a more complex and complete audio playing application ready to release by this weekend, too. Hint, it’ll have something to do with 8-bit chiptunes. So if you’re in Chicago, sign up! It’ll be fun!]]></summary></entry><entry><title type="html">Debugging Asynchronous performSelector - Calls</title><link href="https://www.dribin.org/dave/blog/archives/2010/03/19/debugging_async_perform_selector/" rel="alternate" type="text/html" title="Debugging Asynchronous performSelector - Calls" /><published>2010-03-19T23:42:49-05:00</published><updated>2010-03-19T23:42:49-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/03/19/debugging_async_perform_selector</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/03/19/debugging_async_perform_selector/"><![CDATA[<p>This afternoon, I had to debug an issue that involved <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelectorOnMainThread:withObject:waitUntilDone:"><code>performSelectorOnMainThread:</code></a>. This method is a great way to get a background thread to safely interact with the user interface.  But when you set a breakpoint or crash nested down in one of these method calls, sometimes it’s useful to get a backtrace of who called <code>performSelectorOnMainThread:</code>.  Unfortunately, by the time our method gets called, we don’t have that information.  The same goes for <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSObject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/performSelector:withObject:afterDelay:"><code> performSelector:withObject:afterDelay:</code></a>.</p>

<p>After some good suggestions on Twitter, and a bit of <strike>casual</strike> <a href="http://twitter.com/ddribin/status/10778596555">recreational</a> coding, I’ve come up with a general purpose solution that involves, of course, <a href="http://www.cocoadev.com/index.pl?MethodSwizzling">method swizzling</a>.</p>

<!--more-->

<p>Take this code in an application delegate as an example:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">applicationDidFinishLaunching</span><span class="p">:(</span><span class="n">NSNotification</span> <span class="o">*</span><span class="p">)</span><span class="nv">aNotification</span>
<span class="p">{</span>
    <span class="n">dispatch_async</span><span class="p">(</span><span class="n">dispatch_get_global_queue</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">),</span> <span class="o">^</span><span class="p">{</span>
        <span class="p">[</span><span class="n">self</span> <span class="nf">performSelectorOnMainThread</span><span class="p">:</span><span class="k">@selector</span><span class="p">(</span><span class="nf">echo</span><span class="p">:)</span> <span class="n">withObject</span><span class="o">:</span><span class="s">@"foo"</span> <span class="n">waitUntilDone</span><span class="o">:</span><span class="nb">NO</span><span class="p">];</span>
    <span class="p">});</span>
    
    <span class="p">[</span><span class="n">self</span> <span class="nf">performSelector</span><span class="p">:</span><span class="k">@selector</span><span class="p">(</span><span class="nf">echo</span><span class="p">:)</span> <span class="n">withObject</span><span class="o">:</span><span class="s">@"bar"</span> <span class="n">afterDelay</span><span class="o">:</span><span class="mi">3</span><span class="p">.</span><span class="mi">0</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">echo</span><span class="p">:(</span><span class="n">id</span><span class="p">)</span><span class="nv">object</span>
<span class="p">{</span>
    <span class="n">NSLog</span><span class="p">(</span><span class="s">@"echo: %@"</span><span class="p">,</span> <span class="n">object</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>If you set a breakpoint in the <code>echo:</code> method, you’ll see a backtrace like:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) bt
#0  -[PerformDebugAppDelegate echo:] (self=0x10012c480, _cmd=0x100002462, object=0x1000030e8) at /Users/dave/Desktop/PerformDebug/PerformDebugAppDelegate.m:42
#1  0x00007fff83500647 in __NSThreadPerformPerform ()
#2  0x00007fff80477271 in __CFRunLoopDoSources0 ()
#3  0x00007fff80475469 in __CFRunLoopRun ()
#4  0x00007fff80474c2f in CFRunLoopRunSpecific ()
#5  0x00007fff8101ea4e in RunCurrentEventLoopInMode ()
#6  0x00007fff8101e7b1 in ReceiveNextEventCommon ()
#7  0x00007fff8101e70c in BlockUntilNextEventMatchingListInMode ()
#8  0x00007fff870b21f2 in _DPSNextEvent ()
#9  0x00007fff870b1b41 in -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] ()
#10 0x00007fff87077747 in -[NSApplication run] ()
#11 0x00007fff87070468 in NSApplicationMain ()
#12 0x0000000100001a09 in main (argc=1, argv=0x7fff5fbff1f0) at /Users/dave/Desktop/PerformDebug/main.m:29
</code></pre></div></div>

<p>This really isn’t all that helpful.  Yes, <code>echo:</code> was called, but we don’t know who called it.  If <code>echo:</code> is a method that tends to get called from a number of places with a <code>performSelector...</code> variant, we don’t know which one it is.</p>

<p>This afternoon, I took the easy way out, and set an auto-continuing breakpoint on <code>-[NSObject performSelector:onThread:withObject:waitUntilDone:modes:]</code> with a <code>bt</code> action.  This isn’t ideal, though.  First, this method gets called quite a bit, so hitting the breakpoint can slow things down a lot.  Plus, it dumps the stack trace for each call, cluttering the gdb console with mostly useless garbage.</p>

<p>The breakpoint actually helped me debug the issue today, but I’ve run into this situation a number of times in the past and never had a good way to debug it.  Until now.</p>

<h3 id="swizzling-for-fun-and-profit">Swizzling for Fun and Profit</h3>

<p>The key is to swizzle the <code>NSObject</code> implementations of these two methods:</p>

<ul>
  <li><code>performSelector:withObject:afterDelay:inModes:</code></li>
  <li><code>performSelector:onThread:withObject:waitUntilDone:modes:</code></li>
</ul>

<p>In our swizzled implementations, we’d like to capture the backtrace at time they are called.  Later, we can dump out the backtrace for debugging, if we want to.  To do this, we’ll create an intermediate object to hold the backtrace: <code>DDPerformDebugger</code>.  Here are its two most important methods:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="n">id</span><span class="p">)</span><span class="nf">initWithTarget</span><span class="p">:(</span><span class="n">id</span><span class="p">)</span><span class="nv">target</span> <span class="nf">selector</span><span class="p">:(</span><span class="n">SEL</span><span class="p">)</span><span class="nv">selector</span> <span class="nf">argument</span><span class="p">:(</span><span class="n">id</span><span class="p">)</span><span class="nv">argument</span><span class="p">;</span>
<span class="p">{</span>
    <span class="n">self</span> <span class="o">=</span> <span class="p">[</span><span class="n">super</span> <span class="nf">init</span><span class="p">];</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">self</span> <span class="o">==</span> <span class="nb">nil</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">nil</span><span class="p">;</span>
    
    <span class="n">_target</span> <span class="o">=</span> <span class="p">[</span><span class="n">target</span> <span class="nf">retain</span><span class="p">];</span>
    <span class="n">_selector</span> <span class="o">=</span> <span class="n">selector</span><span class="p">;</span>
    <span class="n">_argument</span> <span class="o">=</span> <span class="p">[</span><span class="n">argument</span> <span class="nf">retain</span><span class="p">];</span>
    <span class="c1">// Capture a backtrace at the time we're created</span>
    <span class="n">_frames</span> <span class="o">=</span> <span class="n">backtrace</span><span class="p">(</span><span class="n">_callstack</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">_callstack</span><span class="p">)</span><span class="o">/</span><span class="k">sizeof</span><span class="p">(</span><span class="o">*</span><span class="n">_callstack</span><span class="p">));</span>
    
    <span class="k">return</span> <span class="n">self</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">perform</span><span class="p">;</span>
<span class="p">{</span>
    <span class="p">[</span><span class="n">_target</span> <span class="nf">performSelector</span><span class="p">:</span><span class="n">_selector</span> <span class="nf">withObject</span><span class="p">:</span><span class="n">_argument</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In the initializer, we capture the target, selector, and argument.  But we also capture a backtrace using the very handy <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/backtrace.3.html">backtrace(3)</a> function.</p>

<p>In our swizzled <code>performSelector...</code>, we create an instance of <code>DDPerformDebugger</code>, but instead of passing the target and selector to the original implementation, we use this instance as the target and <code>perform</code> as the selector.  As you can see above, this just forwards it on to the passed in target and selector.  However, as I demonstrate below, we’ll have access to the saved backtrace.  Here’s what the swizzled method looks like:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">dd_performSelector</span><span class="p">:(</span><span class="n">SEL</span><span class="p">)</span><span class="nv">selector</span> <span class="nf">withObject</span><span class="p">:(</span><span class="n">id</span><span class="p">)</span><span class="nv">argument</span> <span class="nf">afterDelay</span><span class="p">:(</span><span class="n">NSTimeInterval</span><span class="p">)</span><span class="nv">delay</span> <span class="nf">inModes</span><span class="p">:(</span><span class="n">NSArray</span> <span class="o">*</span><span class="p">)</span><span class="nv">modes</span><span class="p">;</span>
<span class="p">{</span>
    <span class="n">DDPerformDebugger</span> <span class="o">*</span> <span class="n">debugger</span> <span class="o">=</span> <span class="p">[[</span><span class="n">DDPerformDebugger</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithTarget</span><span class="p">:</span><span class="n">self</span>
                                                                    <span class="nl">selector:</span><span class="n">selector</span>
                                                                    <span class="nl">argument:</span><span class="n">argument</span><span class="p">];</span>
    <span class="p">[</span><span class="n">debugger</span> <span class="nf">autorelease</span><span class="p">];</span>
    
    <span class="c1">// This calls the original implementation.  It's not recursing.</span>
    <span class="p">[</span><span class="n">debugger</span> <span class="nf">dd_performSelector</span><span class="p">:</span><span class="k">@selector</span><span class="p">(</span><span class="n">perform</span><span class="p">)</span>
                      <span class="nl">withObject:</span><span class="nb">nil</span>
                      <span class="nl">afterDelay:</span><span class="n">delay</span>
                         <span class="nl">inModes:</span><span class="n">modes</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The swizzled <code>dd_performSelectorOnMainThread:...</code> looks similar.  Now, when we stop on our breakpoint in <code>echo:</code>, we get the following backtrace:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) bt 5
#0  -[PerformDebugAppDelegate echo:] (self=0x10012b170, _cmd=0x100002462, object=0x1000030e8) at /Users/dave/Desktop/PerformDebug/PerformDebugAppDelegate.m:42
#1  0x000000010000207c in -[DDPerformDebugger perform] (self=0x10101ae00, _cmd=0x7fff85a42a1a) at /Users/dave/Desktop/PerformDebug/DDPerformDebugger.m:157
#2  0x00007fff83500647 in __NSThreadPerformPerform ()
#3  0x00007fff80477271 in __CFRunLoopDoSources0 ()
#4  0x00007fff80475469 in __CFRunLoopRun ()
(More stack frames follow...)
</code></pre></div></div>

<p>This isn’t much help on it’s own.  But if we jump to frame 1, where we’re inside the <code>perform</code> method of our intermediate object, we have access to the backtrace of the original calling point.  I’ve rigged up the <code>description</code> method to show the backtrace, so it’s easy to get:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) po self
&lt;DDPerformDebugger 0x10101ae00: target: &lt;PerformDebugAppDelegate 0x10012b170&gt;, selector: &lt;echo:&gt;, argument: &lt;NSCFString 0x1000030e8&gt;
0   PerformDebug                        0x0000000100001f45 -[DDPerformDebugger initWithTarget:selector:argument:] + 268
1   PerformDebug                        0x0000000100001d3c -[NSObject(DDPerformDebugger) dd_performSelector:onThread:withObject:waitUntilDone:modes:] + 99
2   Foundation                          0x00007fff83512d54 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] + 143
3   PerformDebug                        0x0000000100001b42 __-[PerformDebugAppDelegate applicationDidFinishLaunching:]_block_invoke_1 + 66
4   libSystem.B.dylib                   0x00007fff86eebce8 _dispatch_call_block_and_release + 15
5   libSystem.B.dylib                   0x00007fff86eca279 _dispatch_worker_thread2 + 231
6   libSystem.B.dylib                   0x00007fff86ec9bb8 _pthread_wqthread + 353
7   libSystem.B.dylib                   0x00007fff86ec9a55 start_wqthread + 13
</code></pre></div></div>

<p>We can see we’re on on a GCD thread inside <code>applicationDidFinishLaunching:</code>.  The only downside to the <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/backtrace.3.html">backtrace_symbols(3)</a> function is that it does not utilize debugging information to show line numbers.  We just get an offset into the method.</p>

<p>Fortunately, a command line tool called <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/atos.1.html">atos(1)</a> can provide us with this information.  Given an address, it’ll decode the symbol <em>and</em> line number information. We can even invoke this right from inside gdb:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(gdb) info pid
Inferior has process ID 11017.
(gdb) shell atos -p 11017 0x0000000100001b42
__-[PerformDebugAppDelegate applicationDidFinishLaunching:]_block_invoke_1 (in PerformDebug) (PerformDebugAppDelegate.m:35)
</code></pre></div></div>

<p>And know we know that <code>performSelectorOnMainThread:</code> was originally called from line 35 of PerformDebugAppDelegate.m.  Very helpul!</p>

<p>The full code for <code>DDPerformDebugger</code> is part of my <a href="http://bitbucket.org/ddribin/ddfoundation/">DDFoundation</a> project on BitBucket, but you can grab just the <a href="http://bitbucket.org/ddribin/ddfoundation/src/d41050234d53/lib/DDPerformDebugger.m">one file</a> on its own and and included it with your project.  By default, it does not swizzle anything, so you can compile it in for every build and not worry about taking a performance hit creating those intermediate objects.  To enable the swizzling, just set the <code>DDPerformDebug</code> environment variable to <code>YES</code>.  Grab a sample project, <a href="https://www.dribin.org/dave/resources/files/2010/PerformDebug.tgz">PerformDebug.tgz</a>, and try it out for yourself.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[This afternoon, I had to debug an issue that involved performSelectorOnMainThread:. This method is a great way to get a background thread to safely interact with the user interface. But when you set a breakpoint or crash nested down in one of these method calls, sometimes it’s useful to get a backtrace of who called performSelectorOnMainThread:. Unfortunately, by the time our method gets called, we don’t have that information. The same goes for performSelector:withObject:afterDelay:. After some good suggestions on Twitter, and a bit of casual recreational coding, I’ve come up with a general purpose solution that involves, of course, method swizzling.]]></summary></entry><entry><title type="html">What I Miss from Java</title><link href="https://www.dribin.org/dave/blog/archives/2010/03/02/what_i_miss_from_java/" rel="alternate" type="text/html" title="What I Miss from Java" /><published>2010-03-02T09:28:01-06:00</published><updated>2010-03-02T09:28:01-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/03/02/what_i_miss_from_java</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/03/02/what_i_miss_from_java/"><![CDATA[<p>On Monday, I had a series of tweets (<a href="http://twitter.com/ddribin/status/9844373942">[1]</a>, <a href="http://twitter.com/ddribin/status/9845017202">[2]</a>, <a href="http://twitter.com/ddribin/status/9845380008">[3]</a>) about what I like about Java that I miss in Objective-C/Cocoa that were probably better off in a blog post. I blame <a href="http://twitter.com/jeff_lamarche">Jeff LaMarche</a> for <a href="http://twitter.com/ddribin/status/9843725157">baiting</a> me into the tweet rant, so here’s the the same thing, in blog post format with more detail and other points I forgot to mention.</p>

<h3 id="what-i-miss">What I Miss</h3>

<p>Before settling in on Objective-C, I was a Java guy for about six years or so.  Overall, I much, <em>much</em> prefer coding in Objective-C to Java, and have no intentions of going back to Java.  But that doesn’t mean there’s some things I miss.  Here’s a quick list, with more detail below:</p>

<ul>
  <li>A flexible I/O class hierarchy</li>
  <li>Everything in <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html">java.util.concurrent</a></li>
  <li>Exceptions for errors</li>
  <li>Packages, a.k.a namespaces</li>
  <li>One file for interface/implementation</li>
  <li>Type safe enum classes</li>
  <li>Annotations</li>
  <li>Awesome IDEs (IntelliJ)</li>
</ul>

<!--more-->

<h3 id="a-flexible-io-class-hierarchy">A Flexible I/O Class Hierarchy</h3>

<p>Overall, I feel the <a href="http://java.sun.com/javase/6/docs/api/java/io/package-summary.html">java.io</a> package is really well designed.  I like the difference between <a href="http://java.sun.com/javase/6/docs/api/java/io/InputStream.html">InputStream</a>/<a href="http://java.sun.com/javase/6/docs/api/java/io/OutputStream.html">OutputStream</a> that are byte-oriented and <a href="http://java.sun.com/javase/6/docs/api/java/io/Reader.html">Reader</a>/<a href="http://java.sun.com/javase/6/docs/api/java/io/Writer.html">Writer</a> that are text-oriented. Also, there’s some cool subclasses such as <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/GZIPInputStream.html">GZIPInputStream</a>, <a href="http://java.sun.com/javase/6/docs/api/java/util/zip/GZIPOutputStream.html">GZIPOutputStream</a>, and <a href="http://java.sun.com/javase/6/docs/api/java/io/LineNumberReader.html">LineNumberReader</a></p>

<p>Java’s InputStream and OutputStream are easier to subclass than <a href="http://developer.apple.com/Mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSInputStream_Class/Reference/Reference.html">NSInputStream</a> and <a href="http://developer.apple.com/Mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSOutputStream_Class/Reference/Reference.html">NSOutputStream</a> since there’s fewer methods to deal with.  Plus, there’s a lingering bug in NSInputStream that makes it effectively impossible to subclass in some really handy situations. See this <a href="http://lists.apple.com/archives/macnetworkprog/2007/May/msg00053.html">mailing list post from 2007</a> that mentions rdar://problem/322278.</p>

<h3 id="everything-in-javautilconcurrent">Everything in java.util.concurrent</h3>

<p>Ever since I read <a href="https://www.amazon.com/dp/0321349601?tag=davedribishom-20&amp;camp=0&amp;creative=0&amp;linkCode=as1&amp;creativeASIN=0321349601&amp;adid=0E62AD455C99P68HKK79&amp;">Java Concurrency in Practice</a>, I’ve been drooling over a lot of stuff Java programmers have available in their arsenal in <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html">java.util.concurrent</a>. The <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executor.html">Executor</a> is roughly equivalent to a <a href="http://developer.apple.com/mac/library/documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html">Grand Central Dispatch</a> queue and the<a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html">ExecutorService</a> is roughly equivalent to an <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/NSOperationQueue_class/Reference/Reference.html">NSOperationQueue</a>, but that’s where the similarities end. Granted, I think the Cocoa and GCD APIs are more palatable, especially since the introduction of <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html">blocks</a>, but there’s a bunch of classes we don’t have that would have been really useful at some point or another:</p>

<ul>
  <li><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html">BlockingQueue</a> and it’s implementations are handy for passing objects between threads. The need for this is partially mitigated by GCD, but it’d still be nice to have these to feed objects from one queue to another.</li>
  <li><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html">ConcurrentHashMap</a>is an awesome, thread safe and scalable map/dictionary.</li>
  <li><a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html">CopyOnWriteArrayList</a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArraySet.html">CopyOnWriteArraySet</a> are really nice for mostly read-only data.</li>
  <li>The atomic classes in <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/atomic/package-summary.html">java.util.concurrent.atomic</a> are nicer than dealing with the <a href="http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man3/atomic.3.html#//apple_ref/doc/man/3/atomic">OSAtomic</a> functions.</li>
  <li>The <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html">Future interface</a> has some very handy uses.  Mike Ash just wrote a blog post on <a href="http://mikeash.com/pyblog/friday-qa-2010-02-26-futures.html">futures in Objective-C</a>, but I think I prefer explicit futures to implicit futures.</li>
  <li>The <a href="http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html">SwingWorker</a> class offers nice integration of asynchronous background tasks with the user interface thread.  I’ve used a similar pattern in Objective-C, but I think it’d be nice to have this encapsulated in a reusable object.</li>
  <li>The <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html">java.util.concurrent.locks</a> package has some nice specialty locks such as <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html">ReentrantReadWriteLock</a>.</li>
</ul>

<h3 id="exceptions-for-errors">Exceptions for Errors</h3>

<p>Objective-C may have exceptions, but they are only used for programming errors or essentially fatal runtime errors. Error handling is done with <a href="http://developer.apple.com/mac/library/documentation/cocoa/conceptual/ErrorHandlingCocoa/ErrorHandling/ErrorHandling.html#//apple_ref/doc/uid/TP40001806-CH201-SW1">NSError</a>. This is different than Java, which uses exceptions for expected error cases, such as error reading from a file, or failure to execute a database transaction. This isn’t just a Java thing. Most modern languages like Python, Ruby, and C# use exceptions as Java does. Not using exceptions as error handling was one of the harder habits for me to break; however, I’ve come to embrace NSError and eschew exceptions in Objective-C, even if I don’t like it.</p>

<p>I’ve debated this a number of times with people, but having dealt with both exceptions and NSError, I still prefer exceptions. The big argument against exceptions is that they are non-local jumps causing confusing behavior and subtle bugs. I guess I’ve never seen this happen. Plus there’s also the fact that Foundation and AppKit are not exception safe, so throwing exceptions through these frameworks can and will lead to memory leaks and probably unpredictable behavior. Thus, the best course of action to handle an exception is to gracefully terminate the app.</p>

<p>To me, NSError doesn’t result in more robust code than exceptions. 90% of the time, people just pass NULL or log the NSError in place instead of passing it up to where it’s better handled. A big reason for this is that NSError is returned as an output parameter. Thus to pass an NSError up to a higher level requires  that an NSError be added to every method up the chain. Not only is this ungainly, but it’s sometimes not possible to add an NSError to an existing API. This is also a problem with checked exceptions Java, which is why most Java people endorse unchecked exceptions these days.</p>

<p>Exceptions really shine when you call multiple methods in a row that can fail.  In Objective-C, your best bet is to return early or use a goto. This still litters your code with error handling that drowns out the real code.  With exceptions, the error handling code is nicely separated from the “happy” code path.  Perhaps exceptions aren’t the be-all end-all of error handling, as I’ve recently been intrigued by the <a href="http://book.realworldhaskell.org/read/error-handling.html">error handling of Haskell</a>.  However, this is not something we’ll see in Objective-C any time soon.</p>

<h3 id="packages-aka-namespaces">Packages, a.k.a Namespaces</h3>

<p>Classes in Objective-C live in a big, flat, global namespace. The common workaround is to prefix class names with two or three letters. Thus, I’d name my classes DDObject or some such. The problem with this approach is that two or three letters is just not enough of a namespace. It helps reduce collisions, but it does not eliminate them. Plus, Apple no longer uses only the NS prefix. It uses CA, CI, CV, QC, AB, UI, PS, IO, QL and probably more. A safe prefix today may be a collision tomorrow.</p>

<p>Things get even more dire when it comes to categories. Category smashing happens, and it’s <a href="http://blog.clickablebliss.com/2010/01/19/finding-colliding-category-methods/">hard to debug</a>. The only way to avoid it is to prefix your category methods with some unique prefix, as well.</p>

<p>Packages or namespace could theoretically solve both of these collisions.  This is not an unknown issue.  Many radars have been filed, such as <a href="http://openradar.appspot.com/7025435">rdar://problem/7025435</a>, that are all duped to a very low radar: rdar://problem/2821039. The problem is this isn’t an easy thing to bolt onto an existing language, because, of course, we want it done in a backwards compatible manner that doesn’t impact the performance of objc_msgSend(). So I understand why we don’t have it, but that doesn’t mean I don’t want it.</p>

<h3 id="one-file-for-interface-and-implementation">One File for Interface and Implementation</h3>

<p>There are some good things about the separate of the interface in the .h file and the implementation in the .m file. However, I really despise having to keep these two up-to-date. Many accumulated hours have been lost to compile warnings and errors due to updating one without the other. The repeated method definitions are very <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">un-DRY</a>.</p>

<p>Others suggested that they like this separation of interface from implementation details, only exposing what’s necessary to users of the class, and conceptually I agree. In practice, I find it a chore. Perhaps the repeated code could be mitigated with some Xcode assistance. For example, add a method in the .m and it offers to add it to the .h for you. I think I could deal with this.</p>

<p>However, some of the private details are still exposed in the headers, namely the instance variables. The modern Objective-C runtime, available in 64-bit on Mac OS X and the native iPhone environments, allow synthesized ivars, meaning you can declare properties, and the ivars will automatically be created.  But you can’t really use this until you drop 32-bit Mac OS X and/or the simulator supports the modern runtime.</p>

<p>And even so, I’m not sold on synthesized ivars, as it requires using properties where I previously used ivars. To me, a property is conceptually different than an ivar, even if it’s non-public. Properties can be overridden, can have side effects, are available via key-value coding, and also have more overhead. Most of the time, I don’t want these things, and prefer direct ivar access.  I much prefer explicit ivars. Perhaps way to solve the exposed privates issue would be to declare them in the .m in say a class extension, instead of the .h. The runtime supports adding ivars at runtime, so this sounds technically possible.</p>

<h3 id="type-safe-enum-classes">Type Safe Enum Classes</h3>

<p>Enums in Objective-C are inherited from C. Thus we get all the weaknesses of C enums for free. C enums are not much more than syntactic sugar for integer constants. There’s no way to get type safety, to introspect them, print them, loop over them, or do anything remotely fancy. The one benefit over a #define used to be that the debugger could decode the integer value into a readable name. But these days, all enums in Cocoa are anonymous, defined as such for 64-bit compatibility:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">enum</span> <span class="p">{</span>
    <span class="c1">// Pass in one of the "By" options:</span>
    <span class="n">NSStringEnumerationByLines</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span>
    <span class="c1">// ...</span>
<span class="p">};</span>
<span class="k">typedef</span> <span class="n">NSUInteger</span> <span class="n">NSStringEnumerationOptions</span><span class="p">;</span>
</code></pre></div></div>

<p>Thus most types that are enums are actually typedef’d to NSUInteger.  While this is necessary, it means we no longer get debugger integration with enum constants.</p>

<h3 id="annotations">Annotations</h3>

<p>Annotations in Java are bits of metadata that can be added to classes and methods.  Some of this metadata is used at compile time, but it is also available at runtime.  The runtime uses are intriguing, but one of the compile time annotations that I like is the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Override.html">@override annotation</a>.  This allows you to detect some subtle, yet easy-to-make mistakes when overriding methods in subclasses or a protocol:</p>

<ul>
  <li>Accidentally overriding a superclass’ method.</li>
  <li>Misspelling a superclass’ method, thus not actually overriding it.</li>
  <li>Misspelling an optional protocol method, thus not actually implementing it.</li>
</ul>

<p>I’ve requested similar functionality for Objective-C in <a href="http://openradar.appspot.com/7215146"> rdar://problem/7215146</a>.</p>

<h3 id="awesome-ides-intellij">Awesome IDEs (IntelliJ)</h3>

<p>This one has really nothing to do with the language.  Xcode has really improved over the years.  And while it is generally a very good text editor with project management, I’m afraid it still doesn’t compare to IntelliJ.  I don’t know how other Java IDEs stack up (I was never very impressed with Eclipse), but IntelliJ was the first IDE that sold me on the concept of IDEs (I used Emacs prior to it).</p>

<p>Honestly, this probably deserves a whole post in and of itself, but for starters, Xcode could really use intention actions, see <a href="http://openradar.appspot.com/7215136">rdar://problem/7215136</a>, and much better <a href="https://www.dribin.org/dave/blog/archives/2009/10/24/unit_test_bugs/">unit testing integration</a>.  IntelliJ has a bunch of other small niceties that all add up to a more pleasant development experience.  Unfortunately, it’s been years since I used IntelliJ, so I don’t remember all of the details.  Some I can remember are: real-time syntax checking, automatic import statement management, and customizable code reformatting (yes, I need to file bugs on these, too).</p>

<p>All I <em>do</em> remember as that it was the first and only development environment that really took much of the grunt work out of editing code.  It not only got out of my way, it actually made me more productive.  I dropped the $500 on it out of my own pocket, and it easily paid for itself (in real consulting dollars) in a matter of weeks.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[On Monday, I had a series of tweets ([1], [2], [3]) about what I like about Java that I miss in Objective-C/Cocoa that were probably better off in a blog post. I blame Jeff LaMarche for baiting me into the tweet rant, so here’s the the same thing, in blog post format with more detail and other points I forgot to mention. What I Miss Before settling in on Objective-C, I was a Java guy for about six years or so. Overall, I much, much prefer coding in Objective-C to Java, and have no intentions of going back to Java. But that doesn’t mean there’s some things I miss. Here’s a quick list, with more detail below: A flexible I/O class hierarchy Everything in java.util.concurrent Exceptions for errors Packages, a.k.a namespaces One file for interface/implementation Type safe enum classes Annotations Awesome IDEs (IntelliJ)]]></summary></entry><entry><title type="html">Mac and iPhone Applications with Unit Tests, Refactored</title><link href="https://www.dribin.org/dave/blog/archives/2010/01/18/refactored_mac_iphone_app_with_tests/" rel="alternate" type="text/html" title="Mac and iPhone Applications with Unit Tests, Refactored" /><published>2010-01-18T20:40:37-06:00</published><updated>2010-01-18T20:40:37-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/01/18/refactored_mac_iphone_app_with_tests</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/01/18/refactored_mac_iphone_app_with_tests/"><![CDATA[<p>This is a follow-up to <a href="https://www.dribin.org/dave/blog/archives/2010/01/18/why_unit_test_cocoa_and_iphone/">my post</a> on why you should unit test Cocoa and iPhone applications.  One reason I think Matt is against unit tests, at least given his particular examples, is that the tests themselves are quite large and confusing.  They also use category smashing to override methods and inject mock objects and use runtime trickery to gain access to private instance variables.</p>

<p>These are all <a href="http://c2.com/xp/CodeSmell.html">code smells</a> that something isn’t right.  Remember, TDD is about tests <em>driving</em> development; however you must remember to <a href="http://www.google.com/search?rls=en&amp;q=tdd+listen+to+the+tests&amp;ie=UTF-8&amp;oe=UTF-8">listen to the tests</a> when they are crying out in pain.  I’m going to take Matt’s Mac and iPhone projects with unit tests and re-work them so that they are much more manageable and cleaner.</p>

<!--more-->

<h3>Duplicated Code</h3>

<p>This first smell I want to address is in the duplicated code between the Mac and iPhone applications.  Both apps have a <code>CLLoationManager</code> delegate that listens for updates and formats the location into HTML for the web view, strings labels for the buttons, and a Google Maps URL.  The code between these two apps is identical and is a good example of a violation of the Don’t Repeat Yourself, or <a href="http://c2.com/cgi/wiki?DontRepeatYourself">DRY</a>, Principle.</p>

<p>So how do we remove this duplicated code?  Part of what makes this difficult is that it is highly <a href="http://c2.com/cgi/wiki?CouplingAndCohesion">coupled</a> to the UI.  In the Mac app, this code lives in an <code>NSWindowController</code> subclass, and in the iPhone app it lives in a <code>UIViewController</code> subclass.  Thus we can’t just share an existing class as-is between projects because you can’t use an <code>NSWindowController</code> in an iPhone app and you can’t use a <code>UIViewController</code> in a Mac app.  The answer is to <a href="http://www.refactoring.com/catalog/extractClass.html">extract this code into a new class</a> that can be used from both applications.</p>

<p>Because the primary function of this new class is to take core location updates and format them to various strings, I’m calling the class <code>MyCoreLocationFormatter</code>.  There may be a better name, since using the word formatter may imply an <code>NSFormatter</code> subclass, but let’s stick with it for now.</p>

<p>The sticking point is that we somehow need this new class to update the UI, irrespective of Cocoa vs. Cocoa Touch.  We need to break the direct dependency on Cocoa and Cocoa Touch, and I’ve chosen to use a delegate with a single method as a bit of <a href="http://www.objectmentor.com/resources/articles/dip.pdf">dependency inversion</a>:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">@protocol</span> <span class="nc">MyCoreLocationFormatterDelegate</span> <span class="o">&lt;</span><span class="n">NSObject</span><span class="o">&gt;</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">locationFormatter</span><span class="p">:(</span><span class="n">MyCoreLocationFormatter</span> <span class="o">*</span><span class="p">)</span><span class="nv">formatter</span>
 <span class="nf">didUpdateFormattedString</span><span class="p">:(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="nv">formattedString</span>
            <span class="nf">locationLabel</span><span class="p">:(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="nv">locationLabel</span>
           <span class="nf">accuractyLabel</span><span class="p">:(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="nv">accuracyLabel</span><span class="p">;</span>

<span class="k">@end</span>
</code></pre></div></div>

<p>Thus, when the location changes, it formats the new location into appropriate strings and sends this message to its delegate.  Both <code>WhereIsMyMacWindowController</code> and <code>WhereIsMyPhoneViewController</code> implement this protocol, and when they receive the message, the update their UI accordingly.</p>

<p>There are other ways to achieve similar decoupling.  We could use an <code>NSNotification</code> to send out the update with the strings in the user info dictionary.  Or we could have properties for the three strings and allow interested parties to monitor their updates using <a href="http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html">key-value observing</a>.  On the Mac side, this enables you to use <a href="http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/CocoaBindings/CocoaBindings.html">Cocoa bindings</a> to wire up the UI.  Or we could return a dictionary with the three strings.  Or we could create a new <a href="http://c2.com/cgi/wiki?ValueObject">value object</a> and return that.  Any of these alternatives are viable, however I think using a delegate makes the coupling a bit more explicit and easier to follow.  What’s important is that the direct dependency to the UI layer is broken.</p>

<p>Here’s the full interface of <code>MyCoreLocationFormatter</code>:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">@interface</span> <span class="nc">MyCoreLocationFormatter</span> <span class="p">:</span> <span class="nc">NSObject</span> <span class="o">&lt;</span><span class="n">CLLocationManagerDelegate</span><span class="o">&gt;</span>
<span class="p">{</span>
    <span class="n">id</span><span class="o">&lt;</span><span class="n">MyCoreLocationFormatterDelegate</span><span class="o">&gt;</span> <span class="n">_delegate</span><span class="p">;</span>
    <span class="n">NSString</span> <span class="o">*</span> <span class="n">_formatString</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">@property</span> <span class="p">(</span><span class="n">nonatomic</span><span class="p">,</span> <span class="n">assign</span><span class="p">,</span> <span class="n">readwrite</span><span class="p">)</span> <span class="n">id</span><span class="o">&lt;</span><span class="n">MyCoreLocationFormatterDelegate</span><span class="o">&gt;</span> <span class="n">delegate</span><span class="p">;</span>
<span class="k">@property</span> <span class="p">(</span><span class="n">nonatomic</span><span class="p">,</span> <span class="n">copy</span><span class="p">,</span> <span class="n">readonly</span><span class="p">)</span> <span class="n">NSString</span> <span class="o">*</span> <span class="n">formatString</span><span class="p">;</span>

<span class="k">-</span> <span class="p">(</span><span class="n">id</span><span class="p">)</span><span class="nf">initWithDelegate</span><span class="p">:(</span><span class="n">id</span><span class="o">&lt;</span><span class="n">MyCoreLocationFormatterDelegate</span><span class="o">&gt;</span><span class="p">)</span><span class="nv">delegate</span>
          <span class="nf">formatString</span><span class="p">:(</span><span class="n">NSString</span> <span class="o">*</span><span class="p">)</span><span class="nv">htmlFormatString</span><span class="p">;</span>

<span class="k">-</span> <span class="p">(</span><span class="n">NSURL</span> <span class="o">*</span><span class="p">)</span><span class="nf">googleMapsUrlForLocation</span><span class="p">:(</span><span class="n">CLLocation</span> <span class="o">*</span><span class="p">)</span><span class="nv">currentLocation</span><span class="p">;</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">locationManager</span><span class="p">:(</span><span class="n">CLLocationManager</span> <span class="o">*</span><span class="p">)</span><span class="nv">manager</span>
    <span class="nf">didUpdateToLocation</span><span class="p">:(</span><span class="n">CLLocation</span> <span class="o">*</span><span class="p">)</span><span class="nv">newLocation</span>
           <span class="nf">fromLocation</span><span class="p">:(</span><span class="n">CLLocation</span> <span class="o">*</span><span class="p">)</span><span class="nv">oldLocation</span><span class="p">;</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">locationManager</span><span class="p">:(</span><span class="n">CLLocationManager</span> <span class="o">*</span><span class="p">)</span><span class="nv">manager</span>
       <span class="nf">didFailWithError</span><span class="p">:(</span><span class="n">NSError</span> <span class="o">*</span><span class="p">)</span><span class="nv">error</span><span class="p">;</span>

<span class="k">@end</span>
</code></pre></div></div>

<p>Ignoring the <code>CLLocationManager</code> delegate methods, there are only two methods. The format string is used as the HTML template that gets loaded from the application’s bundle.  The <code>-googleMapsUrlForLocation:</code> method is used to open the location up in a browser.</p>

<p>To test this class, we use a mock object to ensure the delegate is being called properly.  We use instance variables and our fixture methods to setup an instance of <code>MyCoreLocationFormatter</code> and the mock delegate:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">setUp</span>
<span class="p">{</span>
	<span class="c1">// Setup</span>
	<span class="n">_mockDelegate</span> <span class="o">=</span> <span class="p">[</span><span class="n">OCMockObject</span> <span class="nf">mockForProtocol</span><span class="p">:</span><span class="k">@protocol</span><span class="err">(</span><span class="nc">MyCoreLocationFormatterDelegate</span><span class="p">)];</span>
	<span class="n">_formatter</span> <span class="o">=</span> <span class="p">[[</span><span class="n">MyCoreLocationFormatter</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithDelegate</span><span class="p">:</span><span class="n">_mockDelegate</span>
													<span class="nl">formatString:</span><span class="s">@"ll=%f,%f spn=%f,%f"</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">tearDown</span>
<span class="p">{</span>
	<span class="c1">// Verify</span>
	<span class="p">[</span><span class="n">_mockDelegate</span> <span class="nf">verify</span><span class="p">];</span>
	
	<span class="c1">// Teardown</span>
	<span class="p">[</span><span class="n">_formatter</span> <span class="nf">release</span><span class="p">];</span> <span class="n">_formatter</span> <span class="o">=</span> <span class="nb">nil</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>With these fixtures in place, writing our tests are fairly straight forward:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">testUpdateToNewLocationSendsUpdateToDelegate</span>
<span class="p">{</span>
    <span class="c1">// Setup</span>
    <span class="n">CLLocation</span> <span class="o">*</span> <span class="n">location</span> <span class="o">=</span> <span class="p">[</span><span class="n">self</span> <span class="nf">makeLocationWithLatitude</span><span class="p">:</span><span class="o">-</span><span class="mi">37</span><span class="p">.</span><span class="mi">80996889</span> <span class="nf">longitude</span><span class="p">:</span><span class="mi">144</span><span class="p">.</span><span class="mi">96326388</span><span class="p">];</span>
    <span class="p">[[</span><span class="n">_mockDelegate</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">locationFormatter</span><span class="p">:</span><span class="n">_formatter</span>
                     <span class="nl">didUpdateFormattedString:</span><span class="s">@"ll=-37.809969,144.963264 spn=-0.000018,-0.000014"</span>
                                <span class="nl">locationLabel:</span><span class="s">@"-37.809969, 144.963264"</span>
                               <span class="nl">accuractyLabel:</span><span class="p">[</span><span class="n">NSString</span> <span class="nf">stringWithFormat</span><span class="p">:</span><span class="s">@"%f"</span><span class="p">,</span> <span class="n">kCLLocationAccuracyBest</span><span class="p">]];</span>
    
    <span class="c1">// Execute</span>
    <span class="p">[</span><span class="n">_formatter</span> <span class="nf">locationManager</span><span class="p">:</span><span class="nb">nil</span> <span class="nf">didUpdateToLocation</span><span class="p">:</span><span class="n">location</span> <span class="n">fromLocation</span><span class="o">:</span><span class="nb">nil</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">testUpdateToSameLocationDoesNotSendUpdateToDelegate</span>
<span class="p">{</span>
    <span class="c1">// Setup</span>
    <span class="n">CLLocation</span> <span class="o">*</span> <span class="n">location</span> <span class="o">=</span> <span class="p">[</span><span class="n">self</span> <span class="nf">makeLocationWithLatitude</span><span class="p">:</span><span class="o">-</span><span class="mi">37</span><span class="p">.</span><span class="mi">80996889</span> <span class="nf">longitude</span><span class="p">:</span><span class="mi">144</span><span class="p">.</span><span class="mi">96326388</span><span class="p">];</span>
    
    <span class="c1">// Execute</span>
    <span class="p">[</span><span class="n">_formatter</span> <span class="nf">locationManager</span><span class="p">:</span><span class="nb">nil</span> <span class="nf">didUpdateToLocation</span><span class="p">:</span><span class="n">location</span> <span class="n">fromLocation</span><span class="o">:</span><span class="n">location</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">testFailedUpdateSendsUpdateToDelegate</span>
<span class="p">{</span>
    <span class="c1">// Setup</span>
    <span class="n">NSError</span> <span class="o">*</span> <span class="n">error</span> <span class="o">=</span> <span class="p">[</span><span class="n">self</span> <span class="nf">makeFakeErrorWithDescription</span><span class="p">:</span><span class="s">@"Some error description"</span><span class="p">];</span>
    <span class="p">[[</span><span class="n">_mockDelegate</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">locationFormatter</span><span class="p">:</span><span class="n">_formatter</span>
                     <span class="nl">didUpdateFormattedString:</span><span class="s">@"Location manager failed with error: Some error description"</span>
                                <span class="nl">locationLabel:</span><span class="s">@""</span>
                               <span class="nl">accuractyLabel:</span><span class="s">@""</span><span class="p">];</span>
    

    <span class="c1">// Execute</span>
    <span class="p">[</span><span class="n">_formatter</span> <span class="nf">locationManager</span><span class="p">:</span><span class="nb">nil</span> <span class="nf">didFailWithError</span><span class="p">:</span><span class="n">error</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In order to keep the tests short and concise, I’ve moved the lengthy code to create a <code>CLLocation</code> and an <code>NSError</code> out of the tests and into helper methods.  Remember, you’ve got to keep test code clean and maintainable, too.  All three of these tests are only about 35 lines of code.</p>

<p>In contrast, Matt’s two original test methods were over 200 lines of code.  The problem is that Matt’s code is testing the string formatting by asserting the web view’s HTML and text field’s strings.  Separating the responsibility of formatting the strings from updating the UI not only improves the design, but makes testing much simpler.</p>

<p>So we’ve got on almost order of magnitude less code in our test methods that’s cleaner with the same code coverage.  As a bonus, this class can be used in both the Mac and iPhone applications, so we can re-use the core logic.  From an <a href="http://developer.apple.com/mac/library/documentation/General/Conceptual/DevPedia-CocoaCore/MVC.html">MVC</a> perspective, the new <code>MyCoreLocationFormatter</code> class would be considered the model that is used with different views.  Pushing logic out of the controller layer and into a model pays homage to the <a href="http://www.google.com/search?rls=en&amp;q=skinny+controller,+fat+model&amp;ie=UTF-8&amp;oe=UTF-8">skinny controller, fat model</a> design guideline.</p>

<h3>Removing Testing Hacks</h3>

<p>With this class complete, we can now move on to testing the <code>WhereIsMyMacWindowController</code> class.  Matt’s test code uses a couple of hacks in order to enable testing that I consider code smells.</p>

<p>First, it uses runtime trickery, namely <code>object_getInstanceVariable</code> and <code>object_setInstanceVariable</code>, to gain access to the outlet instance variables.  I think this is bad form and prefer to add public accessors for the outlets using properties:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">@property</span> <span class="p">(</span><span class="n">assign</span><span class="p">)</span> <span class="n">IBOutlet</span> <span class="n">WebView</span> <span class="o">*</span><span class="n">webView</span><span class="p">;</span>
<span class="k">@property</span> <span class="p">(</span><span class="n">assign</span><span class="p">)</span> <span class="n">IBOutlet</span> <span class="n">NSTextField</span> <span class="o">*</span><span class="n">locationLabel</span><span class="p">;</span>
<span class="k">@property</span> <span class="p">(</span><span class="n">assign</span><span class="p">)</span> <span class="n">IBOutlet</span> <span class="n">NSTextField</span> <span class="o">*</span><span class="n">accuracyLabel</span><span class="p">;</span>
<span class="k">@property</span> <span class="p">(</span><span class="n">assign</span><span class="p">)</span> <span class="n">IBOutlet</span> <span class="n">NSButton</span> <span class="o">*</span><span class="n">openInBrowserButton</span><span class="p">;</span>
</code></pre></div></div>

<p>Using <code>IBOutlet</code> on a property means the NIB loading code will go through this public interface as well.  Since these properties are already settable by the NIB loading code, I don’t see a big downside to making them public.</p>

<p>Second, the tests use category smashing to inject mock objects of <code>CLLocationManager</code> and <code>NSWorkspace</code> for testing.  Again, I think this is bad form and prefer explicit <a href="http://martinfowler.com/articles/injection.html">dependency injection</a> as a cleaner way to do this.  I’m going to use constructor injection by adding these two initializers to <code>WhereIsMyMacWindowController</code>:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="n">id</span><span class="p">)</span><span class="n">init</span><span class="p">;</span>

<span class="c1">// Designated Initializer</span>
<span class="k">-</span> <span class="p">(</span><span class="n">id</span><span class="p">)</span><span class="nf">initWithLocationManager</span><span class="p">:(</span><span class="n">CLLocationManager</span> <span class="o">*</span><span class="p">)</span><span class="nv">locationManager</span>
            <span class="nf">locationFormatter</span><span class="p">:(</span><span class="n">MyCoreLocationFormatter</span> <span class="o">*</span><span class="p">)</span><span class="nv">locationFormatter</span>
                    <span class="nf">workspace</span><span class="p">:(</span><span class="n">NSWorkspace</span> <span class="o">*</span><span class="p">)</span><span class="nv">workspace</span><span class="p">;</span>
</code></pre></div></div>

<p>The no-argument initializer calls the designated initializer with a new location manager, new location formatter, and the shared workspace.  This allows production code to use the no-argument initializer and allows test code to use the designated initializer in order to inject <a href="http://xunitpatterns.com/Test%20Double.html">test doubles</a>, such as mock objects.</p>

<p>Some may find it odd to pass in an instance of <code>NSWorkspace</code>.  I agree, it is a bit odd, but it’s necessary because it’s a singleton and hard to stub out for testing.  There are other ways to achieve this, such as the category smashing Matt uses, or using a custom factory class that can be overridden by unit tests.  However, eliminating the use of a singleton in the logic and using dependency injection is far more flexible.  What if, for example, we wanted to run tests concurrently, like <a href="http://github.com/gabriel/gh-unit">GHUnit</a> allows?  Now we’ve got to deal with thread safety issues when overriding the  shared global instance. Remember, a singleton is a global in sheep’s clothing.</p>

<p>With these two hacks addressed, our tests in <code>WhereIsMyMacWindowControllerTests</code> become simpler.  Again, I update the fixture to create mock objects for the various dependencies:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">setUp</span>
<span class="p">{</span>
    <span class="c1">// Setup</span>
    <span class="n">_mockLocationManager</span> <span class="o">=</span> <span class="p">[</span><span class="n">OCMockObject</span> <span class="nf">mockForClass</span><span class="p">:[</span><span class="n">CLLocationManager</span> <span class="nf">class</span><span class="p">]];</span>
    <span class="n">_mockLocationFormatter</span> <span class="o">=</span> <span class="p">[</span><span class="n">OCMockObject</span> <span class="nf">mockForClass</span><span class="p">:[</span><span class="n">MyCoreLocationFormatter</span> <span class="nf">class</span><span class="p">]];</span>
    <span class="n">_mockWorkspace</span> <span class="o">=</span> <span class="p">[</span><span class="n">OCMockObject</span> <span class="nf">mockForClass</span><span class="p">:[</span><span class="n">NSWorkspace</span> <span class="nf">class</span><span class="p">]];</span>
    <span class="n">_windowController</span> <span class="o">=</span> <span class="p">[[</span><span class="n">WhereIsMyMacWindowController</span> <span class="nf">alloc</span><span class="p">]</span>
                         <span class="nl">initWithLocationManager:</span><span class="n">_mockLocationManager</span>
                         <span class="nl">locationFormatter:</span><span class="n">_mockLocationFormatter</span>
                         <span class="nl">workspace:</span><span class="nf">_mockWorkspace</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">tearDown</span>
<span class="p">{</span>
    <span class="c1">// Verify</span>
    <span class="p">[</span><span class="n">_mockLocationManager</span> <span class="nf">verify</span><span class="p">];</span>
    <span class="p">[</span><span class="n">_mockLocationFormatter</span> <span class="nf">verify</span><span class="p">];</span>
    <span class="p">[</span><span class="n">_mockWorkspace</span> <span class="nf">verify</span><span class="p">];</span>
    
    <span class="c1">// Teardown</span>
    <span class="p">[</span><span class="n">_windowController</span> <span class="nf">release</span><span class="p">];</span> <span class="n">_windowController</span> <span class="o">=</span> <span class="nb">nil</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here’s a few of the tests to show what a big difference these changes make:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">testWindowDidLoadStartsLocationManager</span>
<span class="p">{</span>
    <span class="c1">// Setup</span>
    <span class="p">[[</span><span class="n">_mockLocationManager</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">setDelegate</span><span class="p">:</span><span class="n">_mockLocationFormatter</span><span class="p">];</span>
    <span class="p">[[</span><span class="n">_mockLocationManager</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">startUpdatingLocation</span><span class="p">];</span>

    <span class="c1">// Execute</span>
    <span class="p">[</span><span class="n">_windowController</span> <span class="nf">windowDidLoad</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">testOpenInDefaultBrowserActionOpensGoogleMapsUrlInWorkspace</span>
<span class="p">{</span>
    <span class="c1">// Setup</span>
    <span class="p">[[[</span><span class="n">_mockLocationManager</span> <span class="nf">stub</span><span class="p">]</span> <span class="nf">andReturn</span><span class="p">:</span><span class="nb">nil</span><span class="p">]</span> <span class="nf">location</span><span class="p">];</span>
    <span class="n">NSURL</span> <span class="o">*</span> <span class="n">dummyUrl</span> <span class="o">=</span> <span class="p">[</span><span class="n">NSURL</span> <span class="nf">URLWithString</span><span class="p">:</span><span class="s">@"http://example.com/"</span><span class="p">];</span>
    <span class="p">[[[</span><span class="n">_mockLocationFormatter</span> <span class="nf">stub</span><span class="p">]</span> <span class="nf">andReturn</span><span class="p">:</span><span class="n">dummyUrl</span><span class="p">]</span> <span class="nf">googleMapsUrlForLocation</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
    <span class="p">[[</span><span class="n">_mockWorkspace</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">openURL</span><span class="p">:</span><span class="n">dummyUrl</span><span class="p">];</span>
    
    <span class="c1">// Execute</span>
    <span class="p">[</span><span class="n">_windowController</span> <span class="nf">openInDefaultBrowser</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">testCloseStopsLocationManager</span>
<span class="p">{</span>
    <span class="c1">// Setup</span>
    <span class="p">[[</span><span class="n">_mockLocationManager</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">stopUpdatingLocation</span><span class="p">];</span>

    <span class="c1">// Execute</span>
    <span class="p">[</span><span class="n">_windowController</span> <span class="nf">close</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Note that I also moved the call to <code>-stopUpdatingLocation</code> from <code>-dealloc</code> to <code>-close</code>.  I try to use <code>-dealloc</code> only for cleaning up memory related resources, which is especially important in a garbage collected environment.  This also means we don’t have to stub out the call to <code>-stopUpdatingLocation</code> everywhere, making our tests simpler, too.</p>

<p>The test to ensure that the location formatter delegate updates the web view and test fields is still a bit lengthy:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">testLocationFormatterDelegateUpdatesUI</span>
<span class="p">{</span>
    <span class="c1">// Setup</span>
    <span class="n">id</span> <span class="n">mockWebView</span> <span class="o">=</span> <span class="p">[</span><span class="n">OCMockObject</span> <span class="nf">mockForClass</span><span class="p">:[</span><span class="n">WebView</span> <span class="nf">class</span><span class="p">]];</span>
    <span class="n">id</span> <span class="n">mockWebFrame</span> <span class="o">=</span> <span class="p">[</span><span class="n">OCMockObject</span> <span class="nf">mockForClass</span><span class="p">:[</span><span class="n">WebFrame</span> <span class="nf">class</span><span class="p">]];</span>
    <span class="n">id</span> <span class="n">mockLocationLabel</span> <span class="o">=</span> <span class="p">[</span><span class="n">OCMockObject</span> <span class="nf">mockForClass</span><span class="p">:[</span><span class="n">NSTextField</span> <span class="nf">class</span><span class="p">]];</span>
    <span class="n">id</span> <span class="n">mockAccuracyLabel</span> <span class="o">=</span> <span class="p">[</span><span class="n">OCMockObject</span> <span class="nf">mockForClass</span><span class="p">:[</span><span class="n">NSTextField</span> <span class="nf">class</span><span class="p">]];</span>
    
    <span class="n">_windowController</span><span class="p">.</span><span class="n">webView</span> <span class="o">=</span> <span class="n">mockWebView</span><span class="p">;</span>
    <span class="n">_windowController</span><span class="p">.</span><span class="n">locationLabel</span> <span class="o">=</span> <span class="n">mockLocationLabel</span><span class="p">;</span>
    <span class="n">_windowController</span><span class="p">.</span><span class="n">accuracyLabel</span> <span class="o">=</span> <span class="n">mockAccuracyLabel</span><span class="p">;</span>
    
    <span class="p">[[[</span><span class="n">mockWebView</span> <span class="nf">stub</span><span class="p">]</span> <span class="nf">andReturn</span><span class="p">:</span><span class="n">mockWebFrame</span><span class="p">]</span> <span class="nf">mainFrame</span><span class="p">];</span>
    <span class="p">[[</span><span class="n">mockWebFrame</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">loadHTMLString</span><span class="p">:</span><span class="s">@"html string"</span> <span class="nf">baseURL</span><span class="p">:</span><span class="nb">nil</span><span class="p">];</span>
    <span class="p">[[</span><span class="n">mockLocationLabel</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">setStringValue</span><span class="p">:</span><span class="s">@"location"</span><span class="p">];</span>
    <span class="p">[[</span><span class="n">mockAccuracyLabel</span> <span class="nf">expect</span><span class="p">]</span> <span class="nf">setStringValue</span><span class="p">:</span><span class="s">@"accuracy"</span><span class="p">];</span>
    
    <span class="c1">// Execute</span>
    <span class="p">[</span><span class="n">_windowController</span> <span class="nf">locationFormatter</span><span class="p">:</span><span class="n">_mockLocationFormatter</span>
                <span class="nl">didUpdateFormattedString:</span><span class="s">@"html string"</span>
                           <span class="nl">locationLabel:</span><span class="s">@"location"</span>
                           <span class="nl">accuracyLabel:</span><span class="s">@"accuracy"</span><span class="p">];</span>
    
    <span class="c1">// Verify</span>
    <span class="p">[</span><span class="n">mockWebFrame</span> <span class="nf">verify</span><span class="p">];</span>
    <span class="p">[</span><span class="n">mockLocationLabel</span> <span class="nf">verify</span><span class="p">];</span>
    <span class="p">[</span><span class="n">mockAccuracyLabel</span> <span class="nf">verify</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Personally, I’m not a big fan of these kinds tests, as well as tests that ensure outlets are setup properly after the NIB loads.  If you stick with the skinny controller, fat model principle, the controllers become so simple they’re almost not worth testing.  Just as you don’t test simple accessors because there’s little benefit to doing so, I don’t know that it’s necessarily worth it to get 100% code coverage on your controller classes.  You still get a big benefit if the bulk of your code is in testable model classes, so this isn’t much of a loss.</p>

<p>There’s more changes I’ve made to the Mac application, and I’ve given the same treatment to the iPhone application, but I don’t want to make this post any longer than it already is.  <a href="https://bitbucket.org/ddribin/whereismyx/src/">View</a> the code I put up on Bitbucket, or <a href="https://bitbucket.org/ddribin/whereismyx/get/2010-01-18.tar.bz2">download a tarball</a>, to see the final result.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[This is a follow-up to my post on why you should unit test Cocoa and iPhone applications. One reason I think Matt is against unit tests, at least given his particular examples, is that the tests themselves are quite large and confusing. They also use category smashing to override methods and inject mock objects and use runtime trickery to gain access to private instance variables. These are all code smells that something isn’t right. Remember, TDD is about tests driving development; however you must remember to listen to the tests when they are crying out in pain. I’m going to take Matt’s Mac and iPhone projects with unit tests and re-work them so that they are much more manageable and cleaner.]]></summary></entry><entry><title type="html">Why Unit Test Cocoa and iPhone Applications</title><link href="https://www.dribin.org/dave/blog/archives/2010/01/18/why_unit_test_cocoa_and_iphone/" rel="alternate" type="text/html" title="Why Unit Test Cocoa and iPhone Applications" /><published>2010-01-18T12:33:45-06:00</published><updated>2010-01-18T12:33:45-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/01/18/why_unit_test_cocoa_and_iphone</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/01/18/why_unit_test_cocoa_and_iphone/"><![CDATA[<p>Matt Gallagher, on his absolutely fantastic <a href="http://cocoawithlove.com/">Cocoa with Love</a> blog, recently wrote a series of posts about test driven development (TDD) and unit testing Mac and iPhone applications:</p>

<ul>
  <li><a href="http://cocoawithlove.com/2009/12/sample-mac-application-with-complete.html">A sample Mac application with complete unit tests</a></li>
  <li><a href="http://cocoawithlove.com/2009/12/sample-iphone-application-with-complete.html">A sample iPhone application with complete unit tests</a></li>
  <li><a href="http://cocoawithlove.com/2010/01/high-quality-in-software-development.html">Quality control in application development without unit testing</a></li>
</ul>

<p>However, I heartily disagree with a major point in the conclusion of his final post:</p>

<blockquote>
  <p>Unit testing an application is filled with difficulties and problems. In my development style, I consider the time cost of unit testing an application outweighs its benefits — especially since a unit tested application still requires system tests like user-interface and regression tests for proper validation.</p>
</blockquote>

<p>Before I talk about why I disagree, I want to say that I <em>do</em> agree with the next part of the conclusion:</p>

<blockquote>
  <p>Regardless of whether you use unit tests, formalized system testing — either automated or manual and methodical — is required to fully validate an application and ensure the lowest possible low bug rates.</p>
</blockquote>

<!--more-->

<p>Unit testing, while practicing TDD, is <a href="http://www.makinggoodsoftware.com/2009/11/21/tdd-is-not-about-testing/">not about testing</a>, in the traditional sense.  Unit testing does <em>not</em> tell you that your final application is actually easy to use by the end user.  Unit testing does <em>not</em> tell you that you actually built an application that solves the problems you intended to address.  Unit testing does <em>not</em> tell you if all your units work together once wired up.  That’s what higher level acceptance and system tests are for.  Acceptance and system tests are required to ensure the overall quality of your application.</p>

<p>However, this doesn’t make unit testing worthless.  Applications have two kinds of quality:  <a href="http://c2.com/cgi/wiki?InternalAndExternalQuality">external and internal</a>.  <em>External quality</em> is how the end users perceive the quality of the application: does it crash, is it easy to use, etc.  Acceptance and system tests keep the external quality high.  <em>Internal quality</em> is how the developers perceive the quality of the code: is easy to understand and maintain, etc.  TDD and unit tests are about keeping the internal quality of the application high.  High internal quality makes bugs easier to find and features easier to implement.  Unit tests provide an essential safety net to be able to refactor your code, improve the design, and avoid <a href="http://en.wikipedia.org/wiki/Software_rot">code rot</a>.  Ultimately this makes software cheaper (and more fun!) to write and easier to stay on schedule.</p>

<p>Thus any real world application should have both unit tests <em>and</em> acceptance tests.  They are not mutually exclusive and they do not serve the same purpose.  I honestly believe that if writing unit tests for TDD is slowing you down, then you are not properly practicing TDD.  Remember TDD is a learned skill, and like any learned skill, it’s not something you pick up overnight.  It takes practice.  Is TDD a panacea? No, it’s not going to cure cancer and bring world peace, but I think <a href="http://blog.objectmentor.com/articles/2009/10/08/tdd-triage">it is the best tool we currently have</a> in our arsenal to keep code clean, flexible, and maintainable.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[Matt Gallagher, on his absolutely fantastic Cocoa with Love blog, recently wrote a series of posts about test driven development (TDD) and unit testing Mac and iPhone applications: A sample Mac application with complete unit tests A sample iPhone application with complete unit tests Quality control in application development without unit testing However, I heartily disagree with a major point in the conclusion of his final post: Unit testing an application is filled with difficulties and problems. In my development style, I consider the time cost of unit testing an application outweighs its benefits — especially since a unit tested application still requires system tests like user-interface and regression tests for proper validation. Before I talk about why I disagree, I want to say that I do agree with the next part of the conclusion: Regardless of whether you use unit tests, formalized system testing — either automated or manual and methodical — is required to fully validate an application and ensure the lowest possible low bug rates.]]></summary></entry><entry><title type="html">Handy sudo Settings</title><link href="https://www.dribin.org/dave/blog/archives/2010/01/13/handy_sudo_settings/" rel="alternate" type="text/html" title="Handy sudo Settings" /><published>2010-01-13T22:33:08-06:00</published><updated>2010-01-13T22:33:08-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2010/01/13/handy_sudo_settings</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2010/01/13/handy_sudo_settings/"><![CDATA[<p>By and large, <a href="http://www.gratisoft.us/sudo/"><code>sudo</code></a> on Mac OS X comes setup with some sane defaults.  But here’s two lines I add to my <a href="http://www.gratisoft.us/sudo/man/sudoers.html"><code>/etc/sudoers</code></a> file on a fresh install:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Defaults        passprompt="%u@%h's password: "
Defaults        timestamp_timeout=15
</code></pre></div></div>

<p>The first line changes the password from something generic:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>% sudo whoami
Password:
root
</code></pre></div></div>

<p>To something a lot more useful:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>% sudo whoami
dave@fuji's password: 
root
</code></pre></div></div>

<p>The second line changes the time between needing to re-enter your password from 5 minutes to 15 minutes.  This is handy if you’re confident you’re in a fairly secure physical environment, like an iMac at home, and you find <code>sudo</code> asking for your password too frequently.  If you work in a more paranoid physical environment, you may want to keep the timeout at 5 minutes.</p>

<p>Remember to edit the file with <a href="http://www.gratisoft.us/sudo/man/visudo.html"><code>visudo(8)</code></a>.  Don’t edit it directly.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>% sudo EDITOR=emacs visudo
</code></pre></div></div>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[By and large, sudo on Mac OS X comes setup with some sane defaults. But here’s two lines I add to my /etc/sudoers file on a fresh install: Defaults passprompt="%u@%h's password: " Defaults timestamp_timeout=15 The first line changes the password from something generic: % sudo whoami Password: root To something a lot more useful: % sudo whoami dave@fuji's password: root The second line changes the time between needing to re-enter your password from 5 minutes to 15 minutes. This is handy if you’re confident you’re in a fairly secure physical environment, like an iMac at home, and you find sudo asking for your password too frequently. If you work in a more paranoid physical environment, you may want to keep the timeout at 5 minutes. Remember to edit the file with visudo(8). Don’t edit it directly. % sudo EDITOR=emacs visudo]]></summary></entry><entry><title type="html">My First NES Homebrew</title><link href="https://www.dribin.org/dave/blog/archives/2009/12/20/first_nes_homebrew/" rel="alternate" type="text/html" title="My First NES Homebrew" /><published>2009-12-20T13:40:23-06:00</published><updated>2009-12-20T13:40:23-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/12/20/first_nes_homebrew</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/12/20/first_nes_homebrew/"><![CDATA[<p>One of my gifts to my wife, Nancy, for her birthday this year was the Happy Birthday song, <a href="http://en.wikipedia.org/wiki/Chiptune">chiptune style</a>.  It’s an actual <a href="http://en.wikipedia.org/wiki/Nintendo_Entertainment_System">NES</a> program, hand-coded in <a href="http://en.wikipedia.org/wiki/6502">6502</a> assembly.  This is the first original NES program I’ve written, and could be considered my first <a href="http://en.wikipedia.org/wiki/Homebrew_(video_games)">homebrew</a> or even <a href="http://en.wikipedia.org/wiki/Demo_(computer_programming)">demo</a>.  While you can download the <a href="https://www.dribin.org/dave/resources/files/2009/nancy_birthday.nes">ROM</a> and run it yourself, here’s a video of it running in <a href="http://www.bannister.org/software/nestopia.htm">Nestopia</a>, an NES emulator [<a href="https://www.youtube.com/watch?v=RzIUPaIICqA">YouTube link</a>]:</p>

<iframe width="420" height="315" src="https://www.youtube-nocookie.com/embed/RzIUPaIICqA" frameborder="0" allowfullscreen=""></iframe>

<p>Some interesting stats about this program:</p>

<!--more-->

<ul>
  <li>The song data is 485 bytes for 42 seconds of music.</li>
  <li>The assembled code is 575 bytes.</li>
  <li>It uses 32 bytes of RAM at runtime, not including stack.</li>
  <li>It uses probably 10 bytes of stack.</li>
  <li>The graphics are 8 kilobytes.</li>
  <li>The ROM file is 24 kilobytes (mostly zeroes, though).</li>
  <li>The video file I uploaded to YouTube was 784 kilobytes.</li>
</ul>

<p>Much thanks to BunnyBoy and MetalSlime for their <a href="http://www.nintendoage.com/faq/nerdy_nights_out.html">“Nerdy Nights”</a> NES coding tutorials on <a href="http://www.nintendoage.com/">Nintedo Age</a>.  The NES sound engine is all MetalSlime’s genius. I just plugged in the notes. The music itself was adapted from some <a href="http://www.virtualsheetmusic.com/downloads/Miscellaneous/HappyBirth.html">sheet music</a> I found.  The lame “graphics” are all mine. I don’t know how to do much other than scroll the background and change the color palette, at the moment.</p>

<p>Also, the <a href="http://nesdev.parodius.com/">NesDev</a> archive and wiki were invaluable as a technical references.  For the toolchain, I used <a href="http://www.cc65.org/">cc65</a>, which includes a very nice assembler and linker for 6502.  It would be nice to run this on actual hardware at some point using flash cartridge like the <a href="http://www.retrousb.com/product_info.php?cPath=24&amp;products_id=34">PowerPak</a>.</p>

<p>I started learning NES programming only a few months ago.  It’s just one of those useless skills I’ve wanted to learn for a while now.  I probably had a bit of head start since I learned 6502 assembly back in the day on an <a href="http://en.wikipedia.org/wiki/Apple_II_series">Apple ][</a>.  Granted, that was a long time ago, but it’s a very simple CPU architecture so it comes back pretty fast.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[One of my gifts to my wife, Nancy, for her birthday this year was the Happy Birthday song, chiptune style. It’s an actual NES program, hand-coded in 6502 assembly. This is the first original NES program I’ve written, and could be considered my first homebrew or even demo. While you can download the ROM and run it yourself, here’s a video of it running in Nestopia, an NES emulator [YouTube link]: Some interesting stats about this program:]]></summary></entry><entry><title type="html">Mercurial and HTTP Passwords</title><link href="https://www.dribin.org/dave/blog/archives/2009/12/20/mercurial_http_passwords/" rel="alternate" type="text/html" title="Mercurial and HTTP Passwords" /><published>2009-12-20T10:44:09-06:00</published><updated>2009-12-20T10:44:09-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/12/20/mercurial_http_passwords</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/12/20/mercurial_http_passwords/"><![CDATA[<p>Authenticated <a href="http://mercurial.selenic.com/">Mercurial</a> repositories are generally handled in one of two ways: HTTP authentication or SSH.  Prior to Mercurial version 1.3, the best way to handle authenticated repositories so that you didn’t have to enter your password on every transaction was to use SSH with ssh-agent, or, if you were running Mac OS X, use Jonathan Wight’s <a href="http://bitbucket.org/schwa/hgkeychain/">hgkeychain</a> extension, which stored HTTP passwords in the Mac OS X keychain.  As of Mercurial 1.3, there’s a new way to handle authenticated HTTP repositories that I’ve just started using.</p>

<!--more-->

<p>Mercurial 1.3 added official support was for storing HTTP authentication information in <code>.hg/hgrc</code>.  The official documentation for this is in the <a href="http://www.selenic.com/mercurial/hgrc.5.html#auth">hgrc.5</a> man page, but there’s also a <a href="http://hgtip.com/tips/advanced/2009-10-01-configuring-user-auth-https/">good article on hgtip.com</a> on how to set it up.  The gist of it is you put something like this in your <code>.hg/hgrc</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[auth]
bb.prefix = https://bitbucket.org
bb.username = {username}
bb.password = {password}
</code></pre></div></div>

<p>The problem with this solution is that your password is stored as plaintext.  Enter <a href="http://pypi.python.org/pypi/mercurial_keyring"><code>mercurial_keyring</code></a>, also known as the <a href="http://mercurial.selenic.com/wiki/KeyringExtension">keyring extension</a>.  If you leave the password out of your <code>hgrc</code>, the keyring extension will prompt you for the password and store it in a system specific password database, such as the OS X keychain, Gnome Keyring, or KDE KWallet.</p>

<p>Earlier versions had one drawback: it stored passwords indexed on the repository’s URL.  For example, if you had two repositories on BitBucket, you’d have to enter your password twice, once for each repository.  This wasn’t ideal, especially when you have many repositories on BitBucket.  Once I entered my BitBucket password, I shouldn’t have to enter it again.</p>

<p>So I forked the project and and modified it so that saved passwords are indexed on the URL prefix you setup in <code>hgrc</code>.  Thus, all authenticated BitBucket repositories will share the same password.  My patches were accepted and included in version 0.4.0 of <a href="http://pypi.python.org/pypi/mercurial_keyring"><code>mercurial_keychain</code></a>.  I’ve only been using it for a day now, but it’s been working out well so far.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[Authenticated Mercurial repositories are generally handled in one of two ways: HTTP authentication or SSH. Prior to Mercurial version 1.3, the best way to handle authenticated repositories so that you didn’t have to enter your password on every transaction was to use SSH with ssh-agent, or, if you were running Mac OS X, use Jonathan Wight’s hgkeychain extension, which stored HTTP passwords in the Mac OS X keychain. As of Mercurial 1.3, there’s a new way to handle authenticated HTTP repositories that I’ve just started using.]]></summary></entry><entry><title type="html">NSConference 2010</title><link href="https://www.dribin.org/dave/blog/archives/2009/12/19/nsconference_2010/" rel="alternate" type="text/html" title="NSConference 2010" /><published>2009-12-19T10:23:04-06:00</published><updated>2009-12-19T10:23:04-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/12/19/nsconference_2010</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/12/19/nsconference_2010/"><![CDATA[<p>For those that  missed the announcement, <a href="http://www.nsconference.com/">NSConference 2010</a> is now open for registration.  NSConference is a 2-day conference for Mac and iPhone developers, plus some optional workshops.  If you missed WWDC or C4, or just can’t get enough good technical information related to all things Mac and iPhone, check out NSConference.  There’s one in Europe and the US, so there’s no excuse for not going!  Yours truly will be giving a talk on writing clean code.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[For those that missed the announcement, NSConference 2010 is now open for registration. NSConference is a 2-day conference for Mac and iPhone developers, plus some optional workshops. If you missed WWDC or C4, or just can’t get enough good technical information related to all things Mac and iPhone, check out NSConference. There’s one in Europe and the US, so there’s no excuse for not going! Yours truly will be giving a talk on writing clean code.]]></summary></entry><entry><title type="html">Bottom Bars in Interface Builder</title><link href="https://www.dribin.org/dave/blog/archives/2009/12/18/bottom_bars_in_ib/" rel="alternate" type="text/html" title="Bottom Bars in Interface Builder" /><published>2009-12-18T00:19:01-06:00</published><updated>2009-12-18T00:19:01-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/12/18/bottom_bars_in_ib</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/12/18/bottom_bars_in_ib/"><![CDATA[<p>Bottom bars have been an important user interface element for a while now on Mac OS X.  They’re that gray status bar you see at the bottom of many of Apple’s applications including iTunes, Finder, iChat, iCal, Address Book, and iPhoto.  The Human Interface Guidelines even has a whole <a href="http://developer.apple.com/mac/library/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGWindows/XHIGWindows.html#//apple_ref/doc/uid/20000961-SW6">section on bottom bars</a> describing what they are and when to use them.  In case you’re not familiar with what they look like, here’s a fresh window with a bottom bar:</p>

<p><img src="https://www.dribin.org/dave/resources/files/2009/bottom_bar.png" width="440" height="372" /></p>

<p>In Mac OS X 10.5, Apple added a new API to <code>NSWindow</code> to add bottom bars, somewhat cryptically named <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSWindow_Class/Reference/Reference.html#//apple_ref/occ/instm/NSWindow/setContentBorderThickness:forEdge:"><code>setContentBorderThickness:forEdge:</code></a>.  There was no support for bottom bars in Interface Builder 3.0 and 3.1, though, so you had to call this method in <code>awakeFromNib</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[window setContentBorderThickness:22 forEdge:NSMinYEdge];
</code></pre></div></div>

<p>In Snow Leopard, we finally get Interface Builder support for bottom bars.  I somehow missed this in the new IB until just this week, and it’s easy to use.</p>

<!--more-->

<p>Select the window object and choose the Size tab of the Info Panel.  You can now set the Content Border of the window:</p>

<p><img src="https://www.dribin.org/dave/resources/files/2009/ib_info.png" width="310" height="629" /></p>

<p>Putting this in the Size tab is a bit non-intuitive to me, and would seem to make more sense in the first Attributes tab.  This is is probably one reason why I never noticed this before, but, alas, that’s a minor complaint.  I’m glad it’s there.</p>

<p>The HIG also has a section on <a href="http://developer.apple.com/mac/library/documentation/UserExperience/Conceptual/AppleHIGuidelines/XHIGLayout/XHIGLayout.html">positioning text and controls in a bottom bar</a>.  Unfortunately, IB does not provide automatic snapping guides that enforce this positioning.  You have to manually count pixels yourself by holding down the Option key or using a separate tool like <a href="http://iconfactory.com/software/xscope">xScope</a>, thus I’ve filed:</p>

<p><a href="rdar://problem/7483606">rdar</a>://<a href="http://openradar.appspot.com/7483606">7483606</a>: ER: Interface Builder should enforce positioning of controls in the bottom bar</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[Bottom bars have been an important user interface element for a while now on Mac OS X. They’re that gray status bar you see at the bottom of many of Apple’s applications including iTunes, Finder, iChat, iCal, Address Book, and iPhoto. The Human Interface Guidelines even has a whole section on bottom bars describing what they are and when to use them. In case you’re not familiar with what they look like, here’s a fresh window with a bottom bar: In Mac OS X 10.5, Apple added a new API to NSWindow to add bottom bars, somewhat cryptically named setContentBorderThickness:forEdge:. There was no support for bottom bars in Interface Builder 3.0 and 3.1, though, so you had to call this method in awakeFromNib: [window setContentBorderThickness:22 forEdge:NSMinYEdge]; In Snow Leopard, we finally get Interface Builder support for bottom bars. I somehow missed this in the new IB until just this week, and it’s easy to use.]]></summary></entry><entry><title type="html">Requirements for a New Blogging System</title><link href="https://www.dribin.org/dave/blog/archives/2009/12/04/new_blog_requirements/" rel="alternate" type="text/html" title="Requirements for a New Blogging System" /><published>2009-12-04T01:40:22-06:00</published><updated>2009-12-04T01:40:22-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/12/04/new_blog_requirements</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/12/04/new_blog_requirements/"><![CDATA[<p>This blog currently runs on Movable Type, and has since I started it back in 2003 on version 2.65 (dang, my <a href="https://www.dribin.org/dave/blog/archives/2003/09/06/purr/">first post</a> is quite a snoozer).  I even wrote some <a href="https://www.dribin.org/dave/software/movabletype/">plugins</a> for version 2 and 3 to cope with some of the <a href="https://www.dribin.org/dave/blog/archives/2003/09/24/permalink_urls/">limitations of its permalinks</a>.</p>

<p>However, I recently learned that <a href="http://www.movabletype.org/documentation/mt5/database/migrate-sqlite-postgresql.html">version 5 will only supports MySQL</a>.  This is a huge disappointment as SQLite is one of the major reasons I chose Movable Type (see <a href="https://www.dribin.org/dave/blog/archives/2007/10/11/upgrade_complete/">my comments</a> about upgrading to MT 4).  I don’t know what’s motivating this decision, but it really makes no sense.  Is it really that hard to write database neutral SQL?  Surely this is a solved problem by now.</p>

<p>This is so bad that it’s deal killer for me, and I’m starting to investigate my options going forward.</p>

<!--more-->

<h3>Why Not Movable Type 4</h3>

<p>The simplest option is to just keep running version 4.  Obviously, it works for me, and it’s the choice with the least amount of effort.  But MT4 isn’t perfect, either.</p>

<p>The big issue is it’s templating system.  I blame the templating system on why my blog looks like ass and doesn’t match the rest of the site.</p>

<p>Maybe I’m just an idiot, but the whole theming system hurts my brain.  First off, the entire theme is stored inside the blog engine.  In order to edit the templates, you have to edit them inside the browser.  This is incredibly lame.</p>

<p>You <em>can</em> link individual templates to a file on the file system, but you have to manually do this for each and every template.  In MT4, there’s something like 20 different templates, and I’m not about to go through each and every one linking them to a file.  (Have I mentioned I’m lazy?)</p>

<p>I think you can use a plugin as a theme, but the documentation on that has been very poor.  There’s no “simplest possible theme” plugin that you can use as a starting polint and build up as necessary.  You’ve got to somehow extract an existing theme into a plugin, which of course, there’s no easy way to do, last I looked into it.</p>

<h3>What am I Looking For?</h3>

<p>Here’s my must-have list of requirements for a blogging system:</p>

<ul>
  <li>Generates static pages.</li>
  <li>Does not require a client-server RDBMS.</li>
  <li>Support writing posts in Markdown or Textile.</li>
  <li>Simple, yet flexible templating system based on files on the file system.</li>
</ul>

<h3>Static</h3>

<p>Basically, this falls under the <a href="http://en.wikipedia.org/wiki/Kiss_principle">KISS principle</a>.  My posts and theme almost never change.  There’s no reason to eat up CPU and memory generating a page each and every time someone hits it.  The big downside to static is that it generally means no comments.  Services like <a href="http://disqus.com/">Disqus</a>, though, mean I can add comments even to a statically generated blog.</p>

<p>Static also means fast it’s <em>fast</em>.  I don’t need to install the latest and greatest super-duper-OMGWTFBBQ cache plugin.  And getting <a href="http://daringfireball.net/">Fireballed</a> won’t take down my site.  The few times my site has been linked by more popular sites, my server hasn’t so much as strained itself, let alone failed to serve up pages.</p>

<h3>No Client-Server RDBMS</h3>

<p>I don’t understand why so many blog systems require a full-blown RDBMS like MySQL or Postgres.  Don’t get me wrong, I <em>love</em> Postgres, but it’s overkill for 99% of the blogs out there, including mine.  An RDBMS complicates setup.  It complicates backup.  It’s one more thing I have to keep secure.  It’s, somewhat ironically, a hinderence to scalability (*cough* “Cannot access MySQL” errors *cough*).  There’s a lot of overlap here between static generation, but they’re mutually exclusive as Movable Type itself shows.</p>

<p>If you’re writing a blog engine and you <em>really</em> feel the need to use SQL, for all that is good and holy, use <a href="http://www.sqlite.org/">SQLite</a> or at least allow it as an option.  SQLite will more than scale for most blogs.  The database should be almost entirely read-only.  Even if you support comments, I doubt you are getting comments added in the hundreds per second category, which means, SQLite will be able to handle your load.</p>

<p>Many static site generators forgo a database completely and just use the file system.  You edit the posts by editing ordinary files.  Plus, it means I can check the whole thing into version control, too.  This is very tempting and seems like it’s even better than SQLite.</p>

<h3>Markdown</h3>

<p>I’m a geek.  I don’t need no stickin’ GUI editor for my posts.  Heck, I <em>could</em> even write them in plain HTML, but Markdown does make things like paragraphs, emphasis, lists a little simpler.  I’m also lazy, so making things simpler is a win.</p>

<h3>Templating</h3>

<p>I covered this a bit above in my current dislike for Movable Type 4, but I want a templating system I can edit completely in the file system.  This way I can edit them with a <em>real</em> text editor, and I can store them in version control.  Having stuff like this in version control is so awesome because it gives you a safety net for mistakes.</p>

<h3>Other Considerations</h3>

<p>I love <a href="http://www.red-sweater.com/marsedit/">MarsEdit</a> for posting.  I’ve been <a href="https://www.dribin.org/dave/blog/archives/2003/12/06/test_nnw/">using it</a> ever since it was part of NetNewsWire.  However, none of the static blogging systems have a remote API like this.  I’m perfectly capable of just editing Markdown files, but there’s something to be said for a dedicated blog editing app.  In my ideal world, I could post either by adding a file or through MarsEdit, whichever strikes my fancy.</p>

<h3>Current Contenders</h3>

<p>Unfortunately, static generation and SQLite support rules out the most common blog systems like Wordpress.  However, I’ve already got a few contenders in mind.  They’re all Ruby-based static generation systems, namely:</p>

<ul>
  <li><a href="http://rote.rubyforge.org/">Rote</a></li>
  <li><a href="http://nanoc.stoneship.org/">nanoc</a></li>
  <li><a href="http://webby.rubyforge.org/">Webby</a></li>
  <li><a href="http://github.com/mojombo/jekyll">Jekyll</a></li>
  <li><a href="http://webgen.rubyforge.org/">webgen</a></li>
  <li>Something custom</li>
</ul>

<p>I’ve already got a good idea of the pros and cons of each.  My shortlist is Rote, nanoc, or something custom.  I need to evaluate each a bit more, though, to really find the winner.  Or maybe I’ll just be lazy and stick with MT4.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[This blog currently runs on Movable Type, and has since I started it back in 2003 on version 2.65 (dang, my first post is quite a snoozer). I even wrote some plugins for version 2 and 3 to cope with some of the limitations of its permalinks. However, I recently learned that version 5 will only supports MySQL. This is a huge disappointment as SQLite is one of the major reasons I chose Movable Type (see my comments about upgrading to MT 4). I don’t know what’s motivating this decision, but it really makes no sense. Is it really that hard to write database neutral SQL? Surely this is a solved problem by now. This is so bad that it’s deal killer for me, and I’m starting to investigate my options going forward.]]></summary></entry><entry><title type="html">Using @rpath - Why and How</title><link href="https://www.dribin.org/dave/blog/archives/2009/11/15/rpath/" rel="alternate" type="text/html" title="Using @rpath - Why and How" /><published>2009-11-15T20:54:28-06:00</published><updated>2009-11-15T20:54:28-06:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/11/15/rpath</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/11/15/rpath/"><![CDATA[<p>Last week, Mike Ash <a href="http://www.mikeash.com/?page=pyblog/friday-qa-2009-11-06-linking-and-install-names.html">wrote a post</a> describing the different install name keywords recognized by the Mac OS X dynamic linker: <code>@executable_path</code>, <code>@loader_path</code>, and <code>@rpath</code>.  I wanted to chime in with a bit of advice: if at all possible use <code>@rpath</code>.</p>

<p>This gist is, if you’re targeting 10.5 or later, use <code>@rpath</code>.  There’s no reason I can think of to still use <code>@loader_path</code>.  If you’re still on 10.4, use <code>@loader_path</code>.  And let’s hope that you’re still not targeting 10.3 and earlier, so forget that <code>@executable_path</code> ever existed.  There’s really never a good reason to use <code>@executable_path</code> on 10.4 and later.</p>

<!--more-->

<p>As Mike wrote, <code>@rpath</code> is the most flexible of the three options.  The big benefit that I see is that the same binary of a framework or dynamic library can be used embedded in a app bundle, by a command line tool, or put in <code>~/Library/Frameworks/</code>.  Basically, it allows you to use the framework wherever you want by putting the onus on the linking app or bundle to define where to find it.</p>

<p>The only major downside is that <code>@rpath</code> requires 10.5 or later; however, with 10.6 already shipping, there’s increasingly fewer reasons to support anything earlier than 10.5.</p>

<p>So how do you actually <em>use</em> <code>@rpath</code>?  Ideally, I think that targets should be setup to use <code>@rpath</code> out of the box (see <a href="rdar://problem/7396127">rdar</a>://<a href="http://openradar.appspot.com/7396127">7396127</a>), but unfortunately it takes a bit of legwork.</p>

<p>As of Xcode 3.x, you set the <strong>Installation Directory</strong> build setting of the framework (or library) target to just <code>@rpath</code>:</p>

<p><img src="https://www.dribin.org/dave/resources/files/2009/install_dir_config.png" width="480" height="231" /></p>

<p>This will set the install name to something like this for frameworks:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@rpath/SpiffyKit.framework/Versions/A/SpiffyKit
</code></pre></div></div>

<p>And something like this for dynamic libraries:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>@rpath/libspiffy.dylib
</code></pre></div></div>

<p>The linking application now needs to define what the <code>@rpath</code> expands out to.  For any bundle, such as an application, framework, or plugin, you’d add <code>@loader_path/../Frameworks</code> to the <strong>Runtime Search Paths</strong> build setting to find embedded frameworks:</p>

<p><img src="https://www.dribin.org/dave/resources/files/2009/rpath_config.png" width="480" height="235" /></p>

<p>Note that you’re still using <code>@loader_path</code> here,as it’s still useful to find the framework relative to the actual binary.</p>

<p>If you want to embed dynamic libraries, it’s probably a good idea to put them in their own directory, say <code>Libraries</code> along side the <code>Frameworks</code> directory in the bundle.  If you do this, add <code>@loader_path/../Libraries</code> to the  <strong>Runtime Search Paths</strong> build setting, too.  Remember, you can have more than one Runtime Search Path.</p>

<p>I’ve created a sample app project with an embedded framework project, both setup to use <code>@rpath</code>, on BitBucket called <a href="http://bitbucket.org/ddribin/rpath-demo/">rpath-demo</a></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>% hg clone http://bitbucket.org/ddribin/rpath-demo/
</code></pre></div></div>

<p>It should compile and run on 10.5 and 10.6 using Xcode 3.0 or newer.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[Last week, Mike Ash wrote a post describing the different install name keywords recognized by the Mac OS X dynamic linker: @executable_path, @loader_path, and @rpath. I wanted to chime in with a bit of advice: if at all possible use @rpath. This gist is, if you’re targeting 10.5 or later, use @rpath. There’s no reason I can think of to still use @loader_path. If you’re still on 10.4, use @loader_path. And let’s hope that you’re still not targeting 10.3 and earlier, so forget that @executable_path ever existed. There’s really never a good reason to use @executable_path on 10.4 and later.]]></summary></entry><entry><title type="html">Xcode Unit Test Bugs</title><link href="https://www.dribin.org/dave/blog/archives/2009/10/24/unit_test_bugs/" rel="alternate" type="text/html" title="Xcode Unit Test Bugs" /><published>2009-10-24T12:16:22-05:00</published><updated>2009-10-24T12:16:22-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/10/24/unit_test_bugs</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/10/24/unit_test_bugs/"><![CDATA[<p>One of the themes of my C4 unit testing talk was that unit testing isn’t as prominent in the Cocoa development community as it is in others, such as Java and Ruby.  After I gave my presentation, I was able to talk to other people about unit testing and their experiences with it.  I was pleased to hear that a lot of people <em>are</em> doing unit testing and want to do more of it.</p>

<p>Unfortunately, a lot of the discussions also revolved around “I’d like to start, but I just have a hard time getting going with Xcode” or some other Xcode or OCUnit limitation that got in their way.  While I am grateful for Xcode’s unit testing integration, coming from IntelliJ’s IDEA for Java, which had <a href="http://www.jetbrains.com/idea/features/junit_testng.html">great testing integration</a>, it does leave a lot to be desired.</p>

<!--more-->

<p>Putting my money where my mouth is, I’ve recently opened up a bunch of bugs about improving unit testing in Xcode:</p>

<ul>
  <li><a href="rdar://problem/7215100">rdar</a>://<a href="http://openradar.appspot.com/7215100">7215100</a> Unit tests should be debuggable with no manual configuration</li>
  <li><a href="rdar://problem/7333513">rdar</a>://<a href="http://openradar.appspot.com/7333513">7333513</a> ER: Automatically set build settings when adding a dependent unit test bundle</li>
  <li><a href="rdar://problem/7333519">rdar</a>://<a href="http://openradar.appspot.com/7333519">7333519</a> ER: Automatically create a unit test target when creating an target</li>
  <li><a href="rdar://problem/7333525">rdar</a>://<a href="http://openradar.appspot.com/7333525">7333525</a> ER: Re-release OCUnit as open source</li>
  <li><a href="rdar://problem/7333564">rdar</a>://<a href="http://openradar.appspot.com/7333564">7333564</a> ER: Add an executable for a unit test target instead of a run script phase</li>
  <li><a href="rdar://problem/7333580">rdar</a>://<a href="http://openradar.appspot.com/7333580">7333580</a> ER: Make creating custom OCUnit assertions easier</li>
  <li><a href="rdar://problem/7333600">rdar</a>://<a href="http://openradar.appspot.com/7333600">7333600</a> ER: Allow running of subset of tests</li>
  <li><a href="rdar://problem/7333645">rdar</a>://<a href="http://openradar.appspot.com/7333645">7333645</a> ER: Don’t start NSApplication when injecting tests into a dependent target</li>
</ul>

<p>Please <a href="https://bugreport.apple.com/">file duplicates</a> or your own enhancement requests, if you have specific ideas, to let the Xcode team we want better unit testing.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[One of the themes of my C4 unit testing talk was that unit testing isn’t as prominent in the Cocoa development community as it is in others, such as Java and Ruby. After I gave my presentation, I was able to talk to other people about unit testing and their experiences with it. I was pleased to hear that a lot of people are doing unit testing and want to do more of it. Unfortunately, a lot of the discussions also revolved around “I’d like to start, but I just have a hard time getting going with Xcode” or some other Xcode or OCUnit limitation that got in their way. While I am grateful for Xcode’s unit testing integration, coming from IntelliJ’s IDEA for Java, which had great testing integration, it does leave a lot to be desired.]]></summary></entry><entry><title type="html">Book List from my C4 Talk</title><link href="https://www.dribin.org/dave/blog/archives/2009/09/27/c4_book_list/" rel="alternate" type="text/html" title="Book List from my C4 Talk" /><published>2009-09-27T22:00:42-05:00</published><updated>2009-09-27T22:00:42-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/09/27/c4_book_list</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/09/27/c4_book_list/"><![CDATA[<p>Thanks, <a href="http://rentzsch.com/">Wolf</a>, for putting on another great C4 and giving me the chance to speak about unit testing. At the end of my talk, I put up a list of books for further reading, and wanted to throw up quick and dirty links to those:</p>

<!--more-->

<iframe src="http://rcm.amazon.com/e/cm?lt1=_top&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=davedribishom-20&amp;o=1&amp;p=8&amp;l=as1&amp;m=amazon&amp;f=ifr&amp;md=10FE9736YVPPT7A0FBG2&amp;asins=0201485672" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<p><a href="http://www.amazon.com/gp/product/0201485672?ie=UTF8&amp;tag=davedribishom-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0201485672">Refactoring: Improving the Design of Existing Code</a><img src="http://www.assoc-amazon.com/e/ir?t=davedribishom-20&amp;l=as2&amp;o=1&amp;a=0201485672" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p><em>Refactoring</em> is a classic book on the art of cleaning up code as a you go.  Ten years later, this is still a fantastic book.  It covers code “smells” that indicate code that needs refactoring and describes over seventy different refactorings you can apply.</p>

<iframe src="http://rcm.amazon.com/e/cm?lt1=_top&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=davedribishom-20&amp;o=1&amp;p=8&amp;l=as1&amp;m=amazon&amp;f=ifr&amp;md=10FE9736YVPPT7A0FBG2&amp;asins=0321146530" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<p><a href="http://www.amazon.com/gp/product/0321146530?ie=UTF8&amp;tag=davedribishom-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0321146530">Test Driven Development: By Example</a><img src="http://www.assoc-amazon.com/e/ir?t=davedribishom-20&amp;l=as2&amp;o=1&amp;a=0321146530" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<iframe src="http://rcm.amazon.com/e/cm?lt1=_top&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=davedribishom-20&amp;o=1&amp;p=8&amp;l=as1&amp;m=amazon&amp;f=ifr&amp;md=10FE9736YVPPT7A0FBG2&amp;asins=0131016490" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<p><a href="http://www.amazon.com/gp/product/0131016490?ie=UTF8&amp;tag=davedribishom-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0131016490">Test-Driven Development: A Practical Guide</a><img src="http://www.assoc-amazon.com/e/ir?t=davedribishom-20&amp;l=as2&amp;o=1&amp;a=0131016490" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>These two books are good if you want to learn more about test-driven development.  I’ve only read the Kent Beck book and really enjoyed it, but I’ve heard good things about Astels’ book, too.</p>

<iframe src="http://rcm.amazon.com/e/cm?lt1=_top&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=davedribishom-20&amp;o=1&amp;p=8&amp;l=as1&amp;m=amazon&amp;f=ifr&amp;md=10FE9736YVPPT7A0FBG2&amp;asins=0131177052" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<p><a href="http://www.amazon.com/gp/product/0131177052?ie=UTF8&amp;tag=davedribishom-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0131177052">Working Effectively with Legacy Code</a><img src="http://www.assoc-amazon.com/e/ir?t=davedribishom-20&amp;l=as2&amp;o=1&amp;a=0131177052" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>Unit testing and doing test-driven development is much easier on greenfield projects.  If, however, you have an existing code base that you’d like to add tests to, then <em>Working Effectively with Legacy Code</em> is for you.  I love that Michael Feathers controversially defines “legacy code” as “any code without tests”.</p>

<iframe src="http://rcm.amazon.com/e/cm?lt1=_top&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=davedribishom-20&amp;o=1&amp;p=8&amp;l=as1&amp;m=amazon&amp;f=ifr&amp;md=10FE9736YVPPT7A0FBG2&amp;asins=0131495054" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<p><a href="http://www.amazon.com/gp/product/0131495054?ie=UTF8&amp;tag=davedribishom-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0131495054">xUnit Test Patterns: Refactoring Test Code</a><img src="http://www.assoc-amazon.com/e/ir?t=davedribishom-20&amp;l=as2&amp;o=1&amp;a=0131495054" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>This is a behemoth of a book, but it’s chock full of good information.  It covers a lot of patterns and anti-patterns of test code, and will almost certainly save you time by if you’re new to unit testing.</p>

<iframe src="http://rcm.amazon.com/e/cm?lt1=_top&amp;bc1=FFFFFF&amp;IS2=1&amp;npa=1&amp;bg1=FFFFFF&amp;fc1=000000&amp;lc1=0000FF&amp;t=davedribishom-20&amp;o=1&amp;p=8&amp;l=as1&amp;m=amazon&amp;f=ifr&amp;md=10FE9736YVPPT7A0FBG2&amp;asins=0132350882" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>

<p><a href="http://www.amazon.com/gp/product/0132350882?ie=UTF8&amp;tag=davedribishom-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0132350882">Clean Code: A Handbook of Agile Software Craftsmanship</a><img src="http://www.assoc-amazon.com/e/ir?t=davedribishom-20&amp;l=as2&amp;o=1&amp;a=0132350882" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<p>This book is basically Pimp My Code on steroids.  There’s a few examples of how to clean up code using  refactoring and unit testing, and it covers good OO design principles along the way.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[Thanks, Wolf, for putting on another great C4 and giving me the chance to speak about unit testing. At the end of my talk, I put up a list of books for further reading, and wanted to throw up quick and dirty links to those:]]></summary></entry><entry><title type="html">Concurrent Operations on Snow Leopard</title><link href="https://www.dribin.org/dave/blog/archives/2009/09/13/snowy_concurrent_operations/" rel="alternate" type="text/html" title="Concurrent Operations on Snow Leopard" /><published>2009-09-13T14:24:29-05:00</published><updated>2009-09-13T14:24:29-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/09/13/snowy_concurrent_operations</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/09/13/snowy_concurrent_operations/"><![CDATA[<p>I previously wrote a <a href="https://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/">post about concurrent operations</a> and how to use them for asynchronous APIs like <code>NSURLConnection</code>.  Unfortunately, the code in that post originally contained a serious error that broke when running on 10.6 (I’ve since updated it).  The API documentation for <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html">NSOperation</a> mentions new behavior for concurrent operations:</p>

<blockquote>
  <p><strong>Note:</strong> In Mac OS X v10.6, operation queues ignore the value returned by <code>isConcurrent</code> and always call the <code>start</code> method of your operation from a separate thread. In Mac OS X v10.5, however, operation queues create a thread only if <code>isConcurrent</code> returns <code>NO</code>. In general, if you are always using operations with an operation queue, there is no reason to make them concurrent.</p>
</blockquote>

<p>This new behavior raises a couple of issues.  First, if you’re using a main-thread only API, it obviously won’t work well or at all when called from a background thread.  Also, our <code>start</code> method is designed to start an asynchronous operation and return as quickly as possible.  The thread that where <code>start</code> is called will generally die after the <code>start</code> method returns (most likely due to operation queues being implemented on top of Grand Central Dispatch).  Thus, even if the operation is safe to run on a background thread, if it requires a run loop, it won’t work.  This is because run loops are tied to a thread, and if the thread dies, then any run loop activity dies with it.</p>

<p>The simple fix I’ve found is to ensure that <code>start</code> is called on the main thread.  This makes it safe for main-thread only APIs as well as asynchronous APIs that rely on the run loop:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">start</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="p">[</span><span class="n">NSThread</span> <span class="nf">isMainThread</span><span class="p">])</span>
    <span class="p">{</span>
        <span class="p">[</span><span class="n">self</span> <span class="nf">performSelectorOnMainThread</span><span class="p">:</span><span class="k">@selector</span><span class="p">(</span><span class="n">start</span><span class="p">)</span> <span class="nf">withObject</span><span class="p">:</span><span class="nb">nil</span> <span class="n">waitUntilDone</span><span class="o">:</span><span class="nb">NO</span><span class="p">];</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="p">[</span><span class="n">self</span> <span class="nf">willChangeValueForKey</span><span class="p">:</span><span class="s">@"isExecuting"</span><span class="p">];</span>
    <span class="n">_isExecuting</span> <span class="o">=</span> <span class="nb">YES</span><span class="p">;</span>
    <span class="p">[</span><span class="n">self</span> <span class="nf">didChangeValueForKey</span><span class="p">:</span><span class="s">@"isExecuting"</span><span class="p">];</span>

    <span class="c1">// Start asynchronous API</span>
<span class="p">}</span>
</code></pre></div></div>

<p> This fix works well on both 10.5 and 10.6.</p>

<p>I’ve known about this problem for some time, and I apologize for not updating the previous post as soon as Snow Leopard was released.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[I previously wrote a post about concurrent operations and how to use them for asynchronous APIs like NSURLConnection. Unfortunately, the code in that post originally contained a serious error that broke when running on 10.6 (I’ve since updated it). The API documentation for NSOperation mentions new behavior for concurrent operations: Note: In Mac OS X v10.6, operation queues ignore the value returned by isConcurrent and always call the start method of your operation from a separate thread. In Mac OS X v10.5, however, operation queues create a thread only if isConcurrent returns NO. In general, if you are always using operations with an operation queue, there is no reason to make them concurrent. This new behavior raises a couple of issues. First, if you’re using a main-thread only API, it obviously won’t work well or at all when called from a background thread. Also, our start method is designed to start an asynchronous operation and return as quickly as possible. The thread that where start is called will generally die after the start method returns (most likely due to operation queues being implemented on top of Grand Central Dispatch). Thus, even if the operation is safe to run on a background thread, if it requires a run loop, it won’t work. This is because run loops are tied to a thread, and if the thread dies, then any run loop activity dies with it. The simple fix I’ve found is to ensure that start is called on the main thread. This makes it safe for main-thread only APIs as well as asynchronous APIs that rely on the run loop: - (void)start { if (![NSThread isMainThread]) { [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO]; return; } [self willChangeValueForKey:@"isExecuting"]; _isExecuting = YES; [self didChangeValueForKey:@"isExecuting"]; // Start asynchronous API }  This fix works well on both 10.5 and 10.6. I’ve known about this problem for some time, and I apologize for not updating the previous post as soon as Snow Leopard was released.]]></summary></entry><entry><title type="html">Mmm… bagels!</title><link href="https://www.dribin.org/dave/blog/archives/2009/08/24/bagels/" rel="alternate" type="text/html" title="Mmm… bagels!" /><published>2009-08-24T23:42:30-05:00</published><updated>2009-08-24T23:42:30-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/08/24/bagels</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/08/24/bagels/"><![CDATA[<p>A few weeks ago, okay, almost two months ago now, I decided to make homemade bagels.  I admit it, I’m a bagel snob.  Most bagels you get these days are just round bread with a hole in the middle.  Too soft, no crust.  Bleh.  Not even worth eating.</p>

<p>Granted there are a few places to get good bagels in Chicago, one of my favorite being <a href="http://nybagelsbialys.com/">New York Bagel &amp; Bialy</a> in Niles; however this isn’t very convenient for us city folk.  While there are a few places in the city that import their bagels from Skokie (<a href="http://www.elevencitydiner.com/">Eleven City Diner</a> and <a href="http://www.beansandbagels.com/">Beans &amp; Bagels</a> come to mind), sometimes you just have to take matters into your own hands.</p>

<p><a href="http://picasaweb.google.com/lh/photo/s1PmyB0Ui1pwEvD0UHyiVA?feat=embedwebsite"><img src="http://lh6.ggpht.com/_1LpV4BQICKE/SmPncZgx_7I/AAAAAAAAA0E/3MWUJaT67PM/s288/IMG_1657.JPG" width="288" height="216" /></a></p>

<!--more-->

<p>I ended up trying the recipe from the fine folks at Cooks Illustrated.  It’s in their <a href="http://www.amazon.com/gp/product/0936184744?ie=UTF8&amp;tag=davedribishom-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0936184744">New Best Recipe</a><img src="http://www.assoc-amazon.com/e/ir?t=davedribishom-20&amp;l=as2&amp;o=1&amp;a=0936184744" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
 book or <a href="http://www.amazon.com/gp/product/0936184752?ie=UTF8&amp;tag=davedribishom-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0936184752">Baking Illustrated</a><img src="http://www.assoc-amazon.com/e/ir?t=davedribishom-20&amp;l=as2&amp;o=1&amp;a=0936184752" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />
 book as well as on their <a href="http://www.cooksillustrated.com/recipes/detail.asp?docid=5962">website</a>, if you have an account.  The recipe is fairly straightforward, though will probably need a few specialty ingredients, like high-gluten flour and barley malt syrup.  I had to get both of those at <a href="http://www.kingarthurflour.com/">King Arthur Flour</a>.  The high-gluten flour sounds like it can be used for pizza dough, too.</p>

<p>The end result was fabulous bagels!  Boiling them before baking gave them a nice, chewy crust.  The inside itself was not too soft and dense.  And as good as they were straight out of the oven, I felt they were even better the next day.  These were certainly as a good as any bagel I’ve ever had.  My wife even called them as good as <a href="http://ess-a-bagel.com/">Ess-a-Bagel</a> in New York, which is quite a compliment!  These were definitely worth making again.</p>

<p><a href="http://picasaweb.google.com/lh/photo/IthBQyiJpGvZwakOlGayCQ?feat=embedwebsite"><img src="http://lh3.ggpht.com/_1LpV4BQICKE/SmPnr2tYr5I/AAAAAAAAA0g/m15e2Zn_P78/s288/IMG_1664.JPG" width="288" height="216" /></a></p>

<p>If you like bagels, definitely try making them at home.  The only downside is that you need a decent stand mixer.  Because the dough is so dry, it’s very stiff and gave my stand mixer a real workout.  In fact, I think it was responsible for stripping the gears on my KitchenAid Artisan mixer.  I tried to make another batch of bagels a couple weeks ago, and it wouldn’t run at low speeds anymore.  I can recall a couple other recipes that stressed the motor, too, but I think this dough just pushed it over the edge.</p>

<p>After investigating the repair options, we decided to get a factory refurbished KitchenAid Pro 600.  I have too many attachments to switch to another brand, at this point.  Talk about vendor lock-in, eh?  The motor is more powerful and the gears and gearbox are all metal, so hopefully they won’t strip again.  It’s only got a six month warranty so I just need to put it through its paces for those six months.  The new mixer will arrive in about a week, and the first thing I’m going to do is make another batch of these.</p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="food" /><summary type="html"><![CDATA[A few weeks ago, okay, almost two months ago now, I decided to make homemade bagels. I admit it, I’m a bagel snob. Most bagels you get these days are just round bread with a hole in the middle. Too soft, no crust. Bleh. Not even worth eating. Granted there are a few places to get good bagels in Chicago, one of my favorite being New York Bagel &amp; Bialy in Niles; however this isn’t very convenient for us city folk. While there are a few places in the city that import their bagels from Skokie (Eleven City Diner and Beans &amp; Bagels come to mind), sometimes you just have to take matters into your own hands.]]></summary></entry><entry><title type="html">Concurrent Operations Demystified</title><link href="https://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/" rel="alternate" type="text/html" title="Concurrent Operations Demystified" /><published>2009-05-05T22:47:40-05:00</published><updated>2009-05-05T22:47:40-05:00</updated><id>https://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations</id><content type="html" xml:base="https://www.dribin.org/dave/blog/archives/2009/05/05/concurrent_operations/"><![CDATA[<p><a href="http://developer.apple.com/documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html"><code>NSOperation</code></a> and <a href="http://developer.apple.com/documentation/Cocoa/Reference/NSOperationQueue_class/Reference/Reference.html"><code>NSOperationQueue</code></a> are available on Leopard or the iPhone to help you parallelize your code.  The idea is that if you have code that takes a long time to execute, you create an <code>NSOperation</code> subclass, override <code>main</code>, and put your long running code in there:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">@implementation</span> <span class="nc">CalculatePiOperation</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">main</span>
<span class="p">{</span>
    <span class="c1">// Calculate PI to 1,000,000 digits</span>
<span class="p">}</span>

<span class="k">@end</span>
</code></pre></div></div>

<p>To execute an operation, you typically add it to an <code>NSOperationQueue</code>:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">NSOperationQueue</span> <span class="o">*</span> <span class="n">queue</span> <span class="o">=</span> <span class="p">[[</span><span class="n">NSOperationQueue</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">init</span><span class="p">];</span>
<span class="n">NSOperation</span> <span class="o">*</span> <span class="n">piOperation</span> <span class="o">=</span> <span class="p">[[[</span><span class="n">CalculatePiOperatin</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">init</span><span class="p">]</span> <span class="nf">autorelease</span><span class="p">];</span>
<span class="p">[</span><span class="n">queue</span> <span class="nf">addOperation</span><span class="p">:</span><span class="n">piOperation</span><span class="p">];</span>
</code></pre></div></div>

<p>If you add multiple operations to a queue, they all execute in parallel on background threads, allowing your main thread to deal with the user  interface.  The queue will intelligently schedule the number of parallel operations based on the number of CPU cores your users have, thus effectively taking advantage of your users’ hardware.</p>

<p>The only caveat is that the lifetime of an operation is the <code>main</code> method.  Once that method returns, the operation is finished and it gets removed from the queue.  If you want to use a class that has an asynchronous API, you have to jump through some hoops.  Typically you have to play games with the run loop to ensure that the <code>main</code> method doesn’t return prematurely.</p>

<p>While there are times when you want to do this, it can also be a pain.  In other cases, you may not be allowed to use the API on a background thread because it is designed to only work on the <a href="https://www.dribin.org/dave/blog/archives/2009/02/01/main_thread_apis/">main thread</a>.  Enter concurrent operations.</p>

<!--more-->

<p>Operations come in two flavors: <em>concurrent</em> and <em>non-concurrent</em>.  In an unfortunate case of confusing terminology, the default <code>NSOperation</code> subclass is called non-concurrent.  I say unfortunate because the way the are used on an operation queue, they run in parallel.  So, yes, operations that run in parallel are called non-concurrent.</p>

<p>Concurrent operations are created by overriding the the <code>isConcurrent</code> method in your subclass to return <code>YES</code>:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="n">BOOL</span><span class="p">)</span><span class="n">isConcurrent</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="nb">YES</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<strike>When a concurrent operation is added to an operation queue, it is started not on a background thread, but on the thread on which they were added.  So, yes, concurrent operations all run on the same thread whereas non-concurrent execute in parallel on different threads.  Got that?  Good.</strike>

<p><strong>Update 2009-09-13:</strong> This is no longer true as of 10.6.  The <code>start</code> method is <em>always</em> called on a background thread as of 10.6.  To work properly with main-thread only and asynchronous APIs that rely on the run loop, we need to shunt our work over to the main thread.  More on this in a <a href="https://www.dribin.org/dave/blog/archives/2009/09/13/snowy_concurrent_operations/">followup post</a>.</p>

<p>In any case, another major difference with concurrent threads is that you override <code>start</code>, instead of <code>main</code>.  Also, the operation is not finished once the <code>start</code> method returns.  This allows you to control the lifetime of the operation.</p>

<p>When dealing with asynchronous APIs, we can begin the asynchronous call on the main thread in <code>start</code> and keep the operation running until it finishes.</p>

<p>We also have a few more responsibilities.  We need to keep track of <code>isExecuting</code> and <code>isFinished</code> ourselves, and we need to modify them in a <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html">key-value coding</a> compliant manner.  I typically do this using instance variables.  The operation is only considered finished when the <code>isFinished</code> property changes to <code>YES</code>.</p>

<p>For example, if we want to write an operation that downloads data from a URL using <code>URLConnection</code>, its initializer would be:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="n">id</span><span class="p">)</span><span class="nf">initWithUrl</span><span class="p">:(</span><span class="n">NSURL</span> <span class="o">*</span><span class="p">)</span><span class="nv">url</span>
<span class="p">{</span>
    <span class="n">self</span> <span class="o">=</span> <span class="p">[</span><span class="n">super</span> <span class="nf">init</span><span class="p">];</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">self</span> <span class="o">==</span> <span class="nb">nil</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">nil</span><span class="p">;</span>
    
    <span class="n">_url</span> <span class="o">=</span> <span class="p">[</span><span class="n">url</span> <span class="nf">copy</span><span class="p">];</span>
    <span class="n">_isExecuting</span> <span class="o">=</span> <span class="nb">NO</span><span class="p">;</span>
    <span class="n">_isFinished</span> <span class="o">=</span> <span class="nb">NO</span><span class="p">;</span>
    
    <span class="k">return</span> <span class="n">self</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The <code>start</code> method shunts itself to the main thread, kicks off an asynchronous <code>NSURLConnection</code>, and returns:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">start</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="p">[</span><span class="n">NSThread</span> <span class="nf">isMainThread</span><span class="p">])</span>
    <span class="p">{</span>
        <span class="p">[</span><span class="n">self</span> <span class="nf">performSelectorOnMainThread</span><span class="p">:</span><span class="k">@selector</span><span class="p">(</span><span class="n">start</span><span class="p">)</span> <span class="nf">withObject</span><span class="p">:</span><span class="nb">nil</span> <span class="n">waitUntilDone</span><span class="o">:</span><span class="nb">NO</span><span class="p">];</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">NSLog</span><span class="p">(</span><span class="s">@"opeartion for &lt;%@&gt; started."</span><span class="p">,</span> <span class="n">_url</span><span class="p">);</span>
    
    <span class="p">[</span><span class="n">self</span> <span class="nf">willChangeValueForKey</span><span class="p">:</span><span class="s">@"isExecuting"</span><span class="p">];</span>
    <span class="n">_isExecuting</span> <span class="o">=</span> <span class="nb">YES</span><span class="p">;</span>
    <span class="p">[</span><span class="n">self</span> <span class="nf">didChangeValueForKey</span><span class="p">:</span><span class="s">@"isExecuting"</span><span class="p">];</span>

    <span class="n">NSURLRequest</span> <span class="o">*</span> <span class="n">request</span> <span class="o">=</span> <span class="p">[</span><span class="n">NSURLRequest</span> <span class="nf">requestWithURL</span><span class="p">:</span><span class="n">_url</span><span class="p">];</span>
    <span class="n">_connection</span> <span class="o">=</span> <span class="p">[[</span><span class="n">NSURLConnection</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithRequest</span><span class="p">:</span><span class="n">request</span>
                                                  <span class="nl">delegate:</span><span class="n">self</span><span class="p">];</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">_connection</span> <span class="o">==</span> <span class="nb">nil</span><span class="p">)</span>
        <span class="p">[</span><span class="n">self</span> <span class="nf">finish</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>There are three important points here.  First, we have to make sure we are running on the main thread.  Second, we have to change the <code>isExecuting</code> property to <code>YES</code>.  Third, our <code>start</code> method returns before the <code>NSURLConnection</code> has completed, but the operation is still executing.  This means our operation stays on the queue while the <code>NSURLConnection</code> is running, all without having to play games with the run loop.</p>

<p>We are using a private <code>finish</code> method to end the operation:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">finish</span>
<span class="p">{</span>
    <span class="n">NSLog</span><span class="p">(</span><span class="s">@"operation for &lt;%@&gt; finished. "</span>
          <span class="s">@"status code: %d, error: %@, data size: %u"</span><span class="p">,</span>
          <span class="n">_url</span><span class="p">,</span> <span class="n">_statusCode</span><span class="p">,</span> <span class="n">_error</span><span class="p">,</span> <span class="p">[</span><span class="n">_data</span> <span class="nf">length</span><span class="p">]);</span>
    
    <span class="p">[</span><span class="n">_connection</span> <span class="nf">release</span><span class="p">];</span>
    <span class="n">_connection</span> <span class="o">=</span> <span class="nb">nil</span><span class="p">;</span>
    
    <span class="p">[</span><span class="n">self</span> <span class="nf">willChangeValueForKey</span><span class="p">:</span><span class="s">@"isExecuting"</span><span class="p">];</span>
    <span class="p">[</span><span class="n">self</span> <span class="nf">willChangeValueForKey</span><span class="p">:</span><span class="s">@"isFinished"</span><span class="p">];</span>

    <span class="n">_isExecuting</span> <span class="o">=</span> <span class="nb">NO</span><span class="p">;</span>
    <span class="n">_isFinished</span> <span class="o">=</span> <span class="nb">YES</span><span class="p">;</span>

    <span class="p">[</span><span class="n">self</span> <span class="nf">didChangeValueForKey</span><span class="p">:</span><span class="s">@"isExecuting"</span><span class="p">];</span>
    <span class="p">[</span><span class="n">self</span> <span class="nf">didChangeValueForKey</span><span class="p">:</span><span class="s">@"isFinished"</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The key point here is that we change the <code>isExecuting</code> and <code>isFinished</code> flags.  Only when these are set to <code>NO</code> and <code>YES</code>, respectively, will the operation be removed from the queue.  The queue monitors their values using <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html">key-value observing</a>.</p>

<p>The <code>URLConnection</code> delegate methods accumulate data or end the operation, as appropriate:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">connection</span><span class="p">:(</span><span class="n">NSURLConnection</span> <span class="o">*</span><span class="p">)</span><span class="nv">connection</span>
<span class="nf">didReceiveResponse</span><span class="p">:(</span><span class="n">NSURLResponse</span> <span class="o">*</span><span class="p">)</span><span class="nv">response</span>
<span class="p">{</span>
    <span class="p">[</span><span class="n">_data</span> <span class="nf">release</span><span class="p">];</span>
    <span class="n">_data</span> <span class="o">=</span> <span class="p">[[</span><span class="n">NSMutableData</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">init</span><span class="p">];</span>

    <span class="n">NSHTTPURLResponse</span> <span class="o">*</span> <span class="n">httpResponse</span> <span class="o">=</span> <span class="p">(</span><span class="n">NSHTTPURLResponse</span> <span class="o">*</span><span class="p">)</span><span class="n">response</span><span class="p">;</span>
    <span class="n">_statusCode</span> <span class="o">=</span> <span class="p">[</span><span class="n">httpResponse</span> <span class="nf">statusCode</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">connection</span><span class="p">:(</span><span class="n">NSURLConnection</span> <span class="o">*</span><span class="p">)</span><span class="nv">connection</span>
    <span class="nf">didReceiveData</span><span class="p">:(</span><span class="n">NSData</span> <span class="o">*</span><span class="p">)</span><span class="nv">data</span>
<span class="p">{</span>
    <span class="p">[</span><span class="n">_data</span> <span class="nf">appendData</span><span class="p">:</span><span class="n">data</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">connectionDidFinishLoading</span><span class="p">:(</span><span class="n">NSURLConnection</span> <span class="o">*</span><span class="p">)</span><span class="nv">connection</span>
<span class="p">{</span>
    <span class="p">[</span><span class="n">self</span> <span class="nf">finish</span><span class="p">];</span>
<span class="p">}</span>

<span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">connection</span><span class="p">:(</span><span class="n">NSURLConnection</span> <span class="o">*</span><span class="p">)</span><span class="nv">connection</span>
  <span class="nf">didFailWithError</span><span class="p">:(</span><span class="n">NSError</span> <span class="o">*</span><span class="p">)</span><span class="nv">error</span>
<span class="p">{</span>
    <span class="n">_error</span> <span class="o">=</span> <span class="p">[</span><span class="n">error</span> <span class="nf">copy</span><span class="p">];</span>
    <span class="p">[</span><span class="n">self</span> <span class="nf">finish</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>As you can see, we don’t have to turn an asynchronous API into a synchronous one, and yet we are still able to package up this task as an operation.  While it may seem a little counterintuitive to use an operation, it does have its benefits.  For example, you can use the queue to limit the number of parallel downloads to two:</p>

<div class="language-objc highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">_queue</span> <span class="o">=</span> <span class="p">[[</span><span class="n">NSOperationQueue</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">init</span><span class="p">];</span>
    <span class="p">[</span><span class="n">_queue</span> <span class="nf">setMaxConcurrentOperationCount</span><span class="p">:</span><span class="mi">2</span><span class="p">];</span>
</code></pre></div></div>

<p>Also, you can use operation dependencies to make sure tasks occur in a proper order.</p>

<p>In <a href="http://www.bitmaki.com/textcast/">Textcast</a>, we use concurrent operations almost exclusively.  We package up <code>NSSpeechSynthesizer</code>, <code>PubSub</code>, and <code>WebKit</code> as concurrent operations since they all have asynchronous APIs.  All of these APIs also have thread safety issues of some sort and are better run on the main thread.  Concurrent operations make this easier to manage.</p>

<p>Download a full example project demonstrating how to use concurrent operations: <a href="https://www.dribin.org/dave/resources/files/2009/Concurrent.tgz">Concurrent.tgz</a></p>]]><![CDATA[]]></content><author><name>Dave Dribin</name></author><category term="tech" /><summary type="html"><![CDATA[NSOperation and NSOperationQueue are available on Leopard or the iPhone to help you parallelize your code. The idea is that if you have code that takes a long time to execute, you create an NSOperation subclass, override main, and put your long running code in there: @implementation CalculatePiOperation - (void)main { // Calculate PI to 1,000,000 digits } @end To execute an operation, you typically add it to an NSOperationQueue: NSOperationQueue * queue = [[NSOperationQueue alloc] init]; NSOperation * piOperation = [[[CalculatePiOperatin alloc] init] autorelease]; [queue addOperation:piOperation]; If you add multiple operations to a queue, they all execute in parallel on background threads, allowing your main thread to deal with the user interface. The queue will intelligently schedule the number of parallel operations based on the number of CPU cores your users have, thus effectively taking advantage of your users’ hardware. The only caveat is that the lifetime of an operation is the main method. Once that method returns, the operation is finished and it gets removed from the queue. If you want to use a class that has an asynchronous API, you have to jump through some hoops. Typically you have to play games with the run loop to ensure that the main method doesn’t return prematurely. While there are times when you want to do this, it can also be a pain. In other cases, you may not be allowed to use the API on a background thread because it is designed to only work on the main thread. Enter concurrent operations.]]></summary></entry></feed>