<?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>dow.ngra.de &#187; creative</title>
	<atom:link href="http://dow.ngra.de/category/creative/feed/" rel="self" type="application/rss+xml" />
	<link>http://dow.ngra.de</link>
	<description>no buzzwords allowed</description>
	<lastBuildDate>Sun, 22 Jan 2012 14:52:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Skype Bot for Fun and Profit – Part II – Getting it Running</title>
		<link>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-ii-getting-it-running/</link>
		<comments>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-ii-getting-it-running/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 21:10:21 +0000</pubDate>
		<dc:creator>Toomas Römer</dc:creator>
				<category><![CDATA[cool]]></category>
		<category><![CDATA[creative]]></category>
		<category><![CDATA[humour]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=1533</guid>
		<description><![CDATA[This is a post from the Skype Bot for Fun and Profit series. This is the second part in the series and if you want to get your bot running you will need to have some prerequisites filled out, see the first part for the list. Configuring and running There is a skype-bot project at [...]]]></description>
			<content:encoded><![CDATA[<p><em>This is a post from the <a href="http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit">Skype Bot for Fun and Profit</a> series. This is the second part in the series and if you want to get your bot running you will need to have some prerequisites filled out, see the <a href="http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-i-getting-started">first part</a> for the list.</em></p>
<h3>Configuring and running</h3>
<p><img src="http://dow.ngra.de/wp-content/uploads/2012/01/github.png" alt="" title="github" width="84" height="38" class="alignleft size-full wp-image-1580" />There is a skype-bot project at github. It is written in Java and has support for simple functionality. You can clone it via:</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">git clone https://github.com/toomasr/skype-bot.git</pre></div></div>

<p>The project is maven based and once you import the project into your favourite IDE that has maven support it should compile out of the box. Before we can actually run the project we need to make couple of adjustments. First make a copy of the <b>project.properties</b> file and make it <b>personal.properties</b>. Then change the username, password and pemfile attributes in the file. Make sure that the folder that has the pem file also has a der file that has the same name (except the extension of course).<br />
<span id="more-1533"></span><br />
Next lets build the project. It is sufficient to just issue a <code>mvn install</code> command. You will end up with a <b>skype-bot-0.0.1-SNAPSHOT.jar</b> in the <code>target</code> folder. Before we can run that we need to start the runtime. See <a href="http://dow.ngra.de/?p=1504">Running the Runtime from the previous post</a>.</p>
<p>Now we are ready to start the bot. Issue a <code>java -jar target/skype-bot-0.0.1-SNAPSHOT.jar</code>. Now expecting that the Runtime is still running and that you updated the credentials in the <b>personal.properties</b> file you should see your need friend come online and you can start a chat.</p>
<p>The bot has the commands that he reacts to defined in the <code>org.zeroturnaround.commands</code> package. But for starters you can tell him &#8220;bot: time&#8221; and it will tell you the time.</p>
<h3>Web Server</h3>
<p>The bot also launches a web server on port <b>2500</b> that has defined handler on the url <code>http://0.0.0.0:2500/post</code>. You can send a <b>POST</b> message there with the parameters <bold>message=?</bold> and <bold>group=?</bold>. This will instruct the bot to issue the <bold>message</bold> to the <bold>group</bold>. The group is looked up from the bot&#8217;s list of groups that matches the <code>Conversation.PROPERTY.displayname</code>.</p>
<p>So what can we do with this? Most of the todays services have webhooks. For example GitHub has <a href="http://help.github.com/post-receive-hooks/">Service Hooks</a>, FogBugz have <a href="http://fogbugz.stackexchange.com/questions/8634/fogbugz-web-hooks">Web Hooks</a> and others have similar services. This means that you can register a web hook and when an event happens the bot will tell you over Skype (in a group chat for example).</p>
<h3>What next?</h3>
<p>This is up to you, hopefully you have a friendly bot. Make him tell you important information that you care about and don&#8217;t let him waste your time. Check back to the <a href="http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit ">original article</a> if I&#8217;ve added anything to the series.</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-ii-getting-it-running/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Skype Bot for Fun and Profit &#8211; Part I &#8211; Getting Started</title>
		<link>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-i-getting-started/</link>
		<comments>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-i-getting-started/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 21:09:44 +0000</pubDate>
		<dc:creator>Toomas Römer</dc:creator>
				<category><![CDATA[cool]]></category>
		<category><![CDATA[creative]]></category>
		<category><![CDATA[humour]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=1504</guid>
		<description><![CDATA[This is a post from the Skype Bot for Fun and Profit series. This is the first part in the series and for a complete list see the original article. Join the Skype Developer Program A lot of necessary documentation and also software is behind a login screen at Skype Developer Program. You will need [...]]]></description>
			<content:encoded><![CDATA[<p><em>This is a post from the <a href="http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit">Skype Bot for Fun and Profit</a> series. This is the first part in the series and for a complete list see the <a href="http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit">original article</a>.</em></p>
<h3>Join the Skype Developer Program</h3>
<div id="dev_program"></div>
<p><img src="http://dow.ngra.de/wp-content/uploads/2012/01/skype_developer-150x150.png" alt="" title="Skype Developer Program" width="150" height="150" class="alignleft size-thumbnail wp-image-1575" />A lot of necessary documentation and also software is behind a login screen at <a href="http://developer.skype.com/" title="Skype Developer Program">Skype Developer Program</a>. You will need to join the program to continue and log in. This will cost you 10$. I personally don&#8217;t like the monetary fee for documentation and a SDK but I&#8217;m happy this is not 100$.<br />
<span id="more-1504"></span><br />
Now the biggest challenge has been conquered and you can also open up Skype&#8217;s own <a href="http://developer.skype.com/skypekit/development-guide/java-tutorial/tutorial-guide-java">Getting Started Guide</a>. That guide will go into more details with some of the next steps, so if you get stuck here be sure to check their documentation also.</p>
<h3>Create a new project at Skype</h3>
<div id="project"></div>
<p>Lets create a new project at the developer page. Navigate to My Projects submenu.There you can choose between multiple projects to create.</p>
<p><img src="http://dow.ngra.de/wp-content/uploads/2011/12/my-projects.png" alt="" title="My Projects" width="500" height="82" class="aligncenter size-full wp-image-1510" /></p>
<p>Right now you need to choose <b>SkypeKit for Desktop</b>. You can name the project something along the lines of <b>chat-bot-demo</b> and fill the rest of the form how ever you like (or they require). Now we have a project in place and we can move on.</p>
<h3>Download the SDK and the Runtime</h3>
<p>Navigate to your just created project and lets get the SDK and Runtime. SDK is the library (com.skype.*) that you will use to talk to the runtime (headless Skype client). The SDK you can download right away but for the Runtime you need to put in a request and it can take up to several hours to get the download link (usually just 5-10 minutes).</p>
<p><img src="http://dow.ngra.de/wp-content/uploads/2011/12/sdk_and_runtime.png" alt="" title="SDK and Runtime" width="500" height="168" class="aligncenter size-full wp-image-1515" /></p>
<h3>Build a sid-java-wrapper.jar file</h3>
<div id="sdk"></div>
<p>The SDK comes in source format only, before we can continue we need to get this into a single JAR file and also install it in your local maven repository. To build it we need <a href="http://ant.apache.org/">ANT</a> to be installed (I presume you do). Issue the following commands now:</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">toomasr@cigar:~/$ cd skypekit-sdk_sdk/interfaces/skype/java/api/
toomasr@cigar:~/skypekit-sdk_sdk/interfaces/skype/java/api$ ant
Buildfile: ~/skypekit-sdk_sdk/interfaces/skype/java/api/build.xml
&nbsp;
clean:
   [delete] Deleting directory ~/skypekit-sdk_sdk/interfaces/skype/java/api/bin
&nbsp;
compile:
    [mkdir] Created dir: ~/skypekit-sdk_sdk/interfaces/skype/java/api/bin
    [javac] Compiling 36 source files to ~/skypekit-sdk_sdk/interfaces/skype/java/api/bin
&nbsp;
jar:
      [jar] Building jar: ~/skypekit-sdk_sdk/interfaces/skype/java/api/sid-java-wrapper.jar
&nbsp;
clean-build:
&nbsp;
main:
&nbsp;
BUILD SUCCESSFUL
Total time: 3 seconds</pre></div></div>

<p>We have the sid-java-wrapper.jar file now in that <code>api</code> folder. For easier project setup we will be using maven (and probably for some of you shoot you in the foot as an added bonus). We will need to install the JAR file into our local repository. I will use <b>com.skype</b> as the groupId and <b>skype-sdk</b> as the artifactId. Issue the following command to do the same.</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">toomasr@cigar:~/$ cd ~/skypekit-sdk_sdk/interfaces/skype/java/api/
mvn install:install-file -Dfile=sid-java-wrapper.jar -DgroupId=com.skype -DartifactId=skype-sdk -Dversion=1.0 -Dpackaging=jar</pre></div></div>

<h3>Run the runtime</h3>
<div id="runtime"></div>
<p>Just to check if the runtime starts lets unpack and start the binary. If everything goes successfully you should see something similar. On a Linux machine I had to download couple of different binaries before I got a client that did not die (at least on EC2).</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">toomasr@cigar:~/downloadss/mac-x86-skypekit-novideo_3.5.1.1041_493734/bin/mac-x86$ ./mac-x86-skypekit-novideo 
SkypeRuntime Copyright (C) 2003-2011 Skype Technologies S.A.
SkypeRuntime Version: 3.4.1/mac-x86-skypekit-novideo_3.5.1.1041_493734
Proprietary and confidential, do not share this application.</pre></div></div>

<h3>Development keypair</h3>
<div id="keypair"></div>
<p>Next we need a development keypair. It is a signed RSA private key that you need to request from the Skype developer website. See the screenshot.</p>
<p><img src="http://dow.ngra.de/wp-content/uploads/2012/01/developer_key_pair_resized.png" alt="" title="Developer Key" width="500" height="174" class="alignnone size-full wp-image-1518" /></p>
<p>Once you have the file downloaded lets convert it to a format that is used by the Skype SDK. This is the openssl command for this. Be smarter than me and don&#8217;t accidentally overwrite the downloaded PEM file because they let you download it only once. The keypair is valid for 60 days!</p>

<div class="wp_syntax"><div class="code"><pre class="shell" style="font-family:monospace;">openssl pkcs8 -topk8 -in download-pair.pem -outform DER -out downloaded-pair.der -nocrypt</pre></div></div>

<h3>Create a Skype account for the bot</h3>
<div id="account"></div>
<p>Go to <a href="http://www.skype.com/">skype.com</a> and create an account for you bot. Also add this bot to your friend list and log in once with the bot and accept the request.</p>
<h3>Lets sum it up</h3>
<p>By now we should have the following in place</p>
<ul>
<li><a href="#dev_program">Have 10USD less on you bank account</a></li>
<li><a href="#dev_program">Skype Developer account</a></li>
<li><a href="#project">A project created at Skype Developer page</a></li>
<li><a href="#runtime">Working Skype Runtime</a></li>
<li><a href="#sdk">Skype SDK jar file</a></li>
<li><a href="#keypair">Development Keypair in PEM and DER format</a></li>
<li><a href="#account">New contact on your contact list and its username/password</a></li>
</ul>
<p>If you are missing any of those or had problems getting them then check out the more in depth documentation at <a href="https://developer.skype.com/skypekit/development-guide/java-tutorial/tutorial-guide-java">developer.skype.com</a> or post a comment.</p>
<p>Where to go from now? Check out the next part, <a href="http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-ii-getting-it-running">Getting it Running</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-i-getting-started/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Skype Bot for Fun and Profit</title>
		<link>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit/</link>
		<comments>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit/#comments</comments>
		<pubDate>Thu, 05 Jan 2012 21:08:53 +0000</pubDate>
		<dc:creator>Toomas Römer</dc:creator>
				<category><![CDATA[cool]]></category>
		<category><![CDATA[creative]]></category>
		<category><![CDATA[humour]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=1497</guid>
		<description><![CDATA[Couple of months ago I was travelling and found myself in a hotel room with many hours to kill. For no particular reason I started hacking on a Java based Skype bot. Couple of weeks later I took the time to polish it and enable it for company wide notification chatroom. Now couple of months [...]]]></description>
			<content:encoded><![CDATA[<p><em>Couple of months ago I was travelling and found myself in a hotel room with many hours to kill. For no particular reason I started hacking on a Java based Skype bot. Couple of weeks later I took the time to polish it and enable it for company wide notification chatroom. Now couple of months later I&#8217;m on vacation and will write about how to write a Skype bot in Java.</em></p>
<h3>The Plan</h3>
<div style="float:left"><img src="http://dow.ngra.de/wp-content/uploads/2012/01/183272970_54862f67b4_b.jpg" alt="" title="Bot" width="100" height="187"/><br/><span style="font-size: xx-small;"><span style="font-family: Arial;">Image by </span><a style="font-family: Arial;" href="http://www.flickr.com/photos/flysi/183272970/">Simon Abrams</a></span></div>
<p>The Skype bot needs a bit more work than your average IRC bot because of the proprietary nature of Skype. There is much clicking and downloading of certificate stuff to get you started for example. Also I want to show you how to put the bot into action, so we will go beyond just the bot.<br />
<span id="more-1497"></span></p>
<h4>Getting started</h4>
<p>In this <a href="http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-i-getting-started">Part I &#8211; Getting Started</a> we will go through the steps to get you started with the Skype developer program and download all the necessary software for the bot. The registration process, necessary accounts etc. Once you complete these steps you can develop any other bot out there.</p>
<h4>Hacking on the Java part</a></h4>
<p>In this <a href="http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit-part-ii-getting-it-running">Part II &#8211; Getting It Running</a> we will take a <a href="https://github.com/toomasr/skype-bot/">Java Skype bot</a> and get it running. It requires a little more than just compile and run so it has its own chapter.</p>
<p>We will also look into how to use this bot to notify about important information to Skype chat rooms. </p>
<h4>And maybe something more</h4>
<p>If everything went well then you have your own bot running now. There are many ways to go forward and improve the bot and the services. Lets see if we have time to cover those.</p>
<p>Hopefully next time that I have a <del>dumb</del> crazy idea I go have a beer instead.</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2012/01/06/skype-bot-for-fun-and-profit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fling &#8211; Detecting Little Fockers Furballs</title>
		<link>http://dow.ngra.de/2011/06/15/fling-detecting-little-fockers-furballs/</link>
		<comments>http://dow.ngra.de/2011/06/15/fling-detecting-little-fockers-furballs/#comments</comments>
		<pubDate>Wed, 15 Jun 2011 08:13:44 +0000</pubDate>
		<dc:creator>Toomas Römer</dc:creator>
				<category><![CDATA[cool]]></category>
		<category><![CDATA[creative]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=1384</guid>
		<description><![CDATA[This piece is the second installment in the series of Fling &#8211; Game of Furballs. It has been in the drafts for 6 months because of lack of time and/or interest. I&#8217;m on a bus to Tartu and I just might as well finish this. So in the previous part I gave you an intro [...]]]></description>
			<content:encoded><![CDATA[<p><i>This piece is the second installment in the series of <a href="http://dow.ngra.de/2010/12/27/fling-game-of-furballs/">Fling &#8211; Game of Furballs</a>. It has been in the drafts for 6 months because of lack of time and/or interest. I&#8217;m on a bus to Tartu and I just might as well finish this.</i></p>
<p>So in the previous part I gave you an intro of the game and how I stumbled upon the game and how it took over our lunches (now we have recovered and are back to random discussions). In this part we&#8217;ll look how to detect the furballs from Fling screenshots.</p>
<h2>Abstract</h2>
<p>Lets build a web service that accepts screenshots of Fling and sends you back a webpage link of the solution to the image or just bunch of attachments. </p>
<h2>Solution</h2>
<p>Lets divide and conquer.</p>
<ul>
<li>Image/Color recognition to detect the Furballs (covered in this piece)
<li>Algorithm to solve the puzzles (not covered, but code available)
<li>Algorithm to draw the 1 step screens (not covered, but code available)
<li>Email handling (not covered, but code available)
</ul>
<p><span id="more-1384"></span></p>
<h2>Detecting Furballs</h2>
<p>When I started out with this one I had no idea how to do it. I sent an email to <a href="http://kt.era.ee/">one of my friends</a> who has done image recognition and asked him how to get started. He took a look at the screenshot and asked, why do I need to recognize anything, just detect the color and you can tell if it is an empty square or a furball! It sounded so obvious that I was somewhat ashamed for not thinking of this myself :)</p>
<h2>Python and PIL</h2>
<p>Go get the latest version of <a href="http://www.pythonware.com/products/pil/">PIL</a> installed to have the examples work. Also we&#8217;ll be working from the root of the fling solver project. Just clone my <a href="https://bitbucket.org/hudolejev/flingsolver">BitBucket repo</a>. So lets get started and load up the image and verify that PIL is working. Or you can skip this and take a look at <a href="https://bitbucket.org/hudolejev/flingsolver/src/501a753cea03/blog_demo_1.py">blog_demo_1.py.</a></p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">shot = Image.<span style="color: #008000;">open</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">dirname</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">abspath</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">sys</span>.<span style="color: black;">argv</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>,       
                               <span style="color: #483d8b;">&quot;etc/shots/sample001.png&quot;</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>                          
shot_pix = shot.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>                                                              
shot.<span style="color: black;">show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p><a href="http://dow.ngra.de/wp-content/uploads/2011/06/original.png"><img src="http://dow.ngra.de/wp-content/uploads/2011/06/original-150x150.png" alt="" title="Original Image" width="150" height="150" class="alignright size-thumbnail wp-image-1464" style="margin-left:10px" /></a>Once you execute this an image should pop up, like the one on the right. Now lets isolate a square and dwell into it.</p>
<p>Because the grid is static it is a matter of figuring out the width and height and the offsets as where the squares start. You can use your top notch vision, pixel ruler or little bit of Python to get this right. Run the following and you will see how I&#8217;m using PIL to find the offsets (trial and error). You should see something like <a href="http://dow.ngra.de/wp-content/uploads/2011/06/one_marked.png">this</a>.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">x, y, w, h = <span style="color: #ff4500;">2</span>, <span style="color: #ff4500;">70</span>, <span style="color: #ff4500;">45</span>, <span style="color: #ff4500;">45</span>                                                          
<span style="color: #808080; font-style: italic;"># lets choose the leftmost square and visualise it                                  </span>
draw = ImageDraw.<span style="color: black;">Draw</span><span style="color: black;">&#40;</span>shot<span style="color: black;">&#41;</span>                                                         
draw.<span style="color: black;">rectangle</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>x, y, x+w, y+h<span style="color: black;">&#93;</span>, outline=<span style="color: black;">&#40;</span><span style="color: #ff4500;">255</span>, <span style="color: #ff4500;">255</span>, <span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>                           
<span style="color: #ff7700;font-weight:bold;">del</span> draw                                                                            
shot.<span style="color: black;">show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Ok, excellent. We now know the coordinates. Lets now average the colors. We will iterate through every pixel and take an average of the R, G, B values. We&#8217;ll also display the image for debugging purposes.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># lets find the average color</span>
avgR, avgG, avgB = <span style="color: #ff4500;">0</span>,<span style="color: #ff4500;">0</span>,<span style="color: #ff4500;">0</span>
counter = <span style="color: #ff4500;">0</span>
<span style="color: #808080; font-style: italic;"># load pixels of the image</span>
shot_pix = shot.<span style="color: black;">load</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, w<span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">for</span> j <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">xrange</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">1</span>, h<span style="color: black;">&#41;</span>:
        counter = counter + <span style="color: #ff4500;">1</span>
        avgR = avgR+shot_pix<span style="color: black;">&#91;</span>x+i, y+j<span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>
        avgG = avgG+shot_pix<span style="color: black;">&#91;</span>x+i, y+j<span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">1</span><span style="color: black;">&#93;</span>
        avgB = avgB+shot_pix<span style="color: black;">&#91;</span>x+i, y+j<span style="color: black;">&#93;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">2</span><span style="color: black;">&#93;</span>
&nbsp;
avgR = avgR/counter
avgB = avgB/counter
avgG = avgG/counter
&nbsp;
avgC = <span style="color: black;">&#40;</span>avgR,avgG,avgB<span style="color: black;">&#41;</span>
&nbsp;
draw = ImageDraw.<span style="color: black;">Draw</span><span style="color: black;">&#40;</span>shot<span style="color: black;">&#41;</span>
draw.<span style="color: black;">rectangle</span><span style="color: black;">&#40;</span><span style="color: black;">&#91;</span>x, y, x+w, y+h<span style="color: black;">&#93;</span>, outline=<span style="color: black;">&#40;</span><span style="color: #ff4500;">255</span>, <span style="color: #ff4500;">255</span>, <span style="color: #ff4500;">255</span><span style="color: black;">&#41;</span>, fill=avgC<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">del</span> draw
shot.<span style="color: black;">show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Okay, <a href="http://dow.ngra.de/wp-content/uploads/2011/06/one_avg.png">looks about right</a>. Now lets do this for the whole image. Here I will be reusing code from the flingsolver package. You can do the same.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">fip = ImProcessor<span style="color: black;">&#40;</span><span style="color: #483d8b;">'etc/shots/sample002.png'</span><span style="color: black;">&#41;</span>
fip.<span style="color: black;">debug</span> = <span style="color: #008000;">True</span>
state = fip.<span style="color: black;">process</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
fip.<span style="color: black;">show</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p><img src="http://dow.ngra.de/wp-content/uploads/2011/06/all_average2.png" alt="" title="All Average" width="324" height="478" class="aligncenter size-full wp-image-1474" /></p>
<p>Voila, all squares are marked with their average color. Now detecting furballs and not furballs is quite easy. Just make a conditional based on some color. For example I used:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">def</span> isBall<span style="color: black;">&#40;</span>...<span style="color: black;">&#41;</span>
...
<span style="color: #ff7700;font-weight:bold;">if</span> avgR <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">60</span>, <span style="color: #ff4500;">90</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">and</span> avgG <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">90</span>, <span style="color: #ff4500;">130</span><span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">and</span> avgB <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">36</span>,<span style="color: #ff4500;">55</span><span style="color: black;">&#41;</span>:        
	<span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">False</span>
<span style="color: #ff7700;font-weight:bold;">else</span>:                         
	<span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">True</span></pre></div></div>

<p>For the complete demo you can run blog_demo_1.py from the flingsolver repository. It should generate all the images shown in this post. Happy hacking your own images!</p>
<p>Next time when I have time I will continue with the solving Fling and writing the email handling.</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2011/06/15/fling-detecting-little-fockers-furballs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fling &#8211; Game of Furballs</title>
		<link>http://dow.ngra.de/2010/12/27/fling-game-of-furballs/</link>
		<comments>http://dow.ngra.de/2010/12/27/fling-game-of-furballs/#comments</comments>
		<pubDate>Sun, 26 Dec 2010 23:56:23 +0000</pubDate>
		<dc:creator>Toomas Römer</dc:creator>
				<category><![CDATA[cool]]></category>
		<category><![CDATA[creative]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=1359</guid>
		<description><![CDATA[Couple of months ago a mere 100 lines of Python inspired me to hack on a project for hours and hours from my free time for fun and profit, spend 10 USD on a domain name and play a prank on an investor. This post is an intro as how this all started out. I [...]]]></description>
			<content:encoded><![CDATA[<p><em>Couple of months ago a mere 100 lines of Python inspired me to hack on a project for hours and hours from my free time for fun <del>and profit</del>, spend 10 USD on a domain name and play a prank on an investor.</p>
<p>This post is an intro as how this all started out. I sure hope I get around to write the other posts (see the end of the post for a list of potential subjects).</em></p>
<p>I stumbled upon an iPhone game called <a href="http://itunes.apple.com/us/app/fling/id325815008?mt=8">Fling</a> that I still play every now and then (I purchased it about a year ago). The game is a puzzle game and your mission (should you choose to accept it) is to fling furballs into each other and the ones closest to the edges are flung off the board.</p>
<p>See the animated GIF for a live demo or check out the video on <a href="http://www.youtube.com/watch?v=HfteaRTGyVw">Youtube</a>. Once the board has just a single furball you&#8217;ve won!</p>
<p><a href="http://dow.ngra.de/wp-content/uploads/2010/12/flingAnimated.gif"><img src="http://dow.ngra.de/wp-content/uploads/2010/12/flingAnimated.gif" alt="" title="Animated Fling Game" width="320" height="480" class="aligncenter size-full wp-image-1360" /></a></p>
<p>As you progress the number of Furballs per level increases and finding a solution takes more time. At certain levels it takes a lot of time. Kind of reminds me of really difficult chess puzzles that can steal an hour or two from you.</p>
<p>The puzzle got so popular amongst colleagues of mine from <a href="http://www.zeroturnaround.com/">ZeroTurnaround</a> that during lunch we would place an iPad on the table with one of the levels and who ever found it interesting would give it a shot at some difficult level.</p>
<p>One time over lunch we theorized on how to solve a puzzle of this sort in algorithmic terms. We had different approaches and time estimates but one of the colleagues showed up with a Python solution the next day. Took him less than 90 minutes (apparently attended a not so interesting lecture). And in terms of time complexity we figured that on every move every furball has <code>len(furballs) - 1</code> furballs to kick out so <code>(n-1)!</code> should be a rough upper bound estimate.</p>
<p>These 100 lines of Python code started a chain reaction of learning more Python, detecting furballs from screenshots, solving the puzzle by outputting images with the moves, email exchange with the author and prank pitching him as an investor, writing an email frontend (you can send in your screenshot), profiling Python, checking out Jython and hopefully some more blog posts on the subject.</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2010/12/27/fling-game-of-furballs/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>ClassLoaderLocal: How to avoid ClassLoader leaks on application redeploy</title>
		<link>http://dow.ngra.de/2009/06/15/classloaderlocal-how-to-avoid-classloader-leaks-on-application-redeploy/</link>
		<comments>http://dow.ngra.de/2009/06/15/classloaderlocal-how-to-avoid-classloader-leaks-on-application-redeploy/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 07:51:17 +0000</pubDate>
		<dc:creator>Jevgeni Kabanov</dc:creator>
				<category><![CDATA[creative]]></category>
		<category><![CDATA[Featured]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=926</guid>
		<description><![CDATA[&#8220;OutOfMemoryError: PermGen&#8221; is a very common message to see after a few redeploys. The reason why it&#8217;s so common is that it&#8217;s amazingly easy to leak a class loader. It&#8217;s enough to hold a single outside reference to an object instantiated from a class loaded by the said class loader to prevent that class loader [...]]]></description>
			<content:encoded><![CDATA[<p><script type="text/javascript">var dzone_url = 'http://dow.ngra.de/2009/06/15/classloaderlocal-how-to-avoid-classloader-leaks-on-application-redeploy/';</script><script type="text/javascript">var dzone_title = 'ClassLoaderLocal: How to avoid ClassLoader leaks on application redeploy';</script><script type="text/javascript">var dzone_blurb = '“OutOfMemoryError: PermGen” is a very common message to see after a few redeploys. The reason why it’s so common is that it’s amazingly easy to leak a class loader. In this post I’ll review how we solved this problem in JavaRebel, and share the solution with you.';</script><script type="text/javascript">var dzone_style = '2';</script><script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script> &#8220;OutOfMemoryError: PermGen&#8221; is a very common message to see after a few redeploys. The reason why it&#8217;s so common is that it&#8217;s amazingly easy to leak a class loader. It&#8217;s enough to hold a single outside reference to an object instantiated from a class loaded by the said class loader to prevent that class loader from being GC-d.</p>
<p>In this post I&#8217;ll review how we solved this problem in <a href="http://www.zeroturnaround.com/javarebel/">JavaRebel</a>, and share the solution with you. It&#8217;s not a magical solution, but it will help alleviate some of the problems introduced in both libraries and applications in Java EE.</p>
<p>The most common way to leak is to register some kind of a callback object and never deregister it. E.g. look at the following code:<br />
[java]<br />
Core.addListener(new MyListener());<br />
[/java]<br />
If <code>Core</code> is a part of the framework/platform/container then it will hold to <code>MyListener</code> long after the application was redeployed and the class loader left hanging. </p>
<p>Let&#8217;s see if we can do anything to solve this. The <code>Core</code> implementation looks something like this:<br />
[java]<br />
public class Core {<br />
  List listeners = new ArrayList();</p>
<p>  void addListener(Listener l) {<br />
    listeners.add(l);<br />
  }</p>
<p>  void fireListeners() {<br />
    // Exercise for the reader!<br />
  }<br />
}<br />
[/java]</p>
<p>The problem is that <code>listeners</code> provides a strong reference to the <code>Listener</code> object. What if we replace it by a <a href="http://www.ibm.com/developerworks/library/j-refs/">weak one</a>?</p>
<p>[java]<br />
public class Core {<br />
  List listeners = new ArrayList();</p>
<p>  void addListener(Listener l) {<br />
    listeners.add(new WeakReference(l));<br />
  }</p>
<p>  void fireListeners() {<br />
    // Exercise for the reader!<br />
  }<br />
}<br />
[/java]</p>
<p>Unfortunately although this does solve the problem of GC-ing the class loader, it doesn&#8217;t really work. The <code>Listener</code> behind the weak reference will be GC-d at first opportunity and after that it&#8217;ll no longer receive any callbacks. To illustrate why it&#8217;s a problem the code above is basically equivalent to throwing the reference away altogether:</p>
<p>[java]<br />
public class Core {<br />
  List listeners = new ArrayList();</p>
<p>  void addListener(Listener l) {<br />
    // Listener is ignored and GC-d<br />
  }<br />
}<br />
[/java]</p>
<p>Replacing weak reference with a <em>soft</em> one doesn&#8217;t improve the situation, just delays the inevitable a bit further. Both are useful for caches, where objects can be recreated at will, but not in this case where we have an externally created object.</p>
<p>So what do we do? What we&#8217;d like to do is have the <code>Listener</code> reference to depend on the class loader somehow. Unfortunately, to the best of my knowledge, there isn&#8217;t a ready-made solution for that, and there&#8217;s no way to achieve it with any combinations of weak references without causing problems.</p>
<p>What we&#8217;d like to have is an ability to add a strong reference to the class loader: in other words have it carry a custom property:</p>
<p>[java]<br />
void addListener(Listener l) {<br />
  ClassLoader cl = l.getClass().getClassLoader();<br />
  List lls = (List) cl.getProperty(&#8220;CoreListeners&#8221;);<br />
  if (lls == null) {<br />
    lls = new ArrayList();<br />
    cl.putProperty(&#8220;CoreListeners&#8221;, lls);<br />
  }<br />
  lls.add(l);<br />
}<br />
[/java]</p>
<p>That would work, wouldn&#8217;t it? Well, not quite. We also need to save a reference to the class loaders, so that we could later go over all of them. Here the <code>WeakHashMap</code> is useful:</p>
<p>[java]<br />
Map classLoaders = new WeakHashMap();</p>
<p>void addListener(Listener l) {<br />
   //&#8230;<br />
  classLoaders.put(cl, Boolean.TRUE);<br />
}<br />
[/java]</p>
<p>There&#8217;s not <code>WeakHashSet</code> in Java, so we&#8217;re just using a boolean flag as the value.</p>
<p>So this would probably work, but unfortunately class loaders don&#8217;t have a getProperty()/putProperty() API. However, it turns out that with a bit of a hack we can simulate it, by generating a unique class per class loader to hold the properties for us. Let&#8217;s see how it&#8217;s done!</p>
<p>We start with a little boilerplate:<br />
[java]<br />
class ClassLoaderLocalMap {<br />
  private static Method defineMethod;<br />
  private static Method findLoadedClass;</p>
<p>  static {<br />
    try {<br />
      defineMethod = ClassLoader.class.getDeclaredMethod(<br />
         &#8220;defineClass&#8221;,<br />
          new Class[] {<br />
            String.class,<br />
            byte[].class,<br />
            int.class,<br />
            int.class });<br />
      defineMethod.setAccessible(true);</p>
<p>      findLoadedClass =<br />
        ClassLoader.class.getDeclaredMethod(<br />
          &#8220;findLoadedClass&#8221;,<br />
          new Class[] { String.class});<br />
      findLoadedClass.setAccessible(true);<br />
    }<br />
    catch (NoSuchMethodException e) {<br />
      throw new RuntimeException(e);<br />
    }<br />
  }<br />
}<br />
[/java]</p>
<p>This will give us access to <code>ClassLoader</code> protected methods <code>defineClass()</code> and <code>findLoadedClass()</code> later on. Now let&#8217;s setup the basic API:<br />
[java]<br />
public static void put(<br />
  ClassLoader cl,<br />
  Object  key,<br />
  Object value) {<br />
  // Synchronizing over ClassLoader is safest<br />
  synchronized (cl) {<br />
    getLocalMap(cl).put(key, value);<br />
  }<br />
}</p>
<p>public static Object get(<br />
  ClassLoader cl,<br />
  Object key) {<br />
  // Synchronizing over ClassLoader is safest<br />
  synchronized (cl) {<br />
    return getLocalMap(cl).get(key);<br />
  }<br />
}<br />
[/java]</p>
<p><code>getLocalMap()</code> method should return a map of entries associated with the class loader. How should that work?</p>
<p>Next we introduce a map from class loaders to unique holder class names. We also introduce a <code>nextHolderName()</code> method that generates unique names:<br />
[java]<br />
private static final Map classLoaderToHolderClassName =<br />
  Collections.synchronizedMap(new WeakHashMap())<br />
private static volatile int counter = 1;</p>
<p>private static String nextHolderName() {<br />
  return &#8220;ClassLoaderLocalMapHolder$$GEN$$&#8221; + counter++;<br />
}<br />
[/java]</p>
<p>Finally we can implement the <code>getLocalMap()</code> method (to save space I removed all exception handling):<br />
[java]<br />
private static Map getLocalMap(ClassLoader cl) {<br />
  String holderClassName =<br />
    (String) classLoaderToHolderClassName.get(cl);<br />
  if (holderClassName == null) {<br />
    holderClassName= nextHolderName();<br />
    classLoaderToHolderClassName.put(<br />
      cl, holderClassName);<br />
  }</p>
<p>  Class holderClass =<br />
    (Class) findLoadedClass.invoke(<br />
      cl,<br />
      new Object[] {propertiesClassName});</p>
<p>  if (holderClass  == null) {<br />
    byte[] classBytes =<br />
      buildHolderByteCode(holderClassName);</p>
<p>    holderClass = (Class) defineMethod.invoke(cl,<br />
        new Object[] {<br />
          holderClassName,<br />
          classBytes,<br />
          new Integer(0),<br />
          new Integer(classBytes.length)});<br />
  }</p>
<p>  return (Map) holderClass<br />
    .getDeclaredField(&#8220;localMap&#8221;).get(null);<br />
}<br />
[/java]</p>
<p>The last method to implement is <code>buildHolderByteCode</code>. It&#8217;s quite trivial and builds the following class renamed to the unique name:<br />
[java]<br />
public class ClassLoaderLocalMapHolder$$GEN$$X {<br />
  public static final Map localMap = new HashMap();<br />
}<br />
[/java]<br />
The code can be derived using <a href="http://asm.ow2.org/doc/tutorial.html">ASMifier</a> with just a little customization, you can look it up in the full source code.</p>
<p>Although we could now easily implement the original example it makes sense to do just a little bit extra effort and introduce a <code>ClassLoaderLocal</code>, with behavior similar to the <code>ThreadLocal</code>:<br />
[java]<br />
public class ClassLoaderLocal {<br />
  private Object key = new Object();</p>
<p>  public Object get(ClassLoader cl) {<br />
    if (!ClassLoaderProperties.containsKey(cl, key))<br />
      return null;<br />
    return ClassLoaderProperties.get(cl, key);<br />
  }</p>
<p>  public void set(ClassLoader cl, Object value) {<br />
    ClassLoaderProperties.put(cl, key, value);<br />
  }<br />
}<br />
[/java]</p>
<p>So the original example now becomes:</p>
<p>[java]<br />
Map classLoaders = new WeakHashMap();<br />
ClassLoaderLocal cll = new ClassLoaderLocal();</p>
<p>void addListener(Listener l) {<br />
  ClassLoader cl = l.getClass().getClassLoader();<br />
  List lls = (List) cll.get(cl);<br />
  if (lls == null) {<br />
    lls = new ArrayList();<br />
    cll.set(cl, lls);<br />
  }<br />
  lls.add(l);</p>
<p>  classLoaders.put(cl, Boolean.TRUE);<br />
}<br />
[/java]</p>
<p>In this code if any listener comes from a freed class loader, then it will be GC-d from both <code>Core.classLoaders</code> and <code>ClassLoaderProperties.classLoaderToHolderClassName</code>, as both are <code>WeakHashMap</code>s and there are no strong references to the class loaders. The generated <code>ClassLoaderLocalMapHolder$$GEN$$X</code> class will also be GC-d along with the class loader, so we have effectively eliminated a class loader leak without explicit cleanup calls from the user.</p>
<p>I hope this code will be useful for someone. I cannot give any guarantees whether it will work or not and it&#8217;s clearly a hack (though a solid hack).  Please use it if you actually understand what is happening.</p>
<p>If you see a bug in the code or have a good suggestion, please be sure to comment. There could be a free JavaRebel license in it for you :)</p>
<p>Full source code: <a href='http://dow.ngra.de/wp-content/uploads/2009/06/classloaderlocalmap.java'>ClassLoaderLocalMap.java</a>, <a href='http://dow.ngra.de/wp-content/uploads/2009/06/classloaderlocal.java'>ClassLoaderLocal.java</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2009/06/15/classloaderlocal-how-to-avoid-classloader-leaks-on-application-redeploy/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Where did my OOM go?</title>
		<link>http://dow.ngra.de/2009/03/24/where-did-my-oom-go/</link>
		<comments>http://dow.ngra.de/2009/03/24/where-did-my-oom-go/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 10:54:45 +0000</pubDate>
		<dc:creator>Ivo Mägi</dc:creator>
				<category><![CDATA[cool]]></category>
		<category><![CDATA[creative]]></category>
		<category><![CDATA[humour]]></category>
		<category><![CDATA[cdo]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=785</guid>
		<description><![CDATA[Editor: We have a guest appearance from a CDO of a Fortune 500 company (actually not Fortune 500, but yes, a development manager for 200 devs). The twist? He has a compiler installed and apparently an editor too. The other day I was playing around with a tool for memory analysis and wrote a small [...]]]></description>
			<content:encoded><![CDATA[<p><em>Editor: We have a guest appearance from a CDO of a Fortune 500 company (actually not Fortune 500, but yes, a development manager for 200 devs). The twist? He has a compiler installed and apparently an editor too.</em></p>
<p>The other day I was playing around with a tool for memory analysis and wrote a small snippet using which I would be able to test the new tool. Quickly (<em>Editor: yeah right quickly)</em> created the following and executed it:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.*</span><span style="color: #339933;">;</span>   
<span style="color: #000000; font-weight: bold;">class</span> Leak <span style="color: #009900;">&#123;</span>  
  <span style="color: #000000; font-weight: bold;">static</span> List<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span> list <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<span style="color: #339933;">&lt;</span>Integer<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>  
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&gt;=</span> <span style="color: #cc66cc;">0</span> <span style="color: #339933;">;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>  
      list.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
    <span style="color: #009900;">&#125;</span>  
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;I will either reach here or die trying (with OOM)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
  <span style="color: #009900;">&#125;</span>  
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And what do you think I was displayed by my command prompt <em>(editor: CDOs don't have a command prompt)</em>:</p>
<p>Option A:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Exception</span> in thread <span style="color: #0000ff;">&quot;main&quot;</span> java.<span style="color: #006633;">lang</span>.<span style="color: #003399;">OutOfMemoryError</span><span style="color: #339933;">:</span> Java heap space
        at java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Arrays</span>.<span style="color: #006633;">copyOf</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Arrays</span>.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">2760</span><span style="color: #009900;">&#41;</span>
        at java.<span style="color: #006633;">util</span>.<span style="color: #003399;">Arrays</span>.<span style="color: #006633;">copyOf</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">Arrays</span>.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">2734</span><span style="color: #009900;">&#41;</span>
        at java.<span style="color: #006633;">util</span>.<span style="color: #003399;">ArrayList</span>.<span style="color: #006633;">ensureCapacity</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">ArrayList</span>.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">167</span><span style="color: #009900;">&#41;</span>
        at java.<span style="color: #006633;">util</span>.<span style="color: #003399;">ArrayList</span>.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">ArrayList</span>.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">351</span><span style="color: #009900;">&#41;</span>
        at Leak.<span style="color: #006633;">main</span><span style="color: #009900;">&#40;</span>Leak.<span style="color: #006633;">java</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">6</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>Option B:</p>
<pre>
I will either reach here or die trying (with OOM)
</pre>
<p>Well, as I found out, it doesn’t print out anything. As this is now two years from my last real Java development experience (got demoted to C-level), I went to my hardcore Java hackers. For 10 minutes we all stood with bedazzled faces, before it struck – the memory will be allocated in a way that there is no room for <code>new OutOfMemoryError()</code> to be created.</p>
<p>If you execute the above with 64MB heapsize (which is the default heapsize):</p>
<pre>
C:\work\snippets\leak java -Xmx64m Leak
C:\work\snippets\leak
</pre>
<p>But if you increase (well actually modify) the heap size a bit:</p>
<pre>C:\work\snippets\leak java -Xmx65m Leak
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at java.util.Arrays.copyOf(Arrays.java:2760)
        at java.util.Arrays.copyOf(Arrays.java:2734)
        at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
        at java.util.ArrayList.add(ArrayList.java:351)
        at Leak.main(Leak.java:6)
C:\work\snippets\leak
</pre>
<p>Moral of the story? I definitely would not want to be fixing a production system dying like this <em>(Editor: lucky you, you don't have to) </em>– most likely I would be mad way before I could have grasped anything about the reasons …</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2009/03/24/where-did-my-oom-go/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Mysteries of &#8220;Protected&#8221;</title>
		<link>http://dow.ngra.de/2009/03/13/the-mysteries-of-protected/</link>
		<comments>http://dow.ngra.de/2009/03/13/the-mysteries-of-protected/#comments</comments>
		<pubDate>Fri, 13 Mar 2009 00:08:38 +0000</pubDate>
		<dc:creator>Jevgeni Kabanov</dc:creator>
				<category><![CDATA[creative]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=736</guid>
		<description><![CDATA[This post is a follow up to the Ultimate Java Puzzler. I was going to name it &#8220;The Most Penultimate Java Puzzler Ever to Exist&#8221;, but it just doesn&#8217;t have the same ring to it anymore :) The previous post was about the weird relation between default visibility and method overriding, which in the end [...]]]></description>
			<content:encoded><![CDATA[<p>This post is a follow up to the <a href="http://dow.ngra.de/2009/02/16/the-ultimate-java-puzzler/">Ultimate Java Puzzler</a>. I was going to name it &#8220;The Most Penultimate Java Puzzler Ever to Exist&#8221;, but it just doesn&#8217;t have the same ring to it anymore :)  </p>
<p>The previous post was about the weird relation between <code>default</code> visibility and method overriding, which in the end meant that <code>@Override</code> is broken in some cases. Today we&#8217;ll take a look at <code>protected</code>.</p>
<p>The main issue with <code>protected</code> in Java is that unlike C++ and most other OO languages it can pose in one of two incarnations &#8212; either as visibility from subtypes or as visibility in the same package (the latter is just like the <code>default</code> visibility). This can sometime lead to some confusion, but I have a specific case of interest to offer you.</p>
<p>In the previous post there already was one example involving <code>protected</code>:<br />
[java]<br />
public class /*p1.*/Main {<br />
  public static void main(String[] args) {<br />
    C1 c = new p2.C3();<br />
    System.out.println(c.m());<br />
  }<br />
}<br />
public class /*p1.*/C1 {<br />
  /*default*/ int m() {return 1;}<br />
}<br />
public class /*p1.*/C2 extends C1 {<br />
  protected int m() {return 2;}<br />
}<br />
public class /*p2.*/C3 extends p1.C2 {<br />
  protected int m() {return 3;}<br />
}<br />
[/java]</p>
<p>The relevant part in this example is that <code>protected</code> method is invoked via <code>default</code> visibility, but overridden via subtyping visibility. In case you don&#8217;t remember anymore the output is &#8220;3&#8243;. This shows that visibilities and overriding can be mixed pretty much freely. It is also a good example as it demonstrates why the original phrasing in the JVM spec was wrong. In the original phrasing for the method <code>C3.m</code> to override a method <code>C1.m</code> the latter had to be accessible from the former. In our example this is obviously not the case.</p>
<p>The corrected phrasing, available in the <a href="http://java.sun.com/docs/books/jvms/second_edition/jvms-clarify.html">addendum</a>, refers to the <a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.8">JLS notion of overriding</a>, which adds transitivity. That is if <code>C3.m</code> overrides <code>C2.m</code> and <code>C2.m</code> overrides <code>C1.m</code> then <code>C3.m</code> overrides <code>C1.m</code>.</p>
<p>But getting back to the topic &#8212; when playing around with <a href="http://www.zeroturnaround.com/javarebel/">JavaRebel</a> I stumbled on an even more interesting example where this dual nature of <code>protected</code> makes it act unexpectedly. The setup starts like this:<br />
[java]<br />
public class /*p1.*/Main {<br />
  public static void main(String[] args) {<br />
    p2.C2  c = new p2.C2();<br />
    System.out.println(c.m());<br />
  }<br />
}<br />
public class /*p1.*/C1 {<br />
  protected  int m() {return 1;}<br />
}<br />
public class /*p2.*/C2 extends p1.C1 {<br />
}<br />
[/java]</p>
<p>This compiles and behaves as expected outputting &#8220;1&#8243;. A question I&#8217;d like to ask is: what happens if for some reason later you override the method <code>m()</code> in <code>C2</code>?</p>
<p>[java]<br />
public class /*p1.*/Main {<br />
  public static void main(String[] args) {<br />
    p2.C2  c = new p2.C2();<br />
    System.out.println(c.m());<br />
  }<br />
}<br />
public class /*p1.*/C1 {<br />
  protected  int m() {return 1;}<br />
}<br />
public class /*p2.*/C2 extends p1.C1 {<br />
  protected  int m() {return 2;}<br />
}<br />
[/java]</p>
<p>Stop here for a second, take a look at it and hazard a guess&#8230;</p>
<p><center><img src="http://dow.ngra.de/wp-content/uploads/2009/03/roulette-300x207.jpg" alt="roulette" title="roulette" width="300" height="207" class="alignnone size-medium wp-image-749" /></center></p>
<p>The example seems similar to the previous one, so you&#8217;d expect that the output is &#8220;2&#8243;. But is it?</p>
<p>Let&#8217;s evaluate this from the point of compiler and JVM. Initially the call to <code>C2.m</code> from <code>Main</code> resolved to <code>C1.m()</code>, which is in the same package with <code>Main</code>. When we override the method this is no longer the case and actually the method isn&#8217;t accessible anymore. So the correct answer is that the code won&#8217;t compile.</p>
<p>This is strongly counterintuitive to me, mainly because I always assumed that overriding a method should never affect its caller in such a way. This also isn&#8217;t limited to a compile-time error, as it&#8217;s quite possible to compile the <code>C2</code> without recompiling the rest of the classes and get an <code>IllegalAccessError</code> at runtime. So in my book this reads quite unnatural.</p>
<p>There are definitely more creative ways to f**k up with <code>protected</code> you can come up with, by moving from the &#8220;default&#8221; incarnation to the subtype one. If you know a good one do post it in the comments.</p>
<p>P.S. I&#8217;d love to see what weirdness would come if they&#8217;d actually introduce the <code>module</code> keyword as well. Luckily it&#8217;d be limited mostly to compile time, but as you saw even there things can get tricky.</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2009/03/13/the-mysteries-of-protected/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Is the Relational Database Not an Option in Cloud Computing?</title>
		<link>http://dow.ngra.de/2009/02/20/is-the-relational-database-not-an-option-in-cloud-computing/</link>
		<comments>http://dow.ngra.de/2009/02/20/is-the-relational-database-not-an-option-in-cloud-computing/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 19:16:35 +0000</pubDate>
		<dc:creator>Jevgeni Kabanov</dc:creator>
				<category><![CDATA[creative]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=729</guid>
		<description><![CDATA[InfoQ: Though scalability is a key factor, cloud computing has other advantages that makes it attractive for vendors that do not need to deliver highly scalable applications or services. &#8212; you know when something is way overhyped, when it starts to be presented as a solution to all of your problems, even the ones it [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.infoq.com/news/2009/02/Relational-DB-Cloud">InfoQ:</a> <em>Though scalability is a key factor, cloud computing has other advantages that makes it attractive for vendors that do not need to deliver highly scalable applications or services.</em> &#8212; you know when something is way overhyped, when it starts to be presented as a solution to all of your problems, even the ones it was never intended for. Also the keywords like &#8220;doomed&#8221; give a strong hint&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2009/02/20/is-the-relational-database-not-an-option-in-cloud-computing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Correcting the Billion Dollar Mistake</title>
		<link>http://dow.ngra.de/2009/02/01/correcting-the-billion-dollar-mistake/</link>
		<comments>http://dow.ngra.de/2009/02/01/correcting-the-billion-dollar-mistake/#comments</comments>
		<pubDate>Sun, 01 Feb 2009 20:04:14 +0000</pubDate>
		<dc:creator>Jevgeni Kabanov</dc:creator>
				<category><![CDATA[creative]]></category>
		<category><![CDATA[Featured]]></category>

		<guid isPermaLink="false">http://dow.ngra.de/?p=628</guid>
		<description><![CDATA[Last week I visited Stockholm to speak at the JFokus 2009. The event was quite spectacular, but for me the most interesting part occurred on the evening before the conference. I was sitting at the speaker&#8217;s dinner with Rickard Öberg, Kirk Pepperdine, Simon Ritter and a couple of others. For some reason or other I [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I visited Stockholm to speak at the <a href="http://www.jfokus.se/jfokus/">JFokus 2009</a>. The event was quite spectacular, but for me the most interesting part occurred on the evening before the conference. I was sitting at the speaker&#8217;s dinner with Rickard Öberg, Kirk Pepperdine, Simon Ritter and a couple of others. For some reason or other I started talking to Simon about the problem that&#8217;s recently been on my mind. Perhaps it&#8217;s been eating me after legendary Tony Hoare <a href="http://qconlondon.com/london-2009/presentation/Null+References:+The+Billion+Dollar+Mistake">said this</a>:</p>
<blockquote><p>I call it my billion-dollar mistake. It was the invention of the null reference in 1965. [...] This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.</p></blockquote>
<p>Now since I have a background in functional languages, I know that null references are not necessary. Null value is a member of all types, but some types don&#8217;t have or need a natural notion of absence. In fact in Haskell there is no such thing as an &#8220;absent&#8221; value generic to all types &#8212; types either have to declare it explicitly or wrap the underlying value into a <code>Maybe</code> type that has a dedicated <code>Nothing</code> value.</p>
<p>So e.g. the <code>List</code> type has a notion of an empty list encoded into the type:</p>
<pre>
// Roughly: a list is an empty list
// or a pair of a value and a list
data List a = Nil | Cons a (List a)
</pre>
<p>While the only way to encode an absent structure is to use <code>Maybe</code>:</p>
<pre>
// To build a car you need at most one engine
// and zero or more wheels :)
buildCar :: Maybe Engine -> [Wheel]  -> Car
</pre>
<p>So while I was discussing that with Simon, Kirk banged me on the head to get my attention (just joking, banging me on the head is nowhere near enough to get my attention). Apparently they were discussing more or less the same topic with Rickard, and he had a similar solution for Java. I assumed it was the widely discussed <a href="http://www.jetbrains.com/idea/documentation/howto.html"><code>@NotNull</code></a> annotation, but it was way cooler than that.</p>
<p>Basically in the beginning Rickard started by adding <code>@NotNull</code> support to <a href="http://www.qi4j.org/">Qi4J</a> (BTW an amazing piece of engineering, definitely check it out), so that they could automatically insert runtime assertions for the parameters having the <code>@NotNull</code> annotations, something like that:<br />
[java]<br />
class Test {<br />
  void transfer(<br />
    @NotNull Account from,<br />
    Account to,<br />
    double amount) {<br />
      //&#8230;<br />
  }</p>
<p>  public static void main(String[] args) {<br />
    // Succeeds<br />
    transfer(<br />
      new Account(&#8220;Bugs Bunny&#8221;), null, 1000000.0);<br />
    // Throws NullPointerException<br />
    transfer(<br />
      null, new Account(&#8220;Bugs Bunny&#8221;), 1000000.0);<br />
  }<br />
}<br />
[/java]</p>
<p>However soon after that they discovered that they were inserting <code>@NotNull</code>-s everywhere. So they reverted the notion and decided that they will generate the not null assertions for <em>all</em> parameters <em>except</em> the ones marked as <code>@Optional</code>. And this was the point when I thought to myself &#8220;Jevgeni, this is exactly what you were looking for!&#8221; So I turn to Rickard and I say &#8220;Rickard, this is exactly what I was looking for! This is amazing!&#8221; In fact this truly is amazing as it&#8217;s exactly captures the semantics of the <code>Maybe</code> type that I liked so much in the functional languages.</p>
<p>After that we go into a discussion whether or not it is possible to validate this assertion during compile-time. Opinions were mixed on this one, though I personally am convinced that it shouldn&#8217;t be too easy (your opinion on the topic is welcome, also it will make a great master&#8217;s thesis topic). Eventually I get an idea and I say &#8220;Rickard, I bet I could implement a <a href="http://www.zeroturnaround.com/javarebel/">JavaRebel</a> plugin that would check this at runtime in about half an hour in 50 lines of code&#8221;. And of course Rickard goes &#8220;No way!&#8221;, so I&#8217;m challenged. Next day I sit down for half an hour, then for another half an hour (there was no internet!) and voila &#8212; I have a working JavaRebel plugin (in less that 50 lines of code) that will make your methods throw an exception if you try to pass a null reference to a parameter not marked as <code>@Optional</code> (the plugin code deserves another post altogether). Of course I have to show this to Rickard (and he goes &#8220;No way!&#8221;) and we agree to somehow join forces to promote this sane approach (starting with having a single namespace for the <code>@Optional</code> annotation).</p>
<p>So what do we get? The previous example now looks like this:<br />
[java]<br />
@OptionalCheck<br />
class Test {<br />
  void transfer(<br />
    Account from,<br />
    @Optional Account to,<br />
    double amount) {<br />
      //&#8230;<br />
  }</p>
<p>  public static void main(String[] args) {<br />
    // Succeeds<br />
    transfer(<br />
      new Account(&#8220;Bugs Bunny&#8221;), null, 1000000.0);<br />
    // Throws NullPointerException<br />
    transfer(<br />
      null, new Account(&#8220;Bugs Bunny&#8221;), 1000000.0);<br />
  }<br />
}<br />
[/java]<br />
As you can understand if we make all of the code without the <code>@Optional</code> annotation to throw a <code>NullPointerException</code> for nulls we&#8217;ll break a lot of existing code. Therefore at the moment you also have to annotate the class where you want to enable such semantics with <code>@OptionalCheck</code>. </p>
<p>That&#8217;s pretty much it &#8212; you can <a href="http://repos.zeroturnaround.com/maven2/org/zeroturnaround/javarebel-optional-check-plugin/1.0/javarebel-optional-check-plugin-1.0.jar">download the plugin right away</a> and just drop it in the classpath when <a href="http://www.zeroturnaround.com/javarebel/">JavaRebel</a> is enabled (you&#8217;ll need a 2.0 milestone as 1.x was missing the necessary APIs). At the moment both annotations are in the <code>org.optionalalliance</code> package, but when it changes all you have to do is Organize Imports, so I won&#8217;t sweat the naming too much. Please do let us know what do you think of the approach and feel free to advocate it further :)</p>
<p>Cheers,<br />
Jevgeni Kabanov</p>
<p>P.S. The plugin along with the source is also avalable in our Maven repository:</p>
<ul>
<li>URL: <a href="http://repos.zeroturnaround.com/maven2">http://repos.zeroturnaround.com/maven2</a></li>
<li>Group id: <code>org.zeroturnaround</code></li>
<li>Artifact id: <code>javarebel-optional-check-plugin</code></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dow.ngra.de/2009/02/01/correcting-the-billion-dollar-mistake/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
	</channel>
</rss>

