<?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>Kolios &#187; Coding</title>
	<atom:link href="http://www.kolios.dk/category/tech/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kolios.dk</link>
	<description></description>
	<lastBuildDate>Tue, 31 Aug 2010 11:38:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>How to migrate django models with South</title>
		<link>http://www.kolios.dk/2010/02/12/how-to-migrate-django-models-with-south/</link>
		<comments>http://www.kolios.dk/2010/02/12/how-to-migrate-django-models-with-south/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 09:22:22 +0000</pubDate>
		<dc:creator>sebastien</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[django]]></category>

		<guid isPermaLink="false">http://www.kolios.dk/?p=524</guid>
		<description><![CDATA[<img src="http://www.kolios.dk/icons/coding-48x48.png" width="48" height="48" alt="" title="Coding" /><img src="http://www.kolios.dk/icons/django-48x48.png" width="48" height="48" alt="" title="django" /><br/>Hi django fridayers ! Today on python friday, we will discuss the model and data migration of django. Many of you are probably developing the web app in python and are absolutely amazed about how easy it to create a database schema from your django models. Just run an manage.py syncdb and &#8230;voila ! Your [...]]]></description>
			<content:encoded><![CDATA[<img src="http://www.kolios.dk/icons/coding-48x48.png" width="48" height="48" alt="" title="Coding" /><img src="http://www.kolios.dk/icons/django-48x48.png" width="48" height="48" alt="" title="django" /><br/><p>Hi django fridayers !</p>
<p>Today on python friday, we will discuss the model and data migration of django.</p>
<p>Many of you are probably developing the web app in python and are absolutely amazed about how easy it to create a database schema from your django models. Just run an manage.py syncdb and &#8230;voila ! Your brand new application has all the support needed in the backend database.</p>
<p>But let&#8217;s face it, this is not really practical when it comes to modify an application that is ALREADY online and have data (registered users, stored personal information, &#8230;).</p>
<p><span id="more-524"></span></p>
<h3>The problem</h3>
<p>How can you migrate from one model to another without loosing any data ?</p>
<h3>The solution.</h3>
<p><a title="South migration tool" href="http://south.aeracode.org">South</a></p>
<p>This python package will take care of most of the trouble caused by your model modifications.<br />
With South, you can :</p>
<ul>
<li>Modify the schema of your database according to your model</li>
<li>Migrate your data to make sure that you wont lose any data across the migration</li>
</ul>
<p><!-- more --></p>
<h3>Installing South</h3>
<ul>
<li>download</li>
<li>setup.py install (as root)</li>
<li>edit your settings.py to activate &#8220;south&#8221; in the installed apps</li>
</ul>
<h3>A simple example</h3>
<p>You can now type :</p>
<pre class="brush: bash; gutter: false">$&gt; ./manage syncdb</pre>
<p>to create the good tables in your database. South keep track of every migration in the project database.</p>
<p>Now, let&#8217;s consider that you have a the following model:</p>
<pre class="brush: python">class Customer(models.Model):
    name = models.CharField(max_length= 60)

    def __unicode__(self):
        return self.name</pre>
<p>The first thing you need to do is to initialize south so it can keep track of your<br />
modification of models:</p>
<pre class="brush: bash; gutter: false">$&gt; manage.py startmigration customer initial --initial</pre>
<p>This will create your first migration (initial). The migration will basically creates the tables in your database.<br />
Now, you can apply the migration.</p>
<pre class="brush: bash; gutter: false">$&gt; manage.py migrate</pre>
<p>Now, let&#8217;s assume that you want to change it into:</p>
<pre class="brush: python">class Customer(models.Model):
    name = models.CharField(max_length = 60)
    password = models.CharField('this is a clear text password', max_length=60)</pre>
<p>You have to prepare the migration with the following command:</p>
<pre class="brush: bash; gutter: false">$&gt; ./manage.py startmigration customer add_password --auto</pre>
<p>This creates a migration file that contains your modifications. I let you try to figure out what forward and backward methods are for. Once again, when you think that your migration file is good, you can apply the changes :</p>
<pre class="brush: bash; gutter: false">$&gt; ./manage.py migrate</pre>
<p>At this point, your database is totally synced with your model, so let&#8217;s create some data into it:</p>
<pre class="brush: bash; gutter: false">$&gt; ./manage.py shell
&gt; from customer.models import Customer
&gt; c = Customer()
&gt; c.name="sebastien requiem"
&gt; c.password = "secret"
&gt; c.save()
&gt; Customer.objects.all()
[\]</pre>
<h3>A more complex example with DATA migration</h3>
<p>You now decide to split the field <em>name</em> into <em>firstname</em> and <em>lastname</em>. The natural way would be to delete the field name and create two fields named <em>firstname</em> and <em>lastname</em>. And this is Wrong for many reasons:</p>
<ol>
<li>South will not understand that you want to split the name into two distinct fields</li>
<li>South won&#8217;t be able to migrate your data forward AND backward if you want to roll back</li>
</ol>
<p>The good (and ONLY) way to do it is to so it in three steps:</p>
<ol>
<li>modify your model so you add <em>firstname</em> and <em>lastname</em> fields and migrate the schema</li>
<li>create a migration that migrate your DATA (while name, <em>name</em>, <em>firstname</em> and <em>lastname</em> are all accessible)</li>
<li>delete the <em>name</em> field</li>
</ol>
<p>Now, let&#8217;s assume that you want to change you previous model into the following :</p>
<pre class="brush: python">class Customer(models.Model):
    name = models.CharField(max_length = 60)
    firstname = models.CharField(max_length = 60)
    lastname = models.CharField(max_length = 60)
    password = models.CharField('this is a clear text pasword', length=60)

    def __unicode__(self):
        return self.firstname + ", " + self.lastname</pre>
<h3>Migrating the schema</h3>
<p>Nothing fancy here:</p>
<pre class="brush: bash; gutter: false">$&gt; ./manage.py startmigration customer add_first_last_name --auto
$&gt; ./manage.py migrate</pre>
<h3>Migrate the data</h3>
<pre class="brush: bash; gutter: false">$&gt; ./manage.py startmigration customer first_last_data
now edit the migration file newly created and add the following lines :</pre>
<pre class="brush: python">    def forwards(self, orm):
        for customer in orm.Customer.objects.all():
            try:
                customer.first_name, customer.last_name = adopter.name.split(" ", 1)
            except ValueError:
                customer.first_name, customer.last_name = customer.name, ""
            customer.save()

    def backwards(self, orm):
        for customer in orm.Customer.objects.all():
            customer.name = customer.firstname + " " + customer.lastname
            customer.save()</pre>
<p>As you can see, the variable &#8220;orm&#8221; is in fact the real django ORM. you can use it to write data migration in python with the usual django syntax, which is VERY convenient.</p>
<p>run now you data migration:</p>
<pre class="brush: bash; gutter: false">$&gt; ./manage.py migrate</pre>
<p>A quick django shell will ensure that we have the data present in the database where we expect it to be :</p>
<pre class="brush: bash; gutter: false">$&gt;./manage shell
&gt; from customer.models import Customer
&gt; Customer.objects.all()
[]</pre>
<p>We now just need to delete the remaining an unused field.</p>
<p>Change your model :</p>
<pre class="brush: python">class Customer(models.Model):
    firstname = models.CharField(max_length = 60)
    lastname = models.CharField(max_length = 60)
    password = models.CharField('this is a clear text password', length=60)</pre>
<p>and run a simple migration with &#8211;auto</p>
<pre class="brush: bash">$&gt; ./manage.py startmigration customer remove_name --auto</pre>
<p>and apply</p>
<pre class="brush: bash; gutter: false">$&gt; ./manage.py migrate</pre>
<p>Voila.</p>
<p>References:</p>
<ul>
<li><a title="South migration tool" href="http://south.aeracode.org">The South migration tools</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.kolios.dk/2010/02/12/how-to-migrate-django-models-with-south/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Inkscape module to generate SVG drawings with Python</title>
		<link>http://www.kolios.dk/2009/04/14/inkscape-module-to-generate-svg-drawings-with-python/</link>
		<comments>http://www.kolios.dk/2009/04/14/inkscape-module-to-generate-svg-drawings-with-python/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 09:30:00 +0000</pubDate>
		<dc:creator>sebastien</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[inkscape]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[svg]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.kickban.net/?p=36</guid>
		<description><![CDATA[<img src="http://www.kolios.dk/icons/coding-48x48.png" width="48" height="48" alt="" title="Coding" /><br/>As a new freelancer, I decided to create my own business cards using moo services. This website allow you to create collectors business cards. The principle is simple, you can upload one image per card so the Verso of the card will be different each time. My problem : How to create a business card [...]]]></description>
			<content:encoded><![CDATA[<img src="http://www.kolios.dk/icons/coding-48x48.png" width="48" height="48" alt="" title="Coding" /><br/><p><img class="alignleft size-full wp-image-42" title="inkscape" src="http://www.kickban.net/wp-content/uploads/2009/04/inkscape.png" alt="inkscape" width="134" height="106" />As a new <a title="Kolios Unix freelancer" href="http://www.kolios.dk" target="_blank">freelancer</a>, I decided to create my own business cards using moo services. This website allow you to create collectors business cards. The principle is simple, you can upload one image per card so the Verso of the card will be different each time.</p>
<blockquote><p>My problem : How to create a business card that  match my website layout and make it uniq at the same time ?</p></blockquote>
<p><span id="more-358"></span><br />
<img class="alignleft" title="python powered" src="http://www.python.org/community/logos/python-powered-w-140x56.png" alt="" width="140" height="56" />This is when Python and <a title="Inkscape, the beautiful editor" href="http://www.inkscape.org" target="_blank">Inkscape</a> came to rescue me. Inkscape is a well know (GPL&#8217;ed) SVG graphic editor. If you have never tried it, consider doing it. It is amazing what this soft can produce within a couple of minutes. Beside Inkscape, the website <a title="command line fu is a website referencing unix commands" href="http://commandlinefu.com" target="_blank">commandlinfu.com</a> is a (cool) website providing Unix Commands and explanations of what they do (be careful some commands may be dangerous or invalid though).</p>
<p>So I had an idea. Why not using the website <a href="http://commandlinefu.com" target="_blank">commandlinefu</a>, extract commands from the RSS feed and generate images for my Collector Business cards ?</p>
<p><strong>How ?</strong></p>
<p>Inkscape support plugins and offer a nice python module to help you to create SVG objects.</p>
<p><strong>Let&#8217;s go !</strong></p>
<p>Inkscape expect a couple of things from the module structure.</p>
<pre class="brush: python">#!/usr/bin/env python

# These two lines are only needed if you don't put the script directly into
# the installation directory
import sys
from xml.dom import minidom
import urllib
import re

# This import is for MAc os X only. In GNU systems it should
# be somewhere in /usr/share/inkscape/extensions

sys.path.append('/Applications/Inkscape.app/Contents/Resources/extensions')

# We will use the inkex module with the predefined Effect base class.
import inkex
# The simplestyle module provides functions for style parsing.
from simplestyle import *

class BusinessCard(inkex.Effect)
    """
    Example Inkscape effect extension. It reads an RSS feed and create objects according to the content.
    """
    def __init__(self):
        """
        Constructor.
        Defines the "--what" option of a script.
        """
        # Call the base class constructor.
        inkex.Effect.__init__(self)

        # Define string option "--what" with "-w" shortcut and default value "World".
        self.OptionParser.add_option('-w', '--what', action = 'store',
        type = 'integer', dest = 'cards_number', default = '10',
        help = 'How many images do you want to create?')</pre>
<p>The <em>optionparser</em> is required by Inkscape as it will pass some arguments to the script. We could, for example use this argument to know how many images we want to generate. In our case, the argument will be stored in the variable call cards_number. I let you have a closer look to this <a title="Inkscap Python tutorial" href="http://wiki.inkscape.org/wiki/index.php/PythonEffectTutorial" target="_blank">Wiki Page</a> for any further explanation.</p>
<p>Now that we have the basis for creating an Inkscape plugin, we should define the main actions that this plugin is gonna do:</p>
<ol>
<li>Read the RSS feed</li>
<li>Extract the usefull information (and filter)</li>
<li>Create the SVG objects</li>
<li>Add them to the SVG Layer</li>
<li>Loop to 1</li>
</ol>
<p>Let&#8217;s use Python wonderful XML parser to read our RSS feed</p>
<pre class="brush: python">    # Open the XML ressource and read it
    socket = urllib.urlopen("http://feeds2.feedburner.com/Command-line-fu?format=xml");
    # Create an object representing the XML structure
    self.xmldoc = minidom.parse(socket).documentElement
    socket.close();</pre>
<p>Create the function that will do the loop</p>
<pre class="brush: python">    def effect(self):
        """
        Effect behaviour.
        Overrides base class' method and inserts "Hello World" text into SVG document.
        """
        # Get script's "--what" option value.
        cards_number = self.options.cards_number

        # Get access to main SVG document element and get its dimensions.
        svg = self.document.getroot()

        # Create a new layer.
        layer = inkex.etree.SubElement(svg, 'g')
        layer.set(inkex.addNS('label', 'inkscape'), 'Hello %s Layer' % (what))
        layer.set(inkex.addNS('groupmode', 'inkscape'), 'layer')

        # Create text element from the RSS feed
        itemlist = self.xmldoc.getElementsByTagName('item')

        #we will loop so better initialize variables
        item_x = 0
        item_y = 0

        # in the RSS feed, the iformation we want in contained in between
        # the &lt;code&gt;&lt;/code&gt; markup. Let's use a regexp to get it.
        regexp = re.compile('&lt;code&gt;.*&lt;/code&gt;');

        # Note that here, we should use the cards_number instead of reading
        # the complete rss feed.
        for node in itemlist:
            title = node.getElementsByTagName('title')[0].firstChild.data
            command = regexp.search(node.getElementsByTagName('description')[0].firstChild.data)

            # Get ride of the markup
            command = command.group()
            command = command.replace("&lt;code&gt;", "");
            command = command.replace("&lt;/code&gt;", "");

            # filter in case the comman is too long...
            if len(command) &gt; 40:
                continue</pre>
<p>Ok so now we have to start creating the objects. For this, Inkscape offer us a nice way to do it. Use the inkex extension. the function inkex.addNS is usefull to create everything you need in SVG.</p>
<pre class="brush: python">        #Design the background grey business card
        background = inkex.etree.Element(inkex.addNS('rect', 'svg'))
        background.set('x', str(item_x))
        background.set('y', str(item_y))
        background.set('width', str(520))
        background.set('height', str(348))
        background.set('fill', 'rgb(32, 32, 32)')

        #Our lovely ornge square will fit here
        square = inkex.etree.Element(inkex.addNS('rect', 'svg'))
        square.set('x', str(item_x + 30))
        square.set('y', str(item_y + 30))
        square.set('width', str(84))
        square.set('height', str(84))
        square.set('rx', str(20))
        square.set('ry', str(20))
        square.set('fill', 'rgb(224, 121, 26)')

        #Insert the "K" letter. K stands for Kolios
        K_logo = inkex.etree.Element(inkex.addNS('text','svg'))
        K_logo.text = ("K")
        # Set text position to center of document.
        K_logo.set('x', str(item_x + 61))
        K_logo.set('y', str(item_y + 95))
        K_logo.set('fill', "white")

        # Center text horizontally with CSS style.
        style = {'text-align' : 'left',
            'font-family': 'MammaGamma',
            'font-size': '56'
        }
        K_logo.set('style', formatStyle(style))

        #Insert the Unix Tip
        tip = inkex.etree.Element(inkex.addNS('text','svg'))
        tip.text = (title)
        # Set text position to center of document.
        tip.set('x', str(item_x + 40))
        tip.set('y', str(item_y + 200))
        tip.set('fill', 'rgb(170, 170, 170)')

        # Center text horizontally with CSS style.
        style = {'text-align' : 'left',
            'font-family': 'terminal',
            'font-style': 'italic'
        }
        tip.set('style', formatStyle(style))

        #Insert the Unix Command
        unix = inkex.etree.Element(inkex.addNS('text','svg'))
        unix.text = (command)
        # Set text position to center of document.
        unix.set('x', str(item_x + 30))
        unix.set('y', str(item_y + 180))
        unix.set('fill', 'rgb(224, 121, 26)')

        # Center text horizontally with CSS style.
        style = {'text-align' : 'left',
            'font-family': 'Monaco',
            'font-size': '20'
        }
        unix.set('style', formatStyle(style))

        # Connect elements together.
        layer.append(background)
        layer.append(square)
        layer.append(K_logo)
        layer.append(kolios)
        layer.append(slogan)
        layer.append(unix)
        layer.append(tip)
        item_y = item_y + 360

    # Create effect instance and apply it.
    effect = BusinessCard()
    effect.affect()</pre>
<p>You can notice that we use css-style for the text. This is possible with the use of the module <em>simplestyle.</em></p>
<p>Basically, you create an object and THEN add it to the layer. Pay attention that the order you add objects MATTERS for the rendering depth. In this case the background will be rendered first, then the square&#8230; and so on. All type of objects can be created and the entire list is available at the <a title="W3C - SVG definition" href="http://www.w3.org/TR/SVG/shapes.html" target="_blank">W3c webpage</a>.</p>
<p>But how do I add my plugin to Inkscape ?</p>
<p>Well, last thing but not the least. You python script should be placed in .inkscape/extensions with a description file</p>
<pre class="brush: xml">&lt;inkscape-extension&gt;
    &lt;_name&gt;Business Card&lt;/_name&gt;
    &lt;id&gt;org.ekips.filter.business_card&lt;/id&gt;
    &lt;dependency type="executable" location="extensions"&gt;card.py&lt;/dependency&gt;
    &lt;dependency type="executable" location="extensions"&gt;inkex.py&lt;/dependency&gt;
    &lt;param name="what" type="integer" _gui-text="How many business cards ?"&gt;10&lt;/param&gt;
    &lt;effect&gt;
    &lt;object-type&gt;all&lt;/object-type&gt;
    &lt;effects-menu&gt;
        &lt;submenu _name="Examples"/&gt;
    &lt;/effects-menu&gt;
    &lt;/effect&gt;
    &lt;script&gt;
        &lt;command reldir="extensions" interpreter="python"&gt;card.py&lt;/command&gt;
    &lt;/script&gt;
&lt;/inkscape-extension&gt;</pre>
<p>The file should be named with a .inx extension. I won&#8217;t explain this as this is pretty obvious.</p>
<p>At last, you can take a llok at the final output. The first picture is NOT generated but &#8230; it gives a good example.</p>
<p><a href="http://www.kickban.net/wp-content/uploads/2009/04/cards.jpg"><img class="aligncenter size-full wp-image-148" title="cards" src="http://www.kickban.net/wp-content/uploads/2009/04/cards.jpg" alt="cards" width="529" height="362" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.kolios.dk/2009/04/14/inkscape-module-to-generate-svg-drawings-with-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
