<?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>coder . cl &#187; programming</title>
	<atom:link href="http://coder.cl/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://coder.cl</link>
	<description>web developer &#38; system programmer</description>
	<lastBuildDate>Tue, 15 May 2012 10:46:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>writing python daemons</title>
		<link>http://coder.cl/2012/05/writing-python-daemons/</link>
		<comments>http://coder.cl/2012/05/writing-python-daemons/#comments</comments>
		<pubDate>Sat, 12 May 2012 19:54:41 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2456</guid>
		<description><![CDATA[A daemon in Unix&#8482; and similar operating systems, is a background process, which runs without using the terminal or the X11 system as main I/O system. In other operating system, this is called service. A daemon has a very specific task to do, for example the NTP daemon keeps your computer date updated connecting to [...]]]></description>
			<content:encoded><![CDATA[<p>A <i>daemon</i> in Unix&trade; and similar operating systems, is a background process, which runs without using the terminal or the X11 system as main I/O system. In other operating system, this is called <i>service</i>. A daemon has a very specific task to do, for example the NTP daemon keeps your computer date updated connecting to NTP servers. Many applications that require asynchronous tasks, require this kind of applications to make your life easier. For example a job queue processor for the Gearman job server can be handled with this kind of applications.</p>
<p><span id="more-2456"></span></p>
<p>A daemon, classically on most Unix&trade; systems, first closes the three main I/O streams: <i>stdin</i>, <i>stdout</i> and <i>stderr</i>, then the <tt>fork(2)</tt> system call is used, creating an image of the current process, once the call is made, an <tt>exit(1)</tt> call is made on the parent process, and the child process keeps working in background. Due to the Python philosophy of being a productive language, this not so complex process is already implemented in the <tt>daemon</tt> module, so with this module you can create a daemon program.</p>
<pre name="code" class="brush:python;">

import os
import sys
import daemon
import atexit

def main():
    """
    Main Program
    """

    install_signal_handler()
    atexit.register(at_exit_handler)

    opts = parse_opts()
    config = parse_config(opts)
    if not opts.cwd:
        print("No Working Directory")
        sys.exit(0)

    with daemon.DaemonContext():
        os.chdir(opts.cwd)
        install_signal_handler()
        start_schedule(config, opts)

""" Executes the main() Function """
if __name__ == '__main__':
    main()
</pre>
<p>If you observe the code, it changes the working directory using <tt>os.chdir()</tt> function, because once a daemon is created, its working directory is automatically changed to the root directory or <tt>/</tt>. Some daemons or servers like the Apache HTTP server, have a precompiled working directory, but it also allows to use <tt>chroot</tt> directory to make it work outside the precompiled working directory. Also, it is installing signal handlers, to allow signal processing, like SIGHUP and SIGCHLD. The <tt>parse_opts()</tt> and <tt>parse_config()</tt> functions, are functions to parse daemon arguments and daemon configuration using the <tt>optparse</tt> and <tt>ConfigParser</tt> modules respectively.</p>
<p>The <tt>atexit</tt> module is used to ensure that most program resources &mdash; like files, connections and similar stuff &mdash; are released or closed, once the daemon process terminates. So, the following <tt>atexit</tt> example shows a routine releasing resources.</p>
<pre name="code" class="brush:python;">

from django.db import connections
import atexit

def at_exit_handler():
    """
    At Exit Function (close all connections)
    """
    for con in connections.all():
        try:
            con.close()
        except Exception, exc:
            log().error(exc)
    log().close()
</pre>
<p>The signal handler have very similar behaviour, it register a processing callback, which is executed using each time a signal is received. For example on the SIGHUP signal, I am doing a daemon rehash, rather than doing a daemon termination.</p>
<pre name="code" class="brush:python;">

import signal as sig
import traceback as tb

def rehash_daemon():
    """
    Rehash the daemon, reading configurations again.
    """
    global DAEMON_CONFIG
    DAEMON_CONFIG = parse_config()

def install_signal_handler():
    """
    Signal Handler Installer
    """
    try:
        sig.signal(sig.SIGHUP, rehash_daemon)
    except Exception, exc:
        log().error(repr(exc))
        log().error(tb.format_exc(exc))
        return False
</pre>
<p>This will allow you to create a robust daemons, capable to handle signals, resource releasing on the exit event and similar stuff. Remember that as any language with a garbage collector, Python has the disadvantage of leaking memory if you do not cut the object references properly, due to the reference counting used by the garbage collector inside the GIL cycles. Your daemon design should be optimal.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/05/writing-python-daemons/">Permalink</a> |
<a href="http://coder.cl/2012/05/writing-python-daemons/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/05/writing-python-daemons/&title=writing python daemons">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/05/writing-python-daemons/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>my software design principles</title>
		<link>http://coder.cl/2012/05/my-software-design-principles/</link>
		<comments>http://coder.cl/2012/05/my-software-design-principles/#comments</comments>
		<pubDate>Sat, 05 May 2012 12:35:17 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2448</guid>
		<description><![CDATA[Most modern applications are providing APIs. That allows you to integrate those applications providing APIs with third party applications and create a real cloud computing environment. From an architectural perspective, we should have at least to have in mind the architectural pattern to be used, design patterns to be implemented, the protocol to use and [...]]]></description>
			<content:encoded><![CDATA[<p>Most modern applications are providing APIs. That allows you to integrate those applications providing APIs with third party applications and create a real <i>cloud</i> computing environment. From an architectural perspective, we should have at least to have in mind the architectural pattern to be used, design patterns to be implemented, the protocol to use and the data format to expose the API. The architectural pattern should be simple, the design pattern efficient, the protocol lightweight and the data format flexible for your requirements. With a good API design, it should be stable enough to support changes along the time dynamically.</p>
<p><span id="more-2448"></span></p>
<p>The architectural pattern should be simple. Most people is thinking on the MVC architectural pattern as the most proper architectural for any application. But really the MVC pattern was designed with very old basis and mostly with the idea of generalizing the user interface of desktop applications. Currently, Web Applications are build on top of many technologies, not RDBMS engines only, so you should start using the proper architectural pattern, where technology diversity should follow the maximum cohesion principle, rather than coupling application components.</p>
<p>We have as key principle of design <i>&laquo;minimum coupling, maximum cohesion&raquo;</i>, but I would like to add <i>&laquo;proper generalization&raquo;</i>. So, finally we should have <i>&laquo;minimum coupling, maximum cohesion &amp; proper generalization&raquo;</i> as design basis. If we observe, generalizations are older than software, we can stage that the term comes from Maths, where a generalization is a concept that can be applied to multiple problems and solve them using that concept. Cohesion is the principle of independent components that can work together, and coupling is a design which cannot separate its components. One of the best and classical examples of maximum cohesion on its design is Unix, where there are many small tools that can work together without coupling its functionalities.</p>
<p>A good generalization comes with from a good model, and any good generalization usually is able to solve multiple problems at once. Object Oriented programming provides a rich interface for abstractions, where the generalization is one of the most powerful ones, but in words of real generalization, I can proudly say that Monads are one of the best abstractions and mostly generalization that I ever seen.</p>
<ul>
<li>Haskell Programmer: Hey Java programmer, you know how just about everything is represented by a class?</li>
<li>Java Programmer: Yea&#8230;</li>
<li>HP: Even stuff no business being a class</li>
<li>JP: Well, it is our fundamental abstraction for anything larger than a function. It may be clumsy, but it can be used to implement any other design pattern we need.</li>
<li>HP: Well Monads serve the same role for us.</li>
<li>JP: Nulls?</li>
<li>HP: Maybe Monad</li>
<li>JP: I/O?</li>
<li>HP: IO Monad</li>
<li>JP: Exceptions and error handling?</li>
<li>HP: We have several ways, but mostly Maybe Monad</li>
<li>JP: List comprehension?</li>
<li>HP: Again, Monads</li>
<li>JP: Mutable data structures?</li>
<li>HP: That would be the State Monad<sub><a href="#note_2">[2]</a></sub></li>
</ul>
<p>With the proper generalization you can make your design to be consistent, robust and reliable. But you must leave the generalization concept just as <i>hierarchy</i> problem. It should be stated globally as <i>computational</i> problem rather than design problem only. A generalization as computation can be applied to multiple problems, where applying computational generalizations we can find mapping functions that can be globally used. This can be reached combining the IPO model and Object Oriented models properly, working together.</p>
<p>Software design is not easy. An UML class model is not enough, where it can only display <i>structures</i>, probably with a sequence models and communication models you can reach a good IPO design, but not without the proper knowledge about the implementation. So, any <i>analyst</i> who does not <a href='http://programming-motherfucker.com/' title='Programming, Motherfucker!, Do you speak it?'>knows how to program</a>, is just wasting your <a href='http://www.lnds.net/blog/2012/04/programa-ctm.html' title='¡Programa CTM!'>money and time</a>, with the obvious further reimplementation and redesign of the software product.</p>
<p>And you should start adding the proper generalizations as computations to your design, working together with your hierarchical generalizations, so they can bring you the proper quality along the time.</p>
<p style="font-size:10pt;"><a name="note_2">[2]</a> This is an excerpt from a discussion on a programming forum.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/05/my-software-design-principles/">Permalink</a> |
<a href="http://coder.cl/2012/05/my-software-design-principles/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/05/my-software-design-principles/&title=my software design principles">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/05/my-software-design-principles/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>how important is to optimize haskell code?</title>
		<link>http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/</link>
		<comments>http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/#comments</comments>
		<pubDate>Wed, 02 May 2012 14:36:11 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2419</guid>
		<description><![CDATA[Programming in Haskell is cool. You have various functions and abstractions to work with. But it has several considerations to have in mind once you are programming in this language. The main one about its performance and memory usage &#8212; in my opinion &#8212; is where to place lazy evaluated expressions and where to place [...]]]></description>
			<content:encoded><![CDATA[<p>Programming in Haskell is cool. You have various functions and abstractions to work with. But it has several considerations to have in mind once you are programming in this language. The main one about its performance and memory usage &mdash; in my opinion &mdash; is where to place lazy evaluated expressions and where to place strictly evaluated expressions. There are various articles with very good recommendations, but I want to show you a practical example, where you can see how effectively is used the lazy evaluation and released in a good execution point of the example program.</p>
<p><span id="more-2419"></span></p>
<p>As you know I am currently solving the <a href='http://projecteuler.net/' title='Project Euler'>Project Euler</a> problem set, just as toy project, to practice some Haskell code with some not so complex problems. And yesterday I have implemented the solution for the <a href='http://projecteuler.net/problem=104' title='Project Euler: Problem 104'>problem 104</a>, which is trying to find first pandigital digits from 1 to 9 on the last and first digits of a Fibonacci number. So, the Fibonacci should have more than 9 digits to solve this problem. You can see the code of the solution on <a href='https://github.com/dmw/prjeuler/blob/master/src/problem104.hs' title='Project Euler in Haskell: Solution 104'>this link</a>.</p>
<p>If you observe the code, you will see that it is respecting the Haskell tail call convention, where you must use closures to ensure that the compiled code will be using guarded recursions. Otherwise the functions will become standard recursive functions, rather being compiled as guarded recursions &mdash; which are similar to tail calls.</p>
<pre name="code" class="brush:haskell;">

-- | Calculates the Fibonacci Term N
fib :: Int                      -- ^ Term to calculate.
       -> Integer               -- ^ Fibonacci Term as Result.
fib n = snd . foldl' fib' (1, 0) . dropWhile not $
        [testBit n k | k < - let s = bitSize n in [s - 1, s - 2 .. 0]]
  where
    fib' (f, g) p
      | p         = (f * (f + 2 * g), ss)
      | otherwise = (ss, g * (2 * f - g))
      where ss = f * f + g * g
</pre>
<p>Also it defines two functions to check if the number meets the pandigital requirement, where <tt>isValidDig</tt> is not called immediately from the <tt>checkRange</tt> recursive function, instead of calling that function, it calls the <tt>isValidPan</tt> function, where it is called with the constant expression <tt>[1..9]</tt>, avoiding consecutive List instantiation, and using <tt>`seq`</tt> to avoid lazy evaluations and further stack overloading.</p>
</pre>
<pre name="code" class="brush:haskell;">

-- | Checks if the given number x have valid last n digits
-- and last n digits
isValidDig :: Integer           -- ^ Number to Check.
              -&gt; [Integer]      -- ^ Sequence to Check.
              -&gt; Bool           -- ^ Is valid or not.
isValidDig x xs
  | length (digits 10 x) &lt; length xs = False
  | otherwise = let ds = digits 10 x
                    l = length xs
                    s = sort xs
                    r = sort $ take l ds
                    t = sort $ take l $ reverse ds
                in r == s &amp;&amp; t == s

-- | Checks sequentially if the given range covers the
-- problem of pandigital sequence of digits using the reqDigs
-- sequence.
isValidPan :: Int               -- ^ Number to check.
              -&gt; Bool           -- ^ True when is valid.
isValidPan x = r `seq` isValidDig r [1..9]
               where r = fib x
</pre>
<p>This allows the usage of a small stack space once it is called, due to strict evaluation, where all List instances are not kept in memory, and similar structures are only evaluated once, without keeping that memory in use, and being released once those non recursive functions are finished. Finally we can use <tt>isValidPan</tt> on a guard, without the risk of overloading the stack.</p>
<pre name="code" class="brush:haskell;">

-- | Checks sequentially if the given range covers the
-- problem of pandigital problem.
checkRange :: Int                   -- ^ Starting number.
              -&gt; Int                -- ^ End number
              -&gt; Int                -- ^ Returning Number (-1 on failure).
checkRange m n = sCheckRange m n m
  where sCheckRange x y z
          | z &gt;= y = -1
          | isValidPan z = z
          | otherwise = let r = z + 1
                        in r `seq` sCheckRange x y r
</pre>
<p>The closure used on the <tt>checkRange</tt> function makes the compiler to start using the tail call as it is required by this kind of functions where you must keep very well controlled the evaluation of the program expressions. Any mistake on the evaluation of the program will lead you to use more memory that it is really required, leading to slowness and delayed evaluations where your code could crash with stack overflows.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/problem104.bin_1.png" title="Problem 104 Example Memory Usage" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/problem104.bin_1.png" border="0" alt="Problem 104 Example Memory Usage"/></a></p>
<div>Problem 104 Example Memory Usage</div>
</div>
<p>As you see on the cost centre chart above, the program is using almost a constant amount of memory along its execution, evaluating Fibonacci terms from 1000 to 9000, in 12 seconds approximately. So, the keys of a good memory usage in Haskell is to use evaluation expressions and guarded recursions properly.</p>
<p>Another example is the problem #255 in the Project Euler. This code is using Haskell tail calls to ensure the optimal memory allocation. For example the function used to calculate the rounded square root using the Heron Operation as follows.</p>
<pre name="code" class="brush:haskell;">
-- | Applies the Heron Operation recursively until it returns
-- the round square root and the number of iterations as tuple.
heronOpRec :: Integer                 -- ^ Heron Operation to Apply
           -&gt; (Integer, Integer)      -- ^ Pair (RSR, Iterations)
heronOpRec a = heronOp a a (digitBase $ numDigits a) 0
  where heronOp o n m a
          | o == 0 = (0, 0)
          | o == 1 = (1, 1)
          | o == 2 = (1, 1)
          | o == 3 = (2, 1)
          | n == m = (m, a)
          | otherwise = let x = fromIntegral m
                            y = fromIntegral o / x
                            s = round ((x + y) / 2)
                            t = a + 1
                        in heronOp o m s t
</pre>
<p>And the application of this kind of recursive calls can be seen in the following chart.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/problem255.bin_.png" title="Problem 255 Example Memory Usage" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/problem255.bin_.png" border="0" alt="Problem 255 Example Memory Usage"/></a></p>
<div>Problem 255 Example Memory Usage</div>
</div>
<p>If you compare both charts and see how both problem solutions are programmed, you will see that they keep a very low limit on memory usage. The <a href='https://github.com/dmw/prjeuler/blob/master/src/problem255.hs' title='Project Euler: Problem #255'>problem #255</a> is using numbers purely, and where <a href='https://github.com/dmw/prjeuler/blob/master/src/problem104.hs' title='Project Euler: Problem #104'>problem #104</a> solution is using lists to hold the digits of the number to be checked as pandigital, that is why it has some peaks on the <tt>isValidDig</tt> function, but once the program exits that function that memory is deallocated by the garbage collector.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/">Permalink</a> |
<a href="http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/#comments">One comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/&title=how important is to optimize haskell code?">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/05/how-important-is-to-optimize-haskell-code/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>the self-criticising programmer</title>
		<link>http://coder.cl/2012/04/the-self-criticising-programmer/</link>
		<comments>http://coder.cl/2012/04/the-self-criticising-programmer/#comments</comments>
		<pubDate>Sat, 28 Apr 2012 21:41:22 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2409</guid>
		<description><![CDATA[I am a self-criticising programmer. But I think that I know my self in deep. I know my limits, how much can I bring, how much can I deliver. I know both very well. Along the time, being self-criticising is not about being masochist on thoughts, it is more like being reasonable, thinking on how [...]]]></description>
			<content:encoded><![CDATA[<p>I am a <i>self-criticising programmer</i>. But I think that I know my self in deep. I know my limits, how much can I bring, how much can I deliver. I know both very well. Along the time, being self-criticising is not about being masochist on thoughts, it is more like being reasonable, thinking on how to solve problems reasoning rather than using something like <i>trial and error</i> methods &mdash; usually described as &laquo;the process of learning where doesn&#8217;t happen from failure itself but rather from analysing the failure, making a change, and then trying again&raquo;. Instead of failing, I try to solve problems analysing them.</p>
<p><span id="more-2409"></span></p>
<p>You as programmer probably know about that &mdash; but only if you have gained expertise on certain programming language &mdash; where you have learned more stuff than it was shown to you on a classroom or course. Because you know that to reach a good level on any programming language requires more than courses. It requires book reading, exercising, reasoning on that programming language, learning about its features, its limits and how it is implemented. This clearly avoids many programming errors and reasoning errors. A <i>code monkey</i>, does many failed attempts to solve problems guessing which call should be used on a block of code, rather than reasoning and using the right calls where they are required. There is an old phrase that you will remember, and it is not told as joke I think: <i>&laquo;Read The Fucking Manual&raquo;</i>. RTFM is probably one of the oldest phrases on the Internet. Almost all specifications and user manuals are public documents, you can read them online, print a copy if you want and mainly you can learn from them.</p>
<p>The classical example is how is being used the garbage collector on Java and similar programming languages. There are many applications reaching the <tt>OutOfMemoryError</tt>, due to memory leaks. Because many programmers are misunderstanding the concepts behind what really does a garbage collector, and they are mostly based on reference counting. So, any memory related problems on applications where the language uses a garbage collector, is just a subject of misunderstanding what really does its garbage collector. Other two errors are heap overflow and stack overflow errors, if you reach them, you still need to know in deep the programming language that you are using. So, any programmer reaching that kind of errors still requires more knowledge to be called <i>expert</i>. But that knowledge is public, there is no black box and there is no black magic behind those errors, you just need to read the programming manuals and related documentation. So, there is not excuse to reach that kind of errors.</p>
<p>So, for me if the language or the environment brings me an <i>error</i>, I start researching about that error until I get it solved. For me is not a subject of increasing hardware resources or similar stuff until I get a real proof that it is really required. An <i>error</i> for me need to be solved from my code first, not the environment, because my code is my responsibility, not the environment. An example of almost bug free software is <a href='http://coder.cl/products/pyxser/' title='Python XML Serialization'>pyxser</a>, it does not have memory leaks in its code and it is safe to be used in production environments, you can do up to 1.000.000.000 of continuous and parallel serializations-deserializations with pyxser, without leaking the computer memory, you just need to use the proper calls. A product with that quality was obtained only because I was very strict and self-criticising. So I have created a serializer that does not crashes with cross references and circular references &mdash; which is not implemented in other XML serializers &mdash; and it is very robust because I was a self-criticising programmer. You can try to serialize, for example, a Django Model class instance (object), and you will not be able to do it with other serializers like simplejson. So, being self-criticising is not bad as you think&hellip;</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/the-self-criticising-programmer/">Permalink</a> |
<a href="http://coder.cl/2012/04/the-self-criticising-programmer/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/the-self-criticising-programmer/&title=the self-criticising programmer">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/the-self-criticising-programmer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>freelance project handling rules</title>
		<link>http://coder.cl/2012/04/freelance-project-handling-rules/</link>
		<comments>http://coder.cl/2012/04/freelance-project-handling-rules/#comments</comments>
		<pubDate>Sat, 21 Apr 2012 15:38:03 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[rants]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2400</guid>
		<description><![CDATA[As you know I work as freelance programmer, I have handled many kinds of projects, you can see the list of technologies which I am offering on my services page and some sample products which can tell of what I am capable to do on my products page. As you can see, I have left [...]]]></description>
			<content:encoded><![CDATA[<p>As you know I work as freelance programmer, I have handled many kinds of projects, you can see the list of technologies which I am offering on my <a href='http://coder.cl/services/' title='coder.cl: services'>services page</a> and some sample products which can tell of what I am capable to do on my <a href='http://coder.cl/products/' title='coder.cl: products'>products page</a>. As you can see, I have left some technologies, like PHP, due to the poor budget on many of those projects and messy code that I have seen on them. Since PHP lacks some tools like static analyzers and style checkers, most PHP projects cannot ensure good quality.</p>
<p><span id="more-2400"></span></p>
<p>My set of rules on handling projects and jobs related to programming are mainly related to payment methods, rates, methodologies and <i>who</i> is hiring me. So, non serious proposals are not handled by me. If you come telling me that you need <i>a web page</i>, just forget hiring me, I will not attend you, because I develop <i>applications</i>, not web pages.</p>
<dl>
<dt>refuse fixed price projects</dt>
<dd>Every software project without a well defined specification and clear requirements, is subject of changes, handling fixed price project is subject of spending unpaid work hours. So, my rates are monthly and hourly, depending on how is agreed the payment method. Fixed price projects which does not have a very consistent specification and requirements, will not be handled.</dd>
<dt>refuse projects with the wrong technology</dt>
<dd>As PHP projects, they will be refused. I cannot handle projects that cannot be properly integrated with other tools and languages that do not have strictly necessary tools like static analyzers and style checkers. PHP, Node JS and similar ones which has that kind of lacks, will not be accepted.</dd>
<dt>refuse projects where I did not made the estimation</dt>
<dd>Every software where I did not have made the estimation will be refused, I cannot handle projects where the estimation is not subject of concise methodologies like PERT. So, your compromise is not my compromise if you have made the estimation.</dd>
<dt>refuse projects without version control</dt>
<dt>
<dd>Every project where you are not using version control, will be refused. I cannot stay sending tarballs with my code, creating messy products, everything should be properly branched and tagged on each milestone.</dd>
</dt>
<dt>refuse projects without issue tracking</dt>
<dt>
<dd>Every project should be using issue tracking software, agile or not, but I need that kind of tools to track each development stage, where everything should be clearly specified.</dd>
</dt>
<dt>refuse projects without continuous integration</dt>
<dt>
<dd>I cannot work with projects where you are not properly checking the code. The code should stay clean from its origin, with the proper style and avoiding common errors.</dd>
</dt>
<dt>do not work with novice programmers</dt>
<dt>
<dd>I do not work with novice programmers which are not capable to read a specification and they are not able to handle some basic stuff, like server configuration, command line tools, server administration, and the proper knowledge of the environment where are you working. If you want me as tutor or mentor, just hire me as tutor or mentor, it is a separate job.</dd>
</dt>
</dl>
<p>You must have all those points in mind before hiring me or calling me for a project proposal. Those rules were created due to some failed project &mdash; two to be more precise.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/freelance-project-handling-rules/">Permalink</a> |
<a href="http://coder.cl/2012/04/freelance-project-handling-rules/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/freelance-project-handling-rules/&title=freelance project handling rules">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/freelance-project-handling-rules/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>project euler: problem 102</title>
		<link>http://coder.cl/2012/04/project-euler-problem-102/</link>
		<comments>http://coder.cl/2012/04/project-euler-problem-102/#comments</comments>
		<pubDate>Fri, 20 Apr 2012 10:38:11 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2392</guid>
		<description><![CDATA[I have started my own solutions to the Project Euler in Haskell. Just to practice Haskell and its features. The past problem was the problem 255. Now I have solved the problem 102, using some additional features, not taking the problem as it comes in the Project Euler. Rather than doing a simple solution in [...]]]></description>
			<content:encoded><![CDATA[<p>I have started my own solutions to the Project Euler in Haskell. Just to practice Haskell and its features. The past problem was the problem 255. Now I have solved the problem 102, using some additional features, not taking the problem as it comes in the Project Euler. Rather than doing a simple solution in plain text, I have created a program which renders the triangles in the problem using OpenGL, placing the triangles in a Windows rather than just indicating the number of triangles.</p>
<p><span id="more-2392"></span></p>
<p>Is nice to work with Haskell, you may know that you can work with a very wide variety of technologies in Haskell. Also, the Glasgow Haskell Compiler or GHC, is able to compile machine byte code, creating native executables for its runtime. Since all Project Euler problems are very nice to solve, I have created a <a href='https://github.com/dmw/prjeuler' title='dmw/prjeuler'>github repository</a> with my solutions, to share them, probably you can use them to examine some Haskell code and see if you want to learn it.</p>
<p>The problem 102 is related to triangles and point positions, and it can be seen in <a href='http://projecteuler.net/problem=102' title='Project Euler: Problem 102.'>this link</a>. The main goal of the problem is to indicate the number of triangles which are containing the origin or point <img src='http://s.wordpress.com/latex.php?latex=p%280%2C%200%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p(0, 0)' title='p(0, 0)' class='latex' />, where I have used the <a href='http://en.wikipedia.org/wiki/Cross_product' title='Cross Product'>Cross Product</a> to solve this problem.</p>
<p>First I have defined plane points and triangles as data types in Haskell, deriving the <tt>Num</tt> type class instance on the <tt>LPt</tt> data type which represents a point in a two dimensional space.</p>
<pre name="code" class="brush:haskell;">

data LPt = LPt (Int, Int)
         deriving (Eq, Show, Ord)

data LTrg = LTrg {
  tA        :: LPt
  , tB      :: LPt
  , tC      :: LPt
  } deriving (Eq, Show, Ord)

instance Num LPt where
  x + y = LPt (fstp x + fstp y, sndp x + sndp y)

  x - y = LPt (fstp x - fstp y, sndp x - sndp y)

  x * y = LPt (fstp x * fstp y, sndp x * sndp y)

  abs x = LPt (abs (fstp x), abs (sndp x))

  fromInteger x = LPt (fromInteger x, fromInteger x)

  signum x | fstp x &lt; 0 &amp;&amp; sndp x &lt; 0 = -1
  signum x | fstp x &gt; 0 &amp;&amp; sndp x &gt; 0 = 1
  signum x = 0

crossPt :: LPt -> LPt -> LPt
crossPt x y = LPt (0, fstp x * sndp y - sndp x * fstp y)
</pre>
<p>Then is easy to reach the solution. Where I have plain text file parsing triangle points using the following functions.</p>
<pre name="code" class="brush:haskell;">

mkTriangle :: String -&gt; LTrg
mkTriangle s = LTrg { tA = head g, tB = g !! 1, tC = last g }
               where g = fmap (\x -&gt; LPt (head x, last x) )
                         $ splitEvery 2 ln
                     ln = fmap (read . strip) $ splitOn "," s

mkTriangles :: String -&gt; Int -&gt; Int -&gt; [LTrg]
mkTriangles s l h = drop l
                    $ take h
                    $ fmap mkTriangle
                    $ filter (\ x -&gt; length x &gt; 0 )
                    $ fmap strip
                    $ lines s
</pre>
<p>So, my solution do not creates all triangles on the file, rather than creating all triangles, it just takes a given segment of the file, and renders their position in the OpenGL windows.</p>
<pre name="code" class="brush:haskell;">

trgColor :: LTrg -&gt; IO ()
trgColor xs | trgContained zeroPt xs = colorCyan
trgColor xs = colorGreen

displayTriangle :: LTrg -&gt; IO ()
displayTriangle xs = do _ &lt;- renderPrimitive Polygon $ do
                          trgColor xs
                          mapM ptToGlPt [tA xs, tB xs, tC xs]
                        flush

displayTriangles :: [LTrg] -&gt; F.Font -&gt; IO ()
displayTriangles xs f = do clear [ ColorBuffer, DepthBuffer ]
                           mapM_ displayTriangle xs
                           trgTextCont xs f
                           flush
</pre>
<p>Where the call to the <tt>trgContained</tt> in the guard at the <tt>trgColor</tt> function is what indicates if the triangle contains or not the point <img src='http://s.wordpress.com/latex.php?latex=p%280%2C%200%29&#038;bg=ffffff&#038;fg=000000&#038;s=0' alt='p(0, 0)' title='p(0, 0)' class='latex' /> or zeroPt. So, you can see two sample results as follows.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/prjeuler-problem-102-sample-1.jpg" title="Project Euler: Problem 102 Visualization" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/prjeuler-problem-102-sample-1.jpg" border="0" alt="Project Euler: Problem 102 Visualization"/></a></p>
<div>Project Euler: Problem 102 Visualization Sample 1</div>
<div>./problem102 triangles.txt 70 90</div>
</div>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/prjeuler-problem-102-sample-2.jpg" title="Project Euler: Problem 102 Visualization" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/prjeuler-problem-102-sample-2.jpg" border="0" alt="Project Euler: Problem 102 Visualization"/></a></p>
<div>Project Euler: Problem 102 Visualization Sample 2</div>
<div>./problem102 triangles.txt 23 48</div>
</div>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/project-euler-problem-102/">Permalink</a> |
<a href="http://coder.cl/2012/04/project-euler-problem-102/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/project-euler-problem-102/&title=project euler: problem 102">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/project-euler-problem-102/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>all skills comes with interests</title>
		<link>http://coder.cl/2012/04/all-skills-comes-with-interests/</link>
		<comments>http://coder.cl/2012/04/all-skills-comes-with-interests/#comments</comments>
		<pubDate>Sun, 15 Apr 2012 20:40:18 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[rants]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2388</guid>
		<description><![CDATA[As you know I was working for various medium companies along my career, until I have become a freelancer. In one of those companies, where most programming contracts were made to Informatics Engineers as Software Engineers as role. You expect at least from a Software Engineers the capacity of doing research on almost any topic [...]]]></description>
			<content:encoded><![CDATA[<p>As you know I was working for various medium companies along my career, until I have become a freelancer. In one of those companies, where most programming contracts were made to Informatics Engineers as Software Engineers as role. You expect at least from a Software Engineers the capacity of doing research on almost any topic related to the given programming task and a very good quality solution to the given problem. That was not the case always, as it happens on many areas, not only in software development. Today I will present a story illustrating how something what is done without interest will make you waste your time and money.</p>
<p><span id="more-2388"></span></p>
<p>The most common job position in the last decade in software development is the Web Development. Almost everyone wants a Web Application, something that can run on a browser, without doing too much effort porting an application to desktop applications and similar stuff. So, most software development contracts are based on the Web. If you study something related to Informatics Engineering or Computer Science related topics, you cannot expect that they will prepare you for an immediate job position, and even you cannot expect that you will finish studying that career knowing <i>everything</i> related to it. Studying a career has the intention to get the basic knowledge on certain subject, enough to understand books that will bring you the proper expertise on that subject. Then you can do an MSc and you will be an expert on a small subset of topics covered by your career, also you can do a PhD, and you will be an expert <i>discovering new stuff</i> on a very specific subject of interest. You can read this wonderful article entitled <a href='http://matt.might.net/articles/phd-school-in-pictures/' title='The illustrated guide to a Ph.D.'><i>&laquo;The illustrated guide to a Ph.D.&raquo;</i></a> and you will see what I am referring to.</p>
<p>But if you do your stuff without interests, you will not learn, and you cannot drag any guilty to your environment about not learning enough to reach a good level. Everything is subject of interests, getting a graduate level on any career is not subject of decorating your room with a nice diploma, or showing a good <i>position</i> in your resume.</p>
<p>So, if you decide to get employed as <i>Software Engineer</i> on a <i>Web Developer</i> role, at least I am expecting from you that you will be able to read the <a href='http://www.ietf.org/rfc/rfc2616.txt' title='Hypertext Transfer Protocol &mdash; HTTP/1.1'>Hypertext Transfer Protocol Specification</a> and solve almost anything related to that protocol. A small team in one of those companies was working with a very specific service, mounted over HTTP/1.0 over a standard Apache Tomcat server. Rather than using SOAP or similar protocols, the service was working with HTTP POST parameters, and returning XML as content response. But they were stuck two days trying to solve a small problem. The HTTP client library that they were using was keeping the connections open and not closed, leaving many HTTP connections open on subsequent requests. If you know a little about browsers, probably you know that they are using &mdash; almost all of them &mdash; Keep-Alive connections. So, if you want to research what makes an HTTP client to use Keep-Alive connections, you should start searching for <i>keep-alive</i> and <i>negotiation</i> keywords over the document.</p>
<blockquote><p>
An HTTP/1.1 server MAY assume that a HTTP/1.1 client intends to maintain a persistent connection unless a Connection header including the connection-token &#8220;close&#8221; was sent in the request. If the server chooses to close the connection immediately after sending the response, it SHOULD send a Connection header including the connection-token close. [Hypertext Transfer Protocol -- HTTP/1.1, Section 8.1.2.1 Negotiation, first paragraph]
</p></blockquote>
<p>So, the right header to search for is <tt>Connection</tt>, which controls the HTTP/1.1 behaviour during the protocol negotiation. This is not CURL, which uses a <i>closing</i> connection negotiation due to its nature, which is not the nature of a <i>common</i> HTTP client which uses the standard specification.</p>
<blockquote><p>
HTTP/1.1 defines the &#8220;close&#8221; connection option for the sender to signal that the connection will be closed after completion of the response. [Hypertext Transfer Protocol -- HTTP/1.1, Section 14.10 Connection]
</p></blockquote>
<p>Finally, took me two hours to solve the problem reading the HTTP client library documentation and the HTTP/1.0 specification. The previous hack of destroying the client instance to avoid open connections was removed and the client library started its works using the proper standard behaviour. So, everything is subject of interest. The server was working with the right behaviour, not as some team members were thinking about <i>bugs</i> on the server. All those headaches were subject of a lack of interest on the issues to be solved. I just imagined how many lines of code were dropped and inserted trying to reach the proper solution guessing which API call would close the connection, trying to use many API calls, and just one extra line of code has solved the problem.</p>
<pre name="code" class="brush:java;">

httpRequest.setHeader("Connection", "close");
</pre>
<p>Getting confused if you are under pressure is natural, I accept that. Also I accept that here in Chile being a programmer &mdash; now called <i>Software Engineer</i> &mdash; is not one of the most coolest job positions on the market. It will never will be well paid as manager position. But the lack of interest is not subject of where did you have studied. Probably making a complex career which requires reasoning, reading and effort, is something boring with pressure and not well paid job positions is causing that lack of interest, where most <i>Software Engineers</i> do not work on that job position for a long time. And this problem is not subject to be treated on a classroom, they just will bring you the basis. Reading and enhancing skills is your own responsibility.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/all-skills-comes-with-interests/">Permalink</a> |
<a href="http://coder.cl/2012/04/all-skills-comes-with-interests/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/all-skills-comes-with-interests/&title=all skills comes with interests">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/all-skills-comes-with-interests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>project euler: problem 255</title>
		<link>http://coder.cl/2012/04/project-euler-problem-255/</link>
		<comments>http://coder.cl/2012/04/project-euler-problem-255/#comments</comments>
		<pubDate>Sat, 14 Apr 2012 13:41:14 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2384</guid>
		<description><![CDATA[Haskell is a fabulous language, there is no looping instruction like for or while, everything is stated using recursions, like any other functional language does, preventing states across the execution, as it was defined on the computational model of most functional languages, which is known as &#955;-Calculus. There is no state, only purely functional state-less [...]]]></description>
			<content:encoded><![CDATA[<p>Haskell is a fabulous language, there is no looping instruction like <tt>for</tt> or <tt>while</tt>, everything is stated using recursions, like any other functional language does, preventing states across the execution, as it was defined on the computational model of most functional languages, which is known as <i>&lambda;-Calculus</i>. There is no state, only purely functional state-less execution paths. The <a href='http://projecteuler.net/problem=255' title='Project Euler: Problem 255'>Problem 255</a> on the <a href='http://projecteuler.net/' title='Problem 255'>Project Euler</a>, is related to rounded squares and the Heron&#8217;s method to calculate it, so I have implemented a Haskell program with that algorithm, which is obviously a recursive algorithm.</p>
<p><span id="more-2384"></span></p>
<p>If we see my solution, there is a function pair to solve the problem where <tt>heronOp</tt> is the main recursive function to solve the iterations, avoiding state. On Haskell, thanks to its main functional abstraction called Monad, you can implement state machines and similar tasks using the <a href='http://www.haskell.org/haskellwiki/State_Monad' title='Haskell: State Monad'>State Monad</a>, but states are not really required to solve anything in Haskell.</p>
<pre name="code" class="brush:haskell;">

module Main (main) where

import Data.Digits (digits)
import System.Environment (getArgs)

digitBase :: Int -&gt; Int
digitBase n | odd n = round ((2 * 10) ** ((fromIntegral n - 1) / 2))
digitBase n = round ((7 * 10) ** ((fromIntegral n - 2) / 2))

heronOp :: Int -&gt; Int -&gt; Int -&gt; Int
heronOp o n m | n == m = m
heronOp o n m = heronOp o m (round ((x + y) / 2))
                where x = fromIntegral m
                      y = fromIntegral o / x

main :: IO ()
main = do [x] &lt;- getArgs
          print
            $ heronOp (read x) (read x)
            $ digitBase $ length $ digits (read x) 10
</pre>
<p>There is &mdash; among other interesting approaches &mdash; a paper where the authors are writing about writing operating systems entirely in Haskell [<i>&laquo;A principled approach to operating system construction in Haskell&raquo;</i>], despite it is a functional language, it has solved the stack usage problems along recursive calls using <a href='http://en.wikipedia.org/wiki/Tail_call' title='Tail Call'>tail calls</a>, so you do not need to worry about recursion in almost all code, you just need to make your recursive calls lazy enough to ensure a good stack usage.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/project-euler-problem-255/">Permalink</a> |
<a href="http://coder.cl/2012/04/project-euler-problem-255/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/project-euler-problem-255/&title=project euler: problem 255">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/project-euler-problem-255/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>collatz problem and haskell</title>
		<link>http://coder.cl/2012/04/collatz-problem-and-haskell/</link>
		<comments>http://coder.cl/2012/04/collatz-problem-and-haskell/#comments</comments>
		<pubDate>Wed, 11 Apr 2012 23:34:12 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[haskell]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2378</guid>
		<description><![CDATA[The Collatz problem is Math problem related to a pair of operations which applied recursively will make a number reach 1 always. &#171;The Collatz conjecture is a conjecture in mathematics named after Lothar Collatz, who first proposed it in 1937. The conjecture is also known as the 3n + 1 conjecture, the Ulam conjecture (after [...]]]></description>
			<content:encoded><![CDATA[<p>The Collatz problem is Math problem related to a pair of operations which applied recursively will make a number reach 1 always. <i>&laquo;The Collatz conjecture is a conjecture in mathematics named after Lothar Collatz, who first proposed it in 1937. The conjecture is also known as the 3n + 1 conjecture, the Ulam conjecture (after Stanisław Ulam), Kakutani&#8217;s problem (after Shizuo Kakutani), the Thwaites conjecture (after Sir Bryan Thwaites), Hasse&#8217;s algorithm (after Helmut Hasse), or the Syracuse problem; the sequence of numbers involved is referred to as the hailstone sequence or hailstone numbers, or as wondrous numbers.&raquo;</i></p>
<blockquote><p>
Take any natural number n. If n is even, divide it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process (which has been called &#8220;Half Or Triple Plus One&#8221;, or HOTPO[4]) indefinitely. The conjecture is that no matter what number you start with, you will always eventually reach 1. The property has also been called oneness.
</p></blockquote>
<p><span id="more-2378"></span></p>
<p>It was proposed as problem as part of the <a href='http://projecteuler.net/' title='Project Euler'>Project Euler</a> and by <a href='http://www.programando.org/blog/2012/04/desafio-2012-04-el-problema-de-siracusa/' title='La Sombra de Dijkstra: Desafío 2012-04: El problema de Siracusa'>Eduardo Díaz on his blog</a>, I have implemented my solution in Haskell, because I want to enhance my skills with this language, to reach the most professional coding on it.</p>
<p>My first solution is as follows, is using recursion and <tt>if</tt> statements. Where <tt>if</tt> statements should be avoided, also the <tt>colmax</tt> function can be reduced and eliminated.</p>
<pre name="code" class="brush:haskell;">

module Main (main) where

import System.Environment

collatz :: Int -&gt; [Int] -&gt; [Int]
collatz 1 xs = xs ++ [1]
collatz n xs = if even n
                  then collatz (n `div` 2) $ xs ++ [n]
               else collatz (n * 3 + 1) $ xs ++ [n]

colmax :: [Int] -&gt; Int -&gt; Int -&gt; Int
colmax [] _ m = m
colmax (x:xs) n m = let r = length $ collatz x []
                        in if r &gt; n
                              then colmax xs r x
                           else colmax xs n m

main :: IO ()
main = do [x] &lt;- getArgs
          print $ colmax [1..(read x)] 0 0
</pre>
<p>My second solution uses the Haskell features to avoid <tt>if</tt> statements and some reductions to allow more concise code, mainly due to the lazyness of used functions.</p>
<pre name="code" class="brush:haskell;">

module Main (main) where

import System.Environment
import Data.List
import Data.Ord
import Data.Function

collatz :: Int -&gt; [Int] -&gt; [Int]
collatz n xs | n == 1 = xs ++ [1]
             | even n = collatz (n `div` 2) $ xs ++ [n]
             | otherwise = collatz (n * 3 + 1) $ xs ++ [n]

main :: IO ()
main = do [x] &lt;- getArgs
          print $ fst $ maximumBy (comparing length `on` snd)
            $ fmap (\ x -&gt; (x, collatz x []) ) [1..(read x)]
</pre>
<p>This code looks really well, and seems to be more clear to understand, mainly due to the inline pointfree lambda expression <tt>comparing length `on` snd</tt>. So, the code is easy to understand and clear enough. Without <tt>if</tt> statements and using guards rather than <tt>if</tt>.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/collatz-problem-and-haskell/">Permalink</a> |
<a href="http://coder.cl/2012/04/collatz-problem-and-haskell/#comments">One comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/collatz-problem-and-haskell/&title=collatz problem and haskell">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/collatz-problem-and-haskell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>what is revision control?</title>
		<link>http://coder.cl/2012/04/what-is-revision-control/</link>
		<comments>http://coder.cl/2012/04/what-is-revision-control/#comments</comments>
		<pubDate>Sun, 08 Apr 2012 22:50:33 +0000</pubDate>
		<dc:creator>dmw</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://coder.cl/?p=2370</guid>
		<description><![CDATA[Revision control, also known as version control and source control is the management of changes in the source code of computer programs, documents and any software that is being controlled by Version Control Systems, where someone manages logically organized revisions of those softwares. Where various of those tools are currently integrated in IDEs, Office Suites [...]]]></description>
			<content:encoded><![CDATA[<p>Revision control, also known as version control and source control is the management of changes in the source code of computer programs, documents and any software that is being controlled by Version Control Systems, where someone manages logically organized revisions of those softwares. Where various of those tools are currently integrated in IDEs, Office Suites and similar software. A software developer, for example, uses a VCS to control his source code. There are various well known VCS and DVCS or Distributed Version Control Systems, like <i>git</i>, <i>subversion</i>, <i>mercurial</i>, <i>darcs</i> and others.</p>
<p><span id="more-2370"></span></p>
<p>Currently most VCSs are made with the intention of concurrent development, with many developers modifying the source tree &mdash; including modifications over the same file. With a VCS you can track and expose the modifications over a source tree with a very clear idea of what is happening to the source code, you can see the difference between two <i>commits</i>, where each <i>commit</i> is a modification to the source tree placed on the central repository. Also, most VCSs actually can allow you to create <i>branches</i>, where each branch can be seen as a <i>separate version</i> of the same source code, but with those changes made by an individual developer, and those changes can be <i>merged</i> into the main branch.</p>
<div class="figure">
<a href="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/typical-vcs.png" title="Typical VCS" target="_blank"><img src="http://coder.cl.qfl.wpcdn.arcostream.com/uploads/2012/04/typical-vcs.png" border="0" alt="Typical VCS"/></a></p>
<div>Typical VCS</div>
</div>
<p>Once all changes are verified and tested, and the software is ready for a <i>base line</i>, the master branch or a separate branch is <i>tagged</i>, to mark a software release. Software releases are made based on how the team manages the source tree and the VCS, probably using well defined milestones and goals for each release, allowing well organized structure of the software. Some VCS are allowing those <i>tags</i> to be exported as <i>packages</i>, for example if you have some repositories on Github, you already know that you can create a tag once you have properly verified your software revision and that will allow that tag to be fully downloaded as <i>package</i>, rather than using <i>git</i> itself to checkout the source tree.</p>
<p>So, using separate files to send changes or even using FTP or similar software to maintain a source tree is not an option, you should start using a VCS as your primary repository tool.</p>
<hr />
<p><small>© dmw for <a href="http://coder.cl">coder . cl</a>, 2012. |
<a href="http://coder.cl/2012/04/what-is-revision-control/">Permalink</a> |
<a href="http://coder.cl/2012/04/what-is-revision-control/#comments">No comment</a> |
Add to
<a href="http://del.icio.us/post?url=http://coder.cl/2012/04/what-is-revision-control/&title=what is revision control?">del.icio.us</a>
<br/>
Post tags: <br/>
<br/>
<a href='http://creativecommons.org/licenses/by-nc-sa/3.0/' title='Creative Commons'><img src="http://coder.cl.qfl.wpcdn.arcostream.com/images/creative-commons.png" alt="Creative Commons"> Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0)</a>
</small></p>]]></content:encoded>
			<wfw:commentRss>http://coder.cl/2012/04/what-is-revision-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
<!-- This Quick Cache file was built for ( 2e96b290f6c5ccd2bc6830557c0aba6e coder.cl/category/programming/feed/ ) in 0.53030 seconds, on May 16th, 2012 at 9:33 pm UTC. -->
<!-- This Quick Cache file will automatically expire ( and be re-built automatically ) on May 23rd, 2012 at 9:33 pm UTC -->
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!-- Quick Cache Is Fully Functional :-) ... A Quick Cache file was just served for ( 2e96b290f6c5ccd2bc6830557c0aba6e coder.cl/category/programming/feed/ ) in 0.00054 seconds, on May 18th, 2012 at 12:02 pm UTC. -->
