<?xml version="1.0" encoding="utf-8" ?>
<rss version="2.0" xmlns:admin="http://webns.net/mvcb/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:html="http://www.w3.org/1999/html" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>Random notes from mg</title><link>http://mg.pov.lt/blog</link><description>a blog by Marius Gedminas</description><language>en</language><ttl>60</ttl><dc:creator>Marius Gedminas</dc:creator><admin:generatorAgent rdf:resource="http://pyblosxom.sourceforge.net/"/><admin:errorReportsTo rdf:resource="mailto:marius@gedmin.as"/><item><title>Review: Python Testing: Beginner's Guide</title><guid isPermaLink="false">python-testing-review</guid><link>http://mg.pov.lt/blog/python-testing-review</link><description>I've been testing (as well as writing) Python code for the last eight years, so a book with the words ...</description><content:encoded><![CDATA[
<p>I've been testing (as well as writing) Python code for the last eight years,
so a book with the words <em>Begginer's Guide</em> prominently displayed on
the cover isn't something I'd've decided to buy for myself.  Nevertheless
I jumped at the offer of receiving a free e-copy for reviewing it.</p>

<p style="float: right; margin: 0 0 1em 1em">
<a href="http://www.packtpub.com/python-testing-beginners-guide/book?utm_source=mg.pov.lt&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_002640">
  <img src="http://mg.pov.lt/python-testing.jpg"
       width="250" height="309" alt="Python Testing: Beginner's Guide by Danien Arbuckle" />
</a>
</p>

<p><strong>Short summary:</strong> it's good book.  I learned a thing or two
from it.  I don't know well it would work as an introductionary text for
someone new to unit testing (or Python).  Some of the bits seemed
overcomplicated and underexplained, parts of the example code/tests seemed to
contain design decisions received from mysterious sources.</p>

<p>Incidentally, <a href="http://www.packtpub.com/">Packt</a> uses a simple yet
effective method for watermarking e-books: my name and street address are
displayed in the footer of every page.  What's funny is that the two non-ASCII
characters in the street name are replaced with question marks.  It's not a
data entry problem: the website that let me download those books shows my
address correctly, so it must be happening somewhere in the PDF production
process.  I didn't expect this kind of Unicode buggyness from a publisher.
Then again there were occasional strange little typographical errors in the
text, like not leaving a space in front of an opening parenthesis in an English
sentence, or using a never-seen-before <tt>+q=</tt> operator in Python code.  I
was also left wondering how the following sentence (page 225) could slip past
the editing process:</p>

<blockquote>
  doctest ignores everything between the <tt>Traceback (most recent last call)</tt>.
</blockquote>

<p>Thankfully those small mistakes did not detract from the overall message of
the book.</p>

<p>I liked the author's technique of showing subtly incorrect code, letting the
reader look at it and miss all the bugs, and then showing how unit or
integration tests catch the bugs the reader missed.  I'm pretty sure there's at
least one remaining bug that the author missed in the example package (storing
a schedule doesn't erase old data), which could serve for a new chapter on
regression testing if there's a second edition.</p>

<p>Summary of topics covered:</p>
<ul>
  <li>Terms: unit testing, integration testing, system testing.</li>
  <li>Basics of doctest and unittest, their strengths and weaknesses.</li>
  <li>Using mocks (with Mocker).</li>
  <li>Using Nose.</li>
  <li>Test-Driven Development with lots of example code.</li>
  <li>Using Twill.</li>
  <li>Integration testing with lots of example code.</li>
  <li>Using coverage</li>
  <li>Post-commit hooks to run tests with Bazaar, Mercurial, Git, Darcs,
      Subversion.</li>
  <li>Continuous integration with Buildbot</li>
</ul>

<p>I found the TDD cycle a bit larger than I generally like, but I believe it's
a matter of taste, and perhaps a shorter cycle wouldn't work as well in a
written medium.</p>

<p>I found it a bit jarring how the Twill chapter intrudes between the two
chapters showing unit testing and integration testing of the same sample
package.  I think it would've been better to swap the order of chapters 8 and
9.</p>

<p>I liked the technique presented for picking subsets of the code for
integration tests, although I wonder how well it would work on a larger
project.</p>

<p>Topics not covered:</p>
<ul>
  <li>Functional testing (which is very close but not exactly the same as
      system testing).</li>
  <li>Regression testing (page 46 contains advice about this without mentioning
      the term <em>regression testing</em>).</li>
  <li>Continuous integration with Hudson (simpler to set up than buildbot,
      easily covers 80% of cases).</li>
</ul>

<p>As you can see these holes are all rather small.</p>

<p>Probably the biggest weakness of the book is the complexity of some
things shown:
</p>

<ul>
  <li> writing mocks for pure unit tests </li>
  <li> mocking other instances of the same class under test </li>
  <li> even occasionally mocking <em>self</em>, which needs tricks like
       calling a method's <tt>im_func</tt> directly </li>
  <li> mocking <tt>__reduce_ex__</tt> so you can pickle mocks in an
       <em>integration test</em>, instead of using real classes or simple
       stubs. </li>
  <li> testing the same code multiple times: unit tests, several sets of
       integration tests that test ever-increasing subsets of classes </li>
  <li> <a href="http://buildbot.net/">Buildbot</a> instead of
       <a href="http://hudson-ci.org/">Hudson</a> </li>
</ul>

<p> Seeing the repetitive and redundant mock code in the first few doctest
examples I started asking <em>what's the point?</em>, but the book failed to
provide a compelling answer (the answer provided&mdash;it's easier to locate
bugs&mdash;works just as well for integration tests that focus on individual
classes).  And there are good answers for that question, like instant feedback
from your unit test suite.  Are they worth the additional development effort?
Maybe that depends on the developer.  I don't think they would help me, so I
tend to stick with low-level integration tests I call "unit tests" (as well as
system tests; it's always a mistake to keep all your tests in a single level).
I'm slightly worried that this book might give the wrong impression (testing is
hard) and turn away beginning Python programmers from writing tests
altogether.</p>

<p>Overall I do not feel that I have wasted my time reading <a
  href="http://www.packtpub.com/python-testing-beginners-guide/book?utm_source=mg.pov.lt&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_002640">Python
  Testing</a>.  I look forward to reading <a
  href="http://python.genedrift.org/2010/03/03/python-testing-beginner’s-guide-review/">the</a>
<a
  href="http://www.blog.pythonlibrary.org/2010/03/06/book-review-python-testing/">other</a>
<a
  href="http://mcjeff.blogspot.com/2010/03/review-python-testing-beginners-guide.html">reviews</a>
that showed up on Planet Python.  I gathered that not all reviewers were happy
with the book, but avoided reading their reviews in order not to influence my
own.</p>
]]></content:encoded><dc:date>2010-03-13T19:54:48Z</dc:date></item><item><title>You've got to love profiling</title><guid isPermaLink="false">you-gotta-love-profiling</guid><link>http://mg.pov.lt/blog/you-gotta-love-profiling</link><description>Yesterday I slashed 50% of run time from our applications functional test suite by modifying a single function. I had ...</description><content:encoded><![CDATA[
<p>Yesterday I slashed 50% of run time from our applications functional test
suite by modifying a single function.  I had no idea that function was
responsible for 50% of the run time until I started profiling.</p>

<p>Profiling a Python program is getting easier and easier:</p>

<blockquote>
<pre>
<span class="prompt">$</span> <span class="typing">python -m cProfile -o prof.data bin/test -f</span>
</pre>
</blockquote>

<p>runs our test runner (which is a Python script) under the <a
  href="http://docs.python.org/library/profile.html">profiler</a> and stores
the results in prof.data.</p>

<blockquote>
<pre>
<span class="prompt">$</span> <span class="typing">runsnake prof.data</span>
</pre>
</blockquote>

<p>launches the <a
  href="http://www.vrplumber.com/programming/runsnakerun/">RunSnakeRun</a>
profile viewer, which displays the results visually:</p>

<p style="text-align: center">
<a href="http://mg.pov.lt/run-snake-run.png">
<img style="border: 1px solid #ccc; padding: 6px"
     src="http://mg.pov.lt/run-snake-run-square-map.png"
     alt="RunSnakeRun square map display" width="505" height="370" />
</a>
<br/>
The square map display of RunSnakeRun, with the 'render_restructured_text'
function highlighted.
</p>

<p>Who knew that ReStructuredText rendering could be such a time waster?  A
short caching decorator and the test suite is twice as fast.  The whole
exercise took me less than an hour.  I should've done it sooner.</p>

<p>Other neat tools:</p>

<ul>
  <li><a href="http://docs.python.org/library/profile.html?highlight=pstats#pstats.Stats">pstats</a>
  from the standard library lets you load and display profiler results from the
  command line (try <tt>python -m pstats prof.data</tt>).</li>
  <li><a href="http://pypi.python.org/pypi/pyprof2calltree">pyprof2calltree</a>
  converts Python profiler data files to a format that the popular profiler
  visualization tool <a
    href="http://kcachegrind.sourceforge.net/html/Home.html">kcachegrind</a>
  can understand.  It's somewhat less useful now that RunSnakeRun exists.</li>
  <li><a href="http://pypi.python.org/pypi/profilehooks">profilehooks</a> by
  yours truly has decorators for easily profiling individual functions instead
  of entire scripts.</li>
  <li><a href="http://pypi.python.org/pypi/keas.profile">keas.profile</a> and <a
    href="http://pypi.python.org/pypi/repoze.profile">repoze.profile</a> hook
  up the profiler as WSGI middleware for easy profiling of web apps.</li>
</ul>
]]></content:encoded><dc:date>2010-03-06T18:49:00Z</dc:date></item><item><title>Bye, bye, free time!</title><guid isPermaLink="false">volunteeritis</guid><link>http://mg.pov.lt/blog/volunteeritis</link><description>Things I've taken up to do in the nearest future: Read and review Python Testing: Beginner's Guide and Grok 1.0 ...</description><content:encoded><![CDATA[
<p>Things I've taken up to do in the nearest future:</p>

<ul>
  <li>
    Read and review <a
      href="http://www.packtpub.com/python-testing-beginners-guide/book?utm_source=mg.pov.lt&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_002640">Python
      Testing: Beginner's Guide</a> and <a
      href="http://www.packtpub.com/grok-1-0-web-development/book?utm_source=mg.pov.lt&amp;utm_medium=bookrev&amp;utm_content=blog&amp;utm_campaign=mdb_002639">Grok
      1.0 Web Development</a> for Packt.  (The links are trackable to my blog,
    but I'm not getting anything out of it.  Other than free copies of the
    e-books, which I already received, in exchange for a promise to review them
    on this blog.)
  </li>
  <li>
    Help <a href="http://www.reportlab.com/software/opensource/">Reportlab</a>
    folks set up continuous integration (most likely <a
      href="http://hudson-ci.org/">Hudson</a>, since <a
      href="http://buildbot.net/">Buildbot</a>, while powerful, has a steep
    learning curve).
  </li>
  <li>
    Think about becoming the buildbotmaster for Zope.  Originally I intended
    to volunteer to set up a few buildbots for various Zopeish projects
    (ZTK, BlueBream, Grok, Zope 2) since half of the <a
      href="http://docs.zope.org/zopetoolkit/process/buildbots.html">existing
      ones</a> were down or broken.  Then various people fixed some of the
    broken ones and other people chimed in mentioning existing buildbots that
    nobody else knew about.  There is a need for somebody to coordinate all
    this activity: make sure we have up-to-date test results for all kinds of
    projects, aggregate them in one place, chase up build slaves for exotic
    OSes (i.e. Windows)...  I don't think I'm well suited for this kind of
    organisational activity.
  </li>
  <li>
    Push along the various scratch-my-itch open source projects (<a
      href="http://mg.pov.lt/gtimelog/">GTimeLog</a>, <a
      href="http://mg.pov.lt/irclog2html/">irclog2html</a>,
      <a href="https://launchpad.net/zodbbrowser">zodbbrowser</a>).
  </li>
  <li>
    No idea what, but I've been wanting to do something for <a
      href="http://maemo.org/">Maemo</a>.  Something small, given the copious
    amounts of free time I have.
  </li>
  <li>
    Then there's the paying work.  On the plus side, there are opportunities
    for fun there (today I slashed functional test run time by a half, by
    adding a small caching decorator in front of a single function.
    <a href="http://www.vrplumber.com/programming/runsnakerun/">RunSnakeRun</a>
    and <a href="http://docs.python.org/library/profile.html">cProfile</a>
    rule!)
  </li>
  <li>
    You know what, scratch the Zope buildbotmaster idea.  Maybe I can do
    something technical there, e.g. a cron script to ping the various buildbot,
    scrape HTML/parse emails and aggregate build results.  Maybe.
  </li>
  <li>
    I hope I don't get <a
      href="http://en.wikipedia.org/wiki/Burnout_(psychology)">burnout</a>
    again.  Because that would suck.  Again.  Been there, done that, didn't
    even get a T-shirt.
  </li>
</ul>

<p>I really ought to read Getting Things Done.  Reading it has been on my
todo-list for <em>years</em>.</p>
]]></content:encoded><dc:date>2010-03-05T21:02:41Z</dc:date></item><item><title>Oopsie</title><guid isPermaLink="false">maemo-flood</guid><link>http://mg.pov.lt/blog/maemo-flood</link><description>Sorry for flooding Planet Maemo -- it was a side effect of changing this feed's URL to only include posts ...</description><content:encoded><![CDATA[
<p>Sorry for flooding Planet Maemo -- it was a side effect of changing this
feed's URL to only include posts tagged "maemo".  I'm not sure if the fault
is PyBlosxom's or the aggregator's</p>

<p>As a penance, here's a Terminal trick for you:</p>

<pre>
LABELS='[Tab,Esc,Enter,PgUp,PgDn,F2,VKB]'
KEYS='[Tab,Escape,KP_Enter,Page_Up,Page_Down,F2,Return]'
gconftool -s /apps/osso/xterm/key_labels --type list --list-type string "$LABELS"
gconftool -s /apps/osso/xterm/keys --type list --list-type string "$KEYS"
</pre>

<p>This changes the toolbar to have three extra keys (Enter, F2, and a key that
acts like Enter when the hardware keyboard is open, and opens the virtual
keyboard if the hardware keyboard is closed).</p>

<p><strong>Update:</strong> added screenshot:</p>

<p style="text-align: center">
<a href="http://mg.pov.lt/n900-xterm-toolbar.png">
<img style="border: 1px solid #ccc; padding: 6px"
     src="http://mg.pov.lt/n900-xterm-toolbar.png"
     alt="N900 Terminal with new toolbar buttons" width="400" height="240" />
</a>
<br/>
Nokia N900 Terminal app with new toolbar buttons
</p>
]]></content:encoded><dc:date>2010-03-03T17:45:34Z</dc:date></item><item><title>Weekly Zope developer IRC meetings</title><guid isPermaLink="false">weekly-zope-irc-meeting</guid><link>http://mg.pov.lt/blog/weekly-zope-irc-meeting</link><description>On Tuesday we started what will hopefully become a tradition: weekly IRC meetings for Zope developers. Topics covered include buildbot ...</description><content:encoded><![CDATA[
<p>On Tuesday we started what will hopefully become a tradition: weekly IRC
meetings for Zope developers.  Topics covered include buildbot organization and
maintenance, open issues with the ZTK development process, and the fate of Zope
3.5 (= BlueBream 1.0).</p>

<p>There are <a
  href="http://zope3.pov.lt/irclogs-zope/%23zope.2010-03-02.log.html#t2010-02-02T16:59:56"
  >IRC logs</a> of the meeting, and Christian Theune posted a <a
  href="https://mail.zope.org/pipermail/zope-dev/2010-March/039642.html">summary</a>
  to the mailing list.</p>

<p>My take on this can be summed up as: Zope ain't dead yet!  The project has
fragmented a bit (Zope 2, Zope Toolkit, Grok, BlueBream, Repoze), but we all
share a set of core packages and we want to keep them healthy.</p>

<p>Next meeting is also happening on a Tuesday, at 15:00 UTC on #zope in
FreeNode.</p>
]]></content:encoded><dc:date>2010-03-03T11:09:23Z</dc:date></item><item><title>Latin-1 or Windows-1252?</title><guid isPermaLink="false">latin1-or-cp1252</guid><link>http://mg.pov.lt/blog/latin1-or-cp1252</link><description>Michael Foord wrote about some Latin-1 control character fun in a blog that's hard to read (the RSS feed syndicated ...</description><content:encoded><![CDATA[
<p>Michael Foord wrote about <a
  href="http://www.voidspace.org.uk/python/weblog/arch_d7_2010_01_02.shtml#e1147">some
  Latin-1 control character fun</a> in a blog that's hard to read (the RSS feed
syndicated on Planet Python is truncated, grr!) and hard to reply (<del>no comments
  on the blog!</del> my Chromium's AdBlock+ hid the comment link so I couldn't
find it), but never mind that.</p>

<blockquote>
  <q>Unfortunately the data from the customers included some \x85 characters,
    which were breaking the CSV parsing.</q>
</blockquote>

<p>0x85 is a control character (NEXT LINE or NEL) in Latin-1, but it's a
printable character (HORIZONTAL ELLIPSIS) in Microsoft's code page 1252, which
is often mistaken for Latin-1.  I would venture a suggestion that the encoding
of the customer data was not latin-1 but rather cp1252.</p>

<blockquote><pre>
<span class="prompt">&gt;&gt;&gt;</span> <span class="string">'<span class="escape">\x85</span>'</span>.<span class="name">decode</span>(<span class="string">'cp1252'</span>)
<span class="string">u'<span class="escape">\u2026</span>'</span>
</pre></blockquote>

]]></content:encoded><dc:date>2010-01-07T21:29:39Z</dc:date></item><item><title>GTimeLog: not dead yet!</title><guid isPermaLink="false">gtimelog-not-dead-yet</guid><link>http://mg.pov.lt/blog/gtimelog-not-dead-yet</link><description>Back in 2004 I wrote a small Gtk+ app to help me keep track of my time, and called it ...</description><content:encoded><![CDATA[
<p>Back in 2004 I wrote a small Gtk+ app to help me keep track of my time, and
called it <a href="http://mg.pov.lt/gtimelog/">GTimeLog</a>.  I shared it with
my coworkers, put it on the web (on the general "release early, release often"
principles), and it got sort-of popular before I found the time to polish it
into a state where I wouldn't be ashamed to show it to other people.</p>

<p>Fast-forward to 2008: there are actual users out there (much to my
surprise), I still haven't added the originally-envisioned spit and polish,
haven't done anything to foster a development community, am wracked by guilt of
not doing my maintainerly duties properly, which leads to depression and
burnout.  So I do the only thing I can think of: run away from the project and
basically ignore its existence for a year.  Unreviewed patches accumulate in my
inbox.</p>

<p>It seems that the sabbatical helped: yesterday, triggered by a <a
  href="http://bugs.debian.org/560981">new Debian bug report</a>, I sat down,
fixed the <a href="">bug</a>, implemented a <a
  href="https://bugs.launchpad.net/gtimelog/+bug/308750">feature</a>, applied a
<a href="https://bugs.launchpad.net/gtimelog/+bug/328118">couple</a> of <a
  href="https://bugs.launchpad.net/gtimelog/+bug/255618">patches</a>
languishing in the bug tracker, and <a
  href="http://pypi.python.org/pypi/gtimelog">released version 0.3</a> (which
was totally broken thanks to setuptools magic that suddenly stopped
working; so released 0.3.1 just now).  Then went through my old unread email,
created <a
  href="https://bugs.launchpad.net/gtimelog">bugs in Launchpad</a> and sent
replies to everyone.  Except <a href="http://blog.pierlux.com/en/">Pierre-Luc
  Beaudoin</a>, since his @collabora.co.uk email address bounced.  If anyone
knows how to contact him, I'd appreciate a note.</p>

<p><img src="http://mg.pov.lt/gtimelog-about-dialog.png"
        alt="version is now shown in the about dialog" /></p>

<p>There are also some older changes that I made before I emerged out of the
funk and so hadn't widely announced:</p>

<ul>
  <li>
    There's a <a href="http://groups.google.com/group/gtimelog">mailing
      list</a> for user and developer discussions (if there still are any ;).
  </li>
  <li>
    GTimeLog's <a href="https://code.launchpad.net/gtimelog">source code</a>
    now lives on Launchpad (actually, I <a
      href="http://mg.pov.lt/blog/happenings.html">mentioned</a> this on my
    blog once).
  </li>
</ul>
]]></content:encoded><dc:date>2009-12-17T23:22:52Z</dc:date></item><item><title>Unix is an IDE, or my Vim plugins</title><guid isPermaLink="false">unix-is-an-ide</guid><link>http://mg.pov.lt/blog/unix-is-an-ide</link><description>Unix is an IDE . I do my development (Python web apps mostly) with Vim with a bunch of custom ...</description><content:encoded><![CDATA[
<p><a href="http://c2.com/cgi/wiki?UnixIsAnIde">Unix is an IDE</a>.  I do my
development (Python web apps mostly) with <a href="http://www.vim.org/">Vim</a>
with a <a href="http://mg.pov.lt/vim/">bunch of custom plugins</a>, shell
(in GNOME Terminal: tabs rule!), GNU make, ctags, find + grep,
svn/bzr/hg/git.</p>

<p>The current working directory is my project configuration/state.  I run
tests here (bin/test), I search for code here (vim -t TagName, find + grep), I
run applications here (make run or bin/<em>appname</em>).  I can multitask
freely, for example, if I'm in the middle of typing an SVN commit message, I
can hit Ctrl+Shit+T, get a new terminal tab in the same working directory, and
look something up.  No aliases/environment variables/symlinks/<a
  href="http://blog.doughellmann.com/2009/12/switching-development-contexts-with.html">scripts
  making changes to config files</a>.  I can work on multiple projects at the
same time.  I can work remotely (over ssh).</p>

<p><a href="http://vimeo.com/user1043515">Gary Bernhardt's screencasts on
  Vimeo</a> show how productive you can get if you learn Vim and tailor it
to your needs.  I have Vim scripts that let me</p>

<ul>
  <li>
    See the name of the class and function that I'm editing in the statusbar,
    even if the class/function definition is offscreen:
    <a href="http://mg.pov.lt/vim/plugin/pythonhelper.vim">pythonhelper.vim</a>.
  </li>
  <li>
    See all pyflakes warnings and errors in a list as soon as I press F2 to
    save the file: <a
      href="http://mg.pov.lt/vim/plugin/python_check_syntax.vim">python_check_syntax.vim</a>.
  </li>
  <li>
    Add a "from foo.bar import Something" line at the top of the file if I
    press F5 when my cursor is on Something, looking up the package and module
    from ctags: <a
      href="http://mg.pov.lt/vim/plugin/python-imports.vim">python-imports.vim</a>.
  </li>
  <li>
    Switch between production code and unit tests with a single key if the
    project uses one of several conventions for tests (e.g. ./foo.py
    <tt>&lt;-&gt;</tt> ./tests/test_foo.py):
    <a href="http://mg.pov.lt/vim/plugin/py-test-switcher.vim">py-test-switcher.vim</a>.
  </li>
  <li>
    Generate a command line for running one particular unit test (the one
    my cursor is inside) and copy it into the system clipboard, so I can
    run that test by Alt-Tabbing into my terminal window and pasting.
    <a href="http://mg.pov.lt/vim/plugin/py-test-runner.vim">py-test-runner.vim</a>.
  </li>
  <li>
    Open the right file and move the cursor to the right line if I
    triple-click a line of traceback in a shell (or an email) then press F7 in
    my gvim window:
    <a href="http://mg.pov.lt/vim/plugin/py-test-locator.vim">py-test-locator.vim</a>.
  </li>
  <li>
    Compare my version of the code with the pristine version in source control
    in an interactive side-by-side diff that lets me revert bits I no longer
    want:
    <a href="http://mg.pov.lt/vim/plugin/vcscommand.vim">vcscommand.vim</a>.
  </li>
  <li>
    Highlight which lines of the source are covered by my tests, if I have
    coverage information in trace.py format:
    <a href="http://mg.pov.lt/vim/plugin/py-coverage-highlight.vim">py-coverage-highlight.vim</a>.
  </li>
  <li>
    Show the signature of a function/class's __init__ when I type the name
    of that class/function and an open parenthesis (looked up from tags):
    <a href="http://mg.pov.lt/vim/plugin/py-function-signature.vim">py-function-signature.vim</a>.
  </li>
  <li>
    Fold code into an outline so I only see names of methods or classes
    instead of their full bodies:
    <a href="http://mg.pov.lt/vim/vimrc">vimrc</a>, function PythonFoldLevel.
  </li>
  <li>
    Fold diff files so I can see whole hunks/files and can delete those with
    a single key (well, two keys -- dd).  Useful for reviewing <em>large</em>
    diffs (tens of thousands of lines):
    <a href="http://mg.pov.lt/vim/vimrc">vimrc</a>, function DiffFoldLevel.
  </li>
</ul>

<p>Some of these come from <a href="http://www.vim.org">www.vim.org</a>, some
I've written myself, some I've taken and modified a little bit to avoid an
irritating quirk or add a missing feature.  Some things I don't have (and envy
Emacs or IDE users for having -- like an integrated debugger for Python apps,
and, generally, integration with other tools, running in the background).</p>

<p>It's been my plan for a long time to polish my plugins, release them
somewhere (github?  bitbucket? launchpad?) and upload to vim.org, but as it
doesn't seem to be happening, I thought I'd at least put an <a
  href="http://mg.pov.lt/vim">svn
  export of my ~/.vim</a> on the web.</p>
]]></content:encoded><dc:date>2009-12-08T23:23:53Z</dc:date></item><item><title>Displaying multiline text in Zope 3</title><guid isPermaLink="false">zope3-displaying-multiline-text</guid><link>http://mg.pov.lt/blog/zope3-displaying-multiline-text</link><description>zope.schema has Text and TextLine. The former is for multiline text, the latter is for a single line, as the ...</description><content:encoded><![CDATA[
<p>zope.schema has Text and TextLine.  The former is for multiline text, the
latter is for a single line, as the name suggests.  Zope 3 forms will use a
text area for Text fields and an input box for TextLine fields.  Display
widgets, however, apply no special formatting (other than HTML-quoting of
characters like &lt;, &gt; and &amp;), and since newlines are treated the same
way as spaces in HTML, your multiline text gets collapsed into a single
paragraph.</p>

<p>Here's a pattern I've been using in Zope 3 to display multiline user-entered
text as several paragraphs:</p>

<blockquote>
<pre>
<span class="keyword">import</span> <span class="name">cgi</span>

<span class="keyword">from</span> <span class="name">zope</span>.<span class="name">component</span> <span class="keyword">import</span> <span class="name">adapts</span>
<span class="keyword">from</span> <span class="name">zope</span>.<span class="name">publisher</span>.<span class="name">browser</span> <span class="keyword">import</span> <span class="name">BrowserView</span>
<span class="keyword">from</span> <span class="name">zope</span>.<span class="name">publisher</span>.<span class="name">interfaces</span> <span class="keyword">import</span> <span class="name">IRequest</span>


<span class="def">class</span> <span class="name">SplitToParagraphsView</span>(<span class="name">BrowserView</span>):
    <span class="string">"""Splits a string into paragraphs via newlines."""</span>

    <span class="name">adapts</span>(<span class="name">None</span>, <span class="name">IRequest</span>)

    <span class="def">def</span> <span class="name">paragraphs</span>(<span class="name">self</span>):
        <span class="keyword">if</span> <span class="name">self</span>.<span class="name">context</span> <span class="keyword">is</span> <span class="name">None</span>:
            <span class="keyword">return</span> []
        <span class="keyword">return</span> <span class="name">filter</span>(<span class="name">None</span>, [<span class="name">s</span>.<span class="name">strip</span>() <span class="keyword">for</span> <span class="name">s</span> <span class="keyword">in</span> <span class="name">self</span>.<span class="name">context</span>.<span class="name">splitlines</span>()])

    <span class="def">def</span> <span class="name">__call__</span>(<span class="name">self</span>):
        <span class="keyword">return</span> <span class="string">""</span>.<span class="name">join</span>(<span class="string">'&lt;p&gt;%s&lt;/p&gt;<span class="escape">\n</span>'</span> % <span class="name">cgi</span>.<span class="name">escape</span>(<span class="name">p</span>)
                        <span class="keyword">for</span> <span class="name">p</span> <span class="keyword">in</span> <span class="name">self</span>.<span class="name">paragraphs</span>())
</pre>
</blockquote>

<p>View registration</p>

<blockquote>
<pre>
&lt;<span class="def">configure</span>
    xmlns="http://namespaces.zope.org/zope"&gt;

  &lt;<span class="def">view</span>
      <span class="name">for</span>=<span class="string">"*"</span>
      <span class="name">name</span>=<span class="string">"paragraphs"</span>
      <span class="name">type</span>=<span class="string">"zope.publisher.interfaces.browser.IBrowserRequest"</span>
      <span class="name">factory</span>=<span class="string">".views.SplitToParagraphsView"</span>
      <span class="name">permission</span>=<span class="string">"zope.Public"</span>
      /&gt;

&lt;/<span class="def">configure</span>&gt;
</pre>
</blockquote>

<p>and usage</p>

<blockquote>
<pre>
&lt;<span class="def">p</span> <span class="name">tal</span>:<span class="name">replace</span>=<span class="string">"structure object/attribute/@@paragraphs"</span> /&gt;
</pre>
</blockquote>

<p><strong>Update:</strong>  The view really ought to be registered twice: once
for basestring and once for NoneType.  I was too lazy to figure out the dotted
names for those (or check if zope.interface has external interface declarations
for them), so I registered it for "*".  You should know that this makes the
view available for arbitrary objects (but won't work for most of them, since
they don't have a splitlines method), and that it is, sadly, accessible to
users who may try to hack your system by typing things like @@paragraphs in the
browser's address bar.  Ignas Mikalajūnas offers an <a
  href="http://blog.pow.lt/2009/12/02/formatting-and-processing-text-in-tal-templates/">alternative
  solution using TALES path adapters</a>.</p>
]]></content:encoded><dc:date>2009-12-01T18:52:03Z</dc:date></item><item><title>Maemo Summit 2009</title><guid isPermaLink="false">maemo-summit-2009</guid><link>http://mg.pov.lt/blog/maemo-summit-2009</link><description>The second Maemo Summit is over. Nokia surprised everyone on the first day by handing out 300 pre-release N900 s ...</description><content:encoded><![CDATA[
<p>The second <a
  href="http://wiki.maemo.org/Maemo_Summit_2009">Maemo Summit</a> is over.</p>

<p>Nokia surprised everyone on the first day by handing out 300 pre-release <a
  href="http://maemo.nokia.com/n900/">N900</a>s to the participants.  I'm so
happy now that after a long period of wavering I finally decided to come to the
summit!  The device is much better than I expected/feared (and I haven't even
put a SIM card in yet).  We're supposed to provide feedback and will have to
send the devices back to Nokia in 6 months.
(Nokia insisted on loan contracts <span
  style="text-decoration: line-through">signed in blood</span>, kidding, but
there are contracts.)</p>

<p>The tiny pixels are beautiful.  It's what, 266 pixels per inch?  Even older
225 dpi devices spoiled me: both the first generation iPhone and the first
generation Kindle displays seemed very coarse and pixellated.</p>

<p>The user interface is very smooth.  Having a composition manager improves
apparent responsiveness: even if the app is swapped out and not ready to
redraw, switching between windows appears to be instant since the picture is
cached.  And there's no flicker while the apps are redrawing.  (Flickering
during redraw is one of the main reasons I did not buy a S60 phone and stayed
with good old S40.)  Speaking of swapping, it's barely noticeable.  You can run
more apps than fit in RAM without having to suffer.  The flash memory is
noticeably faster than in a N810.  And there's more of it (32 gigs: 28 gig
partition for user data, the rest for the system: swap, applications, config
files, etc.)</p>

<p>The design and usability of the user interface have improved a lot since the
N810.  The UI is pretty.  Many of the apps are now convenient to use.
Pervasive kinetic scrolling is sweet (except when you have really long lists or
web pages, then it takes <em>forever</em> to reach the end).</p>

<p>Finally there are PIM-y things people missed in older Maemo releases:
calendaring, contacts that can record all kinds of information (such as phone
numbers).</p>

<p>All right, enough gushing.  There were some irritating things too.  For
example, Bluetooth support is buggy/incomplete in the pre-release firmware, so
it's hard to transfer files.  Calendar/contacts sync with S40 phones does not
work either.  GPS is utterly useless when you're offline (no maps, or at least
I haven't found a way to pre-download and cache them; also very long fix times
without network assistance).  Since I have no desire to pay extortionist
roaming charges of my provider (2.5 EUR per megabyte), and haven't had a chance
to go look for a prepaid SIM card, I usually have either WiFi or GPS coverage,
but not both.</p>

<p>As you can guess, playing the device diverted a part of my attention from
the presentations somewhat.  I tried to compensate for that by reporting
on the talks on IRC (using xchat on the device).  I think the strategy
backfired; IRC is rather disruptive and the channel is quite busy lately.</p>

<!-- bonus reading material that doesn't fit with the rest of the post:

On the second day I mostly followed talks about the Maemo 5 UI
(design principles, widgets etc.) and mostly ignored talks about the upcoming
Maemo 6 UI (multitouch, OpenGL acceleration plus animations at widget rather
than window level, flowable layouts supporting both portrait and landscape,
built on top of Qt instead of Gtk+/Clutter, inventing new UI paradigms instead
of copying what came before).  I think my interest in Maemo 6/UI will spike
when I get my hands on a Maemo 6 device, which definitely won't happen any time
soon.

-->
]]></content:encoded><dc:date>2009-10-11T22:22:28Z</dc:date></item><item><title>Escaping hotel firewalls with ssh over port 80</title><guid isPermaLink="false">escaping-hotel-firewall</guid><link>http://mg.pov.lt/blog/escaping-hotel-firewall</link><description>I booked a stay at a particular hotel because the web page said &quot;Free WiFi&quot;. It didn't say &quot;all outgoing ...</description><content:encoded><![CDATA[
<p>I booked a stay at a particular hotel because the web page said "Free WiFi".
It didn't say "all outgoing ports firewalled except for port 80 and a few
other (useless) ones".  Not having SSH access is most painful.  Luckily,
there's a solution.</p>

<p>You need a web server running Apache and SSH.  Enable mod_proxy and
mod_proxy_connect and add this to the <em>first</em> (i.e. default) virtual
host configuration:</p>
<blockquote><pre>
&lt;VirtualHost <em>whatever</em>:80&gt;
...

  # allow ssh to localhost over http proxy
  ProxyRequests on
  AllowCONNECT 22
  &lt;Proxy localhost&gt;
    Order allow,deny
    Allow from all
  &lt;/Proxy&gt;

&lt;/VirtualHost&gt;
</pre></blockquote>
Reload Apache configuration.  The setup is done.  (Instructions based on <a
  href="http://dag.wieers.com/howto/ssh-http-tunneling/">Tunneling SSH over
  HTTP(S)</a> by Dag Wieers.)</p>

<p>On the client side you need <a
  href="http://proxytunnel.sourceforge.net/">proxytunnel</a>.  Sadly, it's not
packaged for Ubuntu yet, but compiling from sources is trivial.  Edit ~/.ssh/config
and add an entry for your proxied ssh connection:</p>

<blockquote><pre>
Host p<em>myservername</em>
ProxyCommand proxytunnel -q -p <em>myserver.mydomain.com</em>:80 -d localhost:22
</pre></blockquote>

<p>That's it.  Now you can <tt>ssh p<em>myservername</em></tt>.  (The p prefix
is a reminder that I'm using a proxied connection: ssh fridge versus ssh
pfridge.  Also it reminds me of Terry Pratchett's <a
  href="http://www.amazon.com/Pyramids-Terry-Pratchett/dp/0061020656">Pyramids</a>.).

<p>For extra fun (e.g. IRC) use ssh's built-in SOCKS5 proxy: <tt>ssh -D 1080
  p<em>myservername</em></tt>.  Then tell the apps to use a SOCKS5 proxy on
localhost.  Since telling each app to use a proxy (and then, later, telling it
to stop using it) is a big *pain*, and some apps (e.g. ssh) don't support
proxies directly, a wrapper like <a
  href="http://tsocks.sourceforge.net/">tsocks</a> is handy.  Edit
/etc/tsocks.conf and set the default socks server to 127.0.0.1, then use
it to run apps:</p>

<blockquote><pre>
<span class="prompt">$</span> <span class="typing">tsocks xchat-gnome</span>
<span class="prompt">$</span> <span class="typing">tsocks bzr push lp:<em>myprojectname</em></span>
</pre></blockquote>

<p>tsocks is packaged for Ubuntu.</p>

<p>If your hotel doesn't have free WiFi, a prepaid SIM card with 3G access
could be cheaper than roaming charges.  Apparently you can get one with a
virtually unlimited (for a short stay, anyway) data plan for 27 EUR in
Amsterdam.</p>
]]></content:encoded><dc:date>2009-10-11T20:09:51Z</dc:date></item><item><title>Pylons and SQL schema migration</title><guid isPermaLink="false">pylons-and-sql-migration</guid><link>http://mg.pov.lt/blog/pylons-and-sql-migration</link><description>I'm at the point in my hobby project where I'd like to be able to change my models without losing ...</description><content:encoded><![CDATA[
<p>I'm at the point in my hobby project where I'd like to be able to change my models
without losing all my test data.  And I'm too lazy to do manual dumps and edit
the SQL in place before reimporting it.</p>

<p>I want a system</p>

<ul>
  <li>that is <em>transparent</em> to the user: if my database is at schema
      version 1, and my code is at version 3, I want it to be automatically
      upgraded to version 3 on server startup.</li>
  <li>that is <em>not too hard</em> on the programmer: dropping a numbered Python or SQL
      script in a directory ought to be sufficient to define a transition from
      schema version X to schema version X+1.</li>
  <li>that <em>handles errors gracefully</em>: makes a backup of the database
      with the old schema version; runs my script in a transaction and aborts
      that transaction if the conversion fails (while showing me enough
      information to debug the problem).</li>
  <li><em>allows prototyping</em> without having to increment the schema number for every
      little change I make to the models; I should be the one who decides that a new
      schema is ready to go out to the world.</li>
</ul>

<p>I've been glancing at <a
  href="http://code.google.com/p/sqlalchemy-migrate/">SQLAlchemy-Migrate</a>, since I've
been brought up to believe <abbr title="Not Invented Here">NIH</abbr>ing is
Bad.  But Migrate is <em>scary</em>.  I have to admit that the longer I stare
at its documentation, the less I can describe <em>why</em> I think so.  All
those shell commands&mdash;but there's an API for invoking them from Python, so maybe I can
achieve my goals.  I'll have to try and see.
</p>

]]></content:encoded><dc:date>2009-09-21T16:44:14Z</dc:date></item><item><title>Pylons with zc.buildout, continued</title><guid isPermaLink="false">pylons-with-buildout-2</guid><link>http://mg.pov.lt/blog/pylons-with-buildout-2</link><description>Last time I mentioned that running bin/buildout with the -N flag makes it run faster (since it skips looking for ...</description><content:encoded><![CDATA[
<p><a href="http://mg.pov.lt/blog/pylons-with-buildout.html">Last time</a> I
mentioned that running bin/buildout with the -N flag makes it run faster
(since it skips looking for newer versions to upgrade).  You can tell
buildout to do this by default by putting 'newest = false' into the [buildout]
section of buildout.cfg. We'll be running bin/buildout a lot now, since we'll
be making changes to the project environment, so this will save wear and tear
on the '-', 'N' and Shift keys.  (And, by the way, I'm not trying to soak up
Google juice by repeating the word 'buildout' a lot, honest!)</p>

<p>I will omit bzr commits from this narrative as it's getting long; you can
assume that every self-contained change was committed separately.</p>

<h4>tests</h4>

<p>  First, I want a bin/test script to run the test
suite.  Pylons uses nose, so we need to tell buildout to install the nosetests
script (under a different name, since I'm used to typing bin/test no matter
what test runner a project happens to use):</p>

<pre>
<span class="prompt">$</span> <span class="typing">bzr diff</span>
=== modified file 'buildout.cfg'
--- buildout.cfg	2009-09-15 19:49:11 +0000
+++ buildout.cfg	2009-09-15 19:49:18 +0000
@@ -8,5 +8,8 @@
 recipe = zc.recipe.egg
 eggs = Pylons
        PasteScript
+       nose
        asharing
 interpreter = python
+scripts = paster
+          nosetests=test

<span class="prompt">$</span> <span class="typing">bin/buildout</span>
...
Generated script '/tmp/AlliterationSharing/bin/paster'.
Generated script '/tmp/AlliterationSharing/bin/test'.
...
<span class="prompt">$</span> <span class="typing">bin/test</span>

----------------------------------------------------------------------
Ran 0 tests in 0.276s

OK
</pre>

<h4>ctags</h4>

<p>Documentation is good, but sometimes you want to look at the source code of
the framework.  There's a tool called <a
  href="http://ctags.sourceforge.net/">ctags</a> that builds a database of
identifiers.  The popular text editors <a href="http://www.vim.org/">Vim</a>
and <a href="http://www.gnu.org/software/emacs/">Emacs</a> can then use the
tags database to jump to a definition of any name with a single keystroke
(Ctrl-] in vim, M-. in emacs).</p>

<p>Building the tags database is complicated by each Python package being
installed into a separate directory.  There's a buildout recipe called
z3c.recipe.tag that finds those directories and lets you build a unified tags
file.  We'll also ask buildout to make sure it <em>unzips</em> any packages
distributed as .egg files, since ctags doesn't process those:</p>

<pre>
<span class="prompt">$</span> <span class="typing">bzr diff</span>
@@ -1,8 +1,9 @@
 [buildout]
 develop = .
-parts = pylons
+parts = pylons ctags
 
 newest = false
+unzip = true
 
 [pylons]
 recipe = zc.recipe.egg
@@ -13,3 +14,7 @@
 interpreter = python
 scripts = paster
           nosetests=test
+
+[ctags]
+recipe = z3c.recipe.tag:tags
+eggs = ${pylons:eggs}

<span class="prompt">$</span> <span class="typing">bin/buildout</span>
...
Generated script '/tmp/AlliterationSharing/bin/ctags'.
...
<span class="prompt">$</span> <span class="typing">bin/ctags</span>
</pre>

<h4>omelette</h4>

<p>ctags lets you find classes and functions by name; it doesn't let you find
packages or modules.  There's another recipe, collective.recipe.omelette that
creates a tree of symlinks mirroring the Python package structure (here
'unzip = true' also comes in handy):</p>

<pre>
<span class="prompt">$</span> <span class="typing">bzr diff</span>
=== modified file 'buildout.cfg'
--- buildout.cfg	2009-09-15 20:04:42 +0000
+++ buildout.cfg	2009-09-15 20:05:30 +0000
@@ -1,6 +1,6 @@
 [buildout]
 develop = .
-parts = pylons ctags
+parts = pylons ctags omelette
 
 newest = false
 unzip = true
@@ -18,3 +18,7 @@
 [ctags]
 recipe = z3c.recipe.tag:tags
 eggs = ${pylons:eggs}
+
+[omelette]
+recipe = collective.recipe.omelette
+eggs = ${pylons:eggs}

<span class="prompt">$</span> <span class="typing">bin/buildout </span>
...
<span class="prompt">$</span> <span class="typing">ls -l parts/omelette</span>
...
</pre>

<p>The symlink tree is created under parts/omelette/.  For example, if you want
to see what webhelper tags were available, you can open
parts/omelette/webhelper/html/builder.py in your editor and see.

<h4>Makefile</h4>

<p>This is getting long (and not everyone may be interested<sup
  class="footnote">1</sup>), but one long post is easier to skip than five
medium ones in a row, so I'll continue.</p>

<blockquote class="footnotes">
  <p><sup>1</sup> Sorry, <a href="http://maemo.org/news/planet-maemo/">Planet
    Maemo</a>!  There's an <a
    href="http://mg.pov.lt/blog/tag/maemo/index.rss">RSS feed of posts tagged
    'maemo'</a>, if you can figure out the URL, which is very well hidden by
    PyBlosxom, *sigh*.
  </p>
</blockquote>

<p>Wouldn't it be nice if new developers could check out your project and start
it up with just a couple of commands?  Make is a time-tested tool that works
well for this:</p>

<pre>
<span class="prompt">$</span> <span class="typing">cat Makefile</span>
# Just remember that you need to use real tabs, not spaces, in a Makefile

PYTHON = python

.PHONY: all
all: bin/paster

.PHONY: run
run: bin/paster
        bin/paster serve development.ini --reload

.PHONY: test check
test check: bin/test
        bin/test

.PHONY: tags
tags: bin/ctags
        bin/ctags

bin/paster bin/test bin/python bin/ctags: bin/buildout
        bin/buildout

bin/buildout: bootstrap.py
        $(PYTHON) bootstrap.py
</pre>

<p>Now all you need to do after checking out is run 'make' to set up a working
development environment.  'make run' or 'make test' will also do that, if
necessary, so this one-liner is sufficient to get a working Hello World
application on port 5000:</p>

<pre>
<span class="prompt">$</span> <span class="typing">bzr branch lp:~mgedmin/+junk/AlliterationSharing &amp;&amp; cd AlliterationSharing &amp;&amp; make run</span>
</pre>

<p>Try it!  You'll get a Bazaar branch with all the history of this little
blog project.</p>
]]></content:encoded><dc:date>2009-09-15T20:31:53Z</dc:date></item><item><title>Starting a Pylons project with zc.buildout</title><guid isPermaLink="false">pylons-with-buildout</guid><link>http://mg.pov.lt/blog/pylons-with-buildout</link><description>For software development I prefer buildout to virtualenv . This is because buildout has a text file describing the state ...</description><content:encoded><![CDATA[
<p>For software development I prefer <a
  href="http://www.buildout.org">buildout</a> to <a
  href="http://pypi.python.org/pypi/virtualenv">virtualenv</a>.  This is
because buildout has a text file describing the state of your working
environent, which can be versioned and used later to recreate it, as well
as during development to modify the environment slightly.</p>

<p>To start a new Pylons project, first create an empty directory.  Let's
call our new project AlliterationSharing<sup
class="footnote">1</sup>, because everybody is sick of 'foo'
and 'bar'.</p>

<blockquote class="footnotes">
<p><sup>1</sup> Generated by randomly picking two words from
/usr/share/dict/words, then chosen over among 120 other variants that weren't
as good.</p>
</blockquote>

<pre>
<span class="prompt">$</span> <span class="typing">mkdir -p ~/src/AlliterationSharing</span>
<span class="prompt">$</span> <span class="typing">cd ~/src/AlliterationSharing</span>
</pre>

<p>Now create a file called buildout.cfg with the following content:</p>

<pre>
<span class="prompt">$</span> <span class="typing">cat buildout.cfg</span>
[buildout]
parts = pylons

[pylons]
recipe = zc.recipe.egg
eggs = Pylons
       PasteScript
interpreter = python
</pre>

<p>Download <a
  href="http://svn.zope.org/zc.buildout/trunk/bootstrap/">bootstrap.py</a> to
it and run it to get bin/buildout.  Note: you can chose which Python version you
want to use by running bootstrap.py with it.  All other scripts under bin/
will be generated by buildout and will use the same Python interpreter.</p>

<pre>
<span class="prompt">$</span> <span class="typing">wget http://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py</span>
<span class="prompt">$</span> <span class="typing">python bootstrap.py</span>
Creating directory '.../AlliterationSharing/bin'.
Creating directory '.../AlliterationSharing/parts'.
Creating directory '.../AlliterationSharing/eggs'.
Creating directory '.../AlliterationSharing/develop-eggs'.
Generated script '.../AlliterationSharing/bin/buildout'.
</pre>

<p>Run bin/buildout to install Pylons into your sandbox.</p>

<pre>
<span class="prompt">$</span> <span class="typing">bin/buildout</span>
Installing pylons.
Generated script '.../AlliterationSharing/bin/paster'.
Generated interpreter '.../AlliterationSharing/bin/python'.
</pre>

<p>Aside: buildout has this very nice feature where it can share Python
packages between projects.  This will save you enormous amounts of time that
would otherwise be spent downloading and unpacking eggs.  To make use of this
facility, create a file ~/.buildout/default.cfg with</p>
<pre>
<span class="prompt">$</span> <span class="typing">cat ~/.buildout/default.cfg </span>
[buildout]
eggs-directory = /home/mg/tmp/buildout-eggs
# XXX replace /home/mg with the full path of *your* home directory
# it would be much nicer if buildout let me use ~ or $HOME
# see <a href="https://bugs.launchpad.net/zc.buildout/+bug/190260">https://bugs.launchpad.net/zc.buildout/+bug/190260</a>
</pre>

<p>Another useful trick is to pass the -N flag to bin/buildout, which will tell
it not to bother looking for newer versions of packages on the Internet when
there's already an existing version installed in your eggs directory.</p>

<p>Back to business: now you've got two new scripts: bin/python and bin/paster.
You can use the first one to play with the interactive Python console where you
can now import pylons and all the dependencies; it has no other value.</p>

<p>Now is a good point to add the files you've created into a version control
system.  I'll arbitrarily use Bazaar.</p>

<pre>
<span class="prompt">$</span> <span class="typing">bzr init .</span>
<span class="prompt">$</span> <span class="typing">bzr add bootstrap.py buildout.cfg</span>
<span class="prompt">$</span> <span class="typing">bzr ignore bin parts eggs develop-eggs .installed.cfg</span>
<span class="prompt">$</span> <span class="typing">bzr commit -m "Create AlliterationSharing project"</span>
</pre>

<p>Run bin/paster create -t pylons to create a skeleton project.</p>

<pre>
<span class="prompt">$</span> <span class="typing">bin/paster create -t pylons asharing</span>
<span class="prompt">$</span> <span class="typing">bzr ignore *.egg-info</span>
<span class="prompt">$</span> <span class="typing">bzr add asharing</span>
<span class="prompt">$</span> <span class="typing">bzr commit -m "Generated project files with paster create"</span>
</pre>

<p>Now paster creates a directory structure that I don't like:</p>

<pre>
AlliterationSharing/
  buildout.cfg
  bin/
  asharing/
    setup.py
    README.txt
    MANIFEST.in
    asharing/
      __init__.py
      config/
      controllers/
      templates/
      public/
</pre>

<p>I'd like the README and setup.py to be in the top level, and I dislike
repeating 'asharing' twice in directory names.  I'll move some files around</p>

<pre>
<span class="prompt">$</span> <span class="typing">cd asharing/</span>
<span class="prompt">$</span> <span class="typing">bzr mv development.ini docs MANIFEST.in README.txt setup.* test.ini ../</span>
<span class="prompt">$</span> <span class="typing">bzr rm ez_setup.*</span>
<span class="prompt">$</span> <span class="typing">cd ..</span>
<span class="prompt">$</span> <span class="typing">bzr mv asharing src</span>
<span class="prompt">$</span> <span class="typing">bzr ci -m "Moved some files around"</span>
</pre>

<p>Now the tree looks like this:</p>

<pre>
AlliterationSharing/
  buildout.cfg
  setup.py
  README.txt
  MANIFEST.in
  bin/
  src/
    asharing/
      __init__.py
      config/
      controllers/
      templates/
      public/
</pre>

<p>We have to tell setup.py where to find the source tree</p>

<pre>
<span class="prompt">$</span> <span class="typing">bzr diff</span>
=== modified file 'MANIFEST.in'
--- MANIFEST.in	2009-09-13 13:04:00 +0000
+++ MANIFEST.in	2009-09-13 13:05:59 +0000
@@ -1,3 +1,3 @@
-include asharing/config/deployment.ini_tmpl
-recursive-include asharing/public *
-recursive-include asharing/templates *
+include src/asharing/config/deployment.ini_tmpl
+recursive-include src/asharing/public *
+recursive-include src/asharing/templates *

=== modified file 'setup.py'
--- setup.py	2009-09-13 13:04:00 +0000
+++ setup.py	2009-09-13 13:04:40 +0000
@@ -17,7 +17,8 @@
         "SQLAlchemy&gt;=0.5",
     ],
     setup_requires=["PasteScript&gt;=1.6.3"],
-    packages=find_packages(exclude=['ez_setup']),
+    packages=find_packages('src', exclude=['ez_setup']),
+    package_dir={'': 'src'},
     include_package_data=True,
     test_suite='nose.collector',
     package_data={'asharing': ['i18n/*/LC_MESSAGES/*.mo']},
</pre>

<p>(I'm not sure if you also need to change package_data and/or setup.cfg; it's
possible that I left i18n in a broken state.  Can somebody comment on
this?)</p>

<p>And we have to tell buildout that we've got a new Python package to enable
in the project environment</p>

<pre>
<span class="prompt">$</span> <span class="typing">bzr diff buildout.cfg </span>
=== modified file 'buildout.cfg'
--- buildout.cfg	2009-09-13 12:57:21 +0000
+++ buildout.cfg	2009-09-13 13:08:05 +0000
@@ -1,8 +1,10 @@
 [buildout]
+develop = .
 parts = pylons
 
 [pylons]
 recipe = zc.recipe.egg
 eggs = Pylons
        PasteScript
+       asharing
 interpreter = python
</pre>

<p>Now you can re-run bin/buildout and start your hello-world project</p>

<pre>
<span class="prompt">$</span> <span class="typing">bzr commit -m "Include the new package in the build"</span>
<span class="prompt">$</span> <span class="typing">bin/buildout -N</span>
<span class="prompt">$</span> <span class="typing">bin/paster serve --reload development.ini</span>
</pre>

<p>Happy hacking!</p>

<p>To be continued: <a href="http://mg.pov.lt/blog/pylons-with-buildout-2.html">telling buildbot to create bin/test; using ctags and omelette</a>.</p>
]]></content:encoded><dc:date>2009-09-13T13:13:14Z</dc:date></item><item><title>Footnotes done well</title><guid isPermaLink="false">footnotes-done-well</guid><link>http://mg.pov.lt/blog/footnotes-done-well</link><description>I like the way footnotes are implemented here: Snakes on the Web by Jacob Kaplan-Moss. (Recorded with byzanz . My ...</description><content:encoded><![CDATA[
<p>I like the way footnotes are implemented here: <a
  href="http://jacobian.org/writing/snakes-on-the-web/"> Snakes on the Web</a>
by Jacob Kaplan-Moss.</p>

<center>
  <img src="http://mg.pov.lt/jacobian-footnote.gif" width="400" height="80"
       alt="mini-screencast of animated footnote" />
</center>

<p><small>(Recorded with <a
    href="http://people.freedesktop.org/~company/byzanz/">byzanz</a>.  My gif-fu
  is nonexistent or I would make it loop, but with a sufficiently long delay
  at the end to avoid irritation.  Now you have to reload the whole page if
  you missed the animation.)</small></p>

<p>I'm somewhat ambivalent about the animation effect.  On one hand, shiny!  On
the other hand, hitting tiny clickable areas is not good usability.  Still,
<em>shiny!</em></p>

<p>Footnotes are kind of a <a
  href="http://mg.pov.lt/blog/footnotes-on-the-web.html">personal pet-peeve of
  mine</a>.</p>
]]></content:encoded><dc:date>2009-09-11T22:58:58Z</dc:date></item><item><title>Local changes to buildout.cfg</title><guid isPermaLink="false">buildout-local-config</guid><link>http://mg.pov.lt/blog/buildout-local-config</link><description>Most of Python packages in the Zope world use Buildout : svn co svn+ssh://svn.zope.org/repos/main/plone.z3cform/trunk plone.z3cform cd plone.z3cform python2.4 bootstrap.py bin/buildout ...</description><content:encoded><![CDATA[
<p>Most of Python packages in the Zope world use <a
  href="http://www.buildout.org">Buildout</a>:</p>

<pre>
svn co svn+ssh://svn.zope.org/repos/main/plone.z3cform/trunk plone.z3cform
cd plone.z3cform
python2.4 bootstrap.py
bin/buildout
bin/test -pvc
</pre>

<p>Now suppose you want to change the buildout environment somehow, e.g.
use the current development version of zope.testing instead of whatever is
specified in buildout.cfg.  Don't edit the existing buildout.cfg (you might
accidentally commit your local debug changes), instead create a new cfg file,
e.g. test.cfg:
</p>

<pre>
[buildout]
extends = buildout.cfg
develop += ../zope.testing

[versions]
# override any existing version pins
zope.testing =
</pre>

<p>Now re-run buildout</p>

<pre>
bin/buildout -c test.cfg
bin/test -pvc
</pre>

<p>And the tests should be run with the newest zope.testing.code.</p>

<p>Only this does not work with plone.z3cform, and I have no clue why.
It generally works with other packages (at least those that use the
zc.recipe.testrunner rather than collective.recipe.z2testrunner).
Buildout is like that sometimes :(</p>
]]></content:encoded><dc:date>2009-08-03T17:26:22Z</dc:date></item><item><title>Python-related updates for the last couple of months</title><guid isPermaLink="false">happenings</guid><link>http://mg.pov.lt/blog/happenings</link><description>Went to EuroPython , met new people, had a great time. Updated gtkeggdeps , the interactive Python package dependency browser. ...</description><content:encoded><![CDATA[
<p>Went to <a href="http://www.europython.eu/">EuroPython</a>, met new people,
had a great time.</p>

<p>Updated <a href="https://launchpad.net/gtkeggdeps">gtkeggdeps</a>, the
interactive Python package dependency browser.  Collaborated with <a
  href="http://thomas-lotze.de/en/">Thomas Lotze</a>, who maintains the engine
(<a href="http://pypi.python.org/pypi/tl.eggdeps">tl.eggdeps</a>) that
gtkeggdeps wraps, to resolve API mismatches.  Moved the sources to <a
  href="https://code.launchpad.net/gtkeggdeps">launchpad.net</a>, added a test
suite, made it use <a href="http://buildout.org">zc.buildout</a> for convenient
development.</p>

<p>Moved the source repository of <a
  href="https://launchpad.net/gtimelog">gtimelog</a>, the simple desktop time
tracker, to <a href="https://code.launchpad.net/gtimelog">launchpad.net</a>.
Failed to do anything else with it.  <tt>:-(</tt></p>

<p>Tried to work on <a
  href="http://code.google.com/p/jrfonseca/wiki/XDot">xdot</a>, wrestled with
git-svn merges, failed abysmally.  <a
  href="http://code.google.com/p/jrfonseca/issues/detail?id=19">Asked
  upstream</a> to upload xdot to <a
  href="http://pypi.python.org/pypi">PyPI</a>.</a>

<p>Released <a href="https://launchpad.net/zodbbrowser">ZODB Browser</a>, but
this deserves a separate post.</p>

<p>Sent a bunch of <a
  href="http://www.divmod.org/trac/wiki/DivmodPyflakes">pyflakes</a> patches from
<a href="https://code.launchpad.net/~mgedmin/pyflakes/pyflakes-mg">my old
  branch</a> upstream, created <a
  href="http://www.divmod.org/trac/query?status=new&status=assigned&status=reopened&reporter=mgedmin&component=Pyflakes&order=priority">trac
  tickets</a> for the rest.  Wrestled with bzr-svn merges, failed abysmally.</p>
]]></content:encoded><dc:date>2009-07-24T23:14:12Z</dc:date></item><item><title>df</title><guid isPermaLink="false">disk-free</guid><link>http://mg.pov.lt/blog/disk-free</link><description>Modern Linux system have all sorts of fake filesystems cluttering the output of df and mount: tmpfs, bind mounts, fuse ...</description><content:encoded><![CDATA[
<p>Modern Linux system have all sorts of fake filesystems cluttering the output
of df and mount: tmpfs, bind mounts, fuse for ~/.gvfs, etc.  I have only one
real partition on my laptop, yet mount returns 22 lines of output.</p>

<p>Question: are there any df-like utilities that filter out all the crap and
show only interesting bits?  The standard df as well as <a
  href="http://kassiopeia.juls.savba.sk/~garabik/software/pydf/">pydf</a> both
display 8 lines instead of 1.  <a
  href="http://nickshontz.com/blog/ubuntu-hard-drive-usage">Discus</a> is
worse: it shows 20.  GUI utilities like <a
  href="http://www.marzocca.net/linux/baobab/">Baobab</a> also suffer from this
confusion, especially bind mounts.</p>

<p>Ironically, Ubuntu's update-motd <a
  href="https://bugs.launchpad.net/ubuntu/+source/update-motd/+bug/399513">gets
  confused</a> by Ubuntu's private user directories and displays disk stats for
~/Private as if it were a real partition.  <!-- This bug probably qualifies as
a <a href="https://wiki.ubuntu.com/PaperCut">paper cut</a>, but I hear Ubunteros
already have more of those than they can fix...  Well, okay, the "average user"
probably never sees /etc/motd, so it fails one of the prerequisites of being
a paper cut. --></p>
]]></content:encoded><dc:date>2009-07-14T22:33:02Z</dc:date></item><item><title>Surprising old-style class behaviour</title><guid isPermaLink="false">suprising-old-style-classes</guid><link>http://mg.pov.lt/blog/suprising-old-style-classes</link><description>Some anonymous Planet Python poster (at least I couldn't find the author's name on the blog) Christian Wyglendowski asks about ...</description><content:encoded><![CDATA[
<p><span style="text-decoration: line-through">Some anonymous Planet Python poster (at least I couldn't find the author's
  name on the blog)</span> Christian Wyglendowski <a
href="http://blog.dowski.com/2009/05/21/odd-old-style-vs-new-style-class-behavior/">asks
about a surprising difference between old-style and new-style classes</a>.
Since the comments on their blog are closed (which you find out only after
pressing Submit), I'll answer here.</p>

<p>The question, slightly paraphrased: given a class</p>
<blockquote><pre>
<span class="def">class</span> <span class="name">LameContainerOld</span>:
    <span class="def">def</span> <span class="name">__init__</span>(<span class="name">self</span>):
        <span class="name">self</span>.<span class="name">_items</span> = {<span class="string">'bar'</span>:<span class="string">'test'</span>}
 
    <span class="def">def</span> <span class="name">__getitem__</span>(<span class="name">self</span>, <span class="name">name</span>):
        <span class="keyword">return</span> <span class="name">self</span>.<span class="name">_items</span>[<span class="name">name</span>]
 
    <span class="def">def</span> <span class="name">__getattr__</span>(<span class="name">self</span>, <span class="name">attr</span>):
        <span class="keyword">return</span> <span class="name">getattr</span>(<span class="name">self</span>.<span class="name">_items</span>, <span class="name">attr</span>)
</pre></blockquote>
<p>why does the 'in' operator work</p>
<blockquote><pre>
<span class="prompt">&gt;&gt;&gt;</span> <span class="name">container</span> = <span class="name">LameContainerOld</span>()
<span class="prompt">&gt;&gt;&gt;</span> <span class="string">'foo'</span> <span class="keyword">in</span> <span class="name">container</span>
<span class="output">False</span>
<span class="prompt">&gt;&gt;&gt;</span> <span class="string">'bar'</span> <span class="keyword">in</span> <span class="name">container</span>
<span class="output">True</span>
</pre></blockquote>
<p>when the equivalent new-style class raises a KeyError: 0 exception? Also, why
does __getattr__ appear to be called to get the bound __getitem__ method of the
dict?</p>
<blockquote><pre>
<span class="prompt">&gt;&gt;&gt;</span> <span class="name">container</span>.<span class="name">__getitem__</span>
<span class="output">&lt;bound method LameContainerNew.__getitem__ of {'bar': 'test'}></span>
</pre></blockquote>

<p>What actually happens here is that LameOldContainer.__getattr__ gets called
for special methods such as __contains__ and __repr__.  This is why (1) the
'in' check works, and (2) it appears, at first glance, that you get the wrong
__getitem__ bound method.   If you pay close attention to the output, you'll
see that it's the __getitem__ of LameOldContainer; it's just that
repr(LameOldContainer()) gets proxied through to the dict.__repr__ when you
don't expect it:</p>

<blockquote><pre>
<span class="prompt">&gt;&gt;&gt;</span> <span class="name">container</span>
<span class="output">{'bar': 'test'}</span>
</pre></blockquote>

</p>Special methods never go through __getattr__ for new-style classes,
therefore neither __contains__ nor __repr__ are proxied if you make the
container inherit object.  If there's no __contains__ method, Python falls back
to the sequence protocol and starts calling __getitem__ for numbers 0 through
infinity, or until it gets an IndexError exception.</p>
]]></content:encoded><dc:date>2009-05-21T19:12:52Z</dc:date></item><item><title>Enabling comments in PyBlosxom</title><guid isPermaLink="false">blog-comments</guid><link>http://mg.pov.lt/blog/blog-comments</link><description>I've just spent the whole night setting up blog comments. PyBlosxom doesn't make it painless, sadly, more like the opposite. ...</description><content:encoded><![CDATA[
<p>I've just spent the whole night setting up blog comments.  PyBlosxom doesn't
make it painless, sadly, more like the opposite.</p>

<p>First: don't be scared by the list of comment-related plugins on the
PyBlosxom site.  There's only one important plugin: comments.  All others
depend on it and enhance its functionality. The last three or four times I was
about to add comments to my blog I got scared at step one: evaluate the
available plugins.  Don't repeat my mistake!</p>

<p>Second, follow the instructions carefully.  There's no shortcut.</p>

<p>Third, fix what's broken.  Be prepared to debug the source code.  <tt>print
  &gt;&gt; sys.stderr, "message"</tt> is your friend.</p>

<p>Fourth, fiddle with the look (CSS and HTML).</p>

<p>Fifth, write a blog post and eagerly await your first comments.</p>

<p>Step 3 screams for an explanation, doesn't it?  Problem 1: the comments
plugin requires that you use categories in your blog.  I'm not (I'm holding out
for tags).  Workaround: comment out <tt>if entry['absolute_path']</tt> check in
cb_story and cb_story_end.</p>

<p>Problem 2: the AJAX post returns "Empty response from server".  Workaround:
modify cb_story_end to call readComments directly if <tt>entry['num_comments']
  is
  None</tt>, since cb_story, which usually does the read, is not called during
the AJAX post.</p>

<p>Problem 3: if you enable comment moderation (by setting comment_draft_ext to
a different value from comment_ext), the AJAX post returns "Empty response from
server" once more.  Workaround: modify cb_prepare to notice this case and set
<tt>data['moderated'] = True</tt>, create a new template comment-moderated and
render it in cb_story_end just like the preview template is rendered; also modify
__shouldOutput to return True when rendering comment-moderated.</p>

<p>I'll post patches to the pyblosxom mailing tomorrow, unless I forget.  It's
6 am already, and I'm kind of sleepy.  I just hope I haven't inadvertently
broken my RSS feed or flooded any planets.</p>

<p>Oh, and a helpful hint: don't name the post you're writing
<tt>comments.txt</tt>, or the #comments anchor will point to the start of the
story instead of the comments.</p>
]]></content:encoded><dc:date>2009-05-16T03:13:33Z</dc:date></item></channel></rss>