<?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>Tudor Barbu&#039;s professional blog &#187; tips and tricks</title>
	<atom:link href="http://blog.motane.lu/tag/tips-and-tricks/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.motane.lu</link>
	<description>Ramblings about software development</description>
	<lastBuildDate>Thu, 02 Feb 2012 17:38:27 +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>Multiple inheritance in PHP</title>
		<link>http://blog.motane.lu/2012/01/21/multiple-inheritance-in-php/</link>
		<comments>http://blog.motane.lu/2012/01/21/multiple-inheritance-in-php/#comments</comments>
		<pubDate>Sat, 21 Jan 2012 12:32:06 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[extreme php]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1878</guid>
		<description><![CDATA[I wrote yesterday an article introducing Cosmin&#8217;s blog. His most recent article is on multiple inheritance and how easy it would be to implement that into weakly typed like PHP. Just have a look at the article. Having learned OOP in Java, I am generally against multiple inheritance. I believe that if the answer is [...]]]></description>
			<content:encoded><![CDATA[<p>I wrote yesterday an article introducing Cosmin&#8217;s blog. His <a href="http://cosmi.nu/multiple-inheritance-suddenly-more-easy-in-php-than-in-c/45" title="Multiple inheritance suddleny more easy in PHP than in C" class="outgoing">most recent article</a> is on multiple inheritance and how easy it would be to implement that into weakly typed like PHP. Just have a look at the article.</p>
<p>Having learned OOP in Java, I am generally against multiple inheritance. I believe that if the answer is multiple inheritance, you&#8217;re asking the wrong question. But, for &#8220;academic&#8221; reasons, I tried to implement multiple inheritance in PHP. And I came up with the following abomination.</p>
<p>First, create a parent class from which all classes in need of multiple inheritance extend. The parent classes will be placed in the $_parents array as strings. When the main object is instantiated, the constructor creates objects from all the parent classes. And by using __call() I&#8217;m just going to redirect method calls on the main object to the first suitable parent object. I know it sounds complicated, so long story short, just read the code! I&#8217;m a developer, not a writer!</p>
<pre class="brush: php; title: ; notranslate">
/**
 * Abomination class implementing multiple inheritance via
 * __call magic method
 */
abstract class MultipleInheritance
{
    /**
     * List of parent classes
     *
     * @var array
     * @access protected
     */
    protected $_parents = array();    

    /**
     * List of parent objects - generated automatically
     *
     * @var array
     * @access private
     */
    private $_parentObjects = array();

    /**
     * Constructor (thank you captain Obvious)
     *
     * - init the parent objects
     *
     * @access public
     */
    public function __construct()
    {
        foreach ($this-&gt;_parents as $parentClass) {
            $this-&gt;_parentObjects []= new $parentClass();
        }
    }

    /**
     * __call magic method
     *
     * @param string $name
     * @param array $arguments
     * @access public
     * @return mixed
     */
    public function __call($name, array $arguments)
    {
        foreach ($this-&gt;_parentObjects as $object) {
            if (method_exists($object, $name)) {
                return call_user_func_array(array($object, $name), $arguments);
            }
        }

        throw new Exception('No such method: ' . $name);
    }
}
</pre>
<p>Now, some very sexist implementations of Mom and Dad classes:</p>
<pre class="brush: php; title: ; notranslate">
class Dad
{
    /**
     * Can parallel park
     *
     * @access public
     * @return void
     */
    public function park()
    {
        echo 'Look, I can parallel park' . PHP_EOL;
    }    

    /**
     * Can ground the kids
     *
     * @access public
     * @return void
     */
    public function ground()
    {
        echo 'Grounded by DAD' . PHP_EOL;
    }
}

class Mom
{
    protected $_parents = array('GrandMa');

    /**
     * Makes sandwiches
     *
     * @access public
     * @return void
     */
    public function makeSandwich()
    {
        echo 'Just making a sandwich' . PHP_EOL;
    }    

    /**
     * Can grounds the kids
     *
     * @access public
     * @return void
     */
    public function ground()
    {
        echo 'Grounded by MOM' . PHP_EOL;
    }
}
</pre>
<p>&#8230;and finally the child class:</p>
<pre class="brush: php; title: ; notranslate">
class Child extends MultipleInheritance
{
    protected $_parents = array('Dad', 'Mom');
}
</pre>
<p>Let&#8217;s try it out:</p>
<pre class="brush: php; title: ; notranslate">
$child = new Child();
$child-&gt;park();
$child-&gt;makeSandwich();
$child-&gt;ground();
</pre>
<p>And it works. And when two parent classes have the same method &#8211; ground() in this case &#8211; the method belonging to the first encountered class is executed. And voila, multiple inheritance in PHP. Well, sort of.</p>
<p>Now there&#8217;s a small problem with the <strong>instanceof</strong> operator. And by small problem I mean it doesn&#8217;t work and there&#8217;s no way to fix it. The following code</p>
<pre class="brush: php; title: ; notranslate">
if ($child instanceof Mom) {
    echo get_class($child) . ' class inherits from Mom' . PHP_EOL;
} else {
    echo get_class($child) . ' class does not inherit from Mom' . PHP_EOL;
}
</pre>
<p>will always go on the &#8220;else&#8221; branch, although in my application&#8217;s logic, the Child class extends from the Mom class. And since PHP doesn&#8217;t allow overloading the operators, there&#8217;s no clean way to do this. Of course, there&#8217;s a hacky way around it, by adding an isInstanceOf() method to the MultipleInheritance class:</p>
<pre class="brush: php; title: ; notranslate">
abstract class MultipleInheritance
{
    // ...

    /**
     * Check inheritance
     *
     * @param string $class
     * @access public
     * @return bool
     */
    public function isInstanceOf($class)
    {
        if (in_array($this-&gt;_parents, $class)) {
            return true;
        }

        foreach ($this-&gt;_parentObjects as $parent) {
            if ($parent instanceof MultipleInheritance) {
                if ($parent-&gt;isInstanceOf($class)) {
                    return true;
                }
            }
        }

        return false;
    }
}
</pre>
<p>&#8230;and using it to check inheritance:</p>
<pre class="brush: php; title: ; notranslate">
if ($child-&gt;isInstanceOf('Mom')) {
    echo get_class($child) . ' class inherits from Mom' . PHP_EOL;
} else {
    echo get_class($child) . ' class does not inherit from Mom' . PHP_EOL;
}
</pre>
<p>But the abomination is not completed yet. Because I used <a href="http://php.net/manual/en/function.method-exists.php" title="method_exists() in the PHP manual" class="outgoing">method_exists()</a> instead of <a href="http://php.net/manual/en/function.is-callable.php" title="is_callable() in the PHP manual" class="outgoing">is_callable()</a>, magic methods in the parent class will not be detected. To fix this, just change the code from:</p>
<pre class="brush: php; title: ; notranslate">
if (method_exists($object, $name)) {
    return call_user_func_array(array($object, $name), $arguments);
}
</pre>
<p>&#8230;to&#8230;</p>
<pre class="brush: php; title: ; notranslate">
if (is_callable($object, $name)) {
    return call_user_func_array(array($object, $name), $arguments);
}
</pre>
<p>&#8230;and it will work. At last, the abomination is ready. Doctor Frankenstein would be proud! Here is a gist with the entire example: <a href="https://gist.github.com/1652646" title="Go to https://gist.github.com/1652646" class="outgoing">https://gist.github.com/1652646</a>.</p>
<p>PS: DO NOT USE MULTIPLE INHERITANCE IN REAL LIFE APPLICATIONS!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2012/01/21/multiple-inheritance-in-php/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Forward POST data</title>
		<link>http://blog.motane.lu/2011/01/25/forward-post-data/</link>
		<comments>http://blog.motane.lu/2011/01/25/forward-post-data/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 16:49:31 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1509</guid>
		<description><![CDATA[I was looking today for a way to gracefully forward a POST request from one page to another in PHP. By &#8220;forwarding the request&#8221; I mean redirecting the user to another page on a different domain with all the POST data intact. I want to stress on the definition, because most people understand &#8220;use cURL [...]]]></description>
			<content:encoded><![CDATA[<p>I was looking today for a way to gracefully forward a POST request from one page to another in PHP. By &#8220;forwarding the request&#8221; I mean redirecting the user to another page <em>on a different domain</em> with all the POST data intact. I want to stress on the definition, because most people understand &#8220;use cURL to create a POST request from PHP&#8221;. Being on a different domain, it kind of rules out cookies and sessions.</p>
<p>The proper way to do it is by issuing a <em><strong>HTTP 307 &#8211; Temporary redirect</strong></em> header &#8211; which will instruct the browser to resend the data to the new URI, indicated by the <em><strong>Location</strong></em> field of the response.</p>
<pre class="brush: php; title: ; notranslate">
header('HTTP/1.1 307 Temporary Redirect');
header('Location: new-location.php');
</pre>
<p>Just for the record, in pre-HTTP 1.1 browsers the POST data gets converted to GET, but if your users don&#8217;t use computers from the 90s, this won&#8217;t be a problem. And it works like a charm. In Chrome and Internet Explorer.  </p>
<p>In Firefox and Opera, the browser will pop-up a dialog, informing the user that the data is being redirected to another page and asking the user&#8217;s permission to continue. Which is an extremely stupid standard behavior. Yes, it&#8217;s in the standard! </p>
<blockquote><p>
If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
</p></blockquote>
<p>&#8230;straight from the HTTP&#8217;s status codes bible, <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html" title="RCF 2616" class="outgoing">RFC 2616</a>. Why do I say it&#8217;s a stupid specification? Because it is! It makes no sense to pop-up a dialog that might confuse the user when the data was already sent. For example, if I&#8217;m a malevolent webmaster, I already have the user&#8217;s data, so at this point displaying the dialog box is useless. I can save the data in my database and have a cronjob connect to the new page or do whatever I please with the POSTed information. However, if the redirect is legitimate, displaying the message box might confuse the user and have him cancel the request, which might break the application&#8217;s logic.</p>
<p>Great work guys, I&#8217;m moments away from converting the POST data into GET and send it in the URL&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2011/01/25/forward-post-data/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>PHP switch</title>
		<link>http://blog.motane.lu/2010/08/31/php-switch/</link>
		<comments>http://blog.motane.lu/2010/08/31/php-switch/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 09:10:24 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[strange stuff]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1424</guid>
		<description><![CDATA[Over the years, I&#8217;ve encountered a lot of strange things in PHP, but this one is off the scale: What do you think that the code above will print? Well&#8230;I&#8217;ll spare you the hassle and give you the answer: This weird behavior originates in the fact that PHP uses the equality operator (==) instead of [...]]]></description>
			<content:encoded><![CDATA[<p>Over the years, I&#8217;ve encountered a lot of strange things in PHP, but this one is off the scale:</p>
<pre class="brush: php; title: ; notranslate">
$value = 'zero';

switch ($value) {
    case 0:
        echo 'value is zero';
        break;
    default:
        echo 'value is not zero';
        break;
}
echo PHP_EOL;
</pre>
<p>What do you think that the code above will print? Well&#8230;I&#8217;ll spare you the hassle and give you the answer:</p>
<pre class="brush: bash; title: ; notranslate">
% php test.php
value is zero
</pre>
<p>This weird behavior originates in the fact that PHP uses the equality operator (==) instead of the identity (===) one when evaluating expressions inside a switch statement. It&#8217;s basically the same as:</p>
<pre class="brush: php; title: ; notranslate">
if ('foo' == 0) {
    echo 'bar';
}
</pre>
<p>&#8230;which also yields unexpected results. I hate this type of casting!!!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/08/31/php-switch/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Import emails for Evolution in Gmail</title>
		<link>http://blog.motane.lu/2010/04/14/import-emails-for-evolution-in-gmail/</link>
		<comments>http://blog.motane.lu/2010/04/14/import-emails-for-evolution-in-gmail/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 15:08:10 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[google apps]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1340</guid>
		<description><![CDATA[Several days ago, I decided to start using Google Apps for my email. I&#8217;m not a Google fanboy, but in some areas they&#8217;re the best. And Gmail is one of those areas. To have virtually unlimited storage space and access to your emails is *very* important. And I also love the way Google groups emails [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.google.com/apps/intl/en/group/index.html" class="outgoing" title="Google Apps Standard Edition"><img src="http://blog.motane.lu/wp-content/uploads/2010/04/google_apps.jpg" alt="Google Apps logo" title="google_apps" width="304" height="300" class="alignleft size-full wp-image-1342" /></a>Several days ago, I decided to start using <a href="http://www.google.com/apps/intl/en/group/index.html" class="outgoing" title="Google Apps Standard Edition">Google Apps</a> for my email. I&#8217;m not a Google fanboy, but in some areas they&#8217;re the best. And Gmail is one of those areas. To have virtually unlimited storage space and access to your emails is *very* important. And I also love the way Google groups emails into conversations. The process was painless, just some minor DNS modifications, filling some forms on Google&#8217;s site and that&#8217;s it. </p>
<p>A problem arose when I wanted to import my existing emails from Evolution to Gmail. Although Google provides <a href="http://www.google.com/support/a/bin/answer.py?hl=en&#038;answer=57920" title="Email migration options" class="outgoing">extensive documentation and even a migration API</a>, I was unable to find something tailored for Evolution. After some Googling and asking around, I decided to use the &#8211; kind of lame, but nevertheless, effective &#8211; IMAP approach.<br />
It&#8217;s quite simple:</p>
<ul>
<li>enable IMAP support in your Gmail CP</li>
<li>add the newly created IMAP account to your Evolution</li>
<li>in Evolution, copy all the emails from your regular account to your Gmail one</li>
<li>wait for the IMAP account to synchronize with the server (it might take a while, depending on the number of emails/attachments)</li>
</ul>
<p>All your current folders will be imported as labels in Gmail. For some unknown reason, it was unable to group all conversations, although I uploaded the &#8220;Sent&#8221; folder. Anyways, if you have a better idea, feel free to post a comment.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/04/14/import-emails-for-evolution-in-gmail/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Iterate thru dates in Python</title>
		<link>http://blog.motane.lu/2010/02/19/iterate-thru-dates-in-python/</link>
		<comments>http://blog.motane.lu/2010/02/19/iterate-thru-dates-in-python/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 14:06:14 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1317</guid>
		<description><![CDATA[Few days ago I was working on some python scripts that needed to iterate back and forth through calendar dates. Working with dates in python is pretty easy, due to its datetime package. Basically is like this: This works, but is somewhat lame and not quite reusable. The most &#8220;python-ish&#8221; way to do it is [...]]]></description>
			<content:encoded><![CDATA[<p>Few days ago I was working on some python scripts that needed to iterate back and forth through calendar dates. Working with dates in python is pretty easy, due to its <a href="http://docs.python.org/library/datetime.html" title="datetime package entry in the manual" class="outgoing">datetime</a> package. </p>
<p>Basically is like this:</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python

import datetime

start_date = datetime.date( year = 2010, month = 2, day = 1 )
end_date = datetime.date( year = 2010, month = 1, day = 1 )

list = []

if start_date &lt;= end_date:
    for n in range( ( end_date - start_date ).days + 1 ):
        list.append( start_date + datetime.timedelta( n ) )
else:
    for n in range( ( start_date - end_date ).days + 1 ):
        list.append( start_date - datetime.timedelta( n ) )

for d in list:
    print d
</pre>
<p>This works, but is somewhat lame and not quite reusable. The most &#8220;python-ish&#8221; way to do it is to create a generator function that will <a href="http://docs.python.org/reference/simple_stmts.html#the-yield-statement" title="Generator functions in python's docs" class="outgoing">yield</a> the current date and can be used in a <em>for</em> loop. So I did it:</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python
import datetime

def daterange( start_date, end_date ):
    if start_date &lt;= end_date:
        for n in range( ( end_date - start_date ).days + 1 ):
            yield start_date + datetime.timedelta( n )
    else:
        for n in range( ( start_date - end_date ).days + 1 ):
            yield start_date - datetime.timedelta( n )

start = datetime.date( year = 2010, month = 2, day = 1 )
end = datetime.date( year = 2010, month = 1, day = 1 )

for date in daterange( start, end ):
    print date
</pre>
<p>Much more elegant <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/02/19/iterate-thru-dates-in-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Insert at the beginning of an array in PHP</title>
		<link>http://blog.motane.lu/2010/02/16/insert-at-the-beginning-of-an-array-in-php/</link>
		<comments>http://blog.motane.lu/2010/02/16/insert-at-the-beginning-of-an-array-in-php/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 22:29:48 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1314</guid>
		<description><![CDATA[Last week, while programming, I needed to insert an array at the beginning of another. So, since basically I was just merging 2 arrays, I tried to do it like this: But it didn&#8217;t work. It was displaying something like: Not a good result, because the arrays&#8217; keys were actually primary keys used by the [...]]]></description>
			<content:encoded><![CDATA[<p>Last week, while programming, I needed to insert an array at the beginning of another. So, since basically I was just merging 2 arrays, I tried to do it like this: </p>
<pre class="brush: php; title: ; notranslate">
$originalArray = array(
    1 =&gt; 'First item',
    4 =&gt; 'Forth item',
    5 =&gt; 'Fift item',
    10 =&gt; 'Tenth item', // and so on
);

$insertAtBegining = array(
    0 =&gt; 'None',
);

$newArray = array_merge($insertAtBegining, $originalArray);
</pre>
<p>But it didn&#8217;t work. <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' />  It was displaying something like:</p>
<pre class="brush: php; title: ; notranslate">
Array
(
    [0] =&gt; None
    [1] =&gt; First item
    [2] =&gt; Forth item
    [3] =&gt; Fifth item
    [4] =&gt; Tenth item
)
</pre>
<p>Not a good result, because the arrays&#8217; keys were actually primary keys used by the RDBMS so it was very important for me to keep the original keys. I didn&#8217;t want to take the lame approach and do a foreach loop:</p>
<pre class="brush: php; title: ; notranslate">
$newArray = $insertAtBegining;
foreach($originalArray as $key =&gt; $value) {
    $newArray[$key] = $value;
}
</pre>
<p>&#8230;because it was too obvious, so I did something less obvious, and much more complicated:</p>
<pre class="brush: php; title: ; notranslate">
$newArray = array_combine(
    array_merge(array_keys($insertAtBegining), array_keys($originalArray)),
    array_merge(array_values($insertAtBegining), array_values($originalArray))
);
</pre>
<p>But in the end, Chris, one of my colleagues who also has a blog at <a href="http://www.segmentationfault.es/" title="Error: Segmentation fault (in Spanish)" class="outgoing">SegmentationFault.es</a> pointed out the most simple and elegant solution:</p>
<pre class="brush: php; title: ; notranslate">
$newArray = $insertAtBegining + $originalArray;
</pre>
<p>This reminds me of the saying &#8220;Keep It Simple Stupid&#8221; <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />   Which Chris uses as a wallpaper&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/02/16/insert-at-the-beginning-of-an-array-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>My Vim configuration</title>
		<link>http://blog.motane.lu/2010/01/26/my-vim-configuration/</link>
		<comments>http://blog.motane.lu/2010/01/26/my-vim-configuration/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 21:55:28 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[efficiency]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[vim]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1293</guid>
		<description><![CDATA[Vim is the editor of the Gods. The Elder Gods. It&#8217;s by far the best text editor I&#8217;ve ever encountered. Although I&#8217;m not a &#8220;vim purist&#8221; (no hjkl ), I&#8217;m fascinated with its power. And there are always new things one can learn about it. It never gets old. For instance, today the head of [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.motane.lu/wp-content/uploads/2010/01/vim-editor_logo-150x150.png" alt="" title="vim-editor_logo" width="150" height="150" class="alignleft size-thumbnail wp-image-1294" />Vim is the editor of the Gods. The Elder Gods. It&#8217;s by far the best text editor I&#8217;ve ever encountered. Although I&#8217;m not a &#8220;vim purist&#8221; (no hjkl <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  ), I&#8217;m fascinated with its power. And there are always new things one can learn about it. It never gets old.</p>
<p>For instance, today the head of my company&#8217;s IT department showed me the following cool trick: if you have an XML file loaded in a buffer and you want to have it properly indented, you just hit Escape in your Vim editor and type</p>
<pre class="brush: plain; title: ; notranslate">
:% !xmllint --format %
</pre>
<p>&#8230; and&#8230;Magic!</p>
<p>Anyway, lately I&#8217;ve spent some time puting together a list of very useful plugins for PHP/Zend Framework and python/django development in order to speed things up and become more productive. My (g)Vim configuration currently uses: </p>
<ul>
<li><a href="http://robrobbins.info/?page_id=2" title="Vilight colorscheme">Vilight colorscheme</a> by Rob Robbins</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=2540" title="snipMate">snipMate</a> by Michael Sanders</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=1658" title="NERD_Tree">NERD_Tree</a> by Martin Grenfell</li>
<li><a href="http://github.com/robhudson/snipmate_for_django" title="django snippets">django snippets</a> by Rob Hudson</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=1879" title="AutoComplPop">AutoComplPop</a> by Takeshi Nishida</li>
</ul>
<p>And a custom gvimrc file. If you want to give it a try, check out my GitHub repository at <a href="http://github.com/motanelu/GVim-configuration" title="Repository with my Gvim configuration">http://github.com/motanelu/GVim-configuration</a>. Installation is very simple, just follow the instructions below (PS: I&#8217;m using GVim. If you&#8217;re using Vim replace <em>gvimrc</em> with <em>vimrc</em>):</p>
<pre class="brush: plain; title: ; notranslate">
cd ~/
mv .vim .vim.bak
mv .gvimrc .gvimrc.bak
git clone git://github.com/motanelu/GVim-configuration.git
mv GVim-configuration .vim
ln -s ~/.vim/gvimrc ~/.gvimrc
</pre>
<p>Post a comment and tell me if you find it useful. If you&#8217;re a Zend Framework user, have a look over the <a href="http://github.com/motanelu/GVim-configuration/blob/master/snippets/zf.snippets" title="Zend Framework snippets">snippets</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/01/26/my-vim-configuration/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Changing the time zone in Ubuntu</title>
		<link>http://blog.motane.lu/2010/01/04/changing-the-time-zone-in-ubuntu/</link>
		<comments>http://blog.motane.lu/2010/01/04/changing-the-time-zone-in-ubuntu/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 18:55:22 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[tips and tricks]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1279</guid>
		<description><![CDATA[This one is from the &#8220;d&#8217;oh&#8221; category. As recently I&#8217;ve moved to Barcelona and since Bucharest and Barcelona are in different time zones, I wanted to set my system&#8217;s time an hour back, in order to display the correct time. I went the easy way: right clicked on the clock in the upper right, selected [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.motane.lu/wp-content/uploads/2008/12/ubuntulogoresized-150x150.png" alt="Ubuntu" title="Ubuntu" width="150" height="150" class="size-thumbnail alignleft" /> This one is from the &#8220;<a href="http://images.google.com/images?q=d%27oh" title="Search on Google Images for d'oh" class="outgoing">d&#8217;oh</a>&#8221; category. As recently I&#8217;ve moved to Barcelona and since Bucharest and Barcelona are in different time zones, I wanted to set my system&#8217;s time an hour back, in order to display the correct time. </p>
<p>I went the easy way: right clicked on the clock in the upper right, selected &#8220;Adjust date and time&#8221; and made the modifications. After a few minutes the clock was showing Bucharest&#8217;s time and my changes were overwritten. I though I must have imagined setting the clock right in the first place &#8211; since I &#8220;tasted&#8221; <a href="http://en.wikipedia.org/wiki/Moritz_(beer)" title="Wikipedia entry for Moritz beer" class="outgoing">Moritz</a> thoroughly &#8211; and did it again. </p>
<p>I&#8217;ve ignored the clock for a while and, later on, when I looked at it, it was displaying Bucharest&#8217;s time again <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>D&#8217;oh! Ubuntu queries it&#8217;s time servers from time to time and sets the hour according to the information retrieved from these servers. And since my timezone was still set to Europe/Bucharest, on each update my system was receiving the time for that area. I&#8217;ve changed the timezone accordingly and everything started working. Magic! </p>
<p>To change the timezone of on you Ubuntu system go to System > Administration > Time and date. Or, if you&#8217;re a console freak, just punch in:</p>
<pre class="brush: bash; title: ; notranslate">
sudo dpkg-reconfigure tzdata
</pre>
<p>in order to set the correct time zone.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2010/01/04/changing-the-time-zone-in-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Django configuration file</title>
		<link>http://blog.motane.lu/2009/12/28/django-configuration-file/</link>
		<comments>http://blog.motane.lu/2009/12/28/django-configuration-file/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 11:01:47 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=1245</guid>
		<description><![CDATA[I&#8217;ve been using Django for quite some time now and I kind of like it. It provides a fast &#8211; really fast &#8211; and clean way of doing things. When I first started with Django, I&#8217;ve used it mainly for simpler projects and kept the larger, more complicated ones on Zend Framework. That&#8217;s because I [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.motane.lu/wp-content/uploads/2009/07/django-logo-negative.png" alt="django web framework" title="django web framework" width="200" height="91" class="alignleft size-full wp-image-882" />I&#8217;ve been using <a href="http://www.djangoproject.com/" title="Django's project homepage" class="outgoing">Django</a> for quite some time now and I kind of like it. It provides a fast &#8211; really fast &#8211; and clean way of doing things. When I first started with Django, I&#8217;ve used it mainly for simpler projects and kept the larger, more complicated ones on <a href="http://framework.zend.com" title="Zend Framework's page">Zend Framework</a>. That&#8217;s because I feel much more comfortable with PHP and Zend Framework rather than python and Django. </p>
<p>But, lately, I&#8217;ve used django for more ambitious projects and some obvious flaws began to annoy me. The first thing &#8211; the one this entry&#8217;s about &#8211; is the configuration file. Django comes with a <a href="http://docs.djangoproject.com/en/dev/topics/settings/" title="Django's manual entry on settings.py" class="outgoing">settings.py</a> file in which all the settings are being held, without any regard to their purpose. </p>
<p>Environment settings like database connection strings, file system paths and debuging are mixed together with application settings like what middleware classes are used, context processors and so on. So I&#8217;ve decided to split the configuration file in two, like in the following example:</p>
<h2><span>local.py</span></h2>
<p>This file holds the host related configuration and each instance of the application should have its own local.py file. One for development, one for testing, one for staging, one for production and so on. This file should not be included in the source control repository, so add a svn/git/whatever ignore on it.</p>
<pre class="brush: python; title: ; notranslate">
# debug settings
DEBUG = True
TEMPLATE_DEBUG = DEBUG

# database configuration
DATABASE_ENGINE = ''
DATABASE_NAME = ''
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''

# media root ex: /var/www/my-project/media
MEDIA_ROOT = ''

# media url ex: media.my-project.tld
MEDIA_URL = ''

# admin media url ex: /media
ADMIN_MEDIA_PREFIX = '/media/'

# application's secret key
SECRET_KEY = 'mY-S3Cr3t-K3y-m|_|st-b3-un1QuE-4nD-h4rD-t0-GueSs'
</pre>
<h2><span>settings.py</span></h2>
<p>This file holds the application related configurations and should be included in the version control system.</p>
<pre class="brush: python; title: ; notranslate">
import os

# root directory for the project
ROOT_DIR = os.path.realpath( os.path.dirname( __file__ ) )

ADMINS = (
	( 'root', 'root@project.tld' ),
)

# import all the local settings
from local import *

MANAGERS = ADMINS
TIME_ZONE = 'Europe/Bucharest'

LANGUAGE_CODE = 'en-us'

SITE_ID = 1

USE_I18N = True

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.cache.FetchFromCacheMiddleware',
)

ROOT_URLCONF = 'my-project.urls'

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
)

# template directories
TEMPLATE_DIRS = (
    os.path.join( ROOT_DIR, 'templates' ),
    os.path.join( ROOT_DIR, 'other', 'template', 'path' ),
)

# django debug toolbar configuration
INTERNAL_IPS = ( '127.0.0.1' )
if DEBUG:
    MIDDLEWARE_CLASSES += 'debug_toolbar.middleware.DebugToolbarMiddleware',
    INSTALLED_APPS += 'debug_toolbar',
</pre>
<p>The last bit is because I usually use in development the incredibly useful Django <a href="http://github.com/robhudson/django-debug-toolbar" title="Django debug_toolbar on Github" class="outgoing">debug_toolbar</a>, and of course, I want it turned off on the live environment. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/12/28/django-configuration-file/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Backslash hell</title>
		<link>http://blog.motane.lu/2009/11/26/backslash-hell/</link>
		<comments>http://blog.motane.lu/2009/11/26/backslash-hell/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 10:28:28 +0000</pubDate>
		<dc:creator>Tudor</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[regular expressions]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tips and tricks]]></category>

		<guid isPermaLink="false">http://blog.motane.lu/?p=365</guid>
		<description><![CDATA[How do you write a regular expression that will match \\test &#8211; two backslashes followed by some text in PHP? Well, obviously you&#8217;ll try something like this: &#8230;but it won&#8217;t work. Furthermore, it will yield an error saying something like: Compilation failed: unmatched parentheses at offset &#8230; And it makes sense, since the backslash has [...]]]></description>
			<content:encoded><![CDATA[<p>How do you write a regular expression that will match <strong>\\test</strong> &#8211; two backslashes followed by some text in PHP? Well, obviously you&#8217;ll try something like this:</p>
<pre class="brush: php; title: ; notranslate">
echo preg_match('/^\\([a-z]+)/', $word) ? 'match' : 'no match';
</pre>
<p>&#8230;but it won&#8217;t work. Furthermore, it will yield an error saying something like:</p>
<blockquote><p>Compilation failed: unmatched parentheses at offset &#8230;</p></blockquote>
<p>And it makes sense, since the backslash has a special meaning, as it&#8217;s the escape character, to give it a literal meaning you have to escape it. Like such:</p>
<pre class="brush: php; title: ; notranslate">
echo preg_match('/^\\\\([a-z]+)/', $word) ? 'match' : 'no match';
</pre>
<p>&#8230;each of the two backslashes is escaped by another backslash placed in front of it. But this also doesn&#8217;t work <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  The correct way to do it is:</p>
<pre class="brush: php; title: ; notranslate">
echo preg_match('/^\\\\\\\\([a-z]+)/', $word) ? 'match' : 'no match';
</pre>
<p>Yeap. That&#8217;s right! With 8 backslashes. For each backslash you wanted matched, you need to add 4 in the regular expression. That&#8217;s because the backslash is considered to be an escape character by both PHP&#8217;s parser and its regexp engine. So, if you type a backslash in PHP, it&#8217;s considered and escape character by PHP&#8217;s parser. </p>
<p>If you write two backslashes in PHP, this construct will be interpreted as a literal backslash by PHP&#8217;s paser and sent to the regexp engine as an escape character. That&#8217;s right: &#8216;\\&#8217; in PHP means a &#8216;\&#8217; for the regexp engine. So, in order to pass a literal backslash to the regexp engine, you need to add 4 backslashes in PHP.</p>
<p>This is what I call backslash hell <img src='http://blog.motane.lu/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.motane.lu/2009/11/26/backslash-hell/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

