<?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>Eugeni&#039;s blog &#187; python</title>
	<atom:link href="http://dodonov.net/blog/category/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://dodonov.net/blog</link>
	<description>My view on technology, open-source, Linux and other cool things.</description>
	<lastBuildDate>Sun, 29 Jan 2012 15:11:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>net_monitor lives again</title>
		<link>http://dodonov.net/blog/2009/09/25/net_monitor-lives-again/</link>
		<comments>http://dodonov.net/blog/2009/09/25/net_monitor-lives-again/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 12:52:55 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[devel]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[Linux-Planet]]></category>
		<category><![CDATA[mandriva]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/?p=581</guid>
		<description><![CDATA[Working on Mandriva network tools, I looked on one of the most essential ones the network monitor (net_monitor). It was introduced a couple of releases before, and was mostly doing its job. However, it has a number of flaws and lack of features that motivated us to look closer at it. The net_monitor currently used <a href='http://dodonov.net/blog/2009/09/25/net_monitor-lives-again/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Working on Mandriva network tools, I looked on one of the most essential ones the network monitor (<strong>net_monitor</strong>). It was introduced a couple of releases before, and was mostly doing its job. However, it has a number of flaws and lack of features that motivated us to look closer at it.</p>

<div id="attachment_588" class="wp-caption aligncenter" style="width: 310px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/09/old.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/09/old-300x194.jpg" alt="Our old friend net_monitor, present in your favorite Mandriva distro!" title="old net_monitor" width="300" height="194" class="size-medium wp-image-588" /></a><p class="wp-caption-text">Our old friend net_monitor, present in your favorite Mandriva distro!</p></div>

<p>The <strong>net_monitor</strong> currently used in all Mandriva versions is written in <strong>perl</strong>, is using internal drakx-net api (and is, therefore, only usable on Mandriva), and also have some issues such as memory leaks and non-usual interface. After a few thoughts and discussions we came to conclusion that it would be more adequate to project and rewrite it from scratch, turning it more modular, expansible and focused on common use cases.</p>

<p>Initially, I thought on using perl to write it, so it would still be part of <strong>drakx-net</strong> suite. However, after thinking on the code and the way it should work I felt that my brain was going to melt down <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (perl is a nice language, but it is certainly not that compatible with <strong>me</strong>). So I ended up with python, which is my language of choice (together with <strong>C</strong>). Also, I&#8217;ve received many comments saying that the <strong>net_monitor</strong> is no more relevant, as every desktop environment provides its own network monitoring tool, and it should be dropped from <strong>drakx-net</strong>. By combining those issues, we came to decision that it would be more proper to separate <strong>net_monitor</strong> into a different package &#8211; this way, it won&#8217;t depend on any <strong>drakx-net</strong> internal functionalities, and user could uninstall it if required and use his own network monitoring tool if he wants to. And, at the same time, users would still have a cute little network monitoring application on their machines.</p>

<p>So, as a picture says more than a thousand words, I guess I&#8217;ll just add some pictures here than additional KBs of text <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (<b>EDIT:</b> please note that the look and features of net_monitor have changed significantly in Mandriva since this post):</p>

<div id="attachment_582" class="wp-caption aligncenter" style="width: 310px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor1.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor1-300x214.jpg" alt="net_monitor monitoring a wireless connection" title="net_monitor1" width="300" height="214" class="size-medium wp-image-582" /></a><p class="wp-caption-text">net_monitor monitoring a wireless connection</p></div>

<div id="attachment_583" class="wp-caption aligncenter" style="width: 310px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor2.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor2-300x214.jpg" alt="net_monitor monitoring a connection for which network accounting was not enabled" title="net_monitor2" width="300" height="214" class="size-medium wp-image-583" /></a><p class="wp-caption-text">net_monitor monitoring a connection for which network accounting was not enabled</p></div>

<div id="attachment_584" class="wp-caption aligncenter" style="width: 310px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor3.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor3-300x224.jpg" alt="net_monitor displaying some statistics about your network usage (provided by vnstat)" title="net_monitor3" width="300" height="224" class="size-medium wp-image-584" /></a><p class="wp-caption-text">net_monitor displaying some statistics about your network usage (provided by vnstat)</p></div>

<div id="attachment_585" class="wp-caption aligncenter" style="width: 249px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor4.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor4-239x300.jpg" alt="looking at daily traffic statistics on my notebook for the past month" title="net_monitor4" width="239" height="300" class="size-medium wp-image-585" /></a><p class="wp-caption-text">looking at daily traffic statistics on my notebook for the past month</p></div>

<div id="attachment_586" class="wp-caption aligncenter" style="width: 310px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor5.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor5-300x228.jpg" alt="...and hourly statistics..." title="net_monitor5" width="300" height="228" class="size-medium wp-image-586" /></a><p class="wp-caption-text">...and hourly statistics...</p></div>

<div id="attachment_587" class="wp-caption aligncenter" style="width: 310px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor6.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/09/net_monitor6-300x228.jpg" alt="...and finding our when I killed my bandwidth.." title="net_monitor6" width="300" height="228" class="size-medium wp-image-587" /></a><p class="wp-caption-text">...and finding our when I killed my bandwidth..</p></div>

<p>Surely, this is just an early and preliminary version, with many missing features and such. If you want to give it a try, just install <strong>net_monitor</strong> package, and it will create <strong>/usr/bin/net_monitor</strong> executable for you. It won&#8217;t conflict with existent <strong>net_monitor</strong> from <strong>drakx-net</strong> which is installed in /usr/sbin, so both of them may coexist on your system. If you look at <strong>/usr/share/doc/net_monitor/TODO</strong>, you&#8217;ll see some of the ideas that I intend to add to it, but the idea is to keep it simple and not transform it into an <strong>emacs</strong> of network monitoring <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  . And, of course, feel free to add your comments and suggestions (and bug reports) here!</p>

<p>P.S.: Just to prevent comments like &#8216;you should focus on fixing bugs instead of wasting time writing new things&#8217;. <strong>Net_monitor</strong> is present in Mandriva for years now, and if you look at <a href="https://qa.mandriva.com/buglist.cgi?quicksearch=net_monitor" onclick="urchinTracker('/outgoing/qa.mandriva.com/buglist.cgi?quicksearch=net_monitor&amp;referer=');">bugzilla list</a> it has a number of bugs and issues. So I am not creating a new app &#8211; I am bringing back from the land of the dead an old one <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .</p>

<p>P.P.S.: Answering in advance to another question &#8211; yes, it would work on any Linux distro which has python and pygtk. You&#8217;ll just have to add some tricks into your network startup scripts to enable vnstat integration, but it will work just fine even without that.</p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2009/09/25/net_monitor-lives-again/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Tomoyo GUI</title>
		<link>http://dodonov.net/blog/2009/07/06/tomoyo-gui/</link>
		<comments>http://dodonov.net/blog/2009/07/06/tomoyo-gui/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 14:09:41 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[devel]]></category>
		<category><![CDATA[mandriva]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/?p=473</guid>
		<description><![CDATA[As promised in the previous post, here come some first insight into the GUI for Tomoyo Linux, which will be present in Mandriva 2010. As far as I know, this is the first GUI for Tomoyo out there (except the TomoyoGUI Eclipse Plugin, but it seems to be quite eclipse-bound and abandoned. Its page is <a href='http://dodonov.net/blog/2009/07/06/tomoyo-gui/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>As promised in the previous post, here come some first insight into the GUI for Tomoyo Linux, which will be present in Mandriva 2010.</p>

<div id="attachment_474" class="wp-caption alignnone" style="width: 310px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/07/tomoyogui1.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/07/tomoyogui1-300x232.jpg" alt="Initial view" title="Tomoyo Gui" width="300" height="232" class="size-medium wp-image-474" /></a><p class="wp-caption-text">Initial view</p></div>

<div id="attachment_475" class="wp-caption alignnone" style="width: 310px"><a href="http://dodonov.net/blog/wp-content/uploads/2009/07/tomoyogui2.jpg"><img src="http://dodonov.net/blog/wp-content/uploads/2009/07/tomoyogui2-300x232.jpg" alt="Active security domains" title="Tomoyo Gui 2" width="300" height="232" class="size-medium wp-image-475" /></a><p class="wp-caption-text">Active security domains</p></div>

<p>As far as I know, this is the first GUI for Tomoyo out there (except the <a href="http://tomoyo.sourceforge.jp/wiki/?TOMOYO-GUI" onclick="urchinTracker('/outgoing/tomoyo.sourceforge.jp/wiki/?TOMOYO-GUI&amp;referer=');">TomoyoGUI Eclipse Plugin</a>, but it seems to be quite eclipse-bound and abandoned. Its page is in Japanese, but the all-mighty google translator helped me to take a peek into it). But, of course, I might be wrong &#8211; so please let me know if you know of any other GUI for Tomoyo Linux.</p>

<p>Obviously there are still a lot of things to do:</p>

<ul>
<li>add support for auditing/tomoyo security log into msec</li>
<li>add support for reloading profile on-the-fly</li>
<li>saving/loading/changing settings on the fly</li>
<li>support complex statements</li>
<li>everything else</li>
</ul>

<p>so keep an eye on this blog for more news.</p>

<p>Regards,
Dr. Eugeni <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2009/07/06/tomoyo-gui/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>quick-n-dirty fr-en translator</title>
		<link>http://dodonov.net/blog/2009/01/22/quick-n-dirty-fr-en-translator-2/</link>
		<comments>http://dodonov.net/blog/2009/01/22/quick-n-dirty-fr-en-translator-2/#comments</comments>
		<pubDate>Thu, 22 Jan 2009 15:58:50 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/?p=247</guid>
		<description><![CDATA[Trabalhando com mandriva, vira e mexe encontro gente falando em francês. Como já faz quase 14 que não falo essa língua , decidi apelar pro meu querido python e google translator. Nada como uns 10 minutos de programação voltada a gambiarras . #!/usr/bin/python # # quick and dirty french2english translator # import urllib import urllib2 <a href='http://dodonov.net/blog/2009/01/22/quick-n-dirty-fr-en-translator-2/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Trabalhando com mandriva, vira e mexe encontro gente falando em francês. Como já faz quase 14 que não falo essa língua <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> , decidi apelar pro meu querido python e google translator.</p>

<p>Nada como uns 10 minutos de programação voltada a gambiarras <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .</p>

<pre><code>#!/usr/bin/python
#
# quick and dirty french2english translator
#

import urllib
import urllib2
from subprocess import Popen, PIPE

URL='http://translate.google.com/translate_t#fr|en|'

print "Paste your message"
msg = []
while 1:
    try:
        line = raw_input('&gt;&gt; ')
        msg.append(line)
    except:
        break

s = "&gt;&gt;" + "\n&gt;&gt;".join(msg)

data = "http://translate.google.com/translate_a/t?client=t&amp;%s&amp;fr&amp;tl=en" % urllib.urlencode({'text':s})
req = urllib2.Request('http://translate.google.com/translate_t', data, {'User-Agent':'Mozilla/5.0'})
resp = urllib2.urlopen(req).read()
p = Popen("lynx -dump -stdin | grep -- '&gt;&gt;'", shell=True, stdin=PIPE, stdout=PIPE)
p.stdin.write(resp)
p.stdin.close()
trans = p.stdout.read()
print trans
</code></pre>

<p>Agora é só dar ctrl-c no texto, depois rodar o programinha e dar ctrl-v seguido por ctrl-d <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .</p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2009/01/22/quick-n-dirty-fr-en-translator-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>python performance</title>
		<link>http://dodonov.net/blog/2008/12/09/python-performance/</link>
		<comments>http://dodonov.net/blog/2008/12/09/python-performance/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 16:24:41 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[devel]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/?p=211</guid>
		<description><![CDATA[Ultimamente eu uso bastante programação funcional em python para tudo. Entretanto, fiquei brincando hoje e descobri que nem sempre ela oferece os melhores resultados. Por exemplo, vamos imaginar a função que vai fazer todas as combinações entre os elementos de uma lista. Ela pode ser escrita de forma funcional: # permutate-func def permutate(l): '''Returns all <a href='http://dodonov.net/blog/2008/12/09/python-performance/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Ultimamente eu uso bastante programação funcional em python para tudo. Entretanto, fiquei brincando hoje e descobri que nem sempre ela oferece os melhores resultados.</p>

<p>Por exemplo, vamos imaginar a função que vai fazer todas as combinações entre os elementos de uma lista. Ela pode ser escrita de forma funcional:</p>

<pre><code># permutate-func
def permutate(l):
    '''Returns all possible combinations of list values'''
    return reduce(lambda x, y: y + x, [ [(x, y) for y in l if x != y] for x in l ])
</code></pre>

<p>ou de forma iterativa:</p>

<pre><code># permutate-iter
def permutate(l):
    '''Returns all possible combinations of list values'''
    res = []
    for x in l:
        for y in l:
            if x != y:
                res.append((x, y))
    return res
</code></pre>

<p>Para listas pequenas não temos muita diferença de desempenho. Agora para listas maiores (por exemplo, com 1000 strings):</p>

<pre><code>dups=['string%d' % x for x in range(1000)]
permutate(dups)
</code></pre>

<p>temos os seguintes resultados para programação funcional:</p>

<pre><code># time permutate-func
real    0m24.494s
user    0m20.763s
sys 0m1.698s
</code></pre>

<p>e os seguintes para o algoritmo iterativo:</p>

<pre><code># time permutate-iter
real    0m1.191s
user    0m1.150s
sys 0m0.036s
</code></pre>

<p>O tempo de <strong>24</strong> segundos caiu para apenas <strong>1</strong> segundo!</p>

<p>Qual conclusão tiramos disso? Embora programação funcional é extremamente poderosa, em alguns casos é melhor usar outras soluções para o problema <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  .</p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/12/09/python-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Decorators em python II</title>
		<link>http://dodonov.net/blog/2008/12/06/decorators-em-python-ii/</link>
		<comments>http://dodonov.net/blog/2008/12/06/decorators-em-python-ii/#comments</comments>
		<pubDate>Sat, 06 Dec 2008 19:46:56 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[devel]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/?p=206</guid>
		<description><![CDATA[Descobri mais uma utilidade para os decorators em python: import threading class Thread(threading.Thread): def __init__(self, f): threading.Thread.__init__(self) self.run = f @Thread def func(): print "Hello world!" func.start() Jeito simples e eficientes para criar funções threadizadas. Update: É possível otimizar esse código para não precisar escrever .start() na mão, e deixar as funções compatíveis com a <a href='http://dodonov.net/blog/2008/12/06/decorators-em-python-ii/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Descobri mais uma utilidade para os decorators em python:</p>

<pre><code>import threading

class Thread(threading.Thread):
    def __init__(self, f):
        threading.Thread.__init__(self)
        self.run = f

@Thread
def func():
    print "Hello world!"

func.start()
</code></pre>

<p>Jeito simples e eficientes para criar funções <em>threadizadas</em>.</p>

<p><strong>Update:</strong> É possível otimizar esse código para não precisar escrever <em>.start()</em> na mão, e deixar as funções compatíveis com a sua versão não-threadizada:</p>

<pre><code>class Thread(threading.Thread):
    def __init__(self, f):
        threading.Thread.__init__(self)
        self.run = f

    def __call__(self):
        return self.start()

@Thread
def func():
    print "Hello world!"

func()
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/12/06/decorators-em-python-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Como tirar screenshot em 4 linhas de código</title>
		<link>http://dodonov.net/blog/2008/10/16/como-tirar-screenshot-em-4-linhas-de-codigo/</link>
		<comments>http://dodonov.net/blog/2008/10/16/como-tirar-screenshot-em-4-linhas-de-codigo/#comments</comments>
		<pubDate>Thu, 16 Oct 2008 15:41:40 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/2008/10/16/como-tirar-screenshot-em-4-linhas-de-codigo/</guid>
		<description><![CDATA[Mais um exemplo do poder de python + gtk. Para tirar um screenshot da tela, salvando-o em formato JPEG, o seguinte código é suficiente: from gtk.gdk import * screenshot = Pixbuf(COLORSPACE_RGB, False, 8, screen_width(), screen_height()) screenshot.get_from_drawable(get_default_root_window(), colormap_get_system(), \ 0, 0, 0, 0, screen_width(), screen_height()) screenshot.save("tela.jpg", "jpeg", {"quality": "75"}) (Tá certo, dividi em 5 linhas para <a href='http://dodonov.net/blog/2008/10/16/como-tirar-screenshot-em-4-linhas-de-codigo/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Mais um exemplo do poder de python + gtk. Para tirar um screenshot da tela, salvando-o em formato JPEG, o seguinte código é suficiente:</p>

<pre><code>from gtk.gdk import *
screenshot = Pixbuf(COLORSPACE_RGB, False, 8, screen_width(), screen_height())
screenshot.get_from_drawable(get_default_root_window(), colormap_get_system(), \
    0, 0, 0, 0, screen_width(), screen_height())
screenshot.save("tela.jpg", "jpeg", {"quality": "75"})
</code></pre>

<p>(Tá certo, dividi em 5 linhas para melhorar a legibilidade, mas no fundo são só 4 linhas mesmo).</p>

<p>Uma das maiores vantagens do python para mim é a legibilidade do código, facilidade de programação, e eficiência. Com quantas linhas de código seria possível fazer esse exemplo em qualquer outra linguagem? (Não vale apelar para <code>import -window root tela.jpg</code> porque aí é ImageMagick que faz toda a mágica!) <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/10/16/como-tirar-screenshot-em-4-linhas-de-codigo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>O poder de programação funcional em Python</title>
		<link>http://dodonov.net/blog/2008/10/04/o-poder-de-programacao-funcional-em-python/</link>
		<comments>http://dodonov.net/blog/2008/10/04/o-poder-de-programacao-funcional-em-python/#comments</comments>
		<pubDate>Sat, 04 Oct 2008 16:00:27 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/2008/10/04/o-poder-de-programacao-funcional-em-python/</guid>
		<description><![CDATA[Cada vez mais e mais eu gosto dos recursos de programação funcional em python. E, como eu uso essa linguagem para resolver tarefas mais variáveis, não dá para não perceber que a velocidade de desenvolvimento e eficiência do código tornam-se cada vez melhores, por simplesmente aplicar técnicas de programação funcional. Por exemplo, sem a programação <a href='http://dodonov.net/blog/2008/10/04/o-poder-de-programacao-funcional-em-python/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Cada vez mais e mais eu gosto dos recursos de programação funcional em python. E, como eu uso essa linguagem para resolver tarefas mais variáveis, não dá para não perceber que a velocidade de desenvolvimento e eficiência do código tornam-se cada vez melhores, por simplesmente aplicar técnicas de programação funcional.</p>

<p>Por exemplo, sem a programação funcional, eu usava o seguinte código antes para ler um arquivo com uma série de números, e determinar a média dos valores:</p>

<p><pre>
fd = open("data.log")
data = fd.readlines()
valores = []</p>

<h1>le os dados</h1>

<p>for line in data:
    line_val = float(line.strip())
    valores.append(line_val)</p>

<h1>calcula a media</h1>

<p>media = 0
for item in valores:
    media += item
media /= len(media)
</pre></p>

<p>Re-escrevendo isso com técnicas de programação funcional, temos o seguinte:</p>

<p><pre></p>

<h1>le os valores do arquivo, transformando-os para floats, e ignorando strings vazias</h1>

<p>valores = [float(val) for val in open("data.log").readlines() if len(val) > 1]</p>

<h1>calcula a media, somando todos os valores e dividindo pelo número de elementos no vetor</h1>

<p>media = reduce(lambda x, y: x+y, valores) / len(valores)
</pre></p>

<p>(É óbvio que é só um exemplo rápido, não estou tratando as excessões aqui, mas para resolver problemas simples do dia-a-dia é mais de que suficiente!)</p>

<p>O essencial são as funções <b>lambda</b>, <b>map</b>, <b>reduce</b> e <b>filter</b>. Todos os detalhes interessantes sobre esse estilo de programação eu achei <a href="http://www.slideshare.net/adambyrtek/functional-programming-with-python" onclick="urchinTracker('/outgoing/www.slideshare.net/adambyrtek/functional-programming-with-python?referer=');">aqui</a>, e recomendo essa apresentação para todos!</p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/10/04/o-poder-de-programacao-funcional-em-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Roadmap &#8211; Django Code &#8211; Trac</title>
		<link>http://dodonov.net/blog/2008/09/02/roadmap-django-code-trac/</link>
		<comments>http://dodonov.net/blog/2008/09/02/roadmap-django-code-trac/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 17:53:37 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/2008/09/02/roadmap-django-code-trac/</guid>
		<description><![CDATA[De acordo com o Django Roadmap, faltam somente 9 tickets para a versão 1.0! Finalmente, depois de alguns anos de desenvolvimento, veremos a versão 1.0 do melhor framework para construção de sites no universo . Roadmap &#8211; Django Code &#8211; Trac]]></description>
			<content:encoded><![CDATA[<p>De acordo com o Django Roadmap, faltam somente 9 tickets para a versão 1.0!</p>

<p>Finalmente, depois de alguns anos de desenvolvimento, veremos a versão 1.0 do melhor framework para construção de sites no universo <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>

<p><a href="http://code.djangoproject.com/roadmap" onclick="urchinTracker('/outgoing/code.djangoproject.com/roadmap?referer=');">Roadmap &#8211; Django Code &#8211; Trac</a></p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/09/02/roadmap-django-code-trac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Functional Programming with Python (RuPy 2008)</title>
		<link>http://dodonov.net/blog/2008/08/05/functional-programming-with-python-rupy-2008/</link>
		<comments>http://dodonov.net/blog/2008/08/05/functional-programming-with-python-rupy-2008/#comments</comments>
		<pubDate>Tue, 05 Aug 2008 02:49:07 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/2008/08/05/functional-programming-with-python-rupy-2008/</guid>
		<description><![CDATA[Uma apresentação excellente sobre programação funcional em python. Recomendo! Functional Programming with Python (RuPy 2008)]]></description>
			<content:encoded><![CDATA[<p>Uma apresentação excellente sobre programação funcional em python. Recomendo!</p>

<p><a href="http://www.slideshare.net/adambyrtek/functional-programming-with-python" onclick="urchinTracker('/outgoing/www.slideshare.net/adambyrtek/functional-programming-with-python?referer=');">Functional Programming with Python (RuPy 2008)</a></p>

<p><hints id="hah_hints"></hints></p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/08/05/functional-programming-with-python-rupy-2008/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Slashdot &#124; World&#8217;s Shortest P2P App: 15 Lines</title>
		<link>http://dodonov.net/blog/2008/07/29/slashdot-worlds-shortest-p2p-app-15-lines/</link>
		<comments>http://dodonov.net/blog/2008/07/29/slashdot-worlds-shortest-p2p-app-15-lines/#comments</comments>
		<pubDate>Tue, 29 Jul 2008 22:34:18 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[devel]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/2008/07/29/slashdot-worlds-shortest-p2p-app-15-lines/</guid>
		<description><![CDATA[Pois é &#8211; é possível fazer uma implementação completa de rede peer-to-peer usando somente 15 linhas de python (com um pouco de gambiarras envolvendo lambdas ). Slashdot &#124; World&#8217;s Shortest P2P App: 15 Lines Impressionante.. como tudo em python!]]></description>
			<content:encoded><![CDATA[<p>Pois é &#8211; é possível fazer uma implementação completa de rede peer-to-peer usando somente 15 linhas de python (com um pouco de gambiarras envolvendo lambdas <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ).</p>

<p><a href="http://yro.slashdot.org/article.pl?sid=05/01/06/2324211&#038;from=rss" onclick="urchinTracker('/outgoing/yro.slashdot.org/article.pl?sid=05/01/06/2324211_038_from=rss&amp;referer=');">Slashdot | World&#8217;s Shortest P2P App: 15 Lines</a></p>

<p>Impressionante.. como tudo em python!</p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/07/29/slashdot-worlds-shortest-p2p-app-15-lines/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Python scripting</title>
		<link>http://dodonov.net/blog/2008/06/27/python-scripting/</link>
		<comments>http://dodonov.net/blog/2008/06/27/python-scripting/#comments</comments>
		<pubDate>Fri, 27 Jun 2008 17:27:50 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[music]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/2008/06/27/python-scripting/</guid>
		<description><![CDATA[Talvez pode ser útil para alguém . Este script pega a lista de músicas do mpd, seleciona um playlist aleatório, e coloca no ipod shuffle. !/usr/bin/python import os,random ipod mountpoint - must be mounted! MOUNTPOINT="/mnt/ipod" def get_files(): '''Reads the list of mp3 files from mpd database''' data = open(".mpd.db").readlines() files = [] for l in <a href='http://dodonov.net/blog/2008/06/27/python-scripting/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Talvez pode ser útil para alguém <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>

<p>Este script pega a lista de músicas do mpd, seleciona um playlist aleatório, e coloca no ipod shuffle.</p>

<p><pre>
<code></p>

<h1>!/usr/bin/python</h1>

<p>import os,random</p>

<h1>ipod mountpoint - must be mounted!</h1>

<p>MOUNTPOINT="/mnt/ipod"</p>

<p>def get_files():
    '''Reads the list of mp3 files from mpd database'''
    data = open(".mpd.db").readlines()
    files = []
    for l in data:
        fields = l.strip().split(":",2)
        if len(fields) &lt; 2:
            continue
        if fields[0] == "file":
            files.append(fields[1].strip())
    return files</p>

<p>def get_free_space():
    '''Gets available space from IPOD partition'''
    line = os.popen("df -k %s | awk '{print $4}'" % MOUNTPOINT).readlines()[-1]
    return int(line)</p>

<p>def fullcp(file, target):
    '''copies file and directory structure'''
    os.system('tar cf - "%s" | (cd %s &amp;&amp; tar xf -)' % (file, target))</p>

<p>if <strong>name</strong> == "<strong>main</strong>":
    try:
        os.mkdir("%s/mp3" % MOUNTPOINT)
    except:
        print "Not creating %s/mp3!" % MOUNTPOINT
    files = get_files()
    freespace = get_free_space()
    while 1:
        # pega arquivo aleatorio
        pos = random.randint(0, len(files))
        curfile = files[pos]
        del files[pos]
        # determina o tamanho
        res = os.stat(curfile)
        size = res[6] / 1000
        if freespace - size &lt; 1:
            break
        freespace -= size
        # copia
        print "Copying [%8dK left]: %s" % (freespace, curfile)
        fullcp(curfile, "%s/mp3/" % MOUNTPOINT)
</code>
</pre></p>

<p>É melhor usar ele junto com <a href="http://shuffle-db.sourceforge.net/" onclick="urchinTracker('/outgoing/shuffle-db.sourceforge.net/?referer=');">Shuffle-DB</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/06/27/python-scripting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Decorators em python</title>
		<link>http://dodonov.net/blog/2008/04/15/decorators-em-python/</link>
		<comments>http://dodonov.net/blog/2008/04/15/decorators-em-python/#comments</comments>
		<pubDate>Tue, 15 Apr 2008 23:56:51 +0000</pubDate>
		<dc:creator>eugeni</dc:creator>
				<category><![CDATA[portuguese]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dodonov.net/blog/2008/04/15/decorators-em-python/</guid>
		<description><![CDATA[Por alguns meses fiquei pensando &#8211; para que servem os decorators em python? Ultimamente é fácil ver código do tipo: @algum_metodo def function(params): ... Aí hoje finalmente decidi descobrir como que isso funciona, e para que serve. Em poucas palavras &#8211; realmente, decoratos são bem úteis. Eles não introduzem muitas novidades na linguagem, mas possibilitam <a href='http://dodonov.net/blog/2008/04/15/decorators-em-python/'>[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Por alguns meses fiquei pensando &#8211; para que servem os <em>decorators</em> em python? Ultimamente é fácil ver código do tipo:</p>

<pre><code>@algum_metodo
def function(params):
...
</code></pre>

<p>Aí hoje finalmente decidi descobrir como que isso funciona, e para que serve.</p>

<p>Em poucas palavras &#8211; realmente, decoratos são bem úteis. Eles não introduzem muitas novidades na linguagem, mas possibilitam evitar duplicação de código, e facilitar a implementação.</p>

<p>Por exemplo, suponhamos que precisamos rastrear todas as chamadas a uma de terminada função. Quais são as alternativas que temos?</p>

<ul>
    <li>Mudar a função para ela fazer um <em>print</em> toda vez que ela é executada, e toda vez que ela termina;</li>
    <li>Fazer um <em>wrapper</em> para essa função;</li>
    <li>Usar um decorator.</li>
</ul>

<p>Vamos pensar em uma função bem simples:</p>

<pre><code>def minhafunc(s):
    print "&lt;&lt;; %s &gt;&gt; " % s
</code></pre>

<p>Como que poderiamos fazer o wrapper para esta função esta função? Por exemplo:</p>

<pre><code> def wrapper(func):
      print "entrando na func!"
      ret = func()
      print "saindo da func!"
      return ret&lt;/code&gt;

      result = wrapper(minhafunc())
</code></pre>

<p>Obviamente, isso funciona.. Mas para funções bem simples.</p>

<p>Um outro jeito seria transformar função automaticamente:</p>

<pre><code> def logger(func):
     def wrapper(param):
         print "entrando na func!"
         ret = func(param)
         print "saindo da func!"
         return ret
    return wrapper

    minhafunc = logger(minhafunc)
</code></pre>

<p>E agora vem a parte &#8220;mágica&#8221;. Decorators simplesmente permitem com que você evite a transformação de <em>python</em> em <em>LISP</em>, tirando a necessidade de empacotamento explícito dessas funções. Em outras palavras:</p>

<pre><code> @logger
     def minhafunc():
           ...
</code></pre>

<p>faz a mesma coisa que:</p>

<pre><code>minhafunc = logger(minhafunc)
</code></pre>

<p>só que logo após a declaração da função.</p>

<p>Só isso <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . É claro, que tem várias outras utilidades os decorators &#8211; facilitar o uso de threads em PyGTK; facilitar desenvolvimento de código sincronizado, etc.</p>

<p>Sem falar que fica bem mais legível o código:</p>

<pre><code>@synchronized
@logged
def minhafunc():
     ...
</code></pre>

<p>P.S.: O wordpress, para variar, deixa zoado o código.. Mas logo-logo este site vai migrar para Django. Desde que aprendi a mexer com ele, a minha opinião sobre os frameworks web mudou.. e muito! <img src='http://dodonov.net/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://dodonov.net/blog/2008/04/15/decorators-em-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Served from: dodonov.net @ 2012-02-07 12:53:55 -->
