<?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>Dirk Raffel</title>
	<atom:link href="http://dirkraffel.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://dirkraffel.com</link>
	<description>Independent software consultant and contractor</description>
	<lastBuildDate>Thu, 24 Nov 2011 19:00:13 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Fixing wrong direction of segments in pgRouting output</title>
		<link>http://dirkraffel.com/2011/09/06/fixing-wrong-direction-of-segments-in-pgrouting-output/</link>
		<comments>http://dirkraffel.com/2011/09/06/fixing-wrong-direction-of-segments-in-pgrouting-output/#comments</comments>
		<pubDate>Tue, 06 Sep 2011 19:31:55 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[GIS]]></category>

		<guid isPermaLink="false">http://dirkraffel.com/?p=545</guid>
		<description><![CDATA[In my last post I covered the steps needed to set up a PostGIS database on Mac OS X together with pgRouting. Now, pgRouting solves my geospatial routing problems quite well, but I have run into a rather annoying problem: pgRouting returns the edges as they are stored in the database and not as traversed, [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post I covered the steps needed to set up a <a href="http://postgis.refractions.net/">PostGIS</a> database on Mac OS X together with <a href="http://www.pgrouting.org/">pgRouting</a>. Now, pgRouting solves my geospatial routing problems quite well, but I have run into a rather annoying problem: pgRouting returns the edges as they are stored in the database and not as traversed, so on some edges the direction (from-to or to-from) needs to be flipped around.</p>
<p>The following QGIS screenshot illustrates the problem (click for bigger version):<br />
<div id="attachment_561" class="wp-caption alignnone" style="width: 310px"><a href="http://dirkraffel.com/blog/wp-content/uploads/2011/09/unordered.png"><img src="http://dirkraffel.com/blog/wp-content/uploads/2011/09/unordered-300x135.png" alt="" title="wrong directions" width="300" height="135" class="size-medium wp-image-561" /></a><p class="wp-caption-text">Some segments with wrong direction</p></div></p>
<p>You can see clearly that the line arrows do not all point in the same direction.</p>
<p>But don’t despair! My SQL skills are admittedly a bit rusty, but I managed to write a <a href="http://www.postgresql.org/docs/9.0/static/plpgsql.html">PL/pgSQL</a> script that fixes the problem.</p>
<pre class="brush: sql">
-- Wrapper for shortest_path() function to find the shortest route between two points
CREATE OR REPLACE FUNCTION dijkstra(
    geom_table varchar, source int4, target int4)
    RETURNS SETOF GEOMS AS
$$
DECLARE
    r record;
    path_result record;
    v_id integer;
    e_id integer;
    geom geoms;
    id integer;
BEGIN
    id := 0;
    FOR path_result IN EXECUTE 'SELECT gid,the_geom FROM ' ||
          'shortest_path(''SELECT gid AS id, start_id::integer AS source, end_id::integer AS target, ' ||
          'length(the_geom)::double precision AS cost FROM ' ||
      quote_ident(geom_table) || ''', ' || quote_literal(source) ||
          ' , ' || quote_literal(target) || ' , false, false), ' ||
          quote_ident(geom_table) || ' WHERE edge_id = gid '
        LOOP
            geom.gid      := path_result.gid;
            geom.the_geom := path_result.the_geom;
            id            := id + 1;
            geom.id       := id;
            RETURN NEXT geom;
        END LOOP;
    RETURN;
END;
$$ LANGUAGE 'plpgsql' VOLATILE STRICT; 

-- Returns records for the route from start to end with correct directions
CREATE OR REPLACE FUNCTION calc_route(
    geom_table varchar, start_id int, end_id int)
    RETURNS SETOF record AS
$$
DECLARE
    r record;
    id int;
    prev int;
    i int;
BEGIN
    prev := 0;
    id   := start_id;
    FOR r IN EXECUTE 'SELECT start_id, end_id, route.* ' ||
      'FROM ' || quote_ident(geom_table) || ' JOIN ' ||
      '(SELECT * FROM dijkstra(' || quote_literal(geom_table) || ',' || start_id || ', ' || end_id || ')) AS route ' ||
      'ON ' || quote_ident(geom_table) || '.gid = route.gid ORDER BY route.id; '
    LOOP
        IF (r.start_id = id AND r.end_id <> prev) THEN
            RETURN NEXT r;
        ELSIF (r.end_id = id AND r.start_id <> prev) THEN
            i           := r.end_id;
            r.end_id    := r.start_id;
            r.start_id  := i;
            r.the_geom  := ST_Reverse(r.the_geom);
            RETURN NEXT r;
        ELSE
            RAISE NOTICE 'error: record % % %', r.start_id, r.end_id, r.id;
            RETURN;
        END IF;
        prev := r.start_id;
        id   := r.end_id;
    END LOOP;
    RETURN;
END;
$$ LANGUAGE 'plpgsql' VOLATILE STRICT;
</pre>
<p>Sample usage:</p>
<pre class="brush: sql">
DROP TABLE IF EXISTS result;
SELECT start_id, end_id, gid, the_geom INTO result FROM calc_route('network', 22353, 21587)
AS (start_id int, end_id int, id int, gid int, the_geom geometry);
</pre>
<p>As a result, here is a QGIS screenshot with all segments in the correct direction (again, click for bigger version)<br />
<div id="attachment_565" class="wp-caption alignnone" style="width: 310px"><a href="http://dirkraffel.com/blog/wp-content/uploads/2011/09/ordered.png"><img src="http://dirkraffel.com/blog/wp-content/uploads/2011/09/ordered-300x144.png" alt="All segments with correct direction" title="correct directions" width="300" height="144" class="size-medium wp-image-565" /></a><p class="wp-caption-text">All segments with correct direction</p></div></p>
<p>A note about line 59: this script assumes that pgRouting returns the segments in the correct order, which means that either the condition from line 50 or from line 52 evaluates to true. So, line 59 should never be executed. However, some people have reported on the pgrouting-users mailing list that the segments returned from pgRouting are not in the right order &#8211; in which case you would see the message from line 59.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2011/09/06/fixing-wrong-direction-of-segments-in-pgrouting-output/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>pgRouting on Mac OS X 10.6.8</title>
		<link>http://dirkraffel.com/2011/07/06/pgrouting-on-mac-os-x-10-6-8/</link>
		<comments>http://dirkraffel.com/2011/07/06/pgrouting-on-mac-os-x-10-6-8/#comments</comments>
		<pubDate>Wed, 06 Jul 2011 19:55:32 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[GIS]]></category>

		<guid isPermaLink="false">http://dirkraffel.com/?p=399</guid>
		<description><![CDATA[Some notes about how to build pgRouting on Mac OS X, in case I have to do this again in the future. I&#8217;m writing this from my memory and I hope I did not forget something, but it should work similar to what I&#8217;ve described. pgRouting adds geospatial routing functionality to a PostGIS / PostgreSQL [...]]]></description>
			<content:encoded><![CDATA[<p>Some notes about how to build <a href="http://www.pgrouting.org/">pgRouting</a> on Mac OS X, in case I have to do this again in the future. <img src='http://dirkraffel.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  I&#8217;m writing this from my memory and I hope I did not forget something, but it should work similar to what I&#8217;ve described.</p>
<p>pgRouting adds geospatial routing functionality to a PostGIS / PostgreSQL geospatial database. So, as a preliminary requirement, we have to start with installing PostgreSQL and PostGIS.</p>
<p>I&#8217;ve done this using <a href="http://macports.org">MacPorts</a>, so</p>
<pre class="brush: text">
$ sudo port -d install postgresql90 postgresql90-server postgis
</pre>
<p>If you like, you can also install pgAdmin3 via MacPorts, an administration program to PostgreSQL</p>
<p>To create a database instance, after install do</p>
<pre class="brush: text">
$ sudo mkdir -p /opt/local/var/db/postgresql90/defaultdb
$ sudo chown postgres:postgres /opt/local/var/db/postgresql90/defaultdb
$ sudo su postgres -c '/opt/local/lib/postgresql90/bin/initdb -D /opt/local/var/db/postgresql90/defaultdb'
</pre>
<p>When executing the last command from above, I remember I had some trouble with the postgres user that was created during installation. Check that the postgres user account can be executed using the <code>su</code> command, e.g. </p>
<pre class="brush: text">
$ sudo su - postgres
</pre>
<p>If not, make sure that the postgres account has a valid shell</p>
<pre class="brush: text">
$ sudo dscl . -create /Users/postgres UserShell /bin/sh
</pre>
<p>Note that the installation has created a startup item for starting <code>postgresql90-server</code> with launchd. It is disabled by default. Execute the following command to start the server, and to cause the server to launch at startup:</p>
<pre class="brush: text">
$ sudo port load postgresql90-server
</pre>
<p>As an alternative to launchd, you can also start the database server using:</p>
<pre class="brush: text">
$ /opt/local/lib/postgresql90/bin/postgres -D /opt/local/var/db/postgresql90/defaultdb
</pre>
<p>or</p>
<pre class="brush: text">
$ /opt/local/lib/postgresql90/bin/pg_ctl -D /opt/local/var/db/postgresql90/defaultdb -l logfile start
</pre>
<p>After starting the server, you might want to look at <code>/opt/local/var/log/postgresql90/postgres.log</code> to check if the server is running OK.</p>
<p>Now, let&#8217;s try to install pgRouting.</p>
<p>The pgRouting package is also available from MacPorts, but only an older version 1.03. So, I just went to www.pgrouting.org and downloaded the latest source package pgrouting-1.05.tar.gz from 2010/11/22.</p>
<p>However, you won&#8217;t be available to successfully build from this archive (at least not on Mac OS X&#8230;)! Instead, you will end up with a couple of &#8220;undefined symbols&#8221; when linking.</p>
<p>For solving this, go to the pgRouting GitHub repository instead. This <a href="https://github.com/pgRouting/pgrouting/issues/5">issue</a> explains the cause why the linking fails on Mac OS X. Fortunately, this issue has already been fixed, so download a current snapshot from the repository and try to build this one instead.</p>
<p>First, you need to edit <code>cmake/FindPostgreSQL.cmake</code>. Add the include path <code>/opt/local/include/postgresql90/server</code><br />
and the library path <code>/opt/local/lib/postgresql90</code> to the file so that cmake is able to locate your PostgreSQL installation.</p>
<p>Then build pgRouting with </p>
<pre class="brush: text">
$ cmake .
$ make
$ sudo make install
</pre>
<p>You should end up with something like this</p>
<pre class="brush: text">
[100%] Built target routing
Install the project...
-- Install configuration: ""
-- Installing: /opt/local/lib/postgresql90/librouting.so
-- Installing: /usr/share/pgrouting/routing_core.sql
-- Installing: /usr/share/pgrouting/routing_core_wrappers.sql
-- Installing: /usr/share/pgrouting/routing_topology.sql
-- Installing: /usr/share/pgrouting/matching.sql
</pre>
<p>Finally,  I hope my memory still serves me right:</p>
<pre class="brush: text">
$ createdb -U postgres -E utf8 template_postgis
$ psql -U postgres -d template_postgis -f /opt/local/share/postgresql90/contrib/postgis-1.5/postgis.sql
$ psql -U postgres -d template_postgis -f /opt/local/share/postgresql90/contrib/postgis-1.5/spatial_ref_sys.sql
$ psql -U postgres -d template_postgis -f /usr/share/pgrouting/routing_core.sql
$ psql -U postgres -d template_postgis -f /usr/share/pgrouting/routing_core_wrappers.sql
$ psql -U postgres -d template_postgis -f /usr/share/pgrouting/routing_topology.sql
</pre>
<p>Create a pgRouting enabled database using the new template_postgis template</p>
<pre class="brush: text">
$ createdb -U postgres -T template_postgis routing
</pre>
<p>That&#8217;s it! If you are new to pgRouting, you can find a good example about route calculation using pgRouting <a href="http://underdark.wordpress.com/2011/02/07/a-beginners-guide-to-pgrouting/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2011/07/06/pgrouting-on-mac-os-x-10-6-8/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Best way to merge color relief with shaded relief map</title>
		<link>http://dirkraffel.com/2011/07/05/best-way-to-merge-color-relief-with-shaded-relief-map/</link>
		<comments>http://dirkraffel.com/2011/07/05/best-way-to-merge-color-relief-with-shaded-relief-map/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 21:39:00 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[GIS]]></category>

		<guid isPermaLink="false">http://dirkraffel.com/?p=349</guid>
		<description><![CDATA[When creating a raster map featuring a shaded relief combined with elevation colors, then chances are that you are using the gdaldem tool to create both the hillshading (gdaldem hillshade) and the color relief map (gdaldem color-relief). But as soon as you have created both images, you might ask yourself how to combine both images [...]]]></description>
			<content:encoded><![CDATA[<p>When creating a raster map featuring a shaded relief combined with elevation colors, then chances are that you are using the <a href="http://www.gdal.org/gdaldem.html">gdaldem</a> tool to create both the hillshading (<code>gdaldem hillshade</code>) and the color relief map (<code>gdaldem color-relief</code>). But as soon as you have created both images, you might ask yourself how to combine both images into one. First, I want this to be reproducible in a script, so GIMP or Photoshop is not a viable option.</p>
<p>Let&#8217;s take a closer look at the results of some different methods I&#8217;ve tried out. The color relief and the hillshade relief images were created with the following commands:</p>
<pre class="brush: bash">
$ gdalwarp -te 29 39 31 41 SRTM30.tif clip.tif</code>
$ gdaldem color-relief clip.tif palette.cpt color.tif</code>
$ gdaldem hillshade clip.tif hills.tif -z 3 -s 111120</code>
</pre>
<div id="attachment_353" class="wp-caption alignleft" style="width: 250px"><a href="http://dirkraffel.com/blog/wp-content/uploads/2011/07/color.png"><img src="http://dirkraffel.com/blog/wp-content/uploads/2011/07/color.png" alt="" title="color" width="240" height="240" class="size-full wp-image-353" /></a><p class="wp-caption-text">Color relief</p></div>
<div id="attachment_355" class="wp-caption alignleft" style="width: 250px"><a href="http://dirkraffel.com/blog/wp-content/uploads/2011/07/hills.png"><img src="http://dirkraffel.com/blog/wp-content/uploads/2011/07/hills.png" alt="" title="hills" width="240" height="240" class="size-full wp-image-355" /></a><p class="wp-caption-text">Hillshade</p></div>
<p><br clear="all" />One option for combining these two images is the <a href="http://fwarmerdam.blogspot.com/2010/01/hsvmergepy.html">hsv_merge.py</a> script from Frank Warmerdam. This script merges the two images in a way where the Hue and Saturation come from the color bands, and the Value comes from the panchromatic band. </p>
<p>But as stated <a href="http://vterrain.org/Imagery/processing.html">here</a>, &#8220;[this approach] works ok, but usually turns vegetation from a deep forest green to a minty pistachio green. This is because vegetation is very reflective in the IR band, which the pan band covers.&#8221; Let&#8217;s take a look at the result of hsv_merge.py:</p>
<pre class="brush: bash">
$ ./hsv_merge.py color.tif hills.tif merged.tif
</pre>
<div id="attachment_368" class="wp-caption alignleft" style="width: 250px"><a href="http://dirkraffel.com/blog/wp-content/uploads/2011/07/merged1.png"><img src="http://dirkraffel.com/blog/wp-content/uploads/2011/07/merged1.png" alt="" title="merged" width="240" height="240" class="size-full wp-image-368" /></a><p class="wp-caption-text">Result of hsv_merge.py</p></div>
<p><br clear="all" />As you can see very clearly, the resulting image doesn&#8217;t match well with the original color relief in the lower green regions. I didn&#8217;t find this result satisfactory, so I looked into whether <a href="http://www.imagemagick.org">ImageMagick</a> can be of help here.</p>
<p>A very simple operation would be </p>
<pre class="brush: bash">
$ composite -blend 60 color.tif hills.tif output.tif
</pre>
<p>but the composite image looks, well, a bit gray (no surprise here):<br />
<div id="attachment_371" class="wp-caption alignleft" style="width: 250px"><a href="http://dirkraffel.com/blog/wp-content/uploads/2011/07/output1.png"><img src="http://dirkraffel.com/blog/wp-content/uploads/2011/07/output1.png" alt="" title="output1" width="240" height="240" class="size-full wp-image-371" /></a><p class="wp-caption-text">Simple blend operation</p></div></p>
<p><br clear="all" />A much better approach consists of two steps: adjusting the gamma level of the hillshade image so that the resulting gamma-corrected hillshade has the RGB value (128, 128, 128) in the plain areas, followed by a <a href="http://www.imagemagick.org/script/compose.php">lighting composition</a>. I&#8217;ve used the &#8220;overlay&#8221; method below, but you can also experiment with the other lighting methods available.</p>
<pre class="brush: bash">
$ convert -gamma .5 hills.tif hills_gamma.tif
$ convert color.tif hills_gamma.tif -compose Overlay -composite output.tif
</pre>
<div id="attachment_375" class="wp-caption alignleft" style="width: 250px"><a href="http://dirkraffel.com/blog/wp-content/uploads/2011/07/hills_gamma.png"><img src="http://dirkraffel.com/blog/wp-content/uploads/2011/07/hills_gamma.png" alt="" title="hills_gamma" width="240" height="240" class="size-full wp-image-375" /></a><p class="wp-caption-text">Gamma-corrected hillshade</p></div>
<div id="attachment_376" class="wp-caption alignleft" style="width: 250px"><a href="http://dirkraffel.com/blog/wp-content/uploads/2011/07/output.png"><img src="http://dirkraffel.com/blog/wp-content/uploads/2011/07/output.png" alt="" title="output" width="240" height="240" class="size-full wp-image-376" /></a><p class="wp-caption-text">Result</p></div>
<p><br clear="all" />Looks good doesn&#8217;t it? Note that the colors of the composite image match very well with the original color relief image.</p>
<p>Finally, note that applying any ImageMagick conversion leads to loosing the georeferencing in the TIFF image. To keep the georeferencing information, you can <a href="http://www.remotesensing.org/geotiff/listgeo.html">save</a> the GeoTIFF metadata to a file, and then <a href="http://www.remotesensing.org/geotiff/geotifcp.html">copy</a> the metadata into a new image:</p>
<pre class="brush: bash">
$ listgeo clip.tif > meta.txt
$ geotifcp -g meta.txt output.tif final.tif
</pre>
<p>After this, <code>final.tif</code> should be georeferenced (you can check this with <code>gdalinfo</code>).</p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2011/07/05/best-way-to-merge-color-relief-with-shaded-relief-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ metaprogramming</title>
		<link>http://dirkraffel.com/2010/03/26/cpp-metaprogramming/</link>
		<comments>http://dirkraffel.com/2010/03/26/cpp-metaprogramming/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 21:42:40 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://dirkraffel.com/?p=215</guid>
		<description><![CDATA[A completely useless but fun-to-write example for C++ template metaprogramming. Did you ever wanted to calculate the control digit of a UIC wagon number at compile-time? This serves just as an example that any computer algorithm can be implemented in some way in a template metaprogram (template metaprogramming is generally Turing-complete). #include &#60;iostream&#62; template &#60;long [...]]]></description>
			<content:encoded><![CDATA[<p>A completely useless but fun-to-write example for C++ template metaprogramming. Did you ever wanted to calculate the <a href="http://en.wikipedia.org/wiki/Coach_number#Calculation_of_the_control_digit">control digit of a UIC wagon number</a> at compile-time? This serves just as an example that any computer algorithm can be implemented in some way in a template metaprogram (template metaprogramming is generally Turing-complete).</p>
<pre class="brush: cpp">
#include &lt;iostream&gt;

template &lt;long long u, int m&gt;
struct S
{
    static long long const val = S&lt;u/10, m%2+1&gt;::val + ((u%10)*m)/10 + ((u%10)*m)%10;
};

template &lt;int m&gt;
struct S&lt;0, m&gt;
{
    static long long const val = 0;
};

template &lt;long long u&gt;
struct UIC
{
    static long long const val = u*10+(10-S&lt;u,2&gt;::val%10)%10;
};

int main()
{
    std::cout &lt;&lt; UIC&lt;21812471217LLU&gt;::val &lt;&lt; std::endl;
    return 0;
}
</pre>
<p>As one would expect, the output is <code>218124712173</code> <img src='http://dirkraffel.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2010/03/26/cpp-metaprogramming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C++ singleton with policies</title>
		<link>http://dirkraffel.com/2010/01/13/cpp-singleton-with-policies/</link>
		<comments>http://dirkraffel.com/2010/01/13/cpp-singleton-with-policies/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 11:34:46 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://dirkraffel.com/?p=178</guid>
		<description><![CDATA[The traditional Singleton pattern only supports a default constructor (one that takes no arguments), but recently I needed to create a singleton from a class which required an integer argument in its constructor. This can be solved quite elegantly with a policy-based design. Take a look at the following (non thread-safe!) implementation: #ifndef SINGLETON_HPP #define [...]]]></description>
			<content:encoded><![CDATA[<p>The traditional <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton pattern</a> only supports a default constructor (one that takes no arguments), but recently I needed to create a singleton from a class which required an integer argument in its constructor.</p>
<p>This can be solved quite elegantly with a <a href="http://en.wikipedia.org/wiki/Policy-based_design">policy-based design</a>. Take a look at the following (non thread-safe!) implementation:</p>
<pre class="brush: cpp">
#ifndef SINGLETON_HPP
#define SINGLETON_HPP

// Creation policies
template&lt;class T&gt; struct CreateWithIntParameter
{
    static T* Create()
    {
        return new T(m_intParameter);
    }
    static const int m_intParameter;
};

// Non-thread-safe singleton
template &lt;class T, template&lt;class&gt; class CreationPolicy&gt;
class Singleton
{
public:
    static T&amp; instance()
    {
        if (!m_instance)
        {
            m_instance = CreationPolicy&lt;T&gt;::Create();
        }
        return *m_instance;
    }
private:
    Singleton();
    Singleton(const Singleton&amp;);
    Singleton&amp; operator=(const Singleton&amp;);

    static T* m_instance;
};

template &lt;class T, template&lt;class&gt; class C&gt;
T* Singleton&lt;T, C&gt;::m_instance = 0;

#endif // SINGLETON_HPP
</pre>
<p>Here is a small example how to use it:</p>
<pre class="brush: cpp">
#include &quot;singleton.hpp&quot;
#include &lt;iostream&gt;

using namespace std;

class Foo
{
public:
    Foo(int a) : m_a(a)
    {
        cout &lt;&lt; &quot;Foo constructed&quot; &lt;&lt; endl;
    }
    void bar()
    {
        cout &lt;&lt; &quot;a = &quot; &lt;&lt; m_a &lt;&lt; endl;
    }
private:
    Foo();
    int m_a;
};

template&lt;&gt; const int CreateWithIntParameter&lt;Foo&gt;::m_intParameter = 5;

typedef Singleton&lt;Foo, CreateWithIntParameter&gt; FooSingleton;

int main()
{
    FooSingleton::instance().bar();
    FooSingleton::instance().bar();
    return 0;
}
</pre>
<p>The output looks like this:<br />
<code><br />
Foo constructed<br />
a = 5<br />
a = 5<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2010/01/13/cpp-singleton-with-policies/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ClearCase and text files with long lines of text</title>
		<link>http://dirkraffel.com/2010/01/08/clearcase-and-text-files-with-long-lines-of-text/</link>
		<comments>http://dirkraffel.com/2010/01/08/clearcase-and-text-files-with-long-lines-of-text/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 09:11:02 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dirkraffel.com/?p=168</guid>
		<description><![CDATA[Note 2 myself just in case I&#8217;ll stumble into this again: I&#8217;ve tried to add a javascript file (jquery-1.3.2.min.js) to clearcase, and got the following response: jquery-1.3.2.min.js is not a 'text file': it contains a line exceeding 8000 bytes. Use a different type manager (such as compressed file). Type manager "text_file_delta" failed create_version operation. Huh? [...]]]></description>
			<content:encoded><![CDATA[<p>Note 2 myself just in case I&#8217;ll stumble into this again:</p>
<p>I&#8217;ve tried to add a javascript file (jquery-1.3.2.min.js) to clearcase, and got the following response:<br />
<code><br />
jquery-1.3.2.min.js is not a 'text file': it contains a line exceeding 8000 bytes. Use a different type manager (such as compressed file).<br />
Type manager "text_file_delta" failed create_version operation.<br />
</code><br />
Huh? Anyway, this can be solved by</p>
<pre class="brush: bash">
$ cleartool chtype -nc compressed_file jquery-1.3.2.min.js
</pre>
<p><code><br />
Change version manager and reconstruct all version for "jquery-1.3.2.min.js"?   [no] y<br />
Changed type of element "jquery-1.3.2.min.js" to "compressed_file".<br />
</code><br />
Afterwards, the file can be checked in without problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2010/01/08/clearcase-and-text-files-with-long-lines-of-text/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A boost::statechart example</title>
		<link>http://dirkraffel.com/2009/12/26/boost-statechart-example/</link>
		<comments>http://dirkraffel.com/2009/12/26/boost-statechart-example/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 21:49:50 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://dirkraffel.com/blog/?p=46</guid>
		<description><![CDATA[How would you transform a statechart (David Harel statechart, or UML state diagram if you like) into executable C++ code? You can use one of the many free and commercial tools that are able to generate very efficient C or C++ code from statecharts, but you can also do so without needing such a tool: [...]]]></description>
			<content:encoded><![CDATA[<p>How would you transform a statechart (David Harel statechart, or UML state diagram if you like) into executable C++ code? You can use one of the many free and commercial tools that are able to generate very efficient C or C++ code from statecharts, but you can also do so without needing such a tool: you might also consider using the Boost statechart library.</p>
<p>For a simple example, consider the following scenario :<br />
<cite>Assume a controller has one push button switch wired to an input, and one lamp wired to an output. The first time the button is pressed the lamp must come on. The next time the button is pressed, the lamp must turn off. On the next press the lamp comes on, etc. etc. Don&#8217;t forget to allow for the button to be released before it is pressed again.</cite></p>
<p>Sounds easy, doesn&#8217;t it? However, often the required behavior is not so trivial (when we&#8217;d like to restore previous state, or when reactions depend on the active state in many orthogonal regions). In this case, I typically use a statechart design. IMO this method scales up very well to large and complicated systems.</p>
<p>A possible solution for our example looks like this: We have two orthogonal regions, one region with two states for button pressed/released and another region with light on/off.<br />
<img class="size-full wp-image-72" title="switch" src="http://dirkraffel.com/blog/wp-content/uploads/2009/12/switch.png" alt="The statechart" width="504" height="326" /></p>
<p>As with many of the Boost libraries, boost::statechart is header-only and uses templates quite heavily. In general, the <a href="http://www.boost.org/doc/libs/1_41_0/libs/statechart/doc/index.html">documentation</a> is quite good, so don&#8217;t be afraid to read it. There is also an excellent <a href="http://www.boost.org/doc/libs/1_41_0/libs/statechart/doc/tutorial.html">tutorial</a> for those just starting out, with plenty of examples.</p>
<p>So without further ado, here&#8217;s the source code that implements the statechart from above:</p>
<pre class="brush: cpp; smart-tabs: true">
#include &lt;boost/statechart/event.hpp&gt;
#include &lt;boost/statechart/state_machine.hpp&gt;
#include &lt;boost/statechart/simple_state.hpp&gt;
#include &lt;boost/statechart/state.hpp&gt;
#include &lt;boost/statechart/transition.hpp&gt;
#include &lt;boost/mpl/list.hpp&gt;
#include &lt;iostream&gt;

using namespace std;

namespace sc = boost::statechart;
namespace mpl = boost::mpl;

struct EvPressButton : sc::event&lt;EvPressButton&gt;
{
  EvPressButton()
  {
    cout &lt;&lt; "Button is pressed" &lt;&lt; endl;
  }
};

struct EvReleaseButton : sc::event&lt;EvReleaseButton&gt;
{
  EvReleaseButton()
  {
    cout &lt;&lt; "Button is released" &lt;&lt; endl;
  }
};

struct EvToggleLight : sc::event&lt;EvToggleLight&gt; {};

struct Active;
struct Switch : sc::state_machine&lt;Switch, Active&gt; {};

struct ButtonReleased;
struct ButtonPressed;
struct LightOff;
struct LightOn;

struct Active: sc::simple_state&lt;Active, Switch,mpl::list&lt;ButtonReleased, LightOff&gt; &gt; {};
struct ButtonPressed : sc::state&lt;ButtonPressed, Active::orthogonal&lt;0&gt; &gt;
{
  typedef sc::transition&lt;EvReleaseButton, ButtonReleased&gt; reactions;
  ButtonPressed(my_context ctx) : my_base(ctx)
  {
    post_event(EvToggleLight());
  }
};

struct ButtonReleased : sc::simple_state&lt;ButtonReleased, Active::orthogonal&lt;0&gt; &gt;
{
  typedef sc::transition&lt;EvPressButton, ButtonPressed&gt; reactions;
};

struct LightOff : sc::simple_state&lt;LightOff, Active::orthogonal&lt;1&gt; &gt;
{
  typedef sc::transition&lt;EvToggleLight, LightOn&gt; reactions;
  LightOff()
  {
    cout &lt;&lt; "Light is off" &lt;&lt; endl;
  }
};

struct LightOn : sc::simple_state&lt;LightOn, Active::orthogonal&lt;1&gt; &gt;
{
  typedef sc::transition&lt;EvToggleLight, LightOff&gt; reactions;
  LightOn()
  {
    cout &lt;&lt; "Light is on" &lt;&lt; endl;
  }
};

int main()
{
  Switch sw;
  sw.initiate();
  for (int i = 0; i &lt; 5; i++)
  {
    sw.process_event(EvPressButton());
    sw.process_event(EvReleaseButton());
  }
  return 0;
}
</pre>
<p>The output:<br />
<code><br />
Light is off<br />
Button is pressed<br />
Light is on<br />
Button is released<br />
Button is pressed<br />
Light is off<br />
Button is released<br />
Button is pressed<br />
Light is on<br />
Button is released<br />
Button is pressed<br />
Light is off<br />
Button is released<br />
Button is pressed<br />
Light is on<br />
Button is released<br />
</code><br />
Which looks about right, I think. <img src='http://dirkraffel.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2009/12/26/boost-statechart-example/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Developing shared libraries with Eclipse CDT</title>
		<link>http://dirkraffel.com/2008/06/27/developing-shared-libraries-with-eclipse-cdt/</link>
		<comments>http://dirkraffel.com/2008/06/27/developing-shared-libraries-with-eclipse-cdt/#comments</comments>
		<pubDate>Fri, 27 Jun 2008 10:01:53 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dirkraffel.wordpress.com/?p=43</guid>
		<description><![CDATA[Consider the following not so uncommon scenario: you have a shared library project in Eclipse and an executable project which uses the shared library. I found that you have to do some additional things for building, running and debugging the executable project in Eclipse (note that I&#8217;m doing this on Linux using CDT 4.0.3): Define [...]]]></description>
			<content:encoded><![CDATA[<p>Consider the following not so uncommon scenario: you have a shared library project in Eclipse and an executable project which uses the shared library.</p>
<p>I found that you have to do some additional things for building, running and debugging the executable project in Eclipse (note that I&#8217;m doing this on Linux using CDT 4.0.3):</p>
<p>Define your shared library&#8217;s project as a reference for your application. In order to do so open the project properties of the executable project, go to project references and select the shared library project (where in my case &#8220;shared&#8221; is also the name of the shared library).</p>
<p>In the project settings of your executable project, add the shared library to the linker settings, as shown in the following screenshot:</p>
<p><a href="http://dirkraffel.files.wordpress.com/2008/06/screenshot-properties-for-test.png"><img class="alignnone size-medium wp-image-44" src="http://dirkraffel.files.wordpress.com/2008/06/screenshot-properties-for-test.png?w=300" alt="" width="300" height="214" /></a></p>
<p>Bear in mind that the library search path must be adjusted every time when switching between Debug and Release versions.</p>
<p>In the project settings of your executable project, add the working directory of your shared library project to the compiler include path, as shown in this screenshot:</p>
<p><a href="http://dirkraffel.files.wordpress.com/2008/06/screenshot-properties-for-test-1.png"><img class="alignnone size-medium wp-image-45" src="http://dirkraffel.files.wordpress.com/2008/06/screenshot-properties-for-test-1.png?w=300" alt="" width="300" height="169" /></a></p>
<p>Now you should be able to compile your application, but in order to run it from within Eclipse, there&#8217;s a last step that needs to be done:</p>
<p>In the run dialog (top menu Run -&gt; Open Run Dialog), define the <tt>LD_LIBRARY_PATH</tt> variable as <tt>${workspace_loc}/shared/Debug/</tt>, as shown inthe following screenshot.</p>
<p><a href="http://dirkraffel.files.wordpress.com/2008/06/screenshot-edit-environment-variable.png"><img class="alignnone size-medium wp-image-46" src="http://dirkraffel.files.wordpress.com/2008/06/screenshot-edit-environment-variable.png?w=300" alt="" width="300" height="91" /></a></p>
<p>Again, this needs to be adjusted when switching between Debug and Release versions.</p>
<p>All this is very tedious stuff, so hopefully this will be a bit improved in the upcoming CDT releases.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2008/06/27/developing-shared-libraries-with-eclipse-cdt/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Debugging multiple processes with Eclipse CDT</title>
		<link>http://dirkraffel.com/2008/06/27/debugging-multiple-processes-with-eclipse-cdt/</link>
		<comments>http://dirkraffel.com/2008/06/27/debugging-multiple-processes-with-eclipse-cdt/#comments</comments>
		<pubDate>Fri, 27 Jun 2008 09:33:06 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dirkraffel.wordpress.com/?p=42</guid>
		<description><![CDATA[For debugging a child process on Linux, gdb has the ability to step into a child process after fork and exec. This behavior can be enabled with the follow-fork-mode child statement. Put the statement set follow-fork-mode child in the .gdbinit file, located in the project work directory. Now, setting some breakpoints in the code of [...]]]></description>
			<content:encoded><![CDATA[<p>For debugging a child process on Linux, gdb has the ability to step into a child process after fork and exec. This behavior can be enabled with the follow-fork-mode child statement.</p>
<p>Put the statement<br />
<code><br />
set follow-fork-mode child<br />
</code><br />
in the <tt>.gdbinit</tt> file, located in the project work directory.<br />
Now, setting some breakpoints in the code of the child process will cause gdb to halt execution.</p>
<p>Btw, I&#8217;ve looked for a corresponding GUI option in the debug dialog (CDT version 4.0.3), but I found none. So it seems that creating a <tt>.gdbinit</tt> file is currently the only solution for this.</p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2008/06/27/debugging-multiple-processes-with-eclipse-cdt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Valgrind on Mac OS X would be great</title>
		<link>http://dirkraffel.com/2008/06/27/valgrind-on-mac-os-x-would-be-great/</link>
		<comments>http://dirkraffel.com/2008/06/27/valgrind-on-mac-os-x-would-be-great/#comments</comments>
		<pubDate>Fri, 27 Jun 2008 09:19:52 +0000</pubDate>
		<dc:creator>Dirk Raffel</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dirkraffel.wordpress.com/?p=41</guid>
		<description><![CDATA[BTW, I just wanted to note that Valgrind is awesome when debugging executables on Linux, especially for finding memory leaks or uninitialized variables. Unfortunately, Valgrind currently only supports Linux. At least the porting plan states that enabling support for the x86/darwin platform is on the top priority list. I&#8217;ll keep my fingers crossed]]></description>
			<content:encoded><![CDATA[<p>BTW, I just wanted to note that <a href="http://www.valgrind.org">Valgrind</a> is awesome when debugging executables on Linux, especially for finding memory leaks or uninitialized variables.</p>
<p>Unfortunately, Valgrind currently only supports Linux. At least the <a href="http://valgrind.org/info/platforms.html">porting plan</a> states that enabling support for the x86/darwin platform is on the top priority list. I&#8217;ll keep my fingers crossed <img src='http://dirkraffel.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://dirkraffel.com/2008/06/27/valgrind-on-mac-os-x-would-be-great/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

