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

<channel>
	<title>/dev/stu</title>
	<atom:link href="http://www.stuartaxon.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stuartaxon.com</link>
	<description>Adding LOC to the web.</description>
	<lastBuildDate>Thu, 10 May 2012 09:43:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Adding files to the django auto refresh</title>
		<link>http://www.stuartaxon.com/2012/05/10/adding-files-to-the-django-auto-refresh/</link>
		<comments>http://www.stuartaxon.com/2012/05/10/adding-files-to-the-django-auto-refresh/#comments</comments>
		<pubDate>Thu, 10 May 2012 09:34:52 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[troubleshooting]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=304</guid>
		<description><![CDATA[Django runserver and the app django-autotest are both good as they&#8217;ll restart when modifcations are made to files in the app they will restart, however not *all* files will trigger a restart. Wanting to get some other files noticed, I added some in the __init__.py of my app, so it looked like this: try:     [...]]]></description>
			<content:encoded><![CDATA[<p>Django runserver and the app django-autotest are both good as they&#8217;ll restart when modifcations are made to files in the app they will restart, however not *all* files will trigger a restart.</p>
<p>Wanting to get some other files noticed, I added some in the __init__.py of my app, so it looked like this:</p>
<pre class="brush:python">try:
    from django.conf import settings

    if settings.DEBUG:
        import forms, util, tests
except:
    pass</pre>
<p>This seemed to be working fine until I swapped to postgres and tried to do syncdb .. and reset, uh oh !</p>
<p>Postgres said (names changed to protect the innocent):</p>
<pre class="brush:sql">2012-05-10 09:47:57 BST STATEMENT:
                    SELECT c.relname
                    FROM pg_catalog.pg_class c
                    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
                    WHERE c.relkind IN ('r', 'v', '')
                        AND n.nspname NOT IN ('pg_catalog', 'pg_toast')
                        AND pg_catalog.pg_table_is_visible(c.oid)
2012-05-10 09:47:57 BST LOG:  could not receive data from client: Connection reset by peer
2012-05-10 09:47:57 BST LOG:  unexpected EOF on client connection
2012-05-10 09:49:14 BST ERROR:  relation "sandwich_maker_filling" does not exist at character 72
2012-05-10 09:49:14 BST STATEMENT:  SELECT "sandwich_maker_filling"."id", "sandwich_maker_filling"."name" FROM "sandwich_maker_filling"
2012-05-10 09:49:14 BST ERROR:  current transaction is aborted, commands ignored until end of transaction block</pre>
<p>And django wasn&#8217;t too happy either:</p>
<pre>Traceback (most recent call last):
  File "manage.py", line 10, in &lt;module&gt;
    execute_from_command_line(sys.argv)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
    utility.execute()
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle
    return self.handle_noargs(**options)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 60, in handle_noargs
    tables = connection.introspection.table_names()
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/db/backends/__init__.py", line 896, in table_names
    return self.get_table_list(cursor)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/introspection.py", line 33, in get_table_list
    AND pg_catalog.pg_table_is_visible(c.oid)""")
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/db/backends/util.py", line 40, in execute
    return self.cursor.execute(sql, params)
  File "/home/stu/.virtualenvs/the_app/local/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 52, in execute
    return self.cursor.execute(query, args)
django.db.utils.DatabaseError: current transaction is aborted, commands ignored until end of transaction block</pre>
<p>In the end the solution was simple, just check for the args where we need the refresh to happen automatically:</p>
<pre class="brush:python">## Automatically reload when forms or tests changed
try:
    from django.conf import settings

    if settings.DEBUG:
        import sys
        if sys.argv == ['manage.py', 'autotest'] or sys.argv == ['manage.py', 'runserver']:
                # Need to check params as otherwise this can break syncdb, reset and
                # Friends !!
                import forms, util, tests
except:
    pass</pre>
<p>Hopefully this will be helpful to somebody with a similar error or that wants autotest or runserver to see more files.<br />
&nbsp;</p>
<p>This article was particularly helpful in debugging this:  <a title="Debugging django syncdb" href="http://linfiniti.com/2010/03/debugging-django-syncdb/">debugging django syncdb</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2012/05/10/adding-files-to-the-django-auto-refresh/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cairo with python Ctypes</title>
		<link>http://www.stuartaxon.com/2012/01/09/cairo-with-python-ctypes/</link>
		<comments>http://www.stuartaxon.com/2012/01/09/cairo-with-python-ctypes/#comments</comments>
		<pubDate>Mon, 09 Jan 2012 18:11:32 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=299</guid>
		<description><![CDATA[Uploaded some experiments with python and ctypes to here: https://gitorious.org/pycairo-ctypes/pycairo-ctypes &#160; This is a really rough proof of concept that the pycairo API can be implemented with ctypes + metclasses. &#160; &#160; So far only ImageSurface is supported on the SVG backend, along with Contexts.   The nice thing about this is that you can use [...]]]></description>
			<content:encoded><![CDATA[<p>Uploaded some experiments with python and ctypes to here:</p>
<p><a href="https://gitorious.org/pycairo-ctypes/pycairo-ctypes">https://gitorious.org/pycairo-ctypes/pycairo-ctypes</a></p>
<p>&nbsp;</p>
<p>This is a really rough proof of concept that the pycairo API can be implemented with ctypes + metclasses.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>So far only ImageSurface is supported on the SVG backend, along with Contexts.   The nice thing about this is that you can use a pycairo like API on pypy, where things should be faster (in theory).</p>
<p>&nbsp;</p>
<p>There&#8217;s a test that can be run to show the outputs the same for pycairo and cairo ctypes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2012/01/09/cairo-with-python-ctypes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using PyCha with Django</title>
		<link>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/</link>
		<comments>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/#comments</comments>
		<pubDate>Fri, 25 Feb 2011 00:10:50 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[charting]]></category>
		<category><![CDATA[charts]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[pycha]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=290</guid>
		<description><![CDATA[A quick post on using Python Charts to generate nice SVG charts for your django website (I&#8217;ve had the code hanging around for ages &#8211; so should just post it). The code is based on the examples there, here I integrate it into Django. To install you&#8217;ll need to do pip install pycha Heres the [...]]]></description>
			<content:encoded><![CDATA[<p>A quick post on using <a href="http://bitbucket.org/lgs/pycha/">Python Charts</a> to generate nice SVG charts for your django website (I&#8217;ve had the code hanging around for ages &#8211; so should just post it).  The code is based on the examples there, here I integrate it into Django.</p>
<p>To install you&#8217;ll need to do</p>
<pre>pip install pycha</pre>
<p>Heres the code for a simple view to output a chart directly to SVG:</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2011/02/linechart.png"><img class="alignnone size-full wp-image-291" title="linechart" src="http://www.stuartaxon.com/wp-content/uploads/2011/02/linechart.png" alt="" width="401" height="316" /></a></p>
<pre class="brush:python"># views.py

from StringIO import StringIO
from django.http import HttpResponse

import cairo

def colors(request):
    in_req = 1

    svg_buffer = StringIO()

    width, height = (500, 400)
    surface = cairo.SVGSurface(svg_buffer, width, height)

    dataSet = (
     ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))),
     ('dataSet 2', ((0, 2), (1, 4), (2, 3))),
     ('dataSet 3', ((0, 5), (1, 1), (2, 0.5))),
    )

    options = {
       'legend': {'hide': True},
       'background': {'color': '#f0f0f0'},
    }

    #import pycha.bar
    #chart = pycha.bar.VerticalBarChart(surface, options)

    import pycha.line
    chart = pycha.line.LineChart(surface, options)
    chart.addDataset(dataSet)
    chart.render()

    del chart
    del surface

    response = ''
    response = HttpResponse(mimetype='image/svg+xml')
    svg_buffer.seek(0)
    response.write( svg_buffer.read() )
    return response
</pre>
<p>The basic idea is that &#8211; instead of the chart outputting to an svg file, the output goes to a buffer, this is triggered by calling the destructors of the chart and it&#8217;s cairo surface.  Once the data is in the buffer, it is rewound and played back to the Http Response.</p>
<p>&nbsp;</p>
<h2>Inline SVG</h2>
<p>As is, this won&#8217;t work as inline svg, because outputting the XML preamble in the middle of the page will cause problems.  Below is an example that let&#8217;s you decide if you need the preamble (full SVG output), or not (SVG fragment for inclusion in a page or another SVG):</p>
<pre class="brush:python"># Create your views here.

from StringIO import StringIO
from django.http import HttpResponse
from django.shortcuts import render_to_response

import cairo

XML_PREAMBLE = '&lt;?xml version="1.0" encoding="UTF-8"?&gt;'

def colors_chart(inline = False):
    """
    Generate colours chart

    Set inline to True to disable the XML preamble
    """
    in_req = 1

    svg_buffer = StringIO()

    width, height = (500, 400)
    surface = cairo.SVGSurface(svg_buffer, width, height)

    dataSet = (
     ('dataSet 1', ((0, 1), (1, 3), (2, 2.5))),
     ('dataSet 2', ((0, 2), (1, 4), (2, 3))),
     ('dataSet 3', ((0, 5), (1, 1), (2, 0.5))),
    )

    options = {
       'legend': {'hide': True},
       'background': {'color': '#f0f0f0'},
    }

    import pycha.bar
    chart = pycha.bar.VerticalBarChart(surface, options)

    #import pycha.line
    #chart = pycha.line.LineChart(surface, options)
    chart.addDataset(dataSet)
    chart.render()

    del chart
    del surface

    response = ''

    if inline:
        svg_buffer.seek(len(XML_PREAMBLE))
    else:
        svg_buffer.seek(0)
    return svg_buffer.read()

def colors_svg(request):
    """ render a pure SVG chart """
    response = HttpResponse(mimetype='image/svg+xml')
    response.write(colors_chart(inline = False))
    return response

def index(request):
    """ render a chart into the template """
    chart_svg = colors_chart(inline = True)

    return render_to_response(
        'shapes_index.html',
        { "chart" : chart_svg },
        mimetype='application/xhtml+xml')
</pre>
<p>An example project with the above code is available here:<br />
<a href="http://www.stuartaxon.com/wp-content/uploads/2011/02/pycha_django.zip">pycha_django</a></p>
<p>&nbsp;</p>
<p>[EDIT 25/2/2011] Fixed PyCha URL</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2011/02/25/using-pycha-with-django/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title></title>
		<link>http://www.stuartaxon.com/2010/09/30/281/</link>
		<comments>http://www.stuartaxon.com/2010/09/30/281/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 23:59:21 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=281</guid>
		<description><![CDATA[[EDIT: 2010/10/05] Oops, I&#8217;ve been using TCC/LE by JPSoft as my shell&#8230; the following doesn&#8217;t work in the normal command prompt [/EDIT] I just had a look at SET and it lets you set user/system variables: Display, create, modify, or delete environment variables. SET [/A /D /E /P /R file... /S /U /V /X] [name[=][value [...]]]></description>
			<content:encoded><![CDATA[<p>[EDIT: 2010/10/05]</p>
<p>Oops, I&#8217;ve been using TCC/LE by JPSoft as my shell&#8230; the following doesn&#8217;t work in the normal command prompt</p>
<p>[/EDIT]</p>
<p>I just had a look at SET and it lets you set user/system variables:</p>
<pre>Display, create, modify, or delete environment variables.

<span style="color: #404040;"><span style="color: #000000;">SET</span> [/A /D /E /P /R file... /S /U /V /X] [name[=][value ]]
        file:  One or more files containing variable definitions
        /A(rithmetic)           <span style="color: #000000;">/S(ystem variables)</span>
        /D(efault variables)    <span style="color: #000000;">/U(ser variables)
</span>        /E(nv vars)             /V(olatile variables)
        /R(ead from file)       /X override VariableExclude
        /P(ause)</span></pre>
<p>So to set save a variables MYAPP_HOME as the current directory, just do</p>
<pre>SET /U MYAPP_HOME=%CD</pre>
<p>Wish I&#8217;d have looked that up a few years ago, it&#8217;ll save a few seconds next time I need to setup some dev sdk <img src='http://www.stuartaxon.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/09/30/281/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple python spectrograph with shoebot</title>
		<link>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/</link>
		<comments>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/#comments</comments>
		<pubDate>Mon, 17 May 2010 20:14:02 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[audio]]></category>
		<category><![CDATA[fft spectrograph]]></category>
		<category><![CDATA[nodebox]]></category>
		<category><![CDATA[portaudio]]></category>
		<category><![CDATA[pyaudio]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[shoebot]]></category>
		<category><![CDATA[visualisation]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=264</guid>
		<description><![CDATA[Seeing&#8221;Realtime FFT Graph of Audio WAV File or Microphone Input with Python&#8230;&#8221;  on python.reddit.com reminded me of one I&#8217;d built in python with shoebot. While it works OK, I feel like I&#8217;m missing a higher level audio library (especially having seen Minim, for C++ and Java). To run it in shoebot: sbot -w audiobot.bot audiobot.bot [...]]]></description>
			<content:encoded><![CDATA[<p>Seeing&#8221;<a title="Permanent Link: Realtime FFT Graph of Audio WAV  File or Microphone Input with Python, Scipy, and WCKgraph" rel="bookmark" href="http://www.swharden.com/blog/2010-03-05-realtime-fft-graph-of-audio-wav-file-or-microphone-input-with-python-scipy-and-wckgraph/">Realtime FFT Graph of Audio WAV File or Microphone Input  with Python</a>&#8230;&#8221;  on python.reddit.com reminded me of one I&#8217;d built in python with <a href="http://shoebot.net">shoebot</a>.</p>
<p>While it works OK, I feel like I&#8217;m missing a higher level audio library (especially having seen Minim, for C++ and Java).</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/05/graphs.gif"><img class="alignnone size-full wp-image-265" title="graphs" src="http://www.stuartaxon.com/wp-content/uploads/2010/05/graphs.gif" alt="" width="358" height="288" /></a></p>
<p>To run it in shoebot:</p>
<pre class="brush:shell">sbot -w audiobot.bot</pre>
<h3>audiobot.bot</h3>
<pre class="brush:python"># Major library imports
import atexit
import pyaudio
from numpy import zeros, short, fromstring, array
from numpy.fft import fft

NUM_SAMPLES = 512
SAMPLING_RATE = 11025

def setup():
    size(350, 260)
    speed(SAMPLING_RATE / NUM_SAMPLES)

_stream = None

def read_fft():
    global _stream
    pa = None

    def cleanup_audio():
        if _stream:
            _stream.stop_stream()
            _stream.close()
        pa.terminate()

    if _stream is None:
        pa = pyaudio.PyAudio()
        _stream = pa.open(format=pyaudio.paInt16, channels=1,
                           rate=SAMPLING_RATE,
                           input=True, frames_per_buffer=NUM_SAMPLES)
        atexit.register(cleanup_audio)

    audio_data  = fromstring(_stream.read(NUM_SAMPLES), dtype=short)
    normalized_data = audio_data / 32768.0

    return fft(normalized_data)[1:1+NUM_SAMPLES/2]

def flatten_fft(scale = 1.0):
    """
    Produces a nicer graph, I'm not sure if this is correct
    """
    for i, v in enumerate(read_fft()):
        yield scale * (i * v) / NUM_SAMPLES

def triple(audio):
    '''return bass/mid/treble'''
    c = audio.copy()
    c.resize(3, 255 / 3)
    return c

def draw():
    '''Draw 3 different colour graphs'''
    global NUM_SAMPLES
    audio = array(list(flatten_fft(scale = 80)))
    freqs = len(audio)
    bass, mid, treble = triple(audio)

    colours = (0.5, 1.0, 0.5), (1, 1, 0), (1, 0.2, 0.5)

    fill(0, 0, 1)
    rect(0, 0, WIDTH, 400)
    translate(50, 200)

    for spectrum, col in zip((bass, mid, treble), colours):
        fill(col)
        for i, s in enumerate(spectrum):
            rect(i, 0, 1, -abs(s))
        else:
            translate(i, 0)

    audio = array(list(flatten_fft(scale = 80)))
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/05/17/shoebot-spectrograph/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Cairo: Surface for recording commands and playback</title>
		<link>http://www.stuartaxon.com/2010/05/13/cairo-surface-for-recording-commands-and-playback/</link>
		<comments>http://www.stuartaxon.com/2010/05/13/cairo-surface-for-recording-commands-and-playback/#comments</comments>
		<pubDate>Thu, 13 May 2010 20:08:18 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[cairo python graphics]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=258</guid>
		<description><![CDATA[An update on my latest cairo adventures&#8230; When cairo 1.10 comes out we&#8217;ll get a RecordingSurface so you can record commands and play them back to another surface, but how to do something similar now ? Skip to the end if you just want the code, explanation of how I got there ahead: My first [...]]]></description>
			<content:encoded><![CDATA[<h2>An update on my latest cairo adventures&#8230;</h2>
<p>When cairo 1.10 comes out we&#8217;ll get a RecordingSurface so you can record commands and play them back to another surface, but how to do something similar now ?</p>
<p>Skip to the end if you just want the code, explanation of how I got there ahead:</p>
<p>My first advice was to try using PDFSurface, and set the file object to None.</p>
<pre class="brush:python"># Record a red rectangle onto a surface.
#
# Create another surface and draw a background on it
# Draw the first surface onto this surface
#
from cairo import PDFSurface, ImageSurface, FORMAT_ARGB32, Context

recording = PDFSurface(None, 200, 200)
target = ImageSurface(FORMAT_ARGB32, 200, 200)

# Record a red rectangle
cr = Context(recording)
cr.set_source_rgb(1.0, 0.0, 1.0)
cr.rectangle(20, 20, 10, 10)

cr.fill_preserve()
cr.set_source_rgb(0.0, 0.0, 1.0)
cr.stroke()

target_context = Context(target)

# Draw background
target_context.set_source_rgb(1.0, 1.0, 0)
target_context.paint()

# Replay recording to target
target_context.set_source_surface(recording)
target_context.paint()

target.write_to_png('output.png')
</pre>
<p>That seems to work, except when I tried in Windows, when it complained that the file object was wrong.</p>
<p>OK, we can work round that:</p>
<pre class="brush:python">def RecordingSurface(w, h):
    if os.name == 'nt':
        fobj = 'nul'
    else:
        fobj = None
    return PDFSurface(fobj, w, h)
</pre>
<p>This seems to be working, but my animation seemed slow&#8230;  time for some benchmarking; I rendered 1000 frames and got a rough wall clock time:<br />
1m48.</p>
<p>Hmm&#8230; perhaps SVGSurface will be quicker:<br />
1m28</p>
<p>This is much better, 20 seconds difference just by changing what kind of surface is returned!</p>
<h3>Animation not smooth though</h3>
<p>The animation still seemed jerky it occured to me that when the surfaces are disposed they will attempt to out their content to the file object !</p>
<p>Luckily, get_similar_surface() comes to the rescue; it returns a surface not associated with a file object.  Using this the original surface can be kept around forever, and never output.</p>
<p>Wallclock time:<br />
50 seconds!</p>
<h3>And here it is:</h3>
<pre class="brush:python">_svg_surface = None
def RecordingSurface(*size):
    '''
    We don't have RecordingSurfaces until cairo 1.10, so this kludge is used

    SVGSurfaces are created, but to stop them ever attempting to output, they
    are kept in a dict.

    When a surface is needed, create_similar is called to get a Surface from
    the SVGSurface of the same size
    '''
    global _svg_surface
    if os.name == 'nt':
        fobj = 'nul'
    else:
        fobj = None
    if _svg_surface is None:
        _svg_surface = SVGSurface(fobj, 0, 0)
    return _svg_surface.create_similar(cairo.CONTENT_COLOR_ALPHA, *size)
</pre>
<p>This is really useful, you can record commands and play them back to other surfaces.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/05/13/cairo-surface-for-recording-commands-and-playback/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A simple cairo draw queue using closures</title>
		<link>http://www.stuartaxon.com/2010/05/12/a-simple-cairo-draw-queue-using-closures/</link>
		<comments>http://www.stuartaxon.com/2010/05/12/a-simple-cairo-draw-queue-using-closures/#comments</comments>
		<pubDate>Wed, 12 May 2010 19:53:53 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[. closure]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[pycairo]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=251</guid>
		<description><![CDATA[Often it&#8217;s useful to be able to store up drawing commands so you can use them later somewhere else (or even just pass them to another thread). This is a simple drawing model, implemented in cairo, hopefully somebody will find it useful. Queue class DrawQueue: ''' A list of draw commands, stored as callables that, [...]]]></description>
			<content:encoded><![CDATA[<p>Often it&#8217;s useful to be able to store up drawing commands so you can use them later somewhere else (or even just pass them to another thread).</p>
<p>This is a simple drawing model, implemented in cairo, hopefully somebody will find it useful.</p>
<p>Queue</p>
<pre class="brush:python">class DrawQueue:
    '''
    A list of draw commands, stored as callables that, are
    passed a set of parameters to draw on from the canvas
    implementation.
    '''
    def __init__(self, render_callables = None):
        self.render_callables = render_callables or deque()

    def append(self, render_callable):
        '''
        Add a render callable to the queue
        '''
        self.render_callables.append(render_callable)

    def render(self, cairo_ctx):
        '''
        Call all the render callables with cairo_ctx
        '''
        for render_callable in self.render_callables:
            render_callable(cairo_ctx)
</pre>
<p>The queue just accepts callables (any old function), and calls them when you call render, passing them a cairo context you pass in.</p>
<p>To get useful functions you can call closure functions like these:</p>
<pre class="brush:python">def paint_closure():
    def paint(ctx):
        ctx.paint()
    return paint

def fill_closure():
    def fill(ctx):
        ctx.fill()
    return fill

def set_source_rgb_closure(r, g, b):
    def set_source_rgb(ctx):
        ctx.set_source_rgb(r, g, b)
    return set_source_rgb

def moveto_closure(x, y):
    def moveto(ctx):
        ctx.move_to(x, y)
    return moveto

def rectangle_closure(x, y, w, h):
    def rectangle(ctx):
        ctx.rectangle(x, y, w, h)
    return rectangle
</pre>
<p>Adding commands to the queue is simple:</p>
<pre class="brush:python">dq = DrawQueue()
dq.append(set_source_rgb_closure(1, 1, 1))
dq.append(paint_closure())
dq.append(moveto_closure(10, 0))
dq.append(rectangle_closure(0, 0, 20, 20))
dq.append(set_source_rgb_closure(0, 0, 0))
dq.append(fill_closure())
</pre>
<p>This is the same drawing model I&#8217;m using in my branch of shoebot, I&#8217;m hoping to expand it to be multithreaded; while a foreground thread adds commands a background thread is executing them.</p>
<p>Here it is all put together in a simple example to draw a black rectangle</p>
<pre class="brush:python">from collections import deque
import cairo

class DrawQueue:
    '''
    A list of draw commands, stored as callables that, are
    passed a set of parameters to draw on from the canvas
    implementation.
    '''
    def __init__(self, render_callables = None):
        self.render_callables = render_callables or deque()

    def append(self, render_callable):
        '''
        Add a render callable to the queue
        '''
        self.render_callables.append(render_callable)

    def render(self, cairo_ctx):
        '''
        Call all the render callables with cairo_ctx
        '''
        for render_callable in self.render_callables:
            render_callable(cairo_ctx)

#### drawing closures
def paint_closure():
    def paint(ctx):
        ctx.paint()
    return paint

def fill_closure():
    def fill(ctx):
        ctx.fill()
    return fill

def set_source_rgb_closure(r, g, b):
    def set_source_rgb(ctx):
        ctx.set_source_rgb(r, g, b)
    return set_source_rgb

def moveto_closure(x, y):
    def moveto(ctx):
        ctx.move_to(x, y)
    return moveto

def rectangle_closure(x, y, w, h):
    def rectangle(ctx):
        ctx.rectangle(x, y, w, h)
    return rectangle

#### /drawing closures

dq = DrawQueue()

# Add some commands to the drawing queue
dq.append(set_source_rgb_closure(1, 1, 1))
dq.append(paint_closure())
dq.append(moveto_closure(10, 0))
dq.append(rectangle_closure(0, 0, 20, 20))
dq.append(set_source_rgb_closure(0, 0, 0))
dq.append(fill_closure())

# Create a surface and context
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200)
ctx = cairo.Context(surface)

# run defered rendering
dq.render(ctx)

surface.write_to_png('output.png')
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/05/12/a-simple-cairo-draw-queue-using-closures/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Processing with Jython and Nodebox/Shoebot libraries</title>
		<link>http://www.stuartaxon.com/2010/02/10/processing-with-jython-and-nodeboxshoebot-libraries/</link>
		<comments>http://www.stuartaxon.com/2010/02/10/processing-with-jython-and-nodeboxshoebot-libraries/#comments</comments>
		<pubDate>Wed, 10 Feb 2010 22:44:21 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[nodebox]]></category>
		<category><![CDATA[processing]]></category>
		<category><![CDATA[shoebot]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=234</guid>
		<description><![CDATA[Update: 26/April/2010 Problems I was having with incomplete images have been fixed in the current version of the web library, available in shoebots mecurial repository. Using Processing from Jython is a promising idea, so I took the base from this post on backspaces.net where they explained how to use Jython and built on it a [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>Update: 26/April/2010</p>
<p>Problems I was having with incomplete images have been fixed in the current version of the web library, available in shoebots mecurial repository.</p></blockquote>
<p>Using <a href="http://processing.org/">Processing</a> from <a href="http://www.jython.org">Jython</a> is a promising idea, so I took the base from this post on <a href="http://backspaces.net/30/processing-with-jython/">backspaces.net</a> where they explained how to use Jython and built on it a little.</p>
<p>This is great as Shoebot/Nodebox have great libraries for data manipulation, while processing is more focused on graphics.</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/slowcessing.png"><img class="alignnone size-medium wp-image-235" title="slowcessing" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/slowcessing-300x203.png" alt="" width="300" height="203" /></a></p>
<p>The result is the attached Netbeans project which demonstrates using the nodebox web library and  drawing with processing.</p>
<h2>Slowcessing</h2>
<p>The glue code is in slowcessing.py</p>
<p>Theres a special version of PApplet (PJApplet), and &#8216;pj_frame&#8217; which can put this in a JFrame.</p>
<p>The other method is &#8216;shoebot_imports&#8217; adds the shoebot imports to the library path</p>
<p>In case anybody doesn&#8217;t want to download the whole project, heres the code:</p>
<p>imagestrip.py</p>
<pre class="brush:python">from slowcessing import PJApplet, pj_frame, shoebot_imports
from processing.opengl import *

shoebot_imports()
import web
import thread

class ImageQueue(list):
    """
    Download images in the background and add them to a list
    """
    def __init__(self, search, size):
        list.__init__(self)
        self._search = search
        self._image_size = size
        thread.start_new_thread(self._get_images, ())

    def _image_downloaded(self, path):
        p = PJApplet()
        self.append(p.loadImage(path))

    def _get_images(self):
        for image in self._search:
            image.download(self._image_size, asynchronous=False)
            self._image_downloaded(image.path)

class WebTest (PJApplet):
  def setup(self):
    self.size(400, 400, self.P3D)
    self.images = ImageQueue(web.morguefile.search("sweets", max=1), size='small')

  def draw(self):
    self.background(0);
    y = (self.height * 0.2) - self.mouseY * (len(self.images) * 0.58)
    for image in self.images:
        self.image(image, 20, y)
        y += image.height

if __name__ == '__main__':
    pj_frame(WebTest)
</pre>
<p>slowcessing.py</p>
<pre class="brush:python">from javax.swing import JFrame

from processing.core import PApplet

class PJApplet(PApplet):
  # rqd due to PApplet's using frameRate and frameRate(n) etc.
  def getField(self, name):
      return PApplet.getDeclaredField(name).get(self)

def pj_frame(pj_applet, **kwargs):
    from time import sleep

    frame = JFrame(kwargs.get('title', 'Slowcessing'))
    frame.defaultCloseOperation = kwargs.get('defaultCloseOperation', JFrame.EXIT_ON_CLOSE)
    frame.resizable = kwargs.get('resizable', False)

    panel = pj_applet()
    frame.add(panel)
    panel.init()

    while panel.defaultSize and not panel.finished:
        sleep(0.5)

    frame.pack()
    frame.visible = 1

    return frame

def shoebot_imports():
    """
    Allow import of the shoebot libraries
    """
    ##APP = 'shoebot'
    import sys
    DIR = sys.prefix + '/share/shoebot/locale'
    ##locale.setlocale(locale.LC_ALL, '')
    ##gettext.bindtextdomain(APP, DIR)
    ###gettext.bindtextdomain(APP)
    ##gettext.textdomain(APP)
    ##_ = gettext.gettext

    LIB_DIR = sys.prefix + '/share/shoebot/lib'
    sys.path.append(LIB_DIR)<span style="text-decoration: line-through;">
</span></pre>
<h2>Problems</h2>
<p>There are some things I couldn&#8217;t work :</p>
<p><span style="text-decoration: line-through;">The callback to say that images have been downloaded happens before the whole file is available, for this reason there are grey parts on the images on the first run.</span></p>
<h3>Nodebox web&#8230;</h3>
<p><span style="text-decoration: line-through;">While I did manage to fix things to get this working in Jython and get Morguefile working, I had a lot of trouble understanding what was going on here.</span></p>
<p>Cheers to Tom De Smedt for fixing these the areas of nodebox-web that I couldn&#8217;t <img src='http://www.stuartaxon.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Processing&#8230;</h3>
<p>Some parts of PApplet to do with image loading seem to be static, which may also explain problems I was getting with reentrancy.</p>
<h2>Download</h2>
<p>If you want to have a go, you&#8217;ll need to:</p>
<p>Install Netbeans 6.8</p>
<p>Install <a href="http://www.jython.org">Jython</a> (2.5 or higher) by installing the Netbeans python module</p>
<p>Add python to the path (if using Netbeans it&#8217;s copy is where Netbeans is installed).</p>
<p>Get nodebox-web by downloading <a href="https://code.goto10.org/hg/shoebot">shoebot</a> and install it with:</p>
<pre>jython setup.py install</pre>
<p>In Netbeans, add all the jars in the processing\lib folder to the Jython classpath, and opengl\library\opengl.jar<br />
<a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/jythonprocessing.png"><img class="alignnone size-medium wp-image-236" title="jythonprocessing" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/jythonprocessing-300x219.png" alt="" width="300" height="219" /></a></p>
<p>Download the <a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/PythonOnProcessing.zip">PythonOnProcessing</a> (tested on Netbeans 6.8)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/02/10/processing-with-jython-and-nodeboxshoebot-libraries/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Cairo to generate SVG in Django</title>
		<link>http://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django/</link>
		<comments>http://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 00:36:27 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[projects]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[cairo]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=217</guid>
		<description><![CDATA[Cairo is a 2D vector graphics api used by Firefox, Gtk and other desktop projects. I&#8217;m going to show here that it can also be used to generate web content, using Django. I&#8217;m going to port two examples from the Michael Urmans Cairo Tutorial for PyGTK Programmers. To understand the cairo and it&#8217;s drawing model [...]]]></description>
			<content:encoded><![CDATA[<p>Cairo is a 2D vector graphics api used by Firefox, Gtk and other desktop projects.</p>
<p>I&#8217;m going to show here that it can also be used to generate web content, using Django.</p>
<p>I&#8217;m going to port two examples from the Michael Urmans <a href="http://www.tortall.net/mu/wiki/PyGTKCairoTutorial">Cairo Tutorial  for PyGTK Programmers</a>.</p>
<p>To understand the cairo and it&#8217;s drawing model I&#8217;d recommend his his <a href="http://www.tortall.net/mu/wiki/CairoTutorial">Cairo Tutorial for Python  Programmers.</a></p>
<blockquote><p>Note:  In this example I&#8217;ll be generating SVGs&#8230;  as I.E. (as of 2010) does not support them, you might want to generate PNG or PDF &#8211; if you need to do this with cairo, look for one of the many cairo tutorials on the web.</p></blockquote>
<p>The example django project can be downloaded at the end of the article.</p>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_shapes.png"><img class="alignnone size-full wp-image-223" title="django_cairo_shapes" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_shapes.png" alt="" width="302" height="230" /></a></p>
<p><span id="more-217"></span></p>
<h2>Prerequisites</h2>
<p>You&#8217;ll need django and pycairo installed&#8230; and a little bit of Django knowledge.</p>
<p>In Windows you can do use easy_install to get the python dependencies:</p>
<pre class="brush:shell">
easy_install pycairo
easy_install django
</pre>
<p>In linux you&#8217;ll need to use your favourite package manager.</p>
<p>Onto the code&#8230;</p>
<h2>Hosting Framework</h2>
<p>The pygtk example starts by building a simple hosting framework</p>
<pre class="brush:python">#! /usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk, gobject, cairo

# Create a GTK+ widget on which we will draw using Cairo
class Screen(gtk.DrawingArea):

    # Draw in response to an expose-event
    __gsignals__ = { "expose-event": "override" }

    # Handle the expose-event by drawing
    def do_expose_event(self, event):

        # Create the cairo context
        cr = self.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()

        self.draw(cr, *self.window.get_size())

    def draw(self, cr, width, height):
        # Fill the background with gray
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

# GTK mumbo-jumbo to show the widget in a window and quit when it's closed
def run(Widget):
    window = gtk.Window()
    window.connect("delete-event", gtk.main_quit)
    widget = Widget()
    widget.show()
    window.add(widget)
    window.present()
    gtk.main()

if __name__ == "__main__":
    run(Screen)
</pre>
<p>This needs to be made ready for the web and the Gtkisms removed:</p>
<p>cairodraw.py</p>
<pre class="brush:python">from cairo import Context, SVGSurface

# Create a GTK+ widget on which we will draw using Cairo
class CairoWidget:

    def __init__(self, Surface = None):
        if Surface == None:
            Surface = SVGSurface

        self.Surface = Surface

    def draw(self, cr, width, height):
        # Fill the background with gray
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

def draw_widget(dest, Widget, Surface = SVGSurface, width = 100, height = 100):
    """
    Convenience function to output CairoWidget to a buffer
    """
    widget = Widget(Surface)
    surface = widget.Surface(dest, width, height)
    widget.draw(Context(surface), width, height)
    surface.finish()
</pre>
<h3>Changes:</h3>
<ul>
<li> Screen class is now CairoWidget as Screen made less sense in this context.</li>
<li>run() is replaced with draw_widget() and it has some new parameters to help it be rendered with django.</li>
<li>The new file is &#8216;cairodraw.py&#8217;, not &#8216;framework.py&#8217;</li>
</ul>
<h2>Initial view&#8230;</h2>
<p>Heres the initial views.py</p>
<pre class="brush:python"># Create your views here.

from django.http import HttpResponse
from cairo import SVGSurface

import cairodraw

from math import pi

class Shapes(cairodraw.CairoWidget):
    def draw(self, cr, width, height):
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

        # draw a rectangle
        cr.set_source_rgb(1.0, 1.0, 1.0)
        cr.rectangle(10, 10, width - 20, height - 20)
        cr.fill()

        # draw lines
        cr.set_source_rgb(0.0, 0.0, 0.8)
        cr.move_to(width / 3.0, height / 3.0)
        cr.rel_line_to(0, height / 6.0)
        cr.move_to(2 * width / 3.0, height / 3.0)
        cr.rel_line_to(0, height / 6.0)
        cr.stroke()

        # and a circle
        cr.set_source_rgb(1.0, 0.0, 0.0)
        radius = min(width, height)
        cr.arc(width / 2.0, height / 2.0, radius / 2.0 - 20, 0, 2 * pi)
        cr.stroke()
        cr.arc(width / 2.0, height / 2.0, radius / 3.0 - 10, pi / 3, 2 * pi / 3)
        cr.stroke()

class Transform(cairodraw.CairoWidget):
    def draw(self, cr, width, height):
        cr.set_source_rgb(0.5, 0.5, 0.5)
        cr.rectangle(0, 0, width, height)
        cr.fill()

        # draw a rectangle
        cr.set_source_rgb(1.0, 1.0, 1.0)
        cr.rectangle(10, 10, width - 20, height - 20)
        cr.fill()

        # set up a transform so that (0,0) to (1,1)
        # maps to (20, 20) to (width - 40, height - 40)
        cr.translate(20, 20)
        cr.scale((width - 40) / 1.0, (height - 40) / 1.0)

        # draw lines
        cr.set_line_width(0.01)
        cr.set_source_rgb(0.0, 0.0, 0.8)
        cr.move_to(1 / 3.0, 1 / 3.0)
        cr.rel_line_to(0, 1 / 6.0)
        cr.move_to(2 / 3.0, 1 / 3.0)
        cr.rel_line_to(0, 1 / 6.0)
        cr.stroke()

        # and a circle
        cr.set_source_rgb(1.0, 0.0, 0.0)
        radius = 1
        cr.arc(0.5, 0.5, 0.5, 0, 2 * pi)
        cr.stroke()
        cr.arc(0.5, 0.5, 0.33, pi / 3, 2 * pi / 3)
        cr.stroke()

def shapes(request):
    response = HttpResponse(mimetype='image/svg+xml')
    cairodraw.draw_widget(response, Shapes)
    return response

def transform(request):
    response = HttpResponse(mimetype='image/svg+xml')
    cairodraw.draw_widget(response, Transform)
    return response
</pre>
<p>The main difference is that Shape and Transform are the same, except they extend cairodraw.CairoWidget.</p>
<h3>urls.py</h3>
<p>This is pretty straightforward.</p>
<pre>(r'^shapes/shapes/$', 'shapes.views.shapes'),</pre>
<pre>(r'^shapes/transform/$', 'shapes.views.transform'),</pre>
<h2>Taking stock&#8230;</h2>
<p>This is a good stage to try things out, heres the django project so far: <a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_1a.zip">django_cairo_1a</a>.</p>
<p>Enter the svgsite directory and run</p>
<pre>python manage.py runserver</pre>
<p>If all is well it should output something like this:</p>
<pre>Validating models...
0 errors found

Django version 1.1.1, using settings 'svgsite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.</pre>
<p>If you visit the two URLs in most browsers except I.E. the output will look like this:</p>
<h3>http://127.0.0.1:8000/shapes/transform/</h3>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_transform.png"><img class="alignnone size-full wp-image-222" title="django_cairo_transform" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_transform.png" alt="" width="302" height="230" /></a></p>
<h3>http://127.0.0.1:8000/shapes/shapes/</h3>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_shapes.png"><img class="alignnone size-full wp-image-223" title="django_cairo_shapes" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_shapes.png" alt="" width="302" height="230" /></a></p>
<h2>Inline SVG and templates&#8230;</h2>
<p>The previous examples output straight SVG, however it would be much better to be able to incorperate SVG into templates and use it with HTML.</p>
<p>Luckily modern browsers support this, and with a couple of changes we can make templates that will output mixed documents like <a href="http://jwatt.org/svg/demos/xhtml-with-inline-svg.xhtml">this</a>.</p>
<h3>Example template:</h3>
<pre>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
 &lt;head&gt;
 &lt;title&gt;SVG embedded inline in XHTML&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
 &lt;h1&gt;Transform&lt;/h1&gt;
 &lt;div style="width:50%, height:40px"&gt;{{transform|safe}}&lt;/div&gt;
 &lt;div&gt;&lt;a href="transform"&gt;Full screen svg&lt;/a&gt;&lt;/div&gt;
 &lt;h1&gt;Shapes&lt;/h1&gt;
 &lt;div style="width:50%"&gt;{{shapes|safe}}&lt;/div&gt;
 &lt;div&gt;&lt;a href="shapes"&gt;Full screen svg&lt;/a&gt;&lt;/div&gt;
 &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The variables &#8216;shapes&#8217; and &#8216;transform&#8217; will be the svg, the key is the &#8216;|safe&#8217;, which means the XML won&#8217;t be processed by django.</p>
<h3>Changes to views to support inline</h3>
<p>To use templates the SVG data is needed as a string to pass to the template.</p>
<p>Heres an index view demonstrating this:</p>
<pre class="brush:python">def index(request):
    buff = StringIO()
    cairodraw.draw_widget(buff, Shapes)
    shapes = buff.getvalue()[38:]

    buff = StringIO()
    cairodraw.draw_widget(buff, Transform)
    transform = buff.getvalue()[38:]

    return render_to_response(
    'shapes_index.html',
    {"transform": transform, "shapes": shapes},
    mimetype='application/xhtml+xml')
</pre>
<p>The main differences are that -<br />
cairodraw.draw_widget() is called with a temporary buffer, we use templates.</p>
<blockquote>
<h4>Evil hack alert:</h4>
<p>OK, I did something naughty&#8230; notice the [38:] ?   Unfortunately django doesn&#8217;t like having  in the middle of the output.  I couldn&#8217;t find a way to turn this off so we chop it off the beginning of the string.</p></blockquote>
<p>Apart from the evil hack this works well and you get output like this:</p>
<h3>http://127.0.0.1:8000/shapes/</h3>
<p><a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_inline_svg.png"><img class="alignnone size-full wp-image-230" title="django_cairo_inline_svg" src="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_inline_svg.png" alt="" width="294" height="652" /></a></p>
<h1></h1>
<h2>Final Version</h2>
<p>Cool, every thing seems to be working !</p>
<p>The final version to try <a href="http://www.stuartaxon.com/wp-content/uploads/2010/02/django_cairo_1b.zip">django_cairo_1b</a>.</p>
<h2>Next time&#8230;.</h2>
<p>I&#8217;ll be looking at using a Cairo based library,  <a href="http://bitbucket.org/lgs/pycha/wiki/Home">PyCha</a> library with django to output smooth looking charts in SVG.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/02/03/using-cairo-to-generate-svg-in-django/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Scripts to help workflow now on google code.</title>
		<link>http://www.stuartaxon.com/2010/01/25/scripts-to-help-workflow-now-on-google-code/</link>
		<comments>http://www.stuartaxon.com/2010/01/25/scripts-to-help-workflow-now-on-google-code/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 14:33:21 +0000</pubDate>
		<dc:creator>stu</dc:creator>
				<category><![CDATA[making windows usable]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[batch]]></category>
		<category><![CDATA[cmd]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[windows]]></category>
		<category><![CDATA[workflow]]></category>

		<guid isPermaLink="false">http://www.stuartaxon.com/?p=210</guid>
		<description><![CDATA[I&#8217;ve uploaded my scripts to help workflow to google code, naming the project batch flow. Heres a summary of some of the things you can do. Clipboard integration Go to a directory in the clipboard. If you have the address bar enabled in explorer: Copy the location, go to the prompt and enter &#8216;pcd&#8217; to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve uploaded my scripts to help workflow to google code, naming the project <a href="http://code.google.com/p/batch-flow/">batch flow</a>.</p>
<p>Heres a summary of some of the things you can do.</p>
<h2>Clipboard integration</h2>
<h3>Go to a directory in the clipboard.</h3>
<p>If you have the address bar enabled in explorer:</p>
<p>Copy the location, go to the prompt and enter &#8216;pcd&#8217; to go to that folder</p>
<p>Go to the location of a setting in netbeans or eclipse:</p>
<p>Copy the location , go to the prompt and enter &#8216;pcd&#8217; to go to the folder (or folder containing the file).</p>
<h3>Get the current directory without dragging:</h3>
<p>Enter &#8216;ccd&#8217;</p>
<h2>Directory bookmarks</h2>
<p>dirsave and dirload let you save named bookmarks.</p>
<h3>Using hotkeys</h3>
<p>If you use the alternate shell <a href="http://www.jpsoft.com/">4nt</a> (or the free <a href="http://www.jpsoft.com/">TCC/LE</a>) you can use the supplied configuration and aliases to access the bookmark functionality from the keyboard:</p>
<p>In the 4nt or tcc/le prompt enter &#8220;option&#8221;, under the &#8220;TCStart/TCExit&#8221; path, change the location to the location where batch-flow is installed + &#8220;\conf&#8221;, for instance on my computer batch-flow is installed to c:\usr\batch-flow, so I set it to</p>
<pre>c:\usr\batch-flow\conf</pre>
<p>Now in new TCC/LE prompts F5-F10 are reserved for directories: Ctrl+Fkey to save, and Alt+Fkey to load.  Alt-F12 lists these shortcuts.</p>
<p>Note:  Alt-F12 only lists shortcuts on FKeys, to list these and other shortcuts enter dirload /l</p>
<blockquote><p>batch-flow comes with other handy hotkeys, use &#8216;alias&#8217; in TCC/LE to see what they are.</p></blockquote>
<h2>Path manipulation</h2>
<h3>addpath</h3>
<p>It&#8217;s annoying after installing a program to have to add it to the path, so there is an &#8216;addpath&#8217; command to do this.</p>
<h3>regpath</h3>
<p>This is a more general utility for viewing the registry path, you can list it, validate it, check for the location of files within it.</p>
<p>Also useful is &#8216;regpath /L&#8217; which sets the local prompts path to the one in the registry.</p>
<h2>Further help</h2>
<p>Most of the commands have help builtin, which you can access by using the /? option.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stuartaxon.com/2010/01/25/scripts-to-help-workflow-now-on-google-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

