<?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>def Tenako.blog () end &#187; programacion</title>
	<atom:link href="http://blog.tenako.com/category/programacion/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tenako.com</link>
	<description></description>
	<lastBuildDate>Sun, 10 Jul 2011 10:15:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>jetty: Shit happens!!</title>
		<link>http://blog.tenako.com/2011/04/09/jetty-shit-happens/</link>
		<comments>http://blog.tenako.com/2011/04/09/jetty-shit-happens/#comments</comments>
		<pubDate>Sat, 09 Apr 2011 12:11:47 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[programacion]]></category>
		<category><![CDATA[shit]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=277</guid>
		<description><![CDATA[For the impatient readers: Don&#8217;t set Jetty&#8217;s &#60;stopPort&#62; to the same &#60;port&#62; where Jetty is running or you might run into some nasty-hard-to-debug problem. Now a full explanation: Imagine the following scenario, Here we have to web services, A and B, both running on the same machine on Jetty webserver and one of them is listening [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://blog.tenako.com/wp-content/uploads/2011/04/empty_response_localhost2.png" ></a>For the impatient readers:</p>
<p><strong>Don&#8217;t set Jetty&#8217;s &lt;stopPort&gt; to the same &lt;port&gt; where Jetty is running or you might run into some nasty-hard-to-debug problem.</strong></p>
<p><strong><span id="more-277"></span><br />
</strong></p>
<p>Now a full explanation:</p>
<p>Imagine the following scenario,</p>
<p><a href="http://blog.tenako.com/wp-content/uploads/2011/04/scenary2.png" ><img class="aligncenter size-full wp-image-311" title="scenary" src="http://blog.tenako.com/wp-content/uploads/2011/04/scenary2.png" alt="" width="500" height="175" /></a></p>
<p>Here we have to web services, A and B, both running on the same machine on <em>Jetty </em>webserver and one of them is listening for petitions on port 9090 (configured via de maven-jetty-plugin). Web service A has to request some data to B and process its reply. Nothing unusual.</p>
<p>So A issue a request to <strong>http://localhost:9090/&lt;path&gt; </strong>expecting an XML response as a result of doing it. But it gets nothing, <em>nada, nichts.</em></p>
<p><em><span style="font-style: normal;"><a href="http://blog.tenako.com/wp-content/uploads/2011/04/empty_response_localhost2.png" ><img class="aligncenter size-full wp-image-312" style="display: block; margin-left: auto; margin-right: auto; border: 0px initial initial;" title="empty_response_localhost" src="http://blog.tenako.com/wp-content/uploads/2011/04/empty_response_localhost2.png" alt="" width="500" height="175" /></a></span> </em></p>
<div><em><br />
</em></div>
<p>Well, at this moment the first thing that came through my mind was that I did something wrong while coding or configurating any of the web services. So I checked everything, but it seemed right. My next move was to create a fake request with <em>curl </em>just to see what happened.</p>
<p>What happened misleaded me even more: web service B was responding. WTF!!</p>
<p><a href="http://blog.tenako.com/wp-content/uploads/2011/04/response_with_curl3.png" ><img class="aligncenter size-full wp-image-316" title="response_with_curl" src="http://blog.tenako.com/wp-content/uploads/2011/04/response_with_curl3.png" alt="" width="500" height="189" /></a></p>
<p>So I went one level down. I ran <em>tcpdump. </em>And what I got? I discovered that the main difference between the requests issued by web service A and <em>curl</em> was the ip version they used: web service A was using ipv4 and <em>curl</em> ipv6.</p>
<p>To force both requests (from the web service and curl) to use ipv4, I run <em>curl</em> against the web service B but now instead of <em>localhost </em>I used 127.0.0.1. And the response was empty, just like if the request came from web service A.</p>
<p><a href="http://blog.tenako.com/wp-content/uploads/2011/04/empty_response_curl_127001.png" ></a><a href="http://blog.tenako.com/wp-content/uploads/2011/04/empty_response_curl_1270011.png" ><img class="aligncenter size-full wp-image-317" title="empty_response_curl_127001" src="http://blog.tenako.com/wp-content/uploads/2011/04/empty_response_curl_1270011.png" alt="" width="500" height="189" /></a><br />
So I thought that all of my troubles had to do with the ip stack beeing used. And I wasted some hours<br />
trying to figure out what was wrong with it.<br />
As I was really desperate with all this, I download Jetty sources to debug it on eclipse. I wanted to know<br />
what was happening with my requests. And here was were light came to me by chance. While debugging Jetty,<br />
an incomming connection from  internet arraived to my &lt;public_ip&gt;:9090  (I guess it was someone doing some kind of portscanning) and got stuck on my breakpoints&#8230;</p>
<p>Mmmm, wait a moment&#8230;</p>
<div><a href="http://blog.tenako.com/wp-content/uploads/2011/04/suspicious-template.jpg" ><img class="aligncenter size-full wp-image-299" title="suspicious-template" src="http://blog.tenako.com/wp-content/uploads/2011/04/suspicious-template.jpg" alt="" width="273" height="233" /></a></div>
<p>Yep, internet addresses are ipv4 only (for most of us), so this ruled out any kind of problem with the ipv4 stack or shit. Now I began to see the light. This was some mess with the adresses.</p>
<p>Just to check I did an alias in my loopback interface to 127.0.0.2 and run again the request with <em>curl </em>to that ip<em>. </em>This time being successful. Ooook.</p>
<p>So, whats wrong with 127.0.0.1:9090?</p>
<p>Netstat output,</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">13</span>:<span style="color: #000000;">29</span>:<span style="color: #000000;">46</span> ~ $ <span style="color: #c20cb9; font-weight: bold;">netstat</span> <span style="color: #660033;">-f</span> inet <span style="color: #660033;">-an</span>
Active Internet connections <span style="color: #7a0874; font-weight: bold;">&#40;</span>including servers<span style="color: #7a0874; font-weight: bold;">&#41;</span>
Proto Recv-Q Send-Q  Local Address          Foreign Address        <span style="color: #7a0874; font-weight: bold;">&#40;</span>state<span style="color: #7a0874; font-weight: bold;">&#41;</span>
tcp4       <span style="color: #000000;">0</span>      <span style="color: #000000;">0</span>  127.0.0.1.9090         <span style="color: #000000; font-weight: bold;">*</span>.<span style="color: #000000; font-weight: bold;">*</span>                    LISTEN
tcp46      <span style="color: #000000;">0</span>      <span style="color: #000000;">0</span>  <span style="color: #000000; font-weight: bold;">*</span>.9090                 <span style="color: #000000; font-weight: bold;">*</span>.<span style="color: #000000; font-weight: bold;">*</span>                    LISTEN
...</pre></div></div>

<p>Lsof output,</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">13</span>:<span style="color: #000000;">49</span>:<span style="color: #000000;">39</span> ~ $ lsof <span style="color: #660033;">-i</span> :<span style="color: #000000;">9090</span>
COMMAND PID     USER   FD   TYPE     DEVICE SIZE<span style="color: #000000; font-weight: bold;">/</span>OFF NODE NAME
java    <span style="color: #000000;">239</span> madtrick   94u  IPv6 0x08c10f80      0t0  TCP <span style="color: #000000; font-weight: bold;">*</span>:websm <span style="color: #7a0874; font-weight: bold;">&#40;</span>LISTEN<span style="color: #7a0874; font-weight: bold;">&#41;</span>
java    <span style="color: #000000;">239</span> madtrick   95u  IPv6 0x08c11460      0t0  TCP <span style="color: #7a0874; font-weight: bold;">&#91;</span>::127.0.0.1<span style="color: #7a0874; font-weight: bold;">&#93;</span>:websm <span style="color: #7a0874; font-weight: bold;">&#40;</span>LISTEN<span style="color: #7a0874; font-weight: bold;">&#41;</span></pre></div></div>

<p>I have two sockets listening on port 9090 and both belong to the same process (as reported by lsof), my Jetty Server.  But requests to 127.0.0.1:9090 are lost meanwhile requests to &lt;any_other_ip&gt;:9090 are processed by the server.</p>
<p>Lets try something, lets change the &lt;stopPort&gt; to 9091 and see what happens&#8230;<br />
Request from web service A, OK.<br />
Request from <em>curl, </em>OK.</p>
<p>Run netstat again,</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">13</span>:<span style="color: #000000;">59</span>:<span style="color: #000000;">50</span> ~ $ <span style="color: #c20cb9; font-weight: bold;">netstat</span> <span style="color: #660033;">-f</span> inet <span style="color: #660033;">-an</span>
Active Internet connections <span style="color: #7a0874; font-weight: bold;">&#40;</span>including servers<span style="color: #7a0874; font-weight: bold;">&#41;</span>
Proto Recv-Q Send-Q  Local Address          Foreign Address        <span style="color: #7a0874; font-weight: bold;">&#40;</span>state<span style="color: #7a0874; font-weight: bold;">&#41;</span>
tcp4       <span style="color: #000000;">0</span>      <span style="color: #000000;">0</span>  127.0.0.1.9091         <span style="color: #000000; font-weight: bold;">*</span>.<span style="color: #000000; font-weight: bold;">*</span>                    LISTEN
tcp46      <span style="color: #000000;">0</span>      <span style="color: #000000;">0</span>  <span style="color: #000000; font-weight: bold;">*</span>.9090                 <span style="color: #000000; font-weight: bold;">*</span>.<span style="color: #000000; font-weight: bold;">*</span>                    LISTEN
...</pre></div></div>

<p>And lsof for ports 9090 and 9091,</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">14</span>:00:<span style="color: #000000;">48</span> ~ $ lsof <span style="color: #660033;">-i</span> :<span style="color: #000000;">9090</span>
COMMAND PID     USER   FD   TYPE     DEVICE SIZE<span style="color: #000000; font-weight: bold;">/</span>OFF NODE NAME
java    <span style="color: #000000;">301</span> madtrick   93u  IPv6 0x08c10f80      0t0  TCP <span style="color: #000000; font-weight: bold;">*</span>:websm <span style="color: #7a0874; font-weight: bold;">&#40;</span>LISTEN<span style="color: #7a0874; font-weight: bold;">&#41;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #000000;">14</span>:00:<span style="color: #000000;">55</span> ~ $ lsof <span style="color: #660033;">-i</span> :<span style="color: #000000;">9091</span>
COMMAND PID     USER   FD   TYPE     DEVICE SIZE<span style="color: #000000; font-weight: bold;">/</span>OFF NODE NAME
java    <span style="color: #000000;">301</span> madtrick   94u  IPv6 0x08c11460      0t0  TCP <span style="color: #7a0874; font-weight: bold;">&#91;</span>::127.0.0.1<span style="color: #7a0874; font-weight: bold;">&#93;</span>:xmltec-xmlmail <span style="color: #7a0874; font-weight: bold;">&#40;</span>LISTEN<span style="color: #7a0874; font-weight: bold;">&#41;</span></pre></div></div>

<p>So you see, Jetty opens another socket which listens on 127.0.0.1:&lt;stopPort&gt;  (lets call it jetty stop daemon) and being that an explicit address it has precedence over the catch all 0.0.0.0:9090 (where Jetty is listening). That&#8217;s why my requests to 127.0.0.1:9090 returned nothing.</p>
<p>This is what was happening before,</p>
<div><a href="http://blog.tenako.com/wp-content/uploads/2011/04/scenary_daemon_bad1.png" ><img class="aligncenter size-full wp-image-313" title="scenary_daemon_bad" src="http://blog.tenako.com/wp-content/uploads/2011/04/scenary_daemon_bad1.png" alt="" width="500" height="215" /></a></div>
<p>And this is whats happens now,</p>
<div><a href="http://blog.tenako.com/wp-content/uploads/2011/04/scenary_daemon_well1.png" ><img class="aligncenter size-full wp-image-339" title="scenary_daemon_well" src="http://blog.tenako.com/wp-content/uploads/2011/04/scenary_daemon_well1.png" alt="" width="500" height="215" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2011/04/09/jetty-shit-happens/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>erlang: mochiweb + BOSH</title>
		<link>http://blog.tenako.com/2010/08/11/erlang-mochiweb-bosh/</link>
		<comments>http://blog.tenako.com/2010/08/11/erlang-mochiweb-bosh/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 19:49:09 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[erlang]]></category>
		<category><![CDATA[programacion]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=215</guid>
		<description><![CDATA[I&#8217;ve been playing with mochiweb for a while and I found it a nice way to improve my Erlang knowledge. For making things more interesting I want to use mochiweb to implement a BOSH manager. If you are not tempted to read the spec documentation about BOSH I can give you this excerpt: BOSH, the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing with <a title="mochiweb at github" href="http://github.com/mochi/mochiweb" onclick="javascript:pageTracker._trackPageview('/outbound/article/github.com');" target="_blank">mochiweb</a> for a while and I found it a nice way to improve my <em>Erlang</em> knowledge. For making things more interesting I want to use mochiweb to implement a <a title="BOSH spect" href="http://xmpp.org/extensions/xep-0124.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/xmpp.org');">BOSH</a> manager. If you are not tempted to read the spec documentation about <em>BOSH </em>I can give you this excerpt:</p>
<blockquote><p>BOSH, the technology defined in this specification, essentially provides  a &#8220;drop-in&#8221; alternative to a long-lived, bidirectional TCP connection &#8230;</p>
<p>For applications that require both &#8220;push&#8221; and &#8220;pull&#8221; semantics, BOSH is  significantly more bandwidth-efficient and responsive than most other  bidirectional HTTP-based transport protocols and the techniques now  commonly known as &#8220;Ajax&#8221;&#8230;</p></blockquote>
<p>That is, BOSH is quite similar to <a title="WebSockets spec" href="http://dev.w3.org/html5/websockets/" onclick="javascript:pageTracker._trackPageview('/outbound/article/dev.w3.org');">WebSockets</a></p>
<p>So, at this point is where mochiweb comes in. It will provide the framework for handling the HTTP requests where the BOSH requests themselves are wrapped. But before going any further lets explain how mochiweb works, with a picture:</p>
<p><a href="http://blog.tenako.com/wp-content/uploads/2010/08/mochiweb_400W3.png" ><img class="aligncenter size-full wp-image-228" title="mochiweb_400W" src="http://blog.tenako.com/wp-content/uploads/2010/08/mochiweb_400W3.png" alt="" width="400" height="333" /></a></p>
<p>What do we have here?</p>
<ol>
<li>An HTTP request comes in, to the address and port <em>mochiweb </em>is configured.</li>
<li>If it&#8217;s a valid HTTP request, a mochiweb_request &#8220;object&#8221; is created and the handler function at the callback module (which is provided when mochiweb starts) is invoked with this <em>mochiweb_request </em>as a parameter. Give a look to <a title="parameterized erlang modules" href="http://userprimary.net/posts/2009/03/04/two-erlang-finds-atomic-names-and-parameterized-modules/" onclick="javascript:pageTracker._trackPageview('/outbound/article/userprimary.net');">this</a> and <a title="parameterized erlang modules proposal" href="http://www.google.es/url?sa=t&amp;source=web&amp;cd=2&amp;ved=0CBwQFjAB&amp;url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.58.79%26rep%3Drep1%26type%3Dpdf&amp;ei=FPdiTNDiAYXl4Ab59LS2Cg&amp;usg=AFQjCNF1B71sV5kf_cGAZx7f8eNm9w5XlQ&amp;sig2=lEngi35jymjdZ0TxxCDUbQ" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.google.es');">this</a> to get a grasp at parameterized modules if you wish to know more about &#8220;objects&#8221; on <em>Erlang</em>.</li>
</ol>
<p>Easy, huh?</p>
<p>And what is all that about a BOSH manager? The BOSH manager handles the connection between the resource-client (for example a browser) and the resource-owner (for example a server). It has to keep HTTP connections opened to fake this bidirectional comunication. That is, the client ask for something about the resource and so it sends a request to the BOSH manager, the BOSH manager sends this same request to the server and waits for a reply. If a reply arrives, then it&#8217;s forwarded to the client. But aside from this, which is no more than plain-old AJAX, BOSH offers PUSH technologies. If any event happens at the server and the client has to be notified, the BOSH manager forwards the event to the client. That&#8217;s why it has to keep HTTP connections opened, it must have a valid path.</p>
<p>In <em>Erlang, </em>creating and destroying processes is extremely cheap, so what I wanted was  to spawn a new process for each single BOSH session (between one client and one or multiple servers). Lets give another picture:</p>
<p><a href="http://blog.tenako.com/wp-content/uploads/2010/08/bosh_manager_500.png" ><img class="aligncenter size-full wp-image-234" title="bosh_manager_500" src="http://blog.tenako.com/wp-content/uploads/2010/08/bosh_manager_500.png" alt="" width="500" height="241" /></a></p>
<p>On the picture above, there are two separate BOSH managers (each of them is a <em>Erlang</em> process) BM1 and BM2 which handler connections from one client to one server (BM1 ) and from another different client to two servers (BM2)</p>
<p>To complete the setup I used, I have to talk about <a title="strophejs home page" href="http://code.stanziq.com/strophe/" onclick="javascript:pageTracker._trackPageview('/outbound/article/code.stanziq.com');">StropheJS</a> which is a library for writing xmpp clients (BOSH is an xmpp extension).</p>
<p>Well, once I have explained more or less what I&#8217;m doing with mochiweb and BOSH, lets got to the details.</p>
<p>First, lets talk about my callback module for mochiweb. It&#8217;s not a ver big one nor a complicated one, not because I don&#8217;t know how to move on but was the error I&#8217;ll talk later which didn&#8217;t allow me to progress. So ladys and gentleman here is my litle callback module:</p>
<pre class="brush: erlang;">

-module(mochibosh).

-export([start/0, start/1, stop/0]).
-export([handler/1]).

-export([init/0]).

-record(mochibosh_state,{procs, xml_models}).

handler(Req) -&gt;
 io:format(&quot;CALLBACK. Petition on port ~p  ~n&quot;, [inet:port(Req:get(socket))]),
 mochibosh ! Req,
 ok.

start() -&gt;
 erlang:register(mochibosh, spawn_link(?MODULE, init, [])),
 start([{ip,&quot;192.168.1.110&quot;}, {port, 8888}]).

start(Options) -&gt;
 Options2 = [{loop, {?MODULE, handler}} | Options],
 mochiweb_http:start(Options2).

stop() -&gt;
 mochibosh ! exit,
 mochiweb_http:stop().

% Internal API

init() -&gt;
 Models = init_xml_models(),
 loop(#mochibosh_state{procs = dict:new(), xml_models = Models}).

loop(State = #mochibosh_state{procs = Procs, xml_models = Models}) -&gt;
 receive
 Request -&gt;
 io:format(&quot;SPAWNED PROCESS. Request received on port ~p ~n&quot;, [inet:port(Request:get(socket))]),
 loop(State)
 end.

init_xml_models()-&gt;
 [{bosh_init, init_xml_model(&quot;bosh_init.xsd&quot;)}].

init_xml_model(Xsdfile) -&gt;
 {ok, Model} = erlsom:compile_xsd_file(Xsdfile),
 Model.
</pre>
<p>It very easy. If want to use it, you cant fire a <em>Erlang</em> terminal and type <em>mochibosh:start() </em>and it will be up and running. The loop<br />
option in the tuple that is passed to <em>mochiweb_http:start </em>is used to provide the callback module. In this case is the mochibosh module itself (?MODULE)</p>
<p>So what would happen if we try it&#8230;.</p>
<p>In one terminal we fire the <em>Erlang</em> shell (erl) and start mochibosh:</p>
<pre class="brush: bash;">

20:38:25 mochibosh $ erl
Erlang R14A (erts-5.8) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.8  (abort with ^G)
1&gt; mochibosh:start().
{ok,&lt;0.34.0&gt;}
</pre>
<p>In another terminal we issue a simple request with <a title="curl homepage" href="http://curl.haxx.se/" onclick="javascript:pageTracker._trackPageview('/outbound/article/curl.haxx.se');">curl</a>&#8230;</p>
<pre class="brush: bash;">

20:40:19 mochibosh $ curl -v http://192.168.1.110:8888
* About to connect() to 192.168.1.110 port 8888 (#0)
*   Trying 192.168.1.110... connected
* Connected to 192.168.1.110 (192.168.1.110) port 8888 (#0)
&gt; GET / HTTP/1.1
&gt; User-Agent: curl/7.21.0 (i386-apple-darwin10.2.0) libcurl/7.21.0 OpenSSL/1.0.0a zlib/1.2.5 libidn/1.19
&gt; Host: 192.168.1.110:8888
&gt; Accept: */*
&gt;
^C
</pre>
<p>And meanwhile in the <em>Erlang </em>shell..</p>
<pre class="brush: bash;">

{ok,&lt;0.34.0&gt;}
CALLBACK. Petition on port {ok,8888}
SPAWNED PROCESS. Request received on port {ok,8888}

2&gt;
</pre>
<p>GREAT!! Everything seems to work. So now, I decided to move on and begin to develop my BOSH manager.</p>
<p>As I sayed, I&#8217;ll be using StropheJS for the browser/client side. For testing purpouses I began using one of the examples shipped with the library: <a title="echobot at github" href="http://github.com/metajack/strophejs/blob/master/examples/echobot.js" onclick="javascript:pageTracker._trackPageview('/outbound/article/github.com');">echobot.js </a>.This example will issue a request for starting a BOSH session (among other things) and that is perfect for my testing pourposes. So lets, try.</p>
<p>(Imagin that the request is sent from echobot to the BOSH manager)</p>
<p>And I expecto to get the same reply from my callback module as when I tryed it with curl. Lets see:</p>
<pre class="brush: bash;">

CALLBACK. Petition on port {ok,8888}
SPAWNED PROCESS. Request received on port {error,einval}
</pre>
<p>WTF!!!!! What&#8217;s that of {error, einval}. Well, I can see that&#8217;s an error, but why? As this post is getting really big, I&#8217;ll leave the explanation for another one.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2010/08/11/erlang-mochiweb-bosh/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Install mochiweb with macports</title>
		<link>http://blog.tenako.com/2010/07/19/install-mochiweb-with-macports/</link>
		<comments>http://blog.tenako.com/2010/07/19/install-mochiweb-with-macports/#comments</comments>
		<pubDate>Mon, 19 Jul 2010 17:32:02 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/2010/07/19/install-mochiweb-with-macports/</guid>
		<description><![CDATA[Just two things: I installed this on a MacBook with a CoreDuo processor. By default macports will try to use all avaliable processors for the building stuff (2 on my case) with the -j option of Make. On my case this ended up with weird compilation errors (something like a race condition between the to [...]]]></description>
			<content:encoded><![CDATA[<p>Just two things:</p>
<ol>
<li>I installed this on a MacBook with a CoreDuo processor. By default macports will try to use all avaliable processors for the building stuff (2 on my case) with the -j option of Make. On my case this ended up with weird compilation errors (something like a race condition between the to make jobs). I fixed it setting the <em>buildmakejobs</em> to 1 (at /opt/etc/macports/macports.conf) so it used just one make job</li>
<li>The Makefile rule for the documentation at <em>&lt;package&gt;/support/include.mk</em> is wrong. The function that make should call at the <em>edoc</em> module is <em>files/3</em> not <em>file</em> as it&#8217;s deprecated.</li>
</ol>
<p>Enjoy!!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2010/07/19/install-mochiweb-with-macports/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ruby: gmaps-geocode 0.1.0 is out !!</title>
		<link>http://blog.tenako.com/2009/07/04/ruby-gmaps-geocode-0-1-0-is-out/</link>
		<comments>http://blog.tenako.com/2009/07/04/ruby-gmaps-geocode-0-1-0-is-out/#comments</comments>
		<pubDate>Sat, 04 Jul 2009 20:12:24 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/2009/07/04/ruby-gmaps-geocode-0-1-0-is-out/</guid>
		<description><![CDATA[Disponible en github]]></description>
			<content:encoded><![CDATA[<p>Disponible en <a title="gmaps-geocode at github" href="http://github.com/madtrick/gmaps-geocode/tree/master" onclick="javascript:pageTracker._trackPageview('/outbound/article/github.com');" target="_blank">github</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2009/07/04/ruby-gmaps-geocode-0-1-0-is-out/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby: ¡Cállate IRB!</title>
		<link>http://blog.tenako.com/2009/06/22/ruby-%c2%a1callate-irb/</link>
		<comments>http://blog.tenako.com/2009/06/22/ruby-%c2%a1callate-irb/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 09:45:46 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=194</guid>
		<description><![CDATA[¿Harto de que en alguna ocasión IRB sea demasiado verboso? Yo si. Por defecto, IRB siempre &#8220;escupirá&#8221; el valor resultante de evaluar la expresión introducida por el usuario. Aunque la mayoría de las veces eso está bien, hay otras en las que sacarias el corazón con una cucharilla de Té  a quien tuvieras delante por [...]]]></description>
			<content:encoded><![CDATA[<p>¿Harto de que en alguna ocasión IRB sea demasiado verboso? Yo si.</p>
<p>Por defecto, IRB siempre &#8220;escupirá&#8221; el valor resultante de evaluar la expresión introducida por el usuario. Aunque la mayoría de las veces eso está bien, hay otras en las que sacarias el corazón con una cucharilla de Té  a quien tuvieras delante por la crispación que produce esta &#8220;verbosidad&#8221;.</p>
<p>Me refiero a situaciones del tipo &#8220;quiero recorrer un array y listar el nombre de sus elementos con puts&#8221;, ejemplo:</p>
<pre class="brush: ruby;">
ArrayEnorme.each do |element| puts &quot;#{element.name}\n&quot; end
</pre>
<p>Con el código anterior vamos a mostrar el nombre de cada elemento del Array. Hasta aquí todo normal. El problema de evaluar esto en IRB es que, si ArrayEnorme tiene bastantes elementos y cada elemento tiene bastantes atributos, las lineas que imprimos con el nombre de cada elemento quedaran &#8220;sepultadas&#8221; por un mont<span>ón</span> de datos inutiles. Es decir, si el buffer de nuestra consola no se ha llenado con estos datos inutiles (perdiendo así las lineas con el nombre de cada elemento) tendremos que hacer scroll <em>ad-infinitum</em>, que para el caso es casí como si se hubierán perdido.</p>
<p>Para evitar esto, os presento mi solución de andar por casa:</p>
<pre class="brush: ruby;">

def toggle_output
context.return_format == &quot;Output canceled\n&quot; ? IRB.conf[:PROMPT][context.prompt_mode][:RETURN] : context.return_format = &quot;Output canceled\n&quot;
end

alias tgo toggle_output
</pre>
<p>Después de copiar las lineas anteriores en nuestro .irbrc podemos hacer pruebas:</p>
<pre class="brush: bash;">
madtrick::madtrick::$irb
irb(main):001:0&gt; 2 + 1
=&gt; 3
irb(main):002:0&gt; toggle_output
Output canceled
irb(main):003:0&gt; 2 + 1
Output canceled
irb(main):004:0&gt; toggle_output
=&gt; &quot;=&gt; %s\n&quot;
irb(main):005:0&gt; 2 + 1
=&gt; 3
</pre>
<p>Y <em>voila</em>, ya podemos callar y dar voz a IRB cuando nos plazca.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2009/06/22/ruby-%c2%a1callate-irb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby: Sketches en IRB</title>
		<link>http://blog.tenako.com/2009/06/19/ruby-sketches-en-irb/</link>
		<comments>http://blog.tenako.com/2009/06/19/ruby-sketches-en-irb/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 16:47:14 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[irb]]></category>
		<category><![CDATA[sketches]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=188</guid>
		<description><![CDATA[Hoy descubrí una gema m-a-r-a-v-i-l-l-o-s-a: Sketches. El concepto que implementa sketches es sencillo: las modificicaciones que hagamos en nuestro editor de texto, se reflejan al instante en la sesión de irb. Es decir, si en el editor de texto creamos una clase y guardamos los cambios, la clase estará disponible automaticamente en la sesión de [...]]]></description>
			<content:encoded><![CDATA[<p>Hoy descubrí una gema m-a-r-a-v-i-l-l-o-s-a: <a href="http://sketches.rubyforge.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/sketches.rubyforge.org');" target="_blank">Sketches</a>.</p>
<p>El concepto que implementa sketches es sencillo: las modificicaciones que hagamos en nuestro editor de texto, se reflejan al instante en la sesión de irb. Es decir, si en el editor de texto creamos una clase y guardamos los cambios, la clase estará disponible automaticamente en la sesión de irb.</p>
<p>Su utilización es sencilla: arrancamos el IRB y lanzamos nuestro editor favorito con el comando sketch. A partir de ahí, el funcionamiento es como expliqué antes.</p>
<p>Mola : )</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2009/06/19/ruby-sketches-en-irb/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby: callcc</title>
		<link>http://blog.tenako.com/2009/06/03/ruby-callc/</link>
		<comments>http://blog.tenako.com/2009/06/03/ruby-callc/#comments</comments>
		<pubDate>Wed, 03 Jun 2009 15:04:00 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[callcc]]></category>
		<category><![CDATA[continuations]]></category>
		<category><![CDATA[frame]]></category>
		<category><![CDATA[stack]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=160</guid>
		<description><![CDATA[callcc, es la abreviatura de call-with-current-continuation, algo así como un goto con esteroides. En el rdoc nos encontramos con la siguiente definición: callcc &#123;&#124;cont&#124; block &#125; =&#62; obj Generates a Continuation object, which it passes to the associated block. Performing a cont.call will cause the callcc to return (as will falling through the end of [...]]]></description>
			<content:encoded><![CDATA[<p><strong>callcc</strong>, es la abreviatura de call-with-current-continuation, algo así como un goto con esteroides.</p>
<p>En el <a href="http://www.ruby-doc.org/core/classes/Kernel.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-doc.org');" target="_blank">rdoc</a> nos encontramos con la siguiente definición:</p>
<blockquote>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">callcc <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>cont<span style="color:#006600; font-weight:bold;">|</span> block <span style="color:#006600; font-weight:bold;">&#125;</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> obj</pre></div></div>

<p>Generates a Continuation object, which it passes to the associated block. Performing a cont.call will cause the callcc to return (as will falling through the end of the block). The value returned by the callcc is the value of the block, or the value passed to cont.call. See class Continuation for more details. Also see Kernel::throw for an alternative mechanism for unwinding a call stack.
</p></blockquote>
<p>Un tanto críptico, ¿No?. Basicamente, callcc almacena la dirección de memoria y el contexto  (en un objeto <a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_continuation.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-doc.org');" target="_blank">Continuation</a>) de donde se le llamo. Sigue siendo raro,¿No?</p>
<p>Mejor un ejemplo. Sea el siguiente metodo:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">&nbsp;
counter = <span style="color:#006666;">0</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> foo
<span style="color:#CC0066; font-weight:bold;">exit</span> <span style="color:#9966CC; font-weight:bold;">if</span> callcc<span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>$cont<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#006600; font-weight:bold;">&#125;</span> == <span style="color:#006666;">3</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;hello world&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
foo
&nbsp;
<span style="color:#ff6633; font-weight:bold;">$cont</span>.<span style="color:#9900CC;">call</span><span style="color:#006600; font-weight:bold;">&#40;</span>counter <span style="color:#006600; font-weight:bold;">+</span>= <span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>(Si ya se que las variables globales son malignas : ( )</p>
<p>Ejecutando el ejemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">madtrick::madtrick::<span style="color: #007800;">$ruby</span> test3.rb
hello world
hello world
hello world</pre></div></div>

<p>Como se puede apreciar, se imprimen tres &#8220;hello world&#8221; con sólo una llamada al método foo. </p>
<p>¿Qué podemos extraer del ejemplo anterior?</p>
<ul>
<li> Cada llamada a la continuación ($cont) nos vuelve a llevar a linea donde se definió.</li>
<li> Si en la llamada a la continuación pasamos algun parámetro, este es devuelto por callcc</li>
</ul>
<p>Tambien podríamos utilizar los ejemplos del post anterior (<a href="http://blog.tenako.com/2009/06/01/ruby-tco-tail-call-optimization/"  target="_blank">Tail Call Optimization</a>) para explicar el funcionamiento de callcc:</p>
<p>Calculo del factorial de un número:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> TCOTest
  <span style="color:#008000; font-style:italic;"># tail-recursive factorial</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> fact<span style="color:#006600; font-weight:bold;">&#40;</span> n, acc = <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> n <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#006666;">2</span> <span style="color:#9966CC; font-weight:bold;">then</span>
      acc
    <span style="color:#9966CC; font-weight:bold;">else</span>
       fact<span style="color:#006600; font-weight:bold;">&#40;</span> n<span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span>, n<span style="color:#006600; font-weight:bold;">*</span>acc <span style="color:#006600; font-weight:bold;">&#41;</span> 
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> fact_cc<span style="color:#006600; font-weight:bold;">&#40;</span> n, acc = <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">&#41;</span>
    cont = callcc<span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>cont<span style="color:#006600; font-weight:bold;">|</span> cont<span style="color:#006600; font-weight:bold;">&#125;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> n <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#006666;">2</span> <span style="color:#9966CC; font-weight:bold;">then</span>
      acc
    <span style="color:#9966CC; font-weight:bold;">else</span>
       n, acc = n<span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span>, n<span style="color:#006600; font-weight:bold;">*</span>acc
       cont.<span style="color:#9900CC;">call</span> cont 
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># length of factorial</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> fact_size<span style="color:#006600; font-weight:bold;">&#40;</span> n <span style="color:#006600; font-weight:bold;">&#41;</span>
    fact<span style="color:#006600; font-weight:bold;">&#40;</span> n <span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">size</span>
  <span style="color:#9966CC; font-weight:bold;">rescue</span>
    $!
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
&nbsp;
  <span style="color:#008000; font-style:italic;"># length of factorial</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> fact_size_cc<span style="color:#006600; font-weight:bold;">&#40;</span> n <span style="color:#006600; font-weight:bold;">&#41;</span>
    fact_cc<span style="color:#006600; font-weight:bold;">&#40;</span> n <span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">size</span>
  <span style="color:#9966CC; font-weight:bold;">rescue</span>
    $!
  <span style="color:#9966CC; font-weight:bold;">end</span>  
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Si lo probamos en el irb vemos que fact_size_cc no da ningún tipo de problema mientras que la función fact_size (sí, por carecer Ruby de TCO) ya que nos quedamos sin espacio en la stack.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">...
irb<span style="color: #7a0874; font-weight: bold;">&#40;</span>main<span style="color: #7a0874; font-weight: bold;">&#41;</span>:009:<span style="color: #000000;">0</span><span style="color: #000000; font-weight: bold;">&gt;</span> t.fact_size <span style="color: #000000;">10000</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #666666; font-style: italic;">#&lt;SystemStackError: stack level too deep&gt;</span>
irb<span style="color: #7a0874; font-weight: bold;">&#40;</span>main<span style="color: #7a0874; font-weight: bold;">&#41;</span>:010:<span style="color: #000000;">0</span><span style="color: #000000; font-weight: bold;">&gt;</span> t.fact_size_cc <span style="color: #000000;">10000</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000;">14808</span></pre></div></div>

<p>El otro ejemplo del post anterior, la función de Fibonacci:</p>
<p>En el ejemplo anterior, utilizábamos la palabra reservada <strong>redo</strong> junto con  un método definido ad-hoc para poder realizar el cálculo:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">  define_method<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:acc</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>i, n, result<span style="color:#006600; font-weight:bold;">|</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> i == <span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span>
      result
    <span style="color:#9966CC; font-weight:bold;">else</span>
      i, n, result = i <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span>, n <span style="color:#006600; font-weight:bold;">+</span> result, n
      <span style="color:#9966CC; font-weight:bold;">redo</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> fib_redo<span style="color:#006600; font-weight:bold;">&#40;</span>i<span style="color:#006600; font-weight:bold;">&#41;</span>
   acc i,<span style="color:#006666;">1</span>,<span style="color:#006666;">0</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Pero tambien se podria haber hecho de esta otra forma:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> fib_call_cc<span style="color:#006600; font-weight:bold;">&#40;</span>i, n = <span style="color:#006666;">1</span>, result = <span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  cont = callcc<span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>cont<span style="color:#006600; font-weight:bold;">|</span> cont<span style="color:#006600; font-weight:bold;">&#125;</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> i == <span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span>
    result
  <span style="color:#9966CC; font-weight:bold;">else</span>
    i, n, result = i <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span>, n <span style="color:#006600; font-weight:bold;">+</span> result, n
    cont.<span style="color:#9900CC;">call</span> cont
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>En el ejemplo anterior se puede apreciar como el contexto se mantiene. En este caso para los valores <strong>i</strong>,<strong>n</strong> y <strong>result</strong>.</p>
<p>Si ejecutamos un simple benchmark (para n en 50000) para comparar redo vs callcc, obtenemos los siguiente:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">&nbsp;
madtrick::madtrick::<span style="color: #007800;">$ruby</span> test.rb 
Time <span style="color: #000000; font-weight: bold;">for</span> fib_redo:      <span style="color: #000000;">0.390000</span>   <span style="color: #000000;">0.010000</span>   <span style="color: #000000;">0.400000</span> <span style="color: #7a0874; font-weight: bold;">&#40;</span>  <span style="color: #000000;">0.403986</span><span style="color: #7a0874; font-weight: bold;">&#41;</span>
Time <span style="color: #000000; font-weight: bold;">for</span> fib_call_cc:   <span style="color: #000000;">0.500000</span>   <span style="color: #000000;">0.000000</span>   <span style="color: #000000;">0.500000</span> <span style="color: #7a0874; font-weight: bold;">&#40;</span>  <span style="color: #000000;">0.519504</span><span style="color: #7a0874; font-weight: bold;">&#41;</span></pre></div></div>

<p>redo (  0.403986) es un poco más rápido que callcc (  0.519504). Echándole un vistazo rapido al codigo de la máquina virtual de Ruby se entiende rápidamente el porque. <strong>redo</strong> esta implentado utilizando goto&#8217;s mientras que callcc es una llamada a una función que se encarga de guardar toda la información necesaria en un objeto Continuation, por lo que necesita más tiempo.</p>
<p>Para mas información sobre callcc, su funcionamiento y los continuations:</p>
<ul>
<li><a href="http://www.intertwingly.net/blog/2005/04/13/Continuations-for-Curmudgeons" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.intertwingly.net');">Continuations</a></li>
<li><a href="http://www.madore.org/~david/computers/callcc.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.madore.org');">Callcc</a></li>
<li><a href="http://www.cs.utk.edu/~huangj/cs360/360/notes/Setjmp/lecture.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.cs.utk.edu');">Setjmp/longjmp</a>, funciones en C con las que se puede implementar un comportamiento similar</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2009/06/03/ruby-callc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby: TCO (Tail Call Optimization)</title>
		<link>http://blog.tenako.com/2009/06/01/ruby-tco-tail-call-optimization/</link>
		<comments>http://blog.tenako.com/2009/06/01/ruby-tco-tail-call-optimization/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 22:21:13 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[recursividad]]></category>
		<category><![CDATA[tco]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=130</guid>
		<description><![CDATA[Leyendo el libro de Programming Erlang descubrí un concepto que no conocia: funciones tail-recursive. En esta pagina lo explican bastante bien (entre otros tipos de recursividad), pero basicamente una función tail-recursive es aquella que no tiene ninguna operación pendiente de ejecutar tras la llamada recursiva. En estas funciones, la llamada recursiva puede ser substituida simplemente [...]]]></description>
			<content:encoded><![CDATA[<p>Leyendo el libro de <a href="http://www.pragprog.com/titles/jaerlang/programming-erlang" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.pragprog.com');" target="_blank">Programming Erlang</a> descubrí un concepto que no conocia: funciones <em>tail-recursive</em>.</p>
<p>En <a href="http://triton.towson.edu/~akayabas/COSC455_Spring2000/Recursion_Iteration.htm" onclick="javascript:pageTracker._trackPageview('/outbound/article/triton.towson.edu');" target="_blank">esta pagina</a> lo explican bastante bien (entre otros tipos de recursividad), pero basicamente una función <em>tail-recursive</em> es aquella que no tiene ninguna operación pendiente de ejecutar tras la llamada recursiva. En estas funciones, la llamada recursiva puede ser substituida simplemente por un salto al comienzo de la función que se llama, con lo que se ahorra espacio en el <em>stack</em>. De esto ultimo se encarga el compilador y es lo que se conoce como <a href="http://c2.com/cgi/wiki?TailCallOptimization" onclick="javascript:pageTracker._trackPageview('/outbound/article/c2.com');" target="_blank">Tail Call Optimization</a> (TCO a partir de ahora).</p>
<p>Así que aparentemente la TCO mola, ¿No?</p>
<p>El problema es que <a href="http://www.ruby-lang.org/es/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-lang.org');" targe="_blank">Ruby</a> no tiene implementada  TCO en su maquina virtual con lo que independientemente de como estructuremos nuestras funciones recursivas, siempre estaremos limitados por el tamaño de nuestra Stack.</p>
<p>Pero siempre hay solución para todo y con Ruby, más. En <a href="http://judofyr.net/posts/tailin-ruby.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/judofyr.net');" target="_blank">ésta página</a> dan dos soluciones para tener una pseudo-TCO.</p>
<p>Copio y pego la primera solución:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#9966CC; font-weight:bold;">Class</span>
  <span style="color:#008000; font-style:italic;"># Sweet stuff!</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> tailcall_optimize<span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#006600; font-weight:bold;">*</span>methods <span style="color:#006600; font-weight:bold;">&#41;</span>
    methods.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>meth<span style="color:#006600; font-weight:bold;">|</span>
      org = instance_method<span style="color:#006600; font-weight:bold;">&#40;</span> meth <span style="color:#006600; font-weight:bold;">&#41;</span>
      define_method<span style="color:#006600; font-weight:bold;">&#40;</span> meth <span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|*</span>args<span style="color:#006600; font-weight:bold;">|</span>
        <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#CC00FF; font-weight:bold;">Thread</span>.<span style="color:#9900CC;">current</span><span style="color:#006600; font-weight:bold;">&#91;</span> meth <span style="color:#006600; font-weight:bold;">&#93;</span>
          throw<span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#ff3333; font-weight:bold;">:recurse</span>, args <span style="color:#006600; font-weight:bold;">&#41;</span>
        <span style="color:#9966CC; font-weight:bold;">else</span>
          <span style="color:#CC00FF; font-weight:bold;">Thread</span>.<span style="color:#9900CC;">current</span><span style="color:#006600; font-weight:bold;">&#91;</span> meth <span style="color:#006600; font-weight:bold;">&#93;</span> = org.<span style="color:#9900CC;">bind</span><span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#0000FF; font-weight:bold;">self</span> <span style="color:#006600; font-weight:bold;">&#41;</span>
          result = <span style="color:#CC0066; font-weight:bold;">catch</span><span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#ff3333; font-weight:bold;">:done</span> <span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
            <span style="color:#CC0066; font-weight:bold;">loop</span> <span style="color:#9966CC; font-weight:bold;">do</span>
              args = <span style="color:#CC0066; font-weight:bold;">catch</span><span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#ff3333; font-weight:bold;">:recurse</span> <span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
                throw<span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#ff3333; font-weight:bold;">:done</span>, <span style="color:#CC00FF; font-weight:bold;">Thread</span>.<span style="color:#9900CC;">current</span><span style="color:#006600; font-weight:bold;">&#91;</span> meth <span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">call</span><span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#006600; font-weight:bold;">*</span>args <span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#41;</span>
              <span style="color:#9966CC; font-weight:bold;">end</span>
            <span style="color:#9966CC; font-weight:bold;">end</span>
          <span style="color:#9966CC; font-weight:bold;">end</span>
          <span style="color:#CC00FF; font-weight:bold;">Thread</span>.<span style="color:#9900CC;">current</span><span style="color:#006600; font-weight:bold;">&#91;</span> meth <span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#0000FF; font-weight:bold;">nil</span>
          result
        <span style="color:#9966CC; font-weight:bold;">end</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> TCOTest
  <span style="color:#008000; font-style:italic;"># tail-recursive factorial</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> fact<span style="color:#006600; font-weight:bold;">&#40;</span> n, acc = <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> n <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#006666;">2</span> <span style="color:#9966CC; font-weight:bold;">then</span> acc <span style="color:#9966CC; font-weight:bold;">else</span> fact<span style="color:#006600; font-weight:bold;">&#40;</span> n<span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span>, n<span style="color:#006600; font-weight:bold;">*</span>acc <span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># length of factorial</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> fact_size<span style="color:#006600; font-weight:bold;">&#40;</span> n <span style="color:#006600; font-weight:bold;">&#41;</span>
    fact<span style="color:#006600; font-weight:bold;">&#40;</span> n <span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">size</span>
  <span style="color:#9966CC; font-weight:bold;">rescue</span>
    $!
  <span style="color:#9966CC; font-weight:bold;">end</span>   
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
t = TCOTest.<span style="color:#9900CC;">new</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># normal method</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> t.<span style="color:#9900CC;">fact_size</span><span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#006666;">10000</span> <span style="color:#006600; font-weight:bold;">&#41;</span>  <span style="color:#008000; font-style:italic;"># =&gt; stack level too deep</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># enable tail-call optimization</span>
<span style="color:#9966CC; font-weight:bold;">class</span> TCOTest
  tailcall_optimize <span style="color:#ff3333; font-weight:bold;">:fact</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># tail-call optimized method</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> t.<span style="color:#9900CC;">fact_size</span><span style="color:#006600; font-weight:bold;">&#40;</span> <span style="color:#006666;">10000</span> <span style="color:#006600; font-weight:bold;">&#41;</span>  <span style="color:#008000; font-style:italic;"># =&gt; 14808</span></pre></div></div>

<p>Esta solución consiste en jugar con catch&#8217;s,throw&#8217;s y Thread.current para relanzar el mismo método una y otra vez sin tener que crear un nuevo frame en el Stack, ya que el codigo del metodo se encuentra definido en un bloque y por tanto reutiliza el codigo. </p>
<p>La segunda opción:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> fib<span style="color:#006600; font-weight:bold;">&#40;</span>i, n = <span style="color:#006666;">1</span>, result = <span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> i == <span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span>
    result
  <span style="color:#9966CC; font-weight:bold;">else</span>
    i, n, result = i <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span>, n <span style="color:#006600; font-weight:bold;">+</span> result, n
    <span style="color:#9966CC; font-weight:bold;">redo</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
fib<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">10000</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Esta solución consiste en hacer uso de la palabra <a href="http://www.rubyist.net/~slagell/ruby/control.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.rubyist.net');" target="_blank">redo</a> la cual reinicia la ejecución de cualquier loop o iterador. El problema con redo es que, como acabo de decir, solo se puede utilizar en loops o iteradores y el método fib anterior no es ninguno de ellos. Por lo que el autor de la página de que se extrajeron las soluciones dice:</p>
<blockquote><p>Unfortunately, “The redo statement restarts the current iteration of a loop or iterator”, so it only throws a LocalJumpError</p></blockquote>
<p><img src="http://blog.tenako.com/wp-content/uploads/2009/06/ruby_spartan1.png" alt="ruby_spartan1" title="ruby_spartan1" width="550" height="343" class="aligncenter size-full wp-image-153" /></p>
<p>Gracias señor espartano. </p>
<p>Así es, esto es Ruby y siempre hay un workaround para todo. En este caso, consiste en crear un nuevo método cuyo cuerpo este contenido en un bloque.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">define_method<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:acc</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>i, n, result<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> i == <span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">1</span>
    result
  <span style="color:#9966CC; font-weight:bold;">else</span>
    i, n, result = i <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span>, n <span style="color:#006600; font-weight:bold;">+</span> result, n
    <span style="color:#9966CC; font-weight:bold;">redo</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> fib<span style="color:#006600; font-weight:bold;">&#40;</span>i<span style="color:#006600; font-weight:bold;">&#41;</span>
  acc<span style="color:#006600; font-weight:bold;">&#40;</span>i, <span style="color:#006666;">1</span>, <span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
fib<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">10000</span><span style="color:#006600; font-weight:bold;">&#41;</span>  <span style="color:#008000; font-style:italic;"># Yeah!</span></pre></div></div>

<p>Y ya podemos utilizar redo. Fin!!</p>
<p>Para mas información, hay un thread en esta lista de correo en el que debaten sobre este tema: <a href="http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/171075" onclick="javascript:pageTracker._trackPageview('/outbound/article/blade.nagaokaut.ac.jp');" target="_blank">Ruby tail recursion</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2009/06/01/ruby-tco-tail-call-optimization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby: Expirar los mensajes de Starling en 3 comodos pasos</title>
		<link>http://blog.tenako.com/2009/03/20/expirar-mensajes-starling/</link>
		<comments>http://blog.tenako.com/2009/03/20/expirar-mensajes-starling/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 17:12:12 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Add new tag]]></category>
		<category><![CDATA[expiry]]></category>
		<category><![CDATA[starling]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=113</guid>
		<description><![CDATA[Si te pasa como a mi, que quieres almacenar mensajes en el starling pero que algunos de ellos lleven &#8220;fecha de caducidad&#8220;, sigue los siguiente pasos. Paso 1 : Abrir en un editor el fichero handler.rb perteneciente a la gema starling-starling. Paso 2 : En el método Handler#set_data añadir la siguiente linea justo antes de [...]]]></description>
			<content:encoded><![CDATA[<p>Si te pasa como a mi, que quieres almacenar mensajes en el starling pero que algunos de ellos lleven &#8220;<a href="http://www.deveiate.org/code/Ruby-MemCache/classes/MemCache.html#M000009" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.deveiate.org');">fecha de caducidad</a>&#8220;, sigue los siguiente pasos.</p>
<ul>
<li><strong>Paso 1 :</strong> Abrir en un editor el fichero handler.rb perteneciente a la gema <a href="http://github.com/starling/starling/tree/master" onclick="javascript:pageTracker._trackPageview('/outbound/article/github.com');">starling-starling</a>.</li>
<li><strong>Paso 2 :</strong> En el método <em>Handler#set_data</em> añadir la siguiente linea justo antes de hacer el pack para generar la variable <em>internal_data</em>.</li>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">  ...
  <span style="color:#9900CC;">expiry</span> = <span style="color:#CC00FF; font-weight:bold;">Time</span>.<span style="color:#9900CC;">now</span>.<span style="color:#9900CC;">to_i</span> <span style="color:#006600; font-weight:bold;">+</span> expiry.<span style="color:#9900CC;">to_i</span> <span style="color:#9966CC; font-weight:bold;">unless</span> expiry.<span style="color:#9900CC;">to_i</span> == <span style="color:#006666;">0</span>
  ...</pre></div></div>

<li><strong>Paso 3 :</strong> Guarda y re-arranca el starling.Todo debería de ir como la seda.</li>
</ul>
<p>Con esto, lo único que hemos hecho es corregir un pequeño bug que hay en <em>Handler#get</em> ya que en este método solo se devuelve un mensaje si su expiry es 0 o si expiry es mayor que now (now en este contexto es Time.now.to_i ). El fallo viene de comparar a now (valor <a href="http://en.wikipedia.org/wiki/Unix_time" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">unix time</a>) con expiry el cual es solo un offset desde el momento en el que decidimos guardar un mensaje en starling.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">  ...
  <span style="color:#9966CC; font-weight:bold;">break</span> <span style="color:#9966CC; font-weight:bold;">if</span> expiry == <span style="color:#006666;">0</span> <span style="color:#006600; font-weight:bold;">||</span> expiry <span style="color:#006600; font-weight:bold;">&gt;</span>= now
&nbsp;
  <span style="color:#0066ff; font-weight:bold;">@expiry_stats</span><span style="color:#006600; font-weight:bold;">&#91;</span>key<span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#006600; font-weight:bold;">+</span>= <span style="color:#006666;">1</span>
  expiry, data = <span style="color:#0000FF; font-weight:bold;">nil</span>
  ...</pre></div></div>

<p>Con la linea que añadimos al método <em>Handler#set_data</em> forzamos que la comparación sea entre dos valores unix time.Uno refiriéndose al momento actual (now) y otro al momento en el que expirara el mensaje (la suma de Time.now.to_i en el momento del almacenarlo y el tiempo de vida del mensaje).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2009/03/20/expirar-mensajes-starling/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Mac &amp; Git &amp; Ssh : Un poquillo de scripting</title>
		<link>http://blog.tenako.com/2009/02/26/mac-os-x-scripting/</link>
		<comments>http://blog.tenako.com/2009/02/26/mac-os-x-scripting/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 21:54:23 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[configd]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[kicker]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[ssh]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=85</guid>
		<description><![CDATA[Planteemos el siguiente problema: Tenemos que hacer push&#8217;es y pull&#8217;es a un repositorio git (mediante ssh). Sencillo, ¿no?.Ahora tengamos en cuenta las siguientes consideraciones: Estas operaciones las vamos a realizar tanto desde nuestra casa (a través de internet) como desde la red donde se encuentra el repositorio, siendo la dirección del repositorio &#8211; git.frusfrusfrus.net, la [...]]]></description>
			<content:encoded><![CDATA[<p>Planteemos el siguiente problema:</p>
<p>Tenemos que hacer push&#8217;es y pull&#8217;es a un repositorio git (mediante ssh).</p>
<p>Sencillo, ¿no?.Ahora tengamos en cuenta las siguientes consideraciones:</p>
<ol>
<li>Estas operaciones las vamos a realizar tanto desde nuestra casa (a través de internet) como desde la red donde se encuentra el repositorio, siendo la dirección del repositorio &#8211; git.frusfrusfrus.net, la misma en ambos casos.</li>
<li>Por culpa de las hadas y de los proxies reversos, si las operaciones la realizamos desde casa el puerto sera el 2280 mientras que si las operaciones las realizamos desde la oficina el puerto será el 22.</li>
<li>Queremos que cualquier tipo de cambio en la configuración sea automático</li>
</ol>
<p>La consideración tres es el motivo de este post, ya que la dos (la unica que plantea algún problema) se podria resolver con un parámetro en la linea de comandos.Es más cómodo  no tener que preocuparse ni de donde estamos, ni tener que acordarse de como era la estructura del comando.</p>
<p>Mi primera opción fue la de crear un script que se ejecutase cada vez que encendiera el ordenador, para lo cual ya le habia hechado un vistazo a <a title="apple's startup item documentation" href="http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/StartupItems.html#//apple_ref/doc/uid/20002132" onclick="javascript:pageTracker._trackPageview('/outbound/article/developer.apple.com');" target="_blank">esta documentación.</a> Pero como <a title="david's webpage" href="http://www.davidbarral.com" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.davidbarral.com');" target="_blank">David</a> tuvo bien a decirme, quizás seria mejor hacerlo siempre que la interfaz de red se levantara.Realmente esto está mucho mejor ya que cubria un abanico de opciones más amplio (volver de hibernación, desactivar y activar de nuevo la tarjeta de red&#8230;) que la idea de crear  un Startup item.</p>
<p>¿Y como co%&amp;o se yo cuando se levanta o se cae una interfaz de red en Mac OS X?</p>
<p>&#8230;google&#8230;google&#8230;google&#8230;google</p>
<p>Resulta que en Mac OS X  la gestión de las interfaces de red (entre otras muchas más cosas) las lleva un demonio: <a title="configd manpage" href="http://www.manpagez.com/man/8/configd/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.manpagez.com');" target="_blank">configd</a>. Este demonio monitoriza el siguiente fichero, /Library/Preferences/SystemConfiguration/preferences.plist. Configd reacciona ante cualquier cambio que se refleje en este fichero, derivando a quien corresponda  la tarea de manejar el evento.</p>
<p>Si el evento tiene que ver con la red del sistema, configd hace entrar en juego al  Kicker.bundle &#8211; que se puede encontrar en /System/library/SystemConfiguration/Kicker.bundle.Lo interesante de este bundle es su fichero de configuración: Kicker.xml en el cual se especifica ante que eventos reaccionar y lo que es más importante, como.</p>
<p>Este es mi fichero Kicker.xml original</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;pre</span> <span style="color: #000066;">lang</span>=<span style="color: #ff0000;">&quot;xml&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #00bbdd;">&lt;!DOCTYPE plist PUBLIC &quot;-//Apple Computer//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;plist</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>execCommand<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>$BUNDLE/Contents/Resources/enable-network<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>execUID<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;integer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/integer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>keys<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>State:/Network/Global/IPv4<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>enable-network<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>keys<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>State:/Network/Global/DNS<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>State:/Network/Global/IPv4<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>State:/Network/Global/IPv6<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>State:/Network/Global/NetInfo<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>network_change<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>postName<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>com.apple.system.config.network_change<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>execCommand<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/usr/sbin/AppleFileServer<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>execUID<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;integer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>0<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/integer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>keys<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
			<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>daemon:AppleFileServer<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>AppleFileServer<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/plist<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>La primera sección dict , indica que se debe de ejecutar el script enable-network cada vez que se reciba un evento de tipo State:/Network/Global/IPv4 lo cual puede indicar que la interfaz se levantó y ha obtenido una ip, que se ha realizado un cambio de ip, que la interfaz se ha desconectado&#8230;etc.</p>
<p>La segunda sección dict indica que ante todos esos eventos : State:/Network/Global/IPv4 , State:/Network/Global/IPv6 &#8230; se va a emitir una notificación con el nombre com.apple.system.config.network_change.Decir que principalmente quien hará uso de este notificación sera <a href="http://www.manpagez.com/man/8/lookupd/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.manpagez.com');" target="_blank">lookupd,</a> como se puede observar en este extracto del sytem.log:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">Feb <span style="color: #000000;">26</span> <span style="color: #000000;">17</span>:<span style="color: #000000;">36</span>:<span style="color: #000000;">52</span> madtrick configd<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">39</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>: posting notification com.apple.system.config.network_change
Feb <span style="color: #000000;">26</span> <span style="color: #000000;">17</span>:<span style="color: #000000;">36</span>:<span style="color: #000000;">52</span> madtrick lookupd<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">538</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>: lookupd <span style="color: #7a0874; font-weight: bold;">&#40;</span>version <span style="color: #000000;">369.8</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> starting - Thu Feb <span style="color: #000000;">26</span> <span style="color: #000000;">17</span>:<span style="color: #000000;">36</span>:<span style="color: #000000;">52</span> <span style="color: #000000;">2009</span>
...
Feb <span style="color: #000000;">26</span> <span style="color: #000000;">19</span>:<span style="color: #000000;">46</span>:<span style="color: #000000;">16</span> madtrick configd<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">39</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>: posting notification com.apple.system.config.network_change
Feb <span style="color: #000000;">26</span> <span style="color: #000000;">19</span>:<span style="color: #000000;">46</span>:<span style="color: #000000;">16</span> madtrick lookupd<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">667</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>: lookupd <span style="color: #7a0874; font-weight: bold;">&#40;</span>version <span style="color: #000000;">369.8</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> starting - Thu Feb <span style="color: #000000;">26</span> <span style="color: #000000;">19</span>:<span style="color: #000000;">46</span>:<span style="color: #000000;">16</span> <span style="color: #000000;">2009</span></pre></div></div>

<p>La tercera y ultima sección no es relevante a lo que estamos hablando, así que nada que comentar.</p>
<p>Bien.Llegados a este punto se me plantean dos opciones:</p>
<ul>
<li> Primera. Crear una nueva entrada en el fichero Kicker.xml para que un script se ejecute ante cualquier evento de tipo  State:/Network/Global/IPv4.</li>
<li>Segunda. Capturar la notificacion com.apple.system.config.network_change y actuar en consecuencia.</li>
</ul>
<p>Aparentemente la más interesante es la segunda.Es menos intrusiva y mas versatil,peeero tambien bastante mas complicada de afrontar de primeras.Por ello queda aplazada a la espera de que algún dia decida leer <a title="mac notification system" href="http://developer.apple.com/documentation/Darwin/Conceptual/MacOSXNotifcationOv/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/TP40005947-CH1-DontLinkElementID_27" onclick="javascript:pageTracker._trackPageview('/outbound/article/developer.apple.com');" target="_blank">esto</a> y  me plantee hacerlo.</p>
<p>Así que nos queda la primera opcion, ejecutar un script ante cada evento.</p>
<blockquote><p><strong>OJO: ANTES DE EDITAR Kicker.xml, HAZ UNA COPIA DE SEGURIDAD</strong></p></blockquote>
<p>Asi que nos ponemos manos a la obra y añadimos la siguiente sección dict al fichero Kicker.xml</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>execCommand<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>/usr/bin/ssh-config<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>execUID<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;integer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>501<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/integer<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>keys<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>State:/Network/Global/IPv4<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/array<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>name<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/key<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>ssh-config<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/string<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
	<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dict<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Donde /usr/bin/ssh-config es el script que se ejecutara ante cada cambio que afecte a la pila IPv4.</p>
<p>Para que los cambios tengan efecto, necesitamos matar el demonio configd y luego volver a levantarlo.</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">madtrick::madtrick::<span style="color: #007800;">$sudo</span> <span style="color: #c20cb9; font-weight: bold;">killall</span> configd
madtrick::madtrick::<span style="color: #007800;">$sudo</span> configd
madtrick::madtrick::<span style="color: #007800;">$ps</span> aux <span style="color: #000000; font-weight: bold;">|</span> <span style="color: #c20cb9; font-weight: bold;">grep</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>c<span style="color: #7a0874; font-weight: bold;">&#93;</span>onfigd</pre></div></div>

<blockquote><p>Nota:</p>
<p>Una par de ocasiones en las que realicé estas operaciones sobre configd la terminal se quedo &#8220;frita&#8221; y el ordenador no queria reiniciarse correctamente.</p>
<p>En otra, system.log indicaba (algo que no se, solo supongo) que se desactivaba la ejecucion del script  enable-network y ssh-config, motivando que cualquier cambio sobre las interfaces de red, no se viera reflejado en la ejecución de estos scripts</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">Feb <span style="color: #000000;">26</span> <span style="color: #000000;">13</span>:<span style="color: #000000;">36</span>:<span style="color: #000000;">53</span> madtrick configd<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">4698</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>: posting notification com.apple.system.config.network_change
Feb <span style="color: #000000;">26</span> <span style="color: #000000;">13</span>:<span style="color: #000000;">36</span>:<span style="color: #000000;">53</span> madtrick lookupd<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">4707</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>: lookupd <span style="color: #7a0874; font-weight: bold;">&#40;</span>version <span style="color: #000000;">369.8</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> starting - Thu Feb <span style="color: #000000;">26</span> <span style="color: #000000;">13</span>:<span style="color: #000000;">36</span>:<span style="color: #000000;">53</span> <span style="color: #000000;">2009</span>
Feb <span style="color: #000000;">26</span> <span style="color: #000000;">13</span>:<span style="color: #000000;">36</span>:<span style="color: #000000;">53</span> madtrick configd<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">4698</span><span style="color: #7a0874; font-weight: bold;">&#93;</span>:   <span style="color: #007800;">target</span>=enable-network: disabled</pre></div></div>

<p>Desde mi punto de vista, considero esto normal ya que configd es un componente esencial para el correcto funcionamiento del sistema, por ello cualquier alteración en su funcionamiento (matarlo es un cambio bastante importante, ¿no?) es más que probable que derive en inestabilidad en el sistema.</p></blockquote>
<p>Llegados a este punto, solo nos queda reiniciar el ordenador (por eso de no jugar mas con configd) y comprobar que nuestro script se ejecuta correctamente.</p>
<p>Por si alguien le interesa el script ssh-config , <a href="http://www.tenako.com/upload/ssh-config.sh" >aqui esta</a>.Lo unico que hace este script es cambiar el puerto para el host git.frusfrusfrus.net de 22 a 2280 o de 2280 a 22 dependiendo de si estoy trabajando desde la red donde se encuentra el repo  o desde casa, respectivamente.</p>
<p>Para terminar, aqui dejo una lista de los enlaces que me fueron utiles.</p>
<p><a title="mac networking tips" href="http://www.afp548.com/article.php?story=20041015131913324" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.afp548.com');" target="_blank">Networking on OS X </a></p>
<p><a title="configd tips" href="http://www.radiotope.com/content/os-x-how-perform-action-during-fast-user-switch" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.radiotope.com');" target="_blank">OS X: How to perform an action during fast user switch</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2009/02/26/mac-os-x-scripting/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

