<?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>mFabrik - web and mobile development &#187; solution</title>
	<atom:link href="http://blog.mfabrik.com/category/solution/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.mfabrik.com</link>
	<description>Freedom delivered.</description>
	<lastBuildDate>Thu, 02 Sep 2010 13:25:54 +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>MooTools setOptions() nullifies object references</title>
		<link>http://blog.mfabrik.com/2008/08/19/mootools-setoptions-nullifies-object-references/</link>
		<comments>http://blog.mfabrik.com/2008/08/19/mootools-setoptions-nullifies-object-references/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 00:21:08 +0000</pubDate>
		<dc:creator>Tuukka Mustonen</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mootools]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[solution]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[addressing]]></category>
		<category><![CDATA[merge]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[problem]]></category>
		<category><![CDATA[reference]]></category>
		<category><![CDATA[setOptions]]></category>
		<category><![CDATA[ui]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://blog.redinnovation.com/?p=64</guid>
		<description><![CDATA[I bumped up into a problem where the object references where resolved as object copies when I passed them to class instances. That might sound easy to resolve, but unfortunately I was already deep in code and it was difficult to see this. Therefore, here&#8217;s a little explanation for those who are facing the same [...]]]></description>
			<content:encoded><![CDATA[<p>I bumped up into a problem where the object references where resolved as object copies when I passed them to class instances. That might sound easy to resolve, but unfortunately I was already deep in code and it was difficult to see this. Therefore, here&#8217;s a little explanation for those who are facing the same frustrating issue.</p>
<p>Say, you have variable &#8216;a&#8217; and you want to pass it to a MooTools class B instance during creation. In the easiest case you&#8217;d use new B({ myReference: a}) and trust on MooTools&#8217; Class.setOptions() to minify the need of code lines. This is what you should do&#8230; well at least that&#8217;s what I did and in this case it was a mistake.</p>
<p>It turns out that Class.setOptions() merges it&#8217;s arguments to this.options and then takes copy of them via $merge(). That means that any variable references you pass to setOptions() will get copied to this.options and.. well, that&#8217;s it. See lines 1170-1173 in uncompressed version of MooTools 1.2:</p>
<pre>var Options = new Class({
    setOptions: function(){
        this.options = $merge.run([this.options].extend(arguments));</pre>
<p>That effectively nullifies the benefits of Class.setOptions() if you want to pass in variable references..</p>
<p>Here&#8217;s a longer example to clarify (use Firebug):</p>
<pre>  // The most basic MooTools class that implements options
  // ref is a variable meant for pointing at given object
  // (won't do that, however)
  var B = new Class({
    Implements: Options,
    options: {
      ref: null
    },
    initialize: function(options) {
      this.setOptions(options);
    }
  });

  // Ok let's create an instance that we can pass to B
  // It's similar with all sorts of variables
  var A = new Class({
    initialize: function() {
      this.somevar = 'untouched';
    }
  });
  var a = new A();

  // Create an instance of B and give it somevar as reference
  var b = new B({ ref: a });

  // prints out "untouched" as should
  console.log(b.options.ref.somevar);

  // Let's change the variable (direct access, bad)
  a.somevar = "changed";

  // b's reference should still point to a, right?
  // In that case the following should print "changed",
  // but because our reference object was copied instead
  // of retaining reference to it, we just get "untouched"
  console.log(b.options.ref.somevar);</pre>
<p>I don&#8217;t know why MooTools wants to make a copy of arguments in setOptions() &#8211; propably for performance reasons.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mfabrik.com/2008/08/19/mootools-setoptions-nullifies-object-references/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Relativity of time &#8211; shortcomings in Python datetime, and workaround</title>
		<link>http://blog.mfabrik.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/</link>
		<comments>http://blog.mfabrik.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 12:39:10 +0000</pubDate>
		<dc:creator>ztane</dc:creator>
				<category><![CDATA[python]]></category>
		<category><![CDATA[solution]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[i18n]]></category>
		<category><![CDATA[internationalization]]></category>
		<category><![CDATA[localization]]></category>
		<category><![CDATA[mxdatetime]]></category>
		<category><![CDATA[pytz]]></category>
		<category><![CDATA[timedelta]]></category>
		<category><![CDATA[timezone]]></category>
		<category><![CDATA[timezone support]]></category>
		<category><![CDATA[utc]]></category>
		<category><![CDATA[zope]]></category>

		<guid isPermaLink="false">http://blog.redinnovation.com/?p=47</guid>
		<description><![CDATA[Recently I found out that the standard library support for date and time calculations in Python is not quite as able as I needed. It turned out that the superficial leanness and simplicity of Python&#8217;s datetime module bit hard back sooner than you expected. Unfortunately, looking for replacements, I found out that the existing replacement [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I found out that the standard library support for date and time calculations in Python is not quite as able as I needed. It turned out that the superficial leanness and simplicity of Python&#8217;s datetime module bit hard back sooner than you expected. Unfortunately, looking for replacements, I found out that the existing replacement modules have some issues on their own. This blog entry highlights various problems with the current Python datetime implementation. A partial solution will be offered, too.</p>
<h1>Basics of time zones</h1>
<p>Time zones are a relatively new invention in the long history of measuring time. During most of the 19th century pretty much each European town had its own definition of local time. It was not until 1880 that Greenwich Mean Time was officially made the standard time in the Great Britain; much of the remaining world had adopted the idea by the 1920s. Today, all countries in the world use standard time zones, though not every one is using full-hour offsets to the GMT as it was originally conceived.</p>
<p>The concept of summer time (daylight saving time in AmE) complicates things further: for example in European Union the member states will switch to summer time on the last Sunday of March at 01:00 GMT exact. The summer time lasts until the last Sunday of October, 01:00 GMT. In Finland, this means that this year on 30th March the official time stepped from <strong>02:59:59 EET to 04:00:00 EEST </strong><code class="literal">in an instant</code>. Likewise, on 26th October this year, the summer time clocks will tick up to <strong>03:59:59 EEST</strong>, and on the<strong> </strong>next second the local time will be<strong> </strong><strong>03:00:00 EET</strong>; and almost a hour later, <strong>03:59:59 EET.</strong> Thus, the number of seconds between <strong>02:59:59</strong> and <strong>04:00:00</strong> on a single day might be 1, 3601, or 7201; the difference between 02:59:59 and 03:00:01 might likewise be 2 or 3602 seconds&#8230; or even undefined.</p>
<p>To alleviate obvious confusions and misunderstandings, a reference time scale can be used for calculations that concern different time zones. The obvious choice is Coordinated Universal Time (UTC) that replaced Greenwich Mean Time as the standard reference time scale for civilian applications in 1972. During the Internet era UTC has become increasingly important.</p>
<h1>Time zones in Python &#8211; welcome to hell</h1>
<p>Suppose you have a shared web calendar application that is used by people all over the world. Each user wants to view the calendar in their respective local time, and you wish to use UTC on the server. The server has been set up with Europe/Helsinki as the local timezone. And you wish to use the facilities provided by the Python standard library modules. Simple date arithmetic would be needed &#8211; what could possibly go wrong? You will soon find out that it is not at all simple. Actually it is annoyingly complicated:</p>
<pre>&gt;&gt;&gt; from datetime import datetime
&gt;&gt;&gt; dt = datetime.now()
&gt;&gt;&gt; dt
datetime.datetime(2008, 6, 19, 14, 51, 41, 296552)
&gt;&gt;&gt; # ok, it prints the local time. Let's try to
&gt;&gt;&gt; # convert it to UTC time...
&gt;&gt;&gt; dt.utctimetuple()
(2008, 6, 19, 14, 51, 41, 3, 171, 0)
&gt;&gt;&gt; # wait, ahem... 14:51:41... that can't be right...
&gt;&gt;&gt; # the docs say: utctimetuple(...)
&gt;&gt;&gt; #     Return UTC time tuple, compatible with time.localtime().
&gt;&gt;&gt; #
&gt;&gt;&gt; # ok.. so UTC time tuple, compatible with localtime...
&gt;&gt;&gt; # WTF?? my local time zone is not UTC... strangely enough
&gt;&gt;&gt; # the last field in the tuple, "is_dst", is 0, or false...
&gt;&gt;&gt;&gt;# I thought June was in summer...
&gt;&gt;&gt;
&gt;&gt;&gt; # Ok, the factory method I need seems to be utcnow
&gt;&gt;&gt; # - that way I can get the time in UTC?)
&gt;&gt;&gt; datetime.utcnow()
datetime.datetime(2008, 6, 19, 11, 59, 9, 750844)
&gt;&gt;&gt; # fair enough, UTC time.

&gt;&gt;&gt; # Let's try simple date arithmetic: the difference
&gt;&gt;&gt; # between now... and now...
&gt;&gt;&gt; datetime.now() - datetime.utcnow()
datetime.timedelta(0, 10799, 999984)
&gt;&gt;&gt; # Hmm... now did that statement really
&gt;&gt;&gt; # take 3 hours to execute?</pre>
<p>The reason for these anomalies is that without any time zone information, instances of the datetime class behave as if they stored time in UTC. For our purposes this is unacceptable: if a user of the hypothetical calendar application proposes a meeting 2 hours from now, be it 17:15 EEST or 14:15 UTC, <code>meeting.start - datetime.now()</code> should on this very moment result in 2 hours regardless of the time zone of the user asking it.</p>
<p>While there are several freely available Python modules that provide date and time calculations, like Zope&#8217;s DateTime, the problem with them is that none of them is really compatible with datetime interface &#8211; if you use code that expects datetime instances, Zope&#8217;s DateTime objects will not help you. Some of the replacement modules, like mxDateUtil seems to use dubious date arithmetic, and are not really useful either. Clearly, we have to either fix the python datetime class somehow, or provide a compatible implementation that works as expected.</p>
<h1>Fixing datetime</h1>
<p>Fortunately, Python datetimes can be made time zone aware, by supplying an instance of tzinfo in the constructor. Unfortunately enough, the Python standard library does not provide any concrete implementations. Dang! Enters: pytz, a Python library that supplies hundreds of concrete time zone definitions.</p>
<pre>&gt;&gt;&gt; import pytz
&gt;&gt;&gt; eurhel = pytz.timezone("Europe/Helsinki")
&gt;&gt;&gt; localt = datetime.now(eurhel)
&gt;&gt;&gt; utct = datetime.now(pytz.utc)
&gt;&gt;&gt; utct - localt
datetime.timedelta(0, 0, 3410)</pre>
<p>Works as expected. And, utct &#8211; datetime.utcnow() fails with &#8220;TypeError: can&#8217;t subtract offset-naive and offset-aware datetimes&#8221; &#8211; which is good, as it would not yield sensible results. However, a look under the hood reveals that something is fundamentally wrong:</p>
<pre>&gt;&gt;&gt; datetime.datetime.now()
datetime.datetime(2008, 6, 23, 18, 2, 31, 101025,
        tzinfo=&lt;DstTzInfo 'Europe/Helsinki' EEST+3:00:00 DST&gt;)
&gt;&gt;&gt; datetime.datetime(2008, 6, 23, 18, 2, 31, 101025, eurhel)
datetime.datetime(2008, 6, 1, 18, 0, tzinfo=&lt;DstTzInfo 'Europe/Helsinki' HMT+1:40:00 STD&gt;)
&gt;&gt;&gt; # after a minute...
&gt;&gt;&gt; datetime.datetime(2008, 6, 23, 18, 2, 31, 101025, eurhel) - datetime.datetime.now(eurhel)
datetime.timedelta(0, 4687, 688091)</pre>
<p>That&#8217;s right, the datetime object created by a call to datetime.datetime constructor now seems to think that Finland uses the ancient &#8220;Helsinki Mean Time&#8221; which was obsoleted in the 1920s. The reason for this behaviour is clearly documented on the pytz page: it seems the Python datetime implementation never asks the tzinfo object what the offset to UTC on the given date would be. And without knowing it pytz seems to default to the first historical definition. Now, some of you fellow readers could insist on the problem going away simply by defaulting to the latest time zone definition. However, the problem would still persist: For example, Venezuela switched to GMT-04:30 on 9th December, 2007, causing the datetime objects representing dates either before, or after the change to become invalid.</p>
<p>The solution offered by pytz pages is to use the normalize and localize methods of pytz tzinfo instances, however this renders the whole datetime system too cumbersome to use. As I wanted to use datetime objects with time zones as easily as possible, I had to subclass the python datetime implementation and hack some internal aspects of it. The module, fixed_datetime also contains a method, set_default_timezone, to allow mimicking of the naive datetime objects; unlike ordinary datetime objects, fixed_datetime.datetime objects are never &#8216;naive&#8217;, but many of the methods will default to the time zone set by the said method.</p>
<pre>&gt;&gt;&gt; import fixed_datetime

&gt;&gt;&gt; # set default timezone...
&gt;&gt;&gt; fixed_datetime.set_default_timezone("Europe/Helsinki")

&gt;&gt;&gt; # uses default timezone...
&gt;&gt;&gt; fixed_datetime.datetime.now()
fixed_datetime.datetime(2008, 6, 23, 18, 33, 20, 525486,
        tzinfo=&lt;DstTzInfo 'Europe/Helsinki' EEST+3:00:00 DST&gt;)

&gt;&gt;&gt; # also works correctly
&gt;&gt;&gt; fixed_datetime.datetime(2008, 6, 23, 18, 33, 20, 525486)
fixed_datetime.datetime(2008, 6, 23, 18, 33, 20, 525486,
        tzinfo=&lt;DstTzInfo 'Europe/Helsinki' EEST+3:00:00 DST&gt;)

&gt;&gt;&gt; # UTC timestamps returned with UTC tzinfo
&gt;&gt;&gt; fixed_datetime.datetime.utcnow()
fixed_datetime.datetime(2008, 6, 23, 15, 37, 44, 777729, tzinfo=&lt;UTC&gt;)

&gt;&gt;&gt; # subtraction still works correctly!
&gt;&gt;&gt; utcdt = fixed_datetime.datetime.utcnow()
&gt;&gt;&gt; heldt = fixed_datetime.datetime.now()
&gt;&gt;&gt; heldt - utcdt
datetime.timedelta(0, 5, 495702)</pre>
<p>As a bonus, fixed_datetime.datetime contains methods to convert datetimes from ISO 8601 format. The method support parsing the time zone field, too:</p>
<pre>&gt;&gt;&gt; fixed_datetime.datetime.fromisoformat("20081010T010203+0500")
fixed_datetime.datetime(2008, 10, 10, 1, 2, 3, tzinfo=&lt;UTC+05:00&gt;)

&gt;&gt;&gt; fixed_datetime.datetime.fromisoformat("2008-10-10 01:02:03Z")
fixed_datetime.datetime(2008, 10, 10, 1, 2, 3, tzinfo=&lt;UTC&gt;)

&gt;&gt;&gt; # fractional hours, decimal comma, odd timezone
&gt;&gt;&gt; fixed_datetime.datetime.fromisoformat("2008-10-10 01,0341666667-04:37")
fixed_datetime.datetime(2008, 10, 10, 1, 2, 3,
        tzinfo=&lt;UTC-04:37&gt;)

&gt;&gt;&gt; fixed_datetime.datetime.today().isoformat(' ')
'2008-06-23 18:54:32+03:00'

&gt;&gt;&gt; # isoformat supports short format, too
&gt;&gt;&gt; fixed_datetime.datetime.now().isoformat(short=True)
'20080623T185303.489792+0300'

&gt;&gt;&gt; # addition across DST boundary works as expected:
&gt;&gt;&gt; before = fixed_datetime.datetime(2008, 10, 26, 2, 0, 0)
&gt;&gt;&gt; before
fixed_datetime.datetime(2008, 10, 26, <strong>2</strong>, 0, tzinfo=
        &lt;DstTzInfo 'Europe/Helsinki' <strong>EEST+3:00:00</strong> <strong>DST</strong>&gt;)

&gt;&gt;&gt; # now, add 2 hours
&gt;&gt;&gt; before + fixed_datetime.timedelta(seconds=7200)
fixed_datetime.datetime(2008, 10, 26, <strong>3</strong>, 0, tzinfo=
        &lt;DstTzInfo 'Europe/Helsinki' <strong>EET+2:00:00</strong> <strong>STD</strong>&gt;)</pre>
<p>You can download the said module below.</p>
<h1>Remaining issues</h1>
<p>Not every remaining issue is solved. Fixed datetime still does not accept &#8220;24&#8243; as hour value (mandated by ISO standard), and will throw an exception on positive leap seconds. Fixed datetime is much slower than the python implementation &#8211; many of the operations need to create intermediate 2 or 3 datetime instances.</p>
<p>Sadly it seems that Java got it right: having one class (<a title="java.util.Date documentation" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Date.html">Date</a>) that stores times in UTC seconds relative to Unix Epoch, and subclasses of abstract <a title="java.util.Calendar documentation" href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html">Calendar</a> class that deal with getting and setting individual components and date arithmetic in a localized way would indeed be the best long-term solution. To some Java&#8217;s date and calendar handling would seem overly complicated, to me it is the simplest way of representing the complex world of different calendars, time zones and other aspects of time keeping. If only someone could persuade Python devs to add something similar to the standard library&#8230;</p>
<h1>Download</h1>
<p>Download <a href="http://blog.redinnovation.com/wp-content/uploads/2008/06/fixed_datetime.py">fixed_datetime.py</a>, released under 3-clause BSD license.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mfabrik.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Wrong swap UUID after hibernation in Feisty</title>
		<link>http://blog.mfabrik.com/2007/10/01/wrong-swap-uuid-after-hibernation-in-feisty/</link>
		<comments>http://blog.mfabrik.com/2007/10/01/wrong-swap-uuid-after-hibernation-in-feisty/#comments</comments>
		<pubDate>Mon, 01 Oct 2007 09:26:17 +0000</pubDate>
		<dc:creator>Tuukka Mustonen</dc:creator>
				<category><![CDATA[debugging]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[solution]]></category>
		<category><![CDATA[ubuntu]]></category>

		<guid isPermaLink="false">http://blog.redinnovation.com/2007/10/01/wrong-swap-uuid-after-hibernation-in-feisty/</guid>
		<description><![CDATA[I&#8217;ve been using uswsusp for suspending/hibernating my Ubuntu Feisty laptop but suddenly it failed to resume from disk hibernation (blank screen with blinking cursor). I booted up in restoration mode and Ubuntu reported that it couldn&#8217;t restore the snapshot. After pressing enter to continue, the system booted up just fine, skipping the snapshot restoration as [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using <a href="http://suspend.sourceforge.net/">uswsusp</a> for suspending/hibernating my Ubuntu Feisty laptop but suddenly it failed to resume from disk hibernation (blank screen with blinking cursor). I booted up in restoration mode and Ubuntu reported that it couldn&#8217;t restore the snapshot. After pressing enter to continue, the system booted up just fine, skipping the snapshot restoration as supposed. The startup problem vanished, but it brought up a new one when trying to hibernate:</p>
<pre>&gt;&gt;&gt; sudo s2disk
Could not use the resume device (try swapon -a)</pre>
<p>Of course, swapon also gives a problem:</p>
<pre>&gt;&gt;&gt; sudo swapon -a
swapon: cannot stat
/dev/disk/by-uuid/4a815ae8-fa5b-4265-826c-d777a723e87b:
No such file or directory</pre>
<p>It seems that the UUID reference for swap is broken. Or is it the swap? At this point I did some Google research and it turned out the behaviour was because of an <a href="https://bugs.launchpad.net/ubuntu/+source/udev/+bug/105490">Ubuntu Feisty bug</a>, which causes the swap UUID change occasionally. It is closely related to hibernation, yet the cause remains unclear. To fix it, let&#8217;s do:</p>
<pre>&gt;&gt;&gt; free -m | grep -i swap
Swap:            0          0          0</pre>
<p>Which indicates that the system doesn&#8217;t find swap at all (because of wrong UUID). To find correct one:</p>
<pre>&gt;&gt;&gt; sudo fdisk -l | grep swap
/dev/sda6      10669   10917  2000061 82  Linux swap / Solaris</pre>
<p>Find your swap there and go for:</p>
<pre>&gt;&gt;&gt; sudo vol_id /dev/sda6
ID_FS_UUID=083d41f0-de57-48d4-92eb-aefde8fd6ec9</pre>
<p>Then you&#8217;ll just have to edit it in /etc/fstab and hibernation should work again. You could also try restoring the original snapshot by editing:</p>
<pre>&gt;&gt;&gt; sudo nano /etc/initramfs-tools/conf.d/resume</pre>
<p>and correcting the reference there also. I didn&#8217;t test this myself, however.</p>
<p>That should do it, but don&#8217;t get too excited: some report that the UUID keeps changing even after the fix, and it has to be manually changed over and over again. Luckily, I haven&#8217;t experienced such behaviour (yet!) and it&#8217;s quick to fix (though you might lose ability to hibernate, which is a really bad thing).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.mfabrik.com/2007/10/01/wrong-swap-uuid-after-hibernation-in-feisty/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
