<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>CoffeeOneSugar's Blog</title>
	<atom:link href="http://coffeeonesugar.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://coffeeonesugar.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Wed, 04 Jan 2012 20:37:31 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='coffeeonesugar.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>CoffeeOneSugar's Blog</title>
		<link>http://coffeeonesugar.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://coffeeonesugar.wordpress.com/osd.xml" title="CoffeeOneSugar&#039;s Blog" />
	<atom:link rel='hub' href='http://coffeeonesugar.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Getting started with Esper in 5 minutes.</title>
		<link>http://coffeeonesugar.wordpress.com/2009/07/21/getting-started-with-esper-in-5-minutes/</link>
		<comments>http://coffeeonesugar.wordpress.com/2009/07/21/getting-started-with-esper-in-5-minutes/#comments</comments>
		<pubDate>Tue, 21 Jul 2009 00:26:32 +0000</pubDate>
		<dc:creator>coffeeonesugar</dc:creator>
				<category><![CDATA[Event Processing]]></category>

		<guid isPermaLink="false">http://coffeeonesugar.wordpress.com/?p=126</guid>
		<description><![CDATA[In a previous post I mentioned my recent enthusiasm for Complex Event Processing (CEP). In short, Complex Event Processors take as an input a stream of data and either redirect parts of it to listeners according to a set of &#8230; <a href="http://coffeeonesugar.wordpress.com/2009/07/21/getting-started-with-esper-in-5-minutes/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=126&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In a previous post I mentioned my recent enthusiasm for Complex Event Processing (CEP). In short, Complex Event Processors take as an input a stream of data and either redirect parts of it to listeners according to a set of predefined rules, or trigger events whenever a pattern is found in the data. This is particularly useful in situations where   massive amounts of data generated need to be analyzed in real-time.</p>
<p>A really brilliant piece of software that allows you to do just that is called ESPER. You can find the website of the project right <a href="http://esper.codehaus.org/">here</a>. Esper provides programmers with a language called EPL, mildly similar to SQL, that facilitate the configuration of the rules and patterns that will be applied on the data stream.</p>
<p>The documentation that comes with ESPER is quite complete, but it lacks practical examples, which makes it look like Esper is complicated to use. So here it is, a five minutes guide to Esper. Esper is available in Java, and C#, although the example that follows is written in Java. I assume that you have already downloaded Esper, which can be done by clicking on <a href="http://dist.codehaus.org/esper/esper-3.1.0.zip">this link</a>. After unzipping the file you have just downloaded, you should have a folder called <code>esper-3.1.0 </code>somewhere on your disk.</p>
<p>Before getting started, you need to add a couple of  libraries to your project. Of course, esper-3.1.0.jar is one of them, but you also need four third-party libraries that are all located in the <code>esper-3.1.0/esper/lib</code> folder.</p>
<p>The five minutes start now. The data we would like to analyze need to be structured in the form of objects before it can be thrown down the pipe to our CEP engine. Let us use a simple example and write a class (some may call it a bean) that represents a stock price at a given time (a stock tick).</p>
<p><pre class="brush: java;">
import java.util.Date;
    public static class Tick {
        String symbol;
        Double price;
        Date timeStamp;

        public Tick(String s, double p, long t) {
            symbol = s;
            price = p;
            timeStamp = new Date(t);
        }
        public double getPrice() {return price;}
        public String getSymbol() {return symbol;}
        public Date getTimeStamp() {return timeStamp;}

        @Override
        public String toString() {
            return &quot;Price: &quot; + price.toString() + &quot; time: &quot; + timeStamp.toString();
        }
    }
</pre></p>
<p>It has three properties: a symbol name (say &#8220;AAPL&#8221; for Apple&#8217;s stock), a price and a time stamp. Before we start generating billions of ticks, we need to inform the engine about the the kind of objects it will have to handle. This is done via the &#8220;Configuration&#8221; object that is used when instantiating the CEP engine.<br />
<pre class="brush: java;">
import com.espertech.esper.client.*;

public class main {

   public static void main(String [] args){

    //The Configuration is meant only as an initialization-time object.
    Configuration cepConfig = new Configuration();
    // We register Ticks as objects the engine will have to handle
    cepConfig.addEventType(&quot;StockTick&quot;,Tick.class.getName());

   // We setup the engine
EPServiceProvider cep = EPServiceProviderManager.getProvider(&quot;myCEPEngine&quot;,cepConfig);
   }
}
</pre><br />
For testing purposes, we now create a function that generates random ticks, and throw them down the pipe to the CEP engine. We call this function &#8220;GenerateRandomTick&#8221;. It takes an EPRuntime object as an argument. This object is used to transmit events to the CEP engine.<br />
<pre class="brush: java;">
import java.util.Random;
import com.espertech.esper.client.*;

public class exampleMain {
   private static Random generator=new Random();

   public static void GenerateRandomTick(EPRuntime cepRT){
    double price = (double) generator.nextInt(10);
    long timeStamp = System.currentTimeMillis();
    String symbol = &quot;AAPL&quot;;
    Tick tick= new Tick(symbol,price,timeStamp);
    System.out.println(&quot;Sending tick:&quot; + tick);
    cepRT.sendEvent(tick);
}

    public static void main(String[] args) {
     //The Configuration is meant only as an initialization-time object.
      Configuration cepConfig = new Configuration();
     cepConfig.addEventType(&quot;StockTick&quot;,Tick.class.getName());

      EPServiceProvider cep=EPServiceProviderManager.getProvider(&quot;myCEPEngine&quot;,cepConfig);

      EPRuntime cepRT = cep.getEPRuntime();
    }
}
</pre> </p>
<p>Now we have a working CEP engine and a fake data feed, it is time to create our first rule, or in the Esper parlance, our first EPL statement. To do so we need to ask the administrator of the engine to record our statement. The CEP engine will then filter the data it receives, and trigger events whenever that data meets the selection rule, or fulfills the pattern defined in the statement.<br />
<pre class="brush: java;">
 public static void main(String[] args) {
//The Configuration is meant only as an initialization-time object.
Configuration cepConfig = new Configuration();
cepConfig.addEventType(&quot;StockTick&quot;,Tick.class.getName());
EPServiceProvider cep = EPServiceProviderManager.getProvider(&quot;myCEPEngine&quot;,cepConfig);
EPRuntime cepRT = cep.getEPRuntime();

// We register an EPL statement
EPAdministrator cepAdm = cep.getEPAdministrator();
EPStatement cepStatement = cepAdm.createEPL(&quot;select * from &quot; +
                                &quot;StockTick(symbol='AAPL').win:length(2) &quot; +
                                &quot;having avg(price) &gt; 6.0&quot;);
    }
</pre><br />
Here, an event in the form of a stock tick will be triggered every time the average over the last 2 ticks is above the value of 6.0.  </p>
<p>The next step now consists in creating a listener and connect it to the events generated by our selection rule. This can be done as follows:<br />
<pre class="brush: java;">
cepStatement.addListener(new CEPListener());
</pre><br />
There are different ways to implement listener, although the following is the simplest one. Here the listener simply prints the object it has received from the engine:<br />
<pre class="brush: java;">
public static class CEPListener implements UpdateListener {
 public void update(EventBean[] newData, EventBean[] oldData) {
         System.out.println(&quot;Event received: &quot;
                            + newData[0].getUnderlying());
    }
}
</pre><br />
So far, so good. It is now time to test our code.  let&#8217;s generate a few ticks and see if things work. This can be done by adding the following line at the end of the main function:<br />
<pre class="brush: java;">
for(int i = 0; i&lt; 5; i++)
    GenerateRandomTick(cepRT);
</pre><br />
The code now looks like this (I have placed the Tick class inside the main program so that you should be able to cut and paste the following in one file and run it):<br />
<pre class="brush: java;">
import com.espertech.esper.client.*;
import java.util.Random;
import java.util.Date;

public class exampleMain {

    public static class Tick {
        String symbol;
        Double price;
        Date timeStamp;

        public Tick(String s, double p, long t) {
            symbol = s;
            price = p;
            timeStamp = new Date(t);
        }
        public double getPrice() {return price;}
        public String getSymbol() {return symbol;}
        public Date getTimeStamp() {return timeStamp;}

        @Override
        public String toString() {
            return &quot;Price: &quot; + price.toString() + &quot; time: &quot; + timeStamp.toString();
        }
    }

    private static Random generator = new Random();

    public static void GenerateRandomTick(EPRuntime cepRT) {

        double price = (double) generator.nextInt(10);
        long timeStamp = System.currentTimeMillis();
        String symbol = &quot;AAPL&quot;;
        Tick tick = new Tick(symbol, price, timeStamp);
        System.out.println(&quot;Sending tick:&quot; + tick);
        cepRT.sendEvent(tick);

    }

    public static class CEPListener implements UpdateListener {

        public void update(EventBean[] newData, EventBean[] oldData) {
            System.out.println(&quot;Event received: &quot; + newData[0].getUnderlying());
        }
    }

    public static void main(String[] args) {

//The Configuration is meant only as an initialization-time object.
        Configuration cepConfig = new Configuration();
        cepConfig.addEventType(&quot;StockTick&quot;, Tick.class.getName());
        EPServiceProvider cep = EPServiceProviderManager.getProvider(&quot;myCEPEngine&quot;, cepConfig);
        EPRuntime cepRT = cep.getEPRuntime();

        EPAdministrator cepAdm = cep.getEPAdministrator();
        EPStatement cepStatement = cepAdm.createEPL(&quot;select * from &quot; +
                &quot;StockTick(symbol='AAPL').win:length(2) &quot; +
                &quot;having avg(price) &gt; 6.0&quot;);

        cepStatement.addListener(new CEPListener());

       // We generate a few ticks...
        for (int i = 0; i &lt; 5; i++) {
            GenerateRandomTick(cepRT);
        }
    }
}
</pre><br />
Output:<br />
<pre class="brush: java;">
log4j:WARN No appenders could be found for logger (com.espertech.esper.epl.metric.MetricReportingPath).
log4j:WARN Please initialize the log4j system properly.
Sending tick:Price: 6.0 time: Tue Jul 21 01:11:15 CEST 2009
Sending tick:Price: 0.0 time: Tue Jul 21 01:11:15 CEST 2009
Sending tick:Price: 7.0 time: Tue Jul 21 01:11:15 CEST 2009
Sending tick:Price: 4.0 time: Tue Jul 21 01:11:15 CEST 2009
Sending tick:Price: 9.0 time: Tue Jul 21 01:11:15 CEST 2009
Event received: Price: 9.0 time: Tue Jul 21 01:11:15 CEST 2009
</pre></p>
<p>As you can see, only the last two ticks have an average above the value of 6.0, and therefore only one event was triggered by the engine. Fantastic! </p>
<p>Oh, you maybe worry about the two first lines. Yeah, there is still a bit of an issue to sort out. In fact, Esper uses a logging package called log4j that causes these warnings. It can be configured using a file called log4j.xml which you will find in the /etc folder of one of the example project in esper-3.1.0/examples. I don&#8217;t think that having a XML configuration file for everything is a very good idea and therefore I have used to following trick to configure the logger. Add the following imports at the beginning of your file:<br />
<pre class="brush: java;">
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
</pre><br />
and this in the main function before the rest of your code:<br />
<pre class="brush: java;">
 public static void main(String [] args){

      SimpleLayout layout = new SimpleLayout();
      ConsoleAppender appender = new ConsoleAppender(new SimpleLayout());
      Logger.getRootLogger().addAppender(appender);
      Logger.getRootLogger().setLevel((Level) Level.WARN);
(...)
</pre></p>
<p>The five minutes are now over.</p>
<p>In my next posts, I will explore EPL statements a little bit more in depth, and provide some code to connect two engines together in order to facilitate what is called &#8220;event refinement&#8221;.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coffeeonesugar.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coffeeonesugar.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coffeeonesugar.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coffeeonesugar.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/coffeeonesugar.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/coffeeonesugar.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/coffeeonesugar.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/coffeeonesugar.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coffeeonesugar.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coffeeonesugar.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coffeeonesugar.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coffeeonesugar.wordpress.com/126/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coffeeonesugar.wordpress.com/126/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coffeeonesugar.wordpress.com/126/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=126&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://coffeeonesugar.wordpress.com/2009/07/21/getting-started-with-esper-in-5-minutes/feed/</wfw:commentRss>
		<slash:comments>30</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f86d07c942cb53f7267a3605fc462141?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coffeeonesugar</media:title>
		</media:content>
	</item>
		<item>
		<title>Complex Event Processing with Esper</title>
		<link>http://coffeeonesugar.wordpress.com/2009/07/19/complex-event-processing-with-esper/</link>
		<comments>http://coffeeonesugar.wordpress.com/2009/07/19/complex-event-processing-with-esper/#comments</comments>
		<pubDate>Sun, 19 Jul 2009 00:04:58 +0000</pubDate>
		<dc:creator>coffeeonesugar</dc:creator>
				<category><![CDATA[Event Processing]]></category>

		<guid isPermaLink="false">http://coffeeonesugar.wordpress.com/?p=108</guid>
		<description><![CDATA[I have been quite busy these days since I discovered this really cool open-source piece of code called Esper. Esper is a Complex Event Processor (CEP). In other words, it is an engine that detects patterns in a stream of &#8230; <a href="http://coffeeonesugar.wordpress.com/2009/07/19/complex-event-processing-with-esper/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=108&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have been quite busy these days since I discovered this really cool open-source piece of code called <a href="http://esper.codehaus.org/">Esper</a>.</p>
<p>Esper is a Complex Event Processor (CEP). In other words, it is an engine that detects patterns in  a stream of high-frequency data, and notify them by sending an event (in the form of a Java object) to a listener. In short:</p>
<blockquote><p>Basically instead of working as a database where you put stuff in to later poll it using SQL queries, Esper works as real time engine that triggers actions when event conditions occur among event streams. A tailored Event Processing Language (EPL) allows registering queries in the engine, using Java objects (POJO, JavaBean) to represent events. A listener class &#8211; which is basically also a POJO &#8211; will then be called by the engine when the EPL condition is matched as events come in. The EPL allows expressing complex matching conditions that include temporal windows, and join different event streams, as well as filter and sort them.</p></blockquote>
<p>It&#8217;s all Java, terribly smart, simple and yet diabolically complete. Everything works with POJOS (no bullshit java objects) and there are testing units. Oh, and it&#8217;s really, really fast. It ships with a query language that is already strangely familiar to those who used to work with SQL.</p>
<p>I will post bits of code on how to use Esper pretty soon, stay tuned.</p>
<p>For those of you who need an introduction on Complex Event processing, they can read this series of articles by Tim Bass:<br />
<a href="http://www.thecepblog.com/2007/05/14/what-is-complex-event-processing-part-1/">What is complex event processing (part 1) </a></p>
<p><a href="http://www.thecepblog.com/2007/05/14/what-is-complex-event-processing-part-1/"></a><br />
The other parts follow right after it.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coffeeonesugar.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coffeeonesugar.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coffeeonesugar.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coffeeonesugar.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/coffeeonesugar.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/coffeeonesugar.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/coffeeonesugar.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/coffeeonesugar.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coffeeonesugar.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coffeeonesugar.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coffeeonesugar.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coffeeonesugar.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coffeeonesugar.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coffeeonesugar.wordpress.com/108/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=108&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://coffeeonesugar.wordpress.com/2009/07/19/complex-event-processing-with-esper/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f86d07c942cb53f7267a3605fc462141?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coffeeonesugar</media:title>
		</media:content>
	</item>
		<item>
		<title>Financial high frequency data for free</title>
		<link>http://coffeeonesugar.wordpress.com/2009/07/18/financial-high-frequency-data-for-free/</link>
		<comments>http://coffeeonesugar.wordpress.com/2009/07/18/financial-high-frequency-data-for-free/#comments</comments>
		<pubDate>Sat, 18 Jul 2009 23:49:17 +0000</pubDate>
		<dc:creator>coffeeonesugar</dc:creator>
				<category><![CDATA[Getting financial data...]]></category>

		<guid isPermaLink="false">http://coffeeonesugar.wordpress.com/?p=104</guid>
		<description><![CDATA[Google and yahoo both claim to provide real-time high-frequency financial data for free. This is partially true if you only intend to watch prices from your browser. For those of you who would like to download tick data, that&#8217;s another &#8230; <a href="http://coffeeonesugar.wordpress.com/2009/07/18/financial-high-frequency-data-for-free/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=104&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Google and yahoo both claim to provide real-time high-frequency financial data for free. This is partially true if you only intend to watch prices from your browser. For those of you who would like to download tick data, that&#8217;s another story.</p>
<p>Unlike daily closing and opening prices, you won&#8217;t be able to simply download tick data in the .csv format to feed your favorite strategy back-tester. You can write an HTML-scraper and let it run for a month or two 24/7 to get a few MB of data.</p>
<p>However, yahoo and google protect themselves against scrapers and hence it is very likely that you won&#8217;t be able to get an uninterrupted stream of quotes this way. For instance, yahoo will give you its very infamous 999 error, which is their http-server way of giving a finger to suspiciously busy users.</p>
<p>You can get around this by a cunning use of proxy servers, and of course, decreasing the frequency of your requests to the server. I will maybe publish the code I used to do it, although I still need to assess the legality of the whole thing before taking the plunge.</p>
<p>In the meantime, I found this:<br />
<a href="http://www.tickdata.com/html/downloads.shtml">Free samples of tick data </a><br />
You can download samples of high-frequency data from different exchanges. Since I only need high-freq data for testing purposes, this is good enough for me, and so maybe for you too.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coffeeonesugar.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coffeeonesugar.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coffeeonesugar.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coffeeonesugar.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/coffeeonesugar.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/coffeeonesugar.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/coffeeonesugar.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/coffeeonesugar.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coffeeonesugar.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coffeeonesugar.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coffeeonesugar.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coffeeonesugar.wordpress.com/104/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coffeeonesugar.wordpress.com/104/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coffeeonesugar.wordpress.com/104/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=104&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://coffeeonesugar.wordpress.com/2009/07/18/financial-high-frequency-data-for-free/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f86d07c942cb53f7267a3605fc462141?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coffeeonesugar</media:title>
		</media:content>
	</item>
		<item>
		<title>Black Swans</title>
		<link>http://coffeeonesugar.wordpress.com/2009/07/09/98/</link>
		<comments>http://coffeeonesugar.wordpress.com/2009/07/09/98/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 20:42:48 +0000</pubDate>
		<dc:creator>coffeeonesugar</dc:creator>
				<category><![CDATA[Quickies...]]></category>

		<guid isPermaLink="false">http://coffeeonesugar.wordpress.com/?p=98</guid>
		<description><![CDATA[Hi folks, A quick one for those who read the books of Nassim Taleb. Three black swans were born last week in Basel.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=98&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Hi folks,</p>
<p>A quick one for those who read the books of Nassim Taleb. Three black swans were born last week in Basel.<a href="http://coffeeonesugar.files.wordpress.com/2009/07/scan10001_lite.jpg"><img class="alignleft size-full wp-image-99" title="Scan10001_lite" src="http://coffeeonesugar.files.wordpress.com/2009/07/scan10001_lite.jpg?w=500" alt="Scan10001_lite"  /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coffeeonesugar.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coffeeonesugar.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coffeeonesugar.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coffeeonesugar.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/coffeeonesugar.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/coffeeonesugar.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/coffeeonesugar.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/coffeeonesugar.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coffeeonesugar.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coffeeonesugar.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coffeeonesugar.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coffeeonesugar.wordpress.com/98/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coffeeonesugar.wordpress.com/98/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coffeeonesugar.wordpress.com/98/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=98&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://coffeeonesugar.wordpress.com/2009/07/09/98/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f86d07c942cb53f7267a3605fc462141?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coffeeonesugar</media:title>
		</media:content>

		<media:content url="http://coffeeonesugar.files.wordpress.com/2009/07/scan10001_lite.jpg" medium="image">
			<media:title type="html">Scan10001_lite</media:title>
		</media:content>
	</item>
		<item>
		<title>A Quick Hack to Get Historical Data from Yahoo!Finance</title>
		<link>http://coffeeonesugar.wordpress.com/2009/02/18/a-quick-hack-to-get-historical-data-from-yahoofinance/</link>
		<comments>http://coffeeonesugar.wordpress.com/2009/02/18/a-quick-hack-to-get-historical-data-from-yahoofinance/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 18:01:17 +0000</pubDate>
		<dc:creator>coffeeonesugar</dc:creator>
		
		<guid isPermaLink="false">http://coffeeonesugar.wordpress.com/?p=68</guid>
		<description><![CDATA[If you need financial data for your softwares, here is a quick hack in Bash (runs on my mac and I suppose on linux too) to get quotes from yahooFinance. This script download a .csv file containing the historical data &#8230; <a href="http://coffeeonesugar.wordpress.com/2009/02/18/a-quick-hack-to-get-historical-data-from-yahoofinance/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=68&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If you need financial data for your softwares, here is a quick hack in Bash (runs on my mac and I suppose on linux too) to get quotes from yahooFinance.</p>
<p>This script download a .csv file containing the historical data from today to the day of your choice for each stock listed on the S&amp;P 1000.</p>
<p>First, you need to download the .csv file containing the symbol of every stock listed on the S&amp;P 1000. This file can be found <a href="http://www2.standardandpoors.com/portal/site/sp/en/us/page.topic/indices_1000/2,3,2,2,0,0,0,0,0,2,3,0,0,0,0,0.html" target="_blank">here</a>. In my case, the file is named 17-FEB-1009_1000.csv.</p>
<p>Then, copy the following to a file called yahooDown.sh :</p>
<pre>
<pre class="brush: java;">
#!/bin/bash
# prices from S&amp;P500 can be downloaded from
#http://www2.standardandpoors.com/portal/site/sp/en/us/page.topic/indices_500/2,3,2,2,0,0,0,0,0,2,3,0,0,0,0,0.html

# We download from today to the date in the command line

#./yahooDown.sh standardPoorList.csv DestDir 1-1-1995
# e.g. ./yahooDown.sh 17-FEB-2009_1000.csv SP1000 1-1-1995

todayDate=$(date &quot;+%d %m %Y&quot;)

# Start date
sDay=$(echo $todayDate | awk '{print $1}')
sMonth=$(echo $todayDate | awk '{print $2}')
sYear=$(echo $todayDate | awk '{print $3}') 

# end date

eDay=$(echo $3 | sed &quot;s:-: :g&quot; | awk '{print $1}')
eMonth=$(echo $3 |sed &quot;s:-: :g&quot; | awk '{print $2}')
eYear=$(echo $3 |sed &quot;s:-: :g&quot; | awk '{print $3}') 

# command to fetch data the CSV files from yahoo

DESTDIR=$2
WGET=&quot;curl&quot;
OPT1=&quot;-o&quot;

COM1=&quot;http://ichart.finance.yahoo.com/table.csv?s=&quot;
COMd=&quot;&amp;d=&quot;$(expr $sMonth - 1)
COMe=&quot;&amp;e=&quot;
COMf=&quot;&amp;f=&quot;
COMg=&quot;&amp;g=d&quot;
COMa=&quot;&amp;a=&quot;$(expr $eMonth - 1)
COMb=&quot;&amp;b=&quot;
COMc=&quot;&amp;c=&quot;
COMlast=&quot;&amp;ignore=.csv&quot;

# the command we pass to wget
for i in $(sed -e &quot;s:,: :&quot; -e &quot;/Symbol*/ d&quot; -e &quot;/^$/ d&quot; $1 | awk '{print $1}'); do

echo &quot;Downloading the data for symbol &quot; $i
WEBURL=&quot;$COM1$i$COMa$COMb$eMonth$COMc$eYear$COMd$COMe$sMonth$COMf$sYear$COMg$COMlast&quot;
COMMAND=&quot;$WGET $OPT1 &quot;$DESTDIR/$i.csv&quot; &quot;$WEBURL&quot;&quot;
$COMMAND

done

</pre></pre>
</pre>
</pre>
</pre>
<p>Now you need to turn it into an executable file. Open a terminal in the directory where the file yahooDown.sh is located and type:</p>
<pre>$ chmod +x yahooDown.sh</pre>
<p>Now, create a directory where you want the .csv files of each stock to be placed:</p>
<pre>$ mkdir SP1000</pre>
<p>Now, just type:</p>
<pre>$ ./yahooDown.sh 17-FEB-2009_1000.csv SP1000 1-1-1998</pre>
<p>Just wait a bit... You should see something like this:</p>
<pre>$ ./yahooDown.sh 17-FEB-2009_1000.csv SP1000 1-1-1990
Downloading the data for symbol  COMS
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  217k    0  217k    0     0  60340      0 --:--:--  0:00:03 --:--:-- 65004
Downloading the data for symbol  NDN
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  147k    0  147k    0     0  26304      0 --:--:--  0:00:05 --:--:-- 35161
Downloading the data for symbol  AHC
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 10817    0 10817    0     0  24368      0 --:--:-- --:--:-- --:--:-- 43963</pre>
<p>and voilà! The historical data of every stock listed on the S&amp;P1000 is now ready to be used in the directory SP1000. Here is a (partial) listing of the same directory on my machine:</p>
<pre>$ ls
AAI.csv		CCMP.csv	FIC.csv		KND.csv		ORLY.csv
AAP.csv		CCRN.csv	FIF.csv		KNDL.csv	OSG.csv
ABAX.csv	CDI.csv		FINL.csv	KNOT.csv	OSK.csv
ABCW.csv	CDNS.csv	FL.csv		KNSY.csv	OSTE.csv
ABFS.csv	CDR.csv		FLO.csv		KNX.csv		OXM.csv
ABM.csv		CEC.csv		FMBI.csv	KOPN.csv	OXPS.csv
ACAP.csv	CECO.csv	FMC.csv		KRC.csv		PACW.csv
ACAT.csv	CELL.csv	FMER.csv	KRG.csv		PALM.csv
ACF.csv		CEM.csv		FNF.csv		KSU.csv		PAS.csv
ACI.csv		CENTA.csv	FNFG.csv	KSWS.csv	PBKS.csv
ACIW.csv	CENX.csv	FOE.csv		KWK.csv		PBY.csv</pre>
<p>Okay, that's all folks.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coffeeonesugar.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coffeeonesugar.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coffeeonesugar.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coffeeonesugar.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/coffeeonesugar.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/coffeeonesugar.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/coffeeonesugar.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/coffeeonesugar.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coffeeonesugar.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coffeeonesugar.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coffeeonesugar.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coffeeonesugar.wordpress.com/68/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coffeeonesugar.wordpress.com/68/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coffeeonesugar.wordpress.com/68/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=68&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://coffeeonesugar.wordpress.com/2009/02/18/a-quick-hack-to-get-historical-data-from-yahoofinance/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f86d07c942cb53f7267a3605fc462141?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coffeeonesugar</media:title>
		</media:content>
	</item>
		<item>
		<title>Event-based programming in Java</title>
		<link>http://coffeeonesugar.wordpress.com/2009/02/15/event-based-programming-in-java/</link>
		<comments>http://coffeeonesugar.wordpress.com/2009/02/15/event-based-programming-in-java/#comments</comments>
		<pubDate>Sun, 15 Feb 2009 00:30:39 +0000</pubDate>
		<dc:creator>coffeeonesugar</dc:creator>
				<category><![CDATA[Java concepts illustrated...]]></category>
		<category><![CDATA[event-driven]]></category>
		<category><![CDATA[EventObject]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://coffeeonesugar.wordpress.com/?p=40</guid>
		<description><![CDATA[Applications dealing with real-time data are often event-driven. In such applications, a data feed regularly passes data structures to one or several functions that will collect and process the data in real-time. The arrival of data constitutes an event, and &#8230; <a href="http://coffeeonesugar.wordpress.com/2009/02/15/event-based-programming-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=40&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Applications dealing with real-time data are often event-driven. In such applications, a data feed regularly passes data structures to one or several functions that will collect and process the data in real-time. The arrival of data constitutes an event, and the objects that are notified of such events are called listeners.</p>
<p>In this first post, we will simply write a couple a classes that actually emit and receive events. In order to introduce the concept of event-driven programming, we will use an analogy with the notes (the events) that are produced by instruments, and caught by listeners.</p>
<p>We first define what we call a sound event. A sound is formed by a note, which we encode on an integer, and a time stamp that corresponds to the moment the note was played.</p>
<pre><pre class="brush: java;">
public class SoundEvent extends EventObject {

    private Integer note;
    private long timestamp;

    public SoundEvent(Object source, Integer s, long time) {
        super(source);
        note = s;
        timestamp = time;
    }

    public Integer getNote() {
        return note;
    }

    public long getTimeStamp() {
        return timestamp;
    }
}
</pre></pre>
</pre>
<p>This class extends EventObject, which contains only one variable storing the object that created the event (the source), and a function to retrieve it [the method getSource()].</p>
<p>Then, we create the SoundMaker class. This class will generate sounds at random, and fire sound events.</p>
<pre><pre class="brush: java;">
public class SoundMaker {

    private Integer sound;
    private List listeners; // List of listeners
    private Random rgen; // Random generator of sounds
    private long timeReference; // time is counted from this reference

    public SoundMaker() {
        listeners = new ArrayList();
        rgen = new Random();
        sound = new Integer(0);
        timeReference=0;
    }

    public void setTimeReference(long i){
    timeReference=i;
    }

    //---end of class
}</pre></pre>
<p>We will now add a couple of methods to this class. First, two functions that will allow us to add listeners to the list of the soundMaker class.</p>
<pre><pre class="brush: java;">
public synchronized void addListener(SoundListener sl) {
        listeners.add(sl);
    }

    public synchronized void removeListener(SoundListener sl) {
        listeners.remove(sl);
    }</pre></pre>
<p>Of course, we also need a function that plays notes, or even entire concerts!</p>
<pre><pre class="brush: java;">
public synchronized void playNote() {
        sound = rgen.nextInt(1000);
        long now = System.currentTimeMillis()-timeReference;
        System.out.println(&quot;[SoundMaker] Playing note &quot; + sound + &quot; @ &quot; + now);
        fireSoundEvent(now);
    }

    public synchronized void playConcert(int nbNotes) {

        for (int j = 0; j &lt; nbNotes; j++) {
            playNote();
        }
    }</pre></pre>
<p>And finally, the most important function of this class, the fireSoundEvent function that will inform every listener that a sound has been played.</p>
<pre><pre class="brush: java;">
public synchronized void fireSoundEvent(long time) {
        SoundEvent soundEvent = new SoundEvent(this, sound, time);
        Iterator it = listeners.iterator();

        while (it.hasNext()) {
            SoundListener sl = it.next();
            sl.soundReceived(soundEvent);
        }
    }</pre></pre>
</pre>
<p>In order to write classes able to listen to the sound of SoundMaker, we define a simple interface that these classes will have to implement:</p>
<pre><pre class="brush: java;">
public interface SoundListener {
    public void soundReceived(SoundEvent event);

}</pre></pre>
</pre>
<p>As an illustration, we write a MusicFan class, that will listen to the event produced by the SoundMaker class:</p>
<pre><pre class="brush: java;">
public class MusicFan implements SoundListener {

    private long timeReference;

    public void setTimeReference(long i){
    timeReference=i;
    }

    public void soundReceived(SoundEvent sound) {

        long now = System.currentTimeMillis()-timeReference;
        long soundTime = sound.getTimeStamp();
        long timelag = now - soundTime;
        Integer note = sound.getNote();

        System.out.println(&quot;[Music fan] &quot; +
        &quot; Hearing note &quot;+ note +
        &quot; @ &quot;+ now +
        &quot; ( with lag = &quot;+ timelag + &quot; )&quot;);

      //  Wait.millisec(20);

    }
}</pre></pre>
<p>We will use the Wait.millisec(long i) function later, but here is its definition:</p>
<pre><pre class="brush: java;">
public class Wait {

    public static void millisec(long nbMsec){
    long t0,t1;
        t0=System.currentTimeMillis();
        do{
            t1=System.currentTimeMillis();
        }
        while (t1-t0&lt;nbMsec);
    }

}</pre></pre>
<p>Okay, now we are ready to write a simple program that connects a listener to a sound maker, and makes it print the note that it has heard.</p>
<pre><pre class="brush: java;">
public class Main {

    public static void main(String[] args) {
        // we create the two classes
        SoundMaker concert= new SoundMaker();
        MusicFan musicfan= new MusicFan();

        // We connect the music fan to the sound maker
        concert.addListener(musicfan);

        // We define the time reference
        long timeReference= System.currentTimeMillis();

        concert.setTimeReference(timeReference);
        musicfan.setTimeReference(timeReference);

        System.out.println(&quot;-----------&quot;);
        // Go!
        concert.playConcert(10);

    }
}</pre></pre>
<p>This produces the following output:</p>
<pre>[SoundMaker] Playing note 127 @ 0
[Music fan]  Hearing note 127 @ 1 ( with lag = 1 )
[SoundMaker] Playing note 564 @ 1
[Music fan]  Hearing note 564 @ 1 ( with lag = 0 )
[SoundMaker] Playing note 748 @ 1
[Music fan]  Hearing note 748 @ 1 ( with lag = 0 )
[SoundMaker] Playing note 38 @ 1
[Music fan]  Hearing note 38 @ 1 ( with lag = 0 )
[SoundMaker] Playing note 293 @ 1
[Music fan]  Hearing note 293 @ 1 ( with lag = 0 )
[SoundMaker] Playing note 558 @ 1
[Music fan]  Hearing note 558 @ 1 ( with lag = 0 )
[SoundMaker] Playing note 100 @ 2
[Music fan]  Hearing note 100 @ 2 ( with lag = 0 )
[SoundMaker] Playing note 5 @ 2
[Music fan]  Hearing note 5 @ 2 ( with lag = 0 )
[SoundMaker] Playing note 985 @ 2
[Music fan]  Hearing note 985 @ 2 ( with lag = 0 )
[SoundMaker] Playing note 140 @ 2
[Music fan]  Hearing note 140 @ 2 ( with lag = 0 )</pre>
<p>Okay, that seems to work alright. However, there is an interesting question that can be asked: what about the garbage collector. Is it going to disturb the emission of notes, or simply quietly work in parallel to the main thread? This is a very important point when dealing with real-time data, since we absolutely do not want to loose data points received while the garbage collection is running. This has been for a long time one of the main argument against the use of Java for real-time applications, so it is quite interesting to test it.</p>
<p><img class="alignleft size-full wp-image-50" title="graph11" src="http://coffeeonesugar.files.wordpress.com/2009/02/graph11.jpg?w=500" alt="graph11"   />I have plotted the time lag between the emission and reception of the event over a period of roughly two seconds. As one can see, the reception of the eventObject is instantaneous <strong>most of the time. </strong>Sometimes tough, it seems that the the reception is slightly delayed, by at most one millisecond. The usual suspect in this case would be the garbage collector. However the introduction of "memory leaks" in the program, e.g. by allocating large arrays on the heap everytime that a sound event is fired, does not seem to increase the size of the lags. Therefore, I believe that it would be erroneous to jump to a conclusion too quickly and declare that garbage collection is responsible to delaying the processing of events. A good test would be to write the same piece of code C++ and check whether the time lags disappear. I was actually quite surprised by this observation, as I thought that the garbage collection would be more visible.</p>
<p>One last comment before I finish this post. Let's see how does the program reacts when we uncomment the waiting function. This function simulates the effect of a listener that would take some time to process the data that was sent to him. So, let us redefine the eventReceived function:</p>
<pre><pre class="brush: java;">
public void soundReceived(SoundEvent sound) {

        long now = System.currentTimeMillis()-timeReference;
        long soundTime = sound.getTimeStamp();
        long timelag = now - soundTime;
        Integer note = sound.getNote();

        System.out.println(&quot;[Music fan] &quot; +
        &quot; Hearing note &quot;+ note +
        &quot; @ &quot;+ now +
        &quot; ( with lag = &quot;+ timelag + &quot; )&quot;);

       Wait.millisec(20);

    }</pre></pre>
</pre>
</pre>
<p>The output of the program is now:</p>
<pre>[SoundMaker] Playing note 32 @ 0
[Music fan]  Hearing note 32 @ 1 ( with lag = 1 )
[SoundMaker] Playing note 131 @ 22
[Music fan]  Hearing note 131 @ 22 ( with lag = 0 )
[SoundMaker] Playing note 910 @ 42
[Music fan]  Hearing note 910 @ 42 ( with lag = 0 )
[SoundMaker] Playing note 969 @ 62
[Music fan]  Hearing note 969 @ 62 ( with lag = 0 )
[SoundMaker] Playing note 272 @ 82
[Music fan]  Hearing note 272 @ 82 ( with lag = 0 )
[SoundMaker] Playing note 414 @ 102
[Music fan]  Hearing note 414 @ 102 ( with lag = 0 )
[SoundMaker] Playing note 793 @ 122
[Music fan]  Hearing note 793 @ 122 ( with lag = 0 )
[SoundMaker] Playing note 953 @ 142
[Music fan]  Hearing note 953 @ 142 ( with lag = 0 )
[SoundMaker] Playing note 112 @ 162
[Music fan]  Hearing note 112 @ 162 ( with lag = 0 )
[SoundMaker] Playing note 261 @ 182
[Music fan]  Hearing note 261 @ 182 ( with lag = 0 )</pre>
<p>You will note that the SoundMaker waits until every one of its listeners have finished to process the sound that was sent to them. This is not quite as in reality, where the arrival time of events is independent of the processing time of the data.</p>
<p>That's all for today folks.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coffeeonesugar.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coffeeonesugar.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coffeeonesugar.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coffeeonesugar.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/coffeeonesugar.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/coffeeonesugar.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/coffeeonesugar.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/coffeeonesugar.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coffeeonesugar.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coffeeonesugar.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coffeeonesugar.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coffeeonesugar.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coffeeonesugar.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coffeeonesugar.wordpress.com/40/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=40&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://coffeeonesugar.wordpress.com/2009/02/15/event-based-programming-in-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f86d07c942cb53f7267a3605fc462141?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coffeeonesugar</media:title>
		</media:content>

		<media:content url="http://coffeeonesugar.files.wordpress.com/2009/02/graph11.jpg" medium="image">
			<media:title type="html">graph11</media:title>
		</media:content>
	</item>
		<item>
		<title>Functions taking a variable number of parameters</title>
		<link>http://coffeeonesugar.wordpress.com/2009/02/14/function-taking-a-variable-number-of-parameters/</link>
		<comments>http://coffeeonesugar.wordpress.com/2009/02/14/function-taking-a-variable-number-of-parameters/#comments</comments>
		<pubDate>Sat, 14 Feb 2009 00:09:54 +0000</pubDate>
		<dc:creator>coffeeonesugar</dc:creator>
				<category><![CDATA[Java concepts illustrated...]]></category>

		<guid isPermaLink="false">http://coffeeonesugar.wordpress.com/?p=17</guid>
		<description><![CDATA[As in C++, Java offers the possibility to write functions taking a variable number of arguments. This feature was incorporated only in version 5, which is just mildly surprising as some more urgent additions, such as e. g. the otherwise &#8230; <a href="http://coffeeonesugar.wordpress.com/2009/02/14/function-taking-a-variable-number-of-parameters/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=17&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As in C++, Java offers the possibility to write functions taking a variable number of arguments. This feature was incorporated only in version 5, which is just mildly surprising as some more urgent additions, such as e. g. the otherwise ubiquitous—at least in C—typedef or enum statements, were not to be included in the language until version 4.</p>
<p>Concept behind functions taking a variable number of parameters is quite simple really: the preprocessor places each parameter in an array and passes it to the function as a unique argument. As in C++, the syntax used in Java is the type of the parameters directly followed by an ellipsis.</p>
<p>In order to illustrate the use of this feature, I have written a small class whose purpose is simply to write in a file the parameters that are passed to a function separated by a coma (the .csv format).</p>
<p>Since this class clearly works as a sort of log, we will use a singleton pattern to make sure that only one instance of the class can exist at once. This also insures that the log file is only created once. So, we start by writing a simple singleton class:</p>
<pre><pre class="brush: java;">
public class LogCSV{
static private  LogCSV thisLog=null;
private FileWriter file;

// The Singleton initializer

static public LogCSV initialize(){
if(thisLog==null){
thisLog = new LogCSV();
}
return thisLog;
}

// The class constructor

private LogCSV(){
try {
file = new FileWriter(&quot;strategyLog.csv&quot;);

// some compulsory error catching...
} catch (IOException ex) {
Logger.getLogger(LogCSV.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</pre></pre>
<p>Now, here it comes. The following &#8220;write&#8221; function will take a variable number of arguments, and write each of them separated by a coma in a file.</p>
<pre><pre class="brush: java;">

 public void write(String... message) {
        int counter = 0;

        try {

            for (String msg : message) {

                file.write(msg);
                if (counter != message.length - 1) {
                    file.write(&quot;,&quot;);
                }

                counter++;
            }

            file.write(&quot;\n&quot;);

        // Error catching jiberish
        } catch (IOException ex) {
            Logger.getLogger(LogCSV.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
</pre></pre>
<p>Note the ellipsis after the type of the first and unique parameter of the function. This indicates to the compiler that the number of parameters may vary. Also, note the form of the &#8220;for&#8221; statement. As I mentionned earlier, the parameters are essentially copied to an array and passed to the function in this form. Therefore, the actual number of parameters can be obtained by retrieving the size of the array using</p>
<pre><pre class="brush: java;">
message.length
</pre></pre>
</pre>
<p>This class can be used as follows:</p>
<pre>
<pre><pre class="brush: java;">
LogCSV log= LogCSV.initialize();
log.write(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;);
</pre></pre>
</pre>
<p>This will write the sequence</p>
<pre>A,B,C</pre>
<p>in the file "strategyLog.csv".</p>
<p>Alright, that's all folks. Oh, before I put my pen down, I sometimes use a little trick when dealing with singleton classes. I just add this function to the class:</p>
<pre><pre class="brush: java;">
static public LogCSV execute() {
return thisLog;
}

</pre></pre>
<p>So that after the class has been initialized, I can call it from anywhere in my code using:</p>
<pre><pre class="brush: java;">

LogCSV.execute().write(&quot;C&quot;,&quot;B&quot;,&quot;C&quot;)

</pre></pre>
<p>Okay, my turn to ask the questions now. Can someone tell me whether it is the compiler or the precompiler that processes the ellipsis. Also, is this syntax of the "for" reserved for functions taking a variable number of parameters, or is it used in other circumstances? I have not seen it elsewhere, so I was just wondering.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coffeeonesugar.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coffeeonesugar.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coffeeonesugar.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coffeeonesugar.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/coffeeonesugar.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/coffeeonesugar.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/coffeeonesugar.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/coffeeonesugar.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coffeeonesugar.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coffeeonesugar.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coffeeonesugar.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coffeeonesugar.wordpress.com/17/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coffeeonesugar.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coffeeonesugar.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=17&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://coffeeonesugar.wordpress.com/2009/02/14/function-taking-a-variable-number-of-parameters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f86d07c942cb53f7267a3605fc462141?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coffeeonesugar</media:title>
		</media:content>
	</item>
		<item>
		<title>BAdaBoum&#8230;</title>
		<link>http://coffeeonesugar.wordpress.com/2009/02/08/hello-world/</link>
		<comments>http://coffeeonesugar.wordpress.com/2009/02/08/hello-world/#comments</comments>
		<pubDate>Sun, 08 Feb 2009 20:11:09 +0000</pubDate>
		<dc:creator>coffeeonesugar</dc:creator>
				<category><![CDATA[on choosing Java...]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Yeah, this is the opening post of this blog. Still a few things to sort out before I start publishing more heavily. These pages are mostly going to be about Java code, but for the sake of my mental health, &#8230; <a href="http://coffeeonesugar.wordpress.com/2009/02/08/hello-world/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=1&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Yeah, this is the opening post of this blog. Still a few things to sort out before I start publishing more heavily. These pages are mostly going to be about Java code, but for the sake of my mental health, thanks god, not only. You may also come across the odd philosophical digression, but promessed I will try to avoid at all cost the too-often encountered soul searching article describing in length some fuzzy vision of post-modern life misery.</p>
<p>Let&#8217;s get started then.<br />
<pre class="brush: java;">
class coffeeOneSugar {
static public void main(String[] args){
System.out.println(&quot;OnLine!&quot;);
}
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coffeeonesugar.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coffeeonesugar.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coffeeonesugar.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coffeeonesugar.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/coffeeonesugar.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/coffeeonesugar.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/coffeeonesugar.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/coffeeonesugar.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coffeeonesugar.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coffeeonesugar.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coffeeonesugar.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coffeeonesugar.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coffeeonesugar.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coffeeonesugar.wordpress.com/1/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coffeeonesugar.wordpress.com&amp;blog=6504688&amp;post=1&amp;subd=coffeeonesugar&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://coffeeonesugar.wordpress.com/2009/02/08/hello-world/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/f86d07c942cb53f7267a3605fc462141?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coffeeonesugar</media:title>
		</media:content>
	</item>
	</channel>
</rss>
