<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>CrzyJcky</title>
    <description>Connecting Ideas</description>
    <link>http://crzyjcky.com/</link>
    <atom:link href="http://crzyjcky.com/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Wed, 16 Dec 2015 06:42:59 +0000</pubDate>
    <lastBuildDate>Wed, 16 Dec 2015 06:42:59 +0000</lastBuildDate>
    <generator>Jekyll v2.4.0</generator>
    
      <item>
        <title>Simplify Complex Query with CQRS</title>
        <description>&lt;iframe src=&quot;//www.slideshare.net/slideshow/embed_code/key/8AgbwTCI6aqywg&quot; width=&quot;595&quot; height=&quot;485&quot; frameborder=&quot;0&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; scrolling=&quot;no&quot; style=&quot;border:1px solid #CCC; border-width:1px; margin-bottom:5px; max-width: 100%;&quot; allowfullscreen=&quot;&quot;&gt; &lt;/iframe&gt;
&lt;div style=&quot;margin-bottom:5px&quot;&gt; &lt;strong&gt; &lt;a href=&quot;//www.slideshare.net/JackyLai7/simplify-complex-query-with-cqrs&quot; title=&quot;Simplify Complex Query with CQRS&quot; target=&quot;_blank&quot;&gt;Simplify Complex Query with CQRS&lt;/a&gt; &lt;/strong&gt; from &lt;strong&gt;&lt;a href=&quot;//www.slideshare.net/JackyLai7&quot; target=&quot;_blank&quot;&gt;Jacky Lai&lt;/a&gt;&lt;/strong&gt; &lt;/div&gt;

&lt;h1 id=&quot;optimization-is-all-about-resource-trade-off&quot;&gt;Optimization is all about Resource Trade-off&lt;/h1&gt;

&lt;p&gt;The performance of an application is based on&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Memory Resource&lt;/li&gt;
  &lt;li&gt;Computing Resource&lt;/li&gt;
  &lt;li&gt;Network Resource&lt;/li&gt;
  &lt;li&gt;Developer Resource&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Disk space Resource&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Disk space resource&lt;/strong&gt; is relatively the cheapest resource compared to others.&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;example-requirement-find-shipping-methods&quot;&gt;Example Requirement: Find Shipping Methods&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;During checkout process, user will be presented a list of shipping methods to choose from, based on the product and shipping address.&lt;/li&gt;
  &lt;li&gt;shippingMethods = findShippingMethodsBy(product, shippingAddress);&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;example-requirement-request-payload&quot;&gt;Example Requirement: Request Payload&lt;/h1&gt;

&lt;p&gt;Request Json Payload:&lt;/p&gt;

&lt;pre class=&quot;brush: javascript; title: ; notranslate&quot; title=&quot;&quot;&gt;
{
	&quot;productId&quot;: ”aabbcc&quot;,
	&quot;address&quot;: ”123 Freedom Cir., Santa Clara, CA 95123&quot;
}
&lt;/pre&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;common-strategy-back-end-processing&quot;&gt;Common Strategy: Back-end Processing&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;Upon receiving request payload:&lt;/li&gt;
&lt;/ul&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;
// step 1: construct hierarchical object graph, an expensive operation.
product = productRepository.findBy(productId);
shippingAddress = new Address(address);

// step 2: find shipping methods.
shippingMethods = findShippingMethodsBy(product, shippingAddress);
&lt;/pre&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;common-strategy-er-diagram&quot;&gt;Common Strategy: ER Diagram&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/common-strategy-er-diagram.png&quot; alt=&quot;common-strategy-er-diagram.png&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;common-strategy---modeling&quot;&gt;Common Strategy - Modeling&lt;/h1&gt;
&lt;p&gt;Model with Hierarchical Data object, e.g.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Product
    &lt;ul&gt;
      &lt;li&gt;size (LARGE, SMALL)&lt;/li&gt;
      &lt;li&gt;type (GIFT_CARD, RESTRICTED)&lt;/li&gt;
      &lt;li&gt;warehouses&lt;/li&gt;
      &lt;li&gt;address&lt;/li&gt;
      &lt;li&gt;shipping methods&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Shipping Address&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;issue-1-network-traffic-increment&quot;&gt;Issue #1: Network Traffic Increment.&lt;/h1&gt;
&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/network-traffic-increment.png&quot; alt=&quot;network-traffic-increment.png&quot; /&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;For each request, &lt;em&gt;application layer&lt;/em&gt; has to fetch &lt;em&gt;huge amount of data&lt;/em&gt; across network from database, and process the data at &lt;em&gt;Application layer&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;question-which-is-the-best-layer-to-filter-data&quot;&gt;Question: Which is the best layer to filter data?&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/which-is-the-best-layer-to-filter-data-browser.png&quot; alt=&quot;which-is-the-best-layer-to-filter-data-browser.png&quot; /&gt;&lt;br /&gt;
&lt;img src=&quot;/wp-content/uploads/2015/12/which-is-the-best-layer-to-filter-data-database.png&quot; alt=&quot;which-is-the-best-layer-to-filter-data-database.png&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;issue-2-read-speed-or-write-speed-pick-one&quot;&gt;Issue #2: Read Speed or Write Speed, Pick One.&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;We cannot optimize both Read and Write speed at the same time.&lt;/li&gt;
  &lt;li&gt;Without adding index,
    &lt;ul&gt;
      &lt;li&gt;time complexity for read = O(n)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;After adding index,
    &lt;ul&gt;
      &lt;li&gt;time complexity for read = O(log n)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;issue-2-read-speed-or-write-speed-pick-one--cont&quot;&gt;Issue #2: Read Speed or Write Speed, Pick One. – Cont.&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;Performance Summary from “The Performance Impact of Adding MySQL Indexes”
    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;http://logicalread.solarwinds.com/impact-of-adding-mysql-indexes-mc12/#.VmkYP51Viko&quot;&gt;http://logicalread.solarwinds.com/impact-of-adding-mysql-indexes-mc12/#.VmkYP51Viko&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;For a table with &lt;strong&gt;553875&lt;/strong&gt; rows.&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;Before Adding Indexes&lt;/th&gt;
      &lt;th&gt;After Adding Indexes&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Insert Operation (sec)&lt;/td&gt;
      &lt;td&gt;7.14&lt;/td&gt;
      &lt;td&gt;24.77 (3x)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Data (mb)&lt;/td&gt;
      &lt;td&gt;33.56&lt;/td&gt;
      &lt;td&gt;33.56&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Index (mb)&lt;/td&gt;
      &lt;td&gt;13.52&lt;/td&gt;
      &lt;td&gt;95.70&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Total = Data + Index (mb)&lt;/td&gt;
      &lt;td&gt;47.08&lt;/td&gt;
      &lt;td&gt;129.27&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;issue-2-read-speed-or-write-speed-pick-one--cont-1&quot;&gt;Issue #2: Read Speed or Write Speed, Pick One. – Cont.&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;What if we use Cache to reduce DB read?&lt;/li&gt;
  &lt;li&gt;Cache is a Key-Value DB.&lt;/li&gt;
  &lt;li&gt;Let’s say it takes 32 DB calls to build a complex object graph:
    &lt;ul&gt;
      &lt;li&gt;Best case: 32 cache hits.&lt;/li&gt;
      &lt;li&gt;Worst case: 32 cache misses + 32 DB calls.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Network IO delays is unavoidable.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;There is another challenge: Cache Data Consistency.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
  &lt;p&gt;There are only two hard things in Computer Science: cache invalidation and naming things.&lt;br /&gt;
– Phil Karlton&lt;/p&gt;
&lt;/blockquote&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;issue-2-read-speed-or-write-speed-pick-one--cont-2&quot;&gt;Issue #2: Read Speed or Write Speed, Pick One. – Cont.&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/read-speed-or-write-speed-no-cache.png&quot; alt=&quot;read-speed-or-write-speed-no-cache.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;We need to maintain consistency for both normalized DB and denormalized DB, and this is tricky.&lt;/p&gt;

&lt;p&gt;Overall Consistency = Consistency (Normalized) &amp;amp;&amp;amp; Consistency (Denormalized)&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/read-speed-or-write-speed-cache.png&quot; alt=&quot;read-speed-or-write-speed-cache.png&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;issue-3-join-logic-has-to-be-at-both-sides-w-r&quot;&gt;Issue #3: “Join” logic has to be at both sides (W, R)&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/join-logic-has-to-be-at-both-sides.png&quot; alt=&quot;join-logic-has-to-be-at-both-sides.png&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;cqrs-comes-to-rescue&quot;&gt;CQRS Comes to Rescue.&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;Proposed by Greg Young.
    &lt;ul&gt;
      &lt;li&gt;Probably the best innovation from C# community to Java community.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Command-Query Responsibility Segregation.
    &lt;ul&gt;
      &lt;li&gt;Command -&amp;gt; Write&lt;/li&gt;
      &lt;li&gt;Query -&amp;gt; Read&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Separate design for Write Operation and Read Operation.
    &lt;ul&gt;
      &lt;li&gt;For Write, we want consistency.&lt;/li&gt;
      &lt;li&gt;For Read, we want speed.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;common-strategy&quot;&gt;Common Strategy&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/common-strategy.png&quot; alt=&quot;common-strategy.png&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Read: &lt;br /&gt;
O(log n) if it is indexed correctly, &lt;br /&gt;
O(n) without index.&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;cqrs&quot;&gt;CQRS&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/cqrs-2.png&quot; alt=&quot;cqrs-2.png&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;benefit-1-fast-read&quot;&gt;Benefit #1: Fast Read&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;Simple read. No join operation.&lt;/li&gt;
  &lt;li&gt;We can achieve O(1) time complexity by using appropriate database.&lt;/li&gt;
  &lt;li&gt;Minimized data transfer – reduced network IO delay.&lt;/li&gt;
  &lt;li&gt;Reduced memory requirement – reduced GC.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/benefit-1-fast-read.png&quot; alt=&quot;benefit-1-fast-read.png&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;benefit-2-fast-write&quot;&gt;Benefit #2: Fast Write&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;Less indexes created.&lt;/li&gt;
  &lt;li&gt;Tables (for write operation) are not polluted by Indexes (which are created for read operation).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;benefit-3-simple-read-logic&quot;&gt;Benefit #3: Simple Read Logic&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;Less convoluted Read-logic.&lt;/li&gt;
  &lt;li&gt;Simple logic reduces mistakes.&lt;/li&gt;
  &lt;li&gt;It promotes knowledge sharing among team members.&lt;/li&gt;
  &lt;li&gt;Shorten development time.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;benefit-4-flexibility---different-databases&quot;&gt;Benefit #4: Flexibility - Different Databases&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/benefit-4-flexibility.png&quot; alt=&quot;benefit-4-flexibility.png&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;benefit-5-consistency&quot;&gt;Benefit #5: Consistency&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/wp-content/uploads/2015/12/benefit-5-consistency.png&quot; alt=&quot;benefit-5-consistency.png&quot; /&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h1 id=&quot;the-end&quot;&gt;The End&lt;/h1&gt;

</description>
        <pubDate>Sun, 13 Dec 2015 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2015/12/13/simplify-hierarchical-query-with-cqrs/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2015/12/13/simplify-hierarchical-query-with-cqrs/</guid>
        
        <category>cqrs</category>
        
        
        <category>design patterns</category>
        
        <category>uncategorized</category>
        
      </item>
    
      <item>
        <title>Good Timing for Writing Unit Test</title>
        <description>&lt;h3 id=&quot;good-timing&quot;&gt;Good Timing:&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Before implementing any new features.&lt;/li&gt;
  &lt;li&gt;Before fixing any bugs.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;bad-timing&quot;&gt;Bad Timing:&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;After the features has been committed.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let me explains why writing test code *AFTER* the features have been committed and running in production is bad idea. A really bad idea.&lt;/p&gt;

&lt;p&gt;I have seen many teams that:  &lt;br /&gt;
1. Postponed the unit-test writing to some time later.  &lt;br /&gt;
2. Developed the code without unit-testing, and assigned another team member to write unit-test code.&lt;/p&gt;

&lt;p&gt;In reality, it doesn’t work.&lt;/p&gt;

&lt;p&gt;If no one complains about the production code, and you unit-test reveals that there could be some errors in the production code, would you want to change the production code to pass the unit test?  &lt;br /&gt;
Most likely you don’t. You are too afraid to change the production code, because you might break something accidentally. If you change the production code, you may also create more tasks for QA, because they have to validate your changes.  &lt;br /&gt;
As a result, You will try to ‘bend’ the unit tests to pass the production code, which make the test useless.&lt;/p&gt;

&lt;p&gt;Besides, we should aim at testing the features / business requirements, rather than testing the class aimlessly. This kind of testing called BDD – Behavior Driven Development. Another reason we should writing test based on requirements is, given a class A, which contains a lot of obsolete methods, there is no point in testing them. We only test what is matter. Normally this important piece of requirement information is lost when there is no proper documentation. To have that information, we should write the test code while we still have it.&lt;/p&gt;

&lt;p&gt;The moment you fix any bugs or implement any new features, this is the good timing for writing unit test, because you have to change the production code anyway, no matter you write unit-test or not.&lt;/p&gt;

&lt;p&gt;It is important that writing the test code *BEFORE* implementing the bugfix, because from psychology stand point, most people will skip the unit test, after they see their code runs fine.&lt;/p&gt;
</description>
        <pubDate>Sun, 14 Dec 2014 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2014/12/14/good-timing-for-writing-unit-test/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2014/12/14/good-timing-for-writing-unit-test/</guid>
        
        
        <category>test</category>
        
        <category>uncategorized</category>
        
      </item>
    
      <item>
        <title>Simple Moving Average with Hadoop</title>
        <description>&lt;p&gt;Given&lt;/p&gt;

&lt;pre class=&quot;brush: plain; title: ; notranslate&quot; title=&quot;&quot;&gt;y(t) = [x(t) + x(t - 1) + x(t - 2) + ... + x(t - N + 1)] / N

where 
t = time,
N = number of values / points for computation.
&lt;/pre&gt;

&lt;p&gt;From the equation, each x(t) will be used in N calculations,&lt;/p&gt;

&lt;pre class=&quot;brush: plain; title: ; notranslate&quot; title=&quot;&quot;&gt;y(t) = [x(t) + x(t - 1) + x(t - 2) + ... + x(t - N + 1)] / N
y(t + 1) = [x(t + 1) + x(t) + x(t - 1) + ... + x(t - N + 2)] / N
y(t + 2) = [x(t + 2) + x(t + 1) + x(t) + ... + x(t - N + 3)] / N
:
y(t + N - 1) = [x(t + N - 1) + x(t + N - 2) + x(t + N - 3) + ... + x(t)] / N
&lt;/pre&gt;

&lt;p&gt;To get a input data (time-series data) for our tutorial, we can visit &lt;a href=&quot;http://finance.yahoo.com/q/hp?s=YHOO&quot;&gt;http://finance.yahoo.com/q/hp?s=YHOO&lt;/a&gt; and download it.&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;package com.company;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class Main {

	private static final int N = 5;

	public static class MovingAverageMapper extends Mapper&amp;lt;LongWritable, Text, Text, FloatWritable&amp;gt; {

		public void map(
				LongWritable key,
				Text value,
				Context context) throws IOException, InterruptedException {
			//
			// http://finance.yahoo.com/q/hp?s=YHOO
			// 
			// Date,Open,High,Low,Close,Volume,Adj Close
			// 2013-09-13,29.47,29.47,28.80,29.26,13836600,29.26
			// 2013-09-12,29.72,30.27,29.50,29.65,22018600,29.65
			// 2013-09-11,29.38,29.41,28.97,29.19,10345700,29.19
			// 2013-09-10,29.43,29.63,29.08,29.48,12992600,29.48
			// 2013-09-09,28.32,29.32,28.32,29.24,21167700,29.24
			// 2013-09-06,28.35,28.50,27.82,28.17,10807500,28.17
			// 2013-09-05,28.10,28.35,27.91,28.23,8989600,28.23
			//

			String line = value.toString();
			String[] cols = StringUtils.getStrings(line);

			String dateString = cols[0];
			Float adjClose = Float.parseFloat(cols[6]);

			// I use joda Time to calculate possible keys for each adjClose value 
			DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(&quot;yyyy-MM-dd&quot;);
			DateTime dateTime = DateTime.parse(dateString, dateTimeFormatter);
			System.out.println(&quot;dateString:&quot; + dateString);
			
			for (int i = 0; i &amp;lt; N; i++) {
				DateTime newDateTime = dateTime.plusDays(i);
				String newDateString = newDateTime.toString(dateTimeFormatter);
				
				System.out.println(&quot;newDateString:&quot; + newDateString);
				context.write(new Text(newDateString), new FloatWritable(adjClose));
			}	
		}
	}

	public static class MovingAverageReducer extends Reducer&amp;lt;Text, FloatWritable, Text, FloatWritable&amp;gt; {
		
		public void reduce(
				Text key,
				Iterable&amp;lt;FloatWritable&amp;gt; values,
				Context context) throws IOException, InterruptedException {
			
			Float sum = 0.0f;
			int n = 0;
			for (FloatWritable value : values) {
				sum += value.get();
				n++;
			}
			
			Float movingAverage = sum / n;
			
			context.write(key, new FloatWritable(movingAverage));
		}
	}

	/**
	 * @param args
	 * @throws IOException 
	 * @throws InterruptedException 
	 * @throws ClassNotFoundException 
	 */
	public static void main(
			String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		
		Configuration configuration = new Configuration();
		String[] otherArgs = new GenericOptionsParser(configuration, args).getRemainingArgs();
		
		String inputPath = otherArgs[0];
		String outputPath = otherArgs[1];
		
		Job job = new Job(configuration, &quot;moving average&quot;);
		job.setJarByClass(Main.class);
		
		job.setMapperClass(MovingAverageMapper.class);
		job.setReducerClass(MovingAverageReducer.class);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(FloatWritable.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(FloatWritable.class);
		
		FileInputFormat.addInputPath(job, new Path(inputPath));
		FileOutputFormat.setOutputPath(job, new Path(outputPath));
		
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

}
&lt;/pre&gt;
</description>
        <pubDate>Sun, 15 Sep 2013 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2013/09/15/simple-moving-average-with-hadoop/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2013/09/15/simple-moving-average-with-hadoop/</guid>
        
        
        <category>big data</category>
        
        <category>hadoop</category>
        
        <category>java</category>
        
        <category>uncategorized</category>
        
      </item>
    
      <item>
        <title>How Hadoop Speed Up Data Processing?</title>
        <description>&lt;p&gt;Hadoop speed up data processing in two ways:&lt;/p&gt;

&lt;h1 id=&quot;a-moving-computation-program-to-data-node&quot;&gt;A. Moving Computation Program to Data Node&lt;/h1&gt;

&lt;ol&gt;
  &lt;li&gt;Traditional Method: Moving Data to Computation Node&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&quot;attachment_281&quot; style=&quot;width: 469px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/?attachment_id=281&quot;&gt;&lt;img class=&quot;size-full wp-image-281 &quot; alt=&quot;traditional-data-transfer&quot; src=&quot;http://crzyjcky.com/wp-content/uploads/2013/09/traditional-data-transfer.png&quot; width=&quot;459&quot; height=&quot;99&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Traditional Method: Moving Data to Computation Node
  &lt;/p&gt;
&lt;/div&gt;

&lt;ol&gt;
  &lt;li&gt;Hadoop Method: Moving Computation Program to Data Node&lt;/li&gt;
&lt;/ol&gt;
&lt;div id=&quot;attachment_282&quot; style=&quot;width: 469px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/09/09/how-hadoop-speed-up-data-processing/hadoop-program-transfer/&quot; rel=&quot;attachment wp-att-282&quot;&gt;&lt;img class=&quot;size-full wp-image-282&quot; alt=&quot;hadoop-program-transfer&quot; src=&quot;http://crzyjcky.com/wp-content/uploads/2013/09/hadoop-program-transfer.png&quot; width=&quot;459&quot; height=&quot;99&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Hadoop Method: Moving Computation Program to Data Node
  &lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;&amp;lt;/ol&amp;gt;&lt;/p&gt;

&lt;p&gt;The size of data is a lot bigger than the size of program. Instead of transferring data from data node, Hadoop distributes computation program to data node. This saves a lot of network bandwidth and data transferring time.&lt;/p&gt;

&lt;h1 id=&quot;b-parallel-processingh2&quot;&gt;B. Parallel Processing&amp;lt;/h2&amp;gt;&lt;/h1&gt;

&lt;p&gt;To enable parallel processing,&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Data is split into several fragments, and is distributed to several data nodes.&lt;/li&gt;
  &lt;li&gt;Data processing can be run in parallel on each fragment.&lt;/li&gt;
  &lt;li&gt;Result will be combined.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href=&quot;http://crzyjcky.com/2013/09/09/how-hadoop-speed-up-data-processing/parallel-computation/&quot; rel=&quot;attachment wp-att-283&quot;&gt;&lt;img class=&quot;alignnone size-full wp-image-283&quot; alt=&quot;parallel-computation&quot; src=&quot;http://crzyjcky.com/wp-content/uploads/2013/09/parallel-computation.png&quot; width=&quot;482&quot; height=&quot;399&quot; /&gt;&lt;/a&gt;&lt;/p&gt;
</description>
        <pubDate>Mon, 09 Sep 2013 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2013/09/09/how-hadoop-speed-up-data-processing/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2013/09/09/how-hadoop-speed-up-data-processing/</guid>
        
        
        <category>hadoop</category>
        
        <category>uncategorized</category>
        
      </item>
    
      <item>
        <title>Hadoop Eclipse Plugin</title>
        <description>&lt;p&gt;Hadoop (1.2.1) Eclipse/STS 3.2.0 Plugin: &lt;a href=&quot;http://crzyjcky.com/2013/09/03/hadoop-eclipse-plugin/hadoop-eclipse-plugin-1-2-1-jar/&quot; rel=&quot;attachment wp-att-270&quot;&gt;hadoop-eclipse-plugin-1.2.1.jar&lt;/a&gt;&lt;/p&gt;
</description>
        <pubDate>Tue, 03 Sep 2013 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2013/09/03/hadoop-eclipse-plugin/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2013/09/03/hadoop-eclipse-plugin/</guid>
        
        
        <category>hadoop</category>
        
        <category>uncategorized</category>
        
      </item>
    
      <item>
        <title>JavaScript OOP</title>
        <description>&lt;h1 id=&quot;the-need-of-oop&quot;&gt;The need of OOP&lt;/h1&gt;

&lt;h2 id=&quot;is-convention-technique-enough&quot;&gt;Is Convention Technique enough?&lt;/h2&gt;

&lt;p&gt;Both techniques have their merits in different types of web application development. Conventional technique allows developer to jump into coding right away, thus has a faster turnaround for small development. OOP technique, if done properly, can localize a testing area, meaning we only have to test the modified part, without testing the whole application. This will be a time-saving and bug reduction technique in a long run.&lt;/p&gt;

&lt;p&gt;Conventional technique – for small scale web application development:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Pro: Easy to start to write. No/less initial planning.&lt;/li&gt;
  &lt;li&gt;Con: Any changes in requirements involve re-test the whole application.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;OOP (Large-scale) technique –&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Pro: Localized the need for test if changes happened.&lt;/li&gt;
  &lt;li&gt;Con: Steep learning curve.&lt;/li&gt;
&lt;/ul&gt;

&lt;div id=&quot;attachment_205&quot; style=&quot;width: 810px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/02/17/javascript-oop/localized-test/&quot; rel=&quot;attachment wp-att-205&quot;&gt;&lt;img class=&quot;size-full wp-image-205&quot; alt=&quot;localized-testing&quot; src=&quot;http://crzyjcky.com/wp-content/uploads/2013/02/localized-test.png&quot; width=&quot;800&quot; height=&quot;600&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    localized-testing
  &lt;/p&gt;
&lt;/div&gt;

&lt;h2 id=&quot;leverage-the-time-proven-knowledge-of-oop&quot;&gt;Leverage the time-proven knowledge of OOP&lt;/h2&gt;

&lt;p&gt;One of the efforts that the industry has taken on is by leveraging OOP concept which has been proven to build large scale application successfully. OOP is by far the most successful design process to date.  &lt;br /&gt;
We have a lot of knowledge/research built upon OOP concept, like&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Design Patterns&lt;/li&gt;
  &lt;li&gt;Domain-Driven Design&lt;/li&gt;
  &lt;li&gt;Model-Driven Design&lt;/li&gt;
  &lt;li&gt;UML&lt;/li&gt;
  &lt;li&gt;Use-Case Driven Design&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;attract-more-developers&quot;&gt;Attract more developers&lt;/h2&gt;

&lt;p&gt;Apart from this, we also have a large user base of Java Developer. Java Developer can easily up to speed by designing JavaScript application in OOP way.&lt;/p&gt;

&lt;h1 id=&quot;the-problem-of-adopting-oop&quot;&gt;The problem of adopting OOP&lt;/h1&gt;

&lt;p&gt;General speaking, JavaScript is an object-oriented language. The main difference between JavaScript and other OOP language (such as Java) is that JavaScript does not support Class construct and Interface. This is the main hurdle for adopting techniques which built on top of other OOP language.  &lt;br /&gt;
Various techniques have been developed in order to emulate the behavior of Class construct (by taking advantage of Closure feature, which is unique feature to JavaScript). However, the various techniques confuses a lot of beginner (imagine that if we have many ways to create a class in Java, it will introduce unnecessary complexity in learning the language).&lt;/p&gt;

&lt;h1 id=&quot;solution&quot;&gt;Solution&lt;/h1&gt;

&lt;p&gt;In order to leverage current OOP design techniques, we have to be able to construct a class. This section is about how to construct a class. Bear in mind that there are a lot of different ways of constructing a “class”, I will only introduce one way of doing so in this article. Trying to cover all the possible ways to construct a class, will only confuse you. All the variants implementation is leveraging the concept of JavaScript closure.&lt;/p&gt;

&lt;h2 id=&quot;constructing-a-class&quot;&gt;Constructing a class&lt;/h2&gt;

&lt;table&gt;
  &lt;tr&gt;
    &lt;td&gt;
      Java
    &lt;/td&gt;
    
    &lt;td&gt;
      JavaScript
    &lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
    &lt;td&gt;
      &lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;
public class Human
{
 public String name = &quot;John&quot;;
 private int age = 20;

 public int getAge()
 {
 	return age;
 }

 public String getName()
 {
 	return name;
 }

 public void sayHello()
 {
 	say(&quot;Hello&quot;);
 }

 private void say(String sentence)
 {
 	System.out.println(sentence);
 }
}

Human human = new Human();
&lt;/pre&gt;
    &lt;/td&gt;
    
    &lt;td&gt;
      &lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;
// Human class declaration
var Human = function() {
	// public variable
	this.name = &quot;John&quot;;
	// private variable
	var age = 20;

	// public method
	this.getAge = function() {
		return age;
	}

	// public method, uses public variable
	this.getName = function() {
		return this.name;
	}

	// public method invokes private method
	this.sayHello = function() {
		say(&quot;hello&quot;);
	}

	// private method
	var say = function(sentence) {
		console.log(sentence); // or alert(sentence);
	}
}

// instantiate Human class
var human = new Human();
&lt;/pre&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;

&lt;p&gt;As you can see, the conversion from Java class to JavaScript class is almost an one-to-one mapping. The rules can be summarized as follows:&lt;/p&gt;

&lt;table&gt;
  &lt;tr&gt;
    &lt;td&gt;
      1
    &lt;/td&gt;
    
    &lt;td&gt;
      Class Delaration
    &lt;/td&gt;
    
    &lt;td&gt;
      &lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;var &amp;lt;className&amp;gt; = function(){}&lt;/pre&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
    &lt;td&gt;
      2
    &lt;/td&gt;
    
    &lt;td&gt;
      Public variable
    &lt;/td&gt;
    
    &lt;td&gt;
      &lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;this.&amp;lt;variableName&amp;gt;&lt;/pre&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
    &lt;td&gt;
      3
    &lt;/td&gt;
    
    &lt;td&gt;
      Private variable
    &lt;/td&gt;
    
    &lt;td&gt;
      &lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;var &amp;lt;variableName&amp;gt;&lt;/pre&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
    &lt;td&gt;
      4
    &lt;/td&gt;
    
    &lt;td&gt;
      Public function
    &lt;/td&gt;
    
    &lt;td&gt;
      &lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;this.&amp;lt;functionName&amp;gt; = function() {}&lt;/pre&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
    &lt;td&gt;
      5
    &lt;/td&gt;
    
    &lt;td&gt;
      Private function
    &lt;/td&gt;
    
    &lt;td&gt;
      &lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;var &amp;lt;functionName&amp;gt; - function() {}&lt;/pre&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
  
  &lt;tr&gt;
    &lt;td&gt;
      6
    &lt;/td&gt;
    
    &lt;td&gt;
      Instantiation
    &lt;/td&gt;
    
    &lt;td&gt;
      &lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;var &amp;lt;instanceName&amp;gt; = new &amp;lt;className&amp;gt;();&lt;/pre&gt;
    &lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;&amp;lt;/ol&amp;gt;&lt;/p&gt;

&lt;h1 id=&quot;leverage-the-power-of-design-patterns&quot;&gt;Leverage the Power of Design Patterns&lt;/h1&gt;

&lt;p&gt;I will show you how to implement Observer Pattern in JavaScript class. A broadcaster generally contains 4 items:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Array of listeners&lt;/li&gt;
  &lt;li&gt;Add listener operation&lt;/li&gt;
  &lt;li&gt;Remove listener operation&lt;/li&gt;
  &lt;li&gt;Broadcast event&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;A listener need to implements an event handler which matches the event broadcasted.&lt;/p&gt;

&lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;// Broadcaster.js

var Broadcaster = function() {
	// 1. listener array
	var listeners = [];

	// 2. add listener
	this.addListener = function(listener) {
		listeners.push(listener);
	}

	// 3. remove listener
	this.removeListener = function(listener) {
		var i = listeners.length;
		while (i--) {
			if (listners[i] === listener) {
				listeners.splice(i, 1);
			}
		}
	}

	// 4. broadcast event
	var broadcast = function(event) {
		var len = listeners.length;
		for ( var i = 0; i &amp;lt; len; i++) {
			listeners[i][event]();
		}
	}

	this.press = function() {
		// 5. broadcast event, which listeners need to provide corresponding handler to handle it
		broadcast(&quot;onPressed&quot;);
	}
}
&lt;/pre&gt;

&lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;// Listener.js

var Listener = function() {
	// the onPressed method name must match the broadcasted event &quot;onPressed&quot;
	this.onPressed = function() {
		alert(&quot;this is one&quot;);
	}
}
&lt;/pre&gt;

&lt;h2 id=&quot;how-about-interface&quot;&gt;How about Interface?&lt;/h2&gt;

&lt;p&gt;If we studied GOF design patterns carefully, we will notice that most design patterns rely on a language construct, called “Interface”. This follows the main principle – “Program to an ‘interface’, not an ‘implementation’.”  &lt;br /&gt;
The way other OOP languages enforces the interface validation rely on compiler to flag error during compilation. However JavaScript is a script which does not require compilation, so there is no way to enforce it during compilation. However if an error is detected during run-time, it is too late already.  &lt;br /&gt;
We have two solutions:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Discipline ourselves to implement all the required methods (which I am using this strategy in this article). Or&lt;/li&gt;
  &lt;li&gt;Use third party JavaScript compiler to compile the JavaScript. Developers need to add an special annotation tag to indicate which interface it is implementing, and the compiler will validate to ensure all the operations have been implemented. An example of this tool is Google Closure Compiler.&amp;lt;/p&amp;gt; &lt;br /&gt;
    Example of annotated JavaScript class with Google Closure Library annotation:&lt;/li&gt;
&lt;/ol&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&amp;gt;/**  * A shape.  * @interface  */ function Shape() {}; Shape.prototype.draw = function() {};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;/**&lt;br /&gt;
 * @constructor&lt;br /&gt;
 * @implements {Shape}&lt;br /&gt;
 */&lt;br /&gt;
function Square() {};&lt;br /&gt;
Square.prototype.draw = function() {&lt;br /&gt;
  …&lt;br /&gt;
};&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;/p&gt;

&lt;h1 id=&quot;demo&quot;&gt;Demo&lt;/h1&gt;

&lt;p&gt;To illustrate the power of OOP/design patterns in JavaScript, I created a simple “Online Movie Ticket System”. I choose to build this ticket system (which is quite common, in my opinion), because the main idea of design pattern is to “provide a solution to common problems”.  &lt;br /&gt;
This application is constructed based on MVC pattern. We have one Model class as a broadcaster, and three listeners, which are SeatMapView, SelectedSeatView, and PriceCalculatorView. Every time the Model change its state, it will notify (broadcast) “onChange” event to all its listeners. The listeners will then respond to the event by its own way (according to its implementation).&lt;/p&gt;

&lt;h2 id=&quot;mockup&quot;&gt;Mockup&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;http://crzyjcky.com/2013/02/17/javascript-oop/mockup/&quot; rel=&quot;attachment wp-att-241&quot;&gt;&lt;img src=&quot;http://crzyjcky.com/wp-content/uploads/2013/02/mockup.png&quot; alt=&quot;mockup&quot; width=&quot;837&quot; height=&quot;403&quot; class=&quot;alignnone size-full wp-image-241&quot; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2 id=&quot;class-diagram&quot;&gt;Class Diagram&lt;/h2&gt;

&lt;div id=&quot;attachment_242&quot; style=&quot;width: 583px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/02/17/javascript-oop/demo-design/&quot; rel=&quot;attachment wp-att-242&quot;&gt;&lt;img src=&quot;http://crzyjcky.com/wp-content/uploads/2013/02/demo-design.png&quot; alt=&quot;demo-class-diagram&quot; width=&quot;573&quot; height=&quot;270&quot; class=&quot;size-full wp-image-242&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    demo-class-diagram
  &lt;/p&gt;
&lt;/div&gt;

&lt;h2 id=&quot;screenshot&quot;&gt;Screenshot&lt;/h2&gt;

&lt;div id=&quot;attachment_244&quot; style=&quot;width: 722px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/02/17/javascript-oop/screenshot/&quot; rel=&quot;attachment wp-att-244&quot;&gt;&lt;img src=&quot;http://crzyjcky.com/wp-content/uploads/2013/02/screenshot.png&quot; alt=&quot;demo-screenshot&quot; width=&quot;712&quot; height=&quot;498&quot; class=&quot;size-full wp-image-244&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    demo-screenshot
  &lt;/p&gt;
&lt;/div&gt;

&lt;h2 id=&quot;code&quot;&gt;Code&lt;/h2&gt;

&lt;p&gt;index.html&lt;/p&gt;

&lt;pre class=&quot;brush: xml; title: ; notranslate&quot; title=&quot;&quot;&gt;&amp;lt;html&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;h1&amp;gt;Sunflower Online Movie Ticket System&amp;lt;/h1&amp;gt;
  &amp;lt;table&amp;gt;
    &amp;lt;tr&amp;gt;
      &amp;lt;td width=&quot;80%&quot; valign=&quot;top&quot;&amp;gt;
        &amp;lt;h2&amp;gt;Seat Map&amp;lt;/h2&amp;gt;
        &amp;lt;table id=&quot;seatMap&quot; width=&quot;100%&quot; border=&quot;1&quot; cellspacing=&quot;0&quot; cellpadding=&quot;0&quot;&amp;gt;
          &amp;lt;tr&amp;gt;
            &amp;lt;td&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;&amp;lt;td align=&quot;center&quot;&amp;gt;1&amp;lt;/td&amp;gt;&amp;lt;td align=&quot;center&quot;&amp;gt;2&amp;lt;/td&amp;gt;&amp;lt;td align=&quot;center&quot;&amp;gt;3&amp;lt;/td&amp;gt;
          &amp;lt;/tr&amp;gt;
          &amp;lt;tr&amp;gt;
            &amp;lt;td align=&quot;center&quot;&amp;gt;A&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;A1&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;A2&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;A3&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;
          &amp;lt;/tr&amp;gt;
          &amp;lt;tr&amp;gt;
            &amp;lt;td align=&quot;center&quot;&amp;gt;B&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;B1&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;B2&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;B3&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;
          &amp;lt;/tr&amp;gt;
          &amp;lt;tr&amp;gt;
            &amp;lt;td align=&quot;center&quot;&amp;gt;C&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;C1&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;C2&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;&amp;lt;td id=&quot;C3&quot;&amp;gt;&amp;nbsp;&amp;lt;/td&amp;gt;
          &amp;lt;/tr&amp;gt;
        &amp;lt;/table&amp;gt;
        
        &amp;lt;h2&amp;gt;Price Calculator&amp;lt;/h2&amp;gt;
        &amp;lt;input id=&quot;priceCalculator&quot; type=&quot;text&quot; size=&quot;60&quot; /&amp;gt;
      &amp;lt;/td&amp;gt;
      &amp;lt;td width=&quot;20%&quot; valign=&quot;top&quot;&amp;gt;
        &amp;lt;h2&amp;gt;Selected Seat&amp;lt;/h2&amp;gt;
        &amp;lt;textarea id=&quot;selectedSeat&quot; rows=&quot;12&quot;&amp;gt;&amp;lt;/textarea&amp;gt;
      &amp;lt;/td&amp;gt;
    &amp;lt;/tr&amp;gt;
  &amp;lt;/table&amp;gt;

&amp;lt;/body&amp;gt;
&amp;lt;script src=&quot;Model.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;SeatMapView.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;SelectedSeatView.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script src=&quot;PriceCalculatorView.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script&amp;gt;
var seatMapElement = document.getElementById(&quot;seatMap&quot;);
var selectedSeatElement = document.getElementById(&quot;selectedSeat&quot;);
var priceCalculatorElement = document.getElementById(&quot;priceCalculator&quot;);

var model = new Model();
var seatMapView = new SeatMapView(seatMapElement);
var selectedSeatView = new SelectedSeatView(selectedSeatElement);
var priceCalculatorView = new PriceCalculatorView(priceCalculatorElement);

// initialization
seatMapView.init(model.getData());
selectedSeatView.init(model.getData());
priceCalculatorView.init(model.getData());

// add listeners
model.addListener(seatMapView);
model.addListener(selectedSeatView);
model.addListener(priceCalculatorView);

seatMapElement.addEventListener(&quot;click&quot;, model.onClickHandler, false);

&amp;lt;/script&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;

&lt;p&gt;Model.js&lt;/p&gt;

&lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;var Model = function() {
  
  // initialization, false = is vacant, not occupied yet
  var seatMap = {};
  seatMap[&quot;A1&quot;] = false;
  seatMap[&quot;A2&quot;] = false;
  seatMap[&quot;A3&quot;] = false;
  seatMap[&quot;B1&quot;] = false;
  seatMap[&quot;B2&quot;] = false;
  seatMap[&quot;B3&quot;] = false;
  seatMap[&quot;C1&quot;] = false;
  seatMap[&quot;C2&quot;] = false;
  seatMap[&quot;C3&quot;] = false;

  var listeners = [];
  
  this.addListener = function(listener) {
    listeners.push(listener);
  }

  this.removeListener = function(listener) {
    var i = listeners.length;
    while (i--) {
      if (listeners[i] === listener) {
        listeners.splice(i, 1);
        break;
      }
    }
  }
  
  var broadcast = function(event, args) {
    var len = listeners.length;
    for (var i = 0; i &amp;lt; len; i++) {
      listeners[i][event](args);
    }
  }
  
  // listener of dom element
  this.onClickHandler = function(e) {
    var element = e.target;
    
    if (!isExist(element.id)) {
      return;
    }

    // toggle value
    seatMap[element.id] = !seatMap[element.id];
    broadcast(&quot;onChange&quot;, seatMap);
  }

  this.getData = function() {
    return seatMap;
  }

  var isExist = function(item) {
    for (var a in seatMap) {
      if (a === item) {
        return true;
      }
    }
    return false;
  }
  
  var toggle = function(value) {
    value = !value;
    
    console.log(seatMap[&quot;A1&quot;]);
    
    broadcast(&quot;onChange&quot;, seatMap);
  }
  
}
&lt;/pre&gt;

&lt;p&gt;PriceCalculatorView.js&lt;/p&gt;

&lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;var PriceCalculatorView = function(priceCalculatorElement) {
  var UNIT_PRICE = 10.00;
  
  this.onChange = function(data) {
    var numberOfSeat = calculateNumberOfSeat(data);
    priceCalculatorElement.value = numberOfSeat + &quot; (seats) x $&quot; + UNIT_PRICE + &quot; (unit price) = $&quot; + (numberOfSeat * UNIT_PRICE);
  }
  
  this.init = function(data) {
    this.onChange(data);
  }
  
  var calculateNumberOfSeat = function(data) {
    var numberOfSeat = 0;
    for (var a in data) {
      if (data[a]) {
        numberOfSeat++;
      }
    }
    return numberOfSeat;
  }
}
&lt;/pre&gt;

&lt;p&gt;SeatMapView.js&lt;/p&gt;

&lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;var SeatMapView = function(seatMapElement) {
  var COLOR_RED = &quot;#F79F81&quot;;
  var COLOR_GREEN = &quot;ACFA58&quot;;
  
  this.onChange = function(data) {
    for (var a in data) {
      var element = document.getElementById(a);
      element.bgColor = data[a] ? COLOR_RED : COLOR_GREEN;
    }
  }
  
  this.init = function(data) {
    this.onChange(data);
  }
}
&lt;/pre&gt;

&lt;p&gt;SelectedSeatView.js&lt;/p&gt;

&lt;pre class=&quot;brush: jscript; title: ; notranslate&quot; title=&quot;&quot;&gt;var SelectedSeatView = function(selectedSeatElement) {
  this.onChange = function(data) {
    selectedSeatElement.innerHTML = &quot;&quot;;
    for (var a in data) {
      if (data[a]) {
        selectedSeatElement.innerHTML += a + &quot;\n&quot;;
      }
    }
  }
  
  this.init = function(data) {
    this.onChange(data);
  }
}
&lt;/pre&gt;

&lt;p&gt;Source code: &lt;a href=&quot;http://crzyjcky.com/2013/02/17/javascript-oop/ticket-system/&quot; rel=&quot;attachment wp-att-247&quot;&gt;ticket-system&lt;/a&gt;&lt;/p&gt;
&lt;script charset=&quot;utf-8&quot; type=&quot;text/javascript&quot; src=&quot;http://ws.amazon.com/widgets/q?ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822/US/crzyjcky-20/8001/d5fcc65f-703e-462a-9fd3-85f0e4919f82&quot;&gt; &lt;/script&gt;

&lt;noscript&gt;
  &lt;a href=&quot;http://ws.amazon.com/widgets/q?ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822%2FUS%2Fcrzyjcky-20%2F8001%2Fd5fcc65f-703e-462a-9fd3-85f0e4919f82&amp;#038;Operation=NoScript&quot;&gt;Amazon.com Widgets&lt;/a&gt;
&lt;/noscript&gt;
</description>
        <pubDate>Sun, 17 Feb 2013 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2013/02/17/javascript-oop/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2013/02/17/javascript-oop/</guid>
        
        
        <category>design patterns</category>
        
        <category>javascript</category>
        
        <category>uncategorized</category>
        
      </item>
    
      <item>
        <title>Who Will Be Your Next Friend?</title>
        <description>&lt;h1 id=&quot;triadic-closure&quot;&gt;Triadic Closure&lt;/h1&gt;

&lt;p&gt;Given 3 people – A, B and C, If A and B are friends, B and C are friends, there is high possibility that A and C are friends, or will be friends. If each person can be represented as a node, 3 nodes form a &lt;strong&gt;Triadic Closure&lt;/strong&gt;.&lt;/p&gt;

&lt;div id=&quot;attachment_178&quot; style=&quot;width: 383px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/01/20/who-will-be-your-next-friend/triadic-closure/&quot; rel=&quot;attachment wp-att-178&quot;&gt;&lt;img src=&quot;http://crzyjcky.com/wp-content/uploads/2013/01/triadic-closure.png&quot; alt=&quot;Triadic Closure&quot; width=&quot;373&quot; height=&quot;613&quot; class=&quot;size-full wp-image-178&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Triadic Closure
  &lt;/p&gt;
&lt;/div&gt;

&lt;h1 id=&quot;exampleh2&quot;&gt;Example&amp;lt;/h2&amp;gt;&lt;/h1&gt;

&lt;div id=&quot;attachment_175&quot; style=&quot;width: 551px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/01/20/who-will-be-your-next-friend/character-relationship-chart/&quot; rel=&quot;attachment wp-att-175&quot;&gt;&lt;img src=&quot;http://crzyjcky.com/wp-content/uploads/2013/01/character-relationship-chart.png&quot; alt=&quot;Character Relationship Chart&quot; width=&quot;541&quot; height=&quot;373&quot; class=&quot;size-full wp-image-175&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Character Relationship Chart
  &lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;Given a character relationship chart, we want to find out who Ken will be friend with next. We can use Neo4j for this analysis.&lt;/p&gt;

&lt;p&gt;First We store the relationship into Neo4j using Cypher language.&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;CREATE gouken = {id:1, name:&quot;Gouken&quot;}, 
chunLi = {id:2, name:&quot;Chun Li&quot;},
ken = {id:3, name:&quot;Ken&quot;},
ryu = {id:4, name:&quot;Ryu&quot;},
eHonda = {id:5, name:&quot;E. Honda&quot;},
guile = {id:6, name:&quot;Guile&quot;};

START n1 = node:node_auto_index(name = &quot;Gouken&quot;), n2 = node:node_auto_index(name = &quot;Ryu&quot;)
CREATE (n1)-[:FRIEND]-(n2);

START n1 = node:node_auto_index(name = &quot;Gouken&quot;), n2 = node:node_auto_index(name = &quot;Ken&quot;)
CREATE (n1)-[:FRIEND]-(n2);

START n1 = node:node_auto_index(name = &quot;Ryu&quot;), n2 = node:node_auto_index(name = &quot;Ken&quot;)
CREATE (n1)-[:FRIEND]-(n2);

START n1 = node:node_auto_index(name = &quot;Ryu&quot;), n2 = node:node_auto_index(name = &quot;Chun Li&quot;)
CREATE (n1)-[:FRIEND]-(n2);

START n1 = node:node_auto_index(name = &quot;Ryu&quot;), n2 = node:node_auto_index(name = &quot;E. Honda&quot;)
CREATE (n1)-[:FRIEND]-(n2);

START n1 = node:node_auto_index(name = &quot;E. Honda&quot;), n2 = node:node_auto_index(name = &quot;Guile&quot;)
CREATE (n1)-[:FRIEND]-(n2);

START n1 = node:node_auto_index(name = &quot;Ken&quot;), n2 = node:node_auto_index(name = &quot;Guile&quot;)
CREATE (n1)-[:FRIEND]-(n2);
&lt;/pre&gt;

&lt;div id=&quot;attachment_176&quot; style=&quot;width: 551px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/01/20/who-will-be-your-next-friend/character-relationship-chart-link/&quot; rel=&quot;attachment wp-att-176&quot;&gt;&lt;img src=&quot;http://crzyjcky.com/wp-content/uploads/2013/01/character-relationship-chart-link.png&quot; alt=&quot;Character Relationship Chart with Possible Link&quot; width=&quot;541&quot; height=&quot;373&quot; class=&quot;size-full wp-image-176&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Character Relationship Chart with Possible Link
  &lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;To find out who will be Ken’s next friend, we can run a query to find all incomplete Triadic Closures:&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;START ken = node:node_auto_index(name = &quot;Ken&quot;)
MATCH (ken)-[:FRIEND]-(commonFriend)-[:FRIEND]-(stranger)-[rel?:FRIEND]-(ken)
WHERE rel is null 
RETURN distinct ken.name, stranger.name;
&lt;/pre&gt;

&lt;p&gt;Result:&lt;/p&gt;

&lt;pre class=&quot;brush: plain; title: ; notranslate&quot; title=&quot;&quot;&gt;==&amp;gt; +--------------------------+
==&amp;gt; | ken.name | stranger.name |
==&amp;gt; +--------------------------+
==&amp;gt; | &quot;Ken&quot;    | &quot;E. Honda&quot;    |
==&amp;gt; | &quot;Ken&quot;    | &quot;Chun Li&quot;     |
==&amp;gt; +--------------------------+
&lt;/pre&gt;

&lt;p&gt;From the result, we know that Ken has high probability to be friend with E. Honda and Chun Li, because they both have common friends.&lt;/p&gt;

&lt;p&gt;The more common friends they share, the higher chance they will be friend eventually. To find out who will have higher chances to be friend with Ken, we can run a query to find out the number of common friends they share with Ken:&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;START ken = node:node_auto_index(name = &quot;Ken&quot;)
MATCH (ken)-[:FRIEND]-(commonFriend)-[:FRIEND]-(stranger)-[rel?:FRIEND]-(ken)
WHERE rel is null 
RETURN distinct ken.name, stranger.name, count(commonFriend);
&lt;/pre&gt;

&lt;p&gt;Result:&lt;/p&gt;

&lt;pre class=&quot;brush: plain; title: ; notranslate&quot; title=&quot;&quot;&gt;==&amp;gt; +------------------------------------------------+
==&amp;gt; | ken.name | stranger.name | count(commonFriend) |
==&amp;gt; +------------------------------------------------+
==&amp;gt; | &quot;Ken&quot;    | &quot;E. Honda&quot;    | 2                   |
==&amp;gt; | &quot;Ken&quot;    | &quot;Chun Li&quot;     | 1                   |
==&amp;gt; +------------------------------------------------+
&lt;/pre&gt;

&lt;p&gt;Ken and E. Honda’s common friends are Ryu and Guile, whereas with Chun Li, their common friend is Ryu only. From the result, we know that Ken will have higher chance to be friend with E. Honda.&lt;/p&gt;
&lt;script charset=&quot;utf-8&quot; type=&quot;text/javascript&quot; src=&quot;http://ws.amazon.com/widgets/q?rt=tf_mfw&amp;#038;ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822/US/crzyjcky-20/8001/72378f6e-c27a-4048-a804-1706d410e0a9&quot;&gt; &lt;/script&gt;

&lt;noscript&gt;
  &lt;a href=&quot;http://ws.amazon.com/widgets/q?rt=tf_mfw&amp;#038;ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822%2FUS%2Fcrzyjcky-20%2F8001%2F72378f6e-c27a-4048-a804-1706d410e0a9&amp;#038;Operation=NoScript&quot;&gt;Amazon.com Widgets&lt;/a&gt;
&lt;/noscript&gt;
</description>
        <pubDate>Sun, 20 Jan 2013 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2013/01/20/who-will-be-your-next-friend/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2013/01/20/who-will-be-your-next-friend/</guid>
        
        <category>neo4j</category>
        
        <category>nosql</category>
        
        <category>social-science</category>
        
        
        <category>neo4j</category>
        
        <category>nosql</category>
        
        <category>social science</category>
        
      </item>
    
      <item>
        <title>Simple Document Search with Lucene</title>
        <description>&lt;p&gt;The way Apache Lucene speed up document search is by searching through special crafted index, instead of opening documents one-by-one during run-time. Using Lucene is a two-step process: creating index, and searching document (via index).&lt;/p&gt;

&lt;h1 id=&quot;part-1-creating-index&quot;&gt;Part 1: Creating Index&lt;/h1&gt;

&lt;p&gt;You have to put all the text files in directory specified by “DATA_DIR”. This program will generates index files and stores them inside “INDEX_DIR” directory.&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;package com.crzyjcky.blog;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;


public class Indexer {

	private static final String INDEX_DIR = &quot;index&quot;;
	private static final String DATA_DIR = &quot;data&quot;;
	
	private IndexWriter indexWriter;
	
	public void index(String indexDir, String dataDir) throws IOException {
		
		Directory dir = FSDirectory.open(new File(indexDir));
		indexWriter = new IndexWriter(dir, new StandardAnalyzer(Version.LUCENE_30), true, IndexWriter.MaxFieldLength.UNLIMITED);
		
		File[] files = new File(DATA_DIR).listFiles();
		for (File file : files) {
			
			Document doc = new Document();
			doc.add(new Field(&quot;contents&quot;, new FileReader(file)));
			doc.add(new Field(&quot;filename&quot;, file.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
			
			indexWriter.addDocument(doc);
			System.out.println(&quot;doc added: &quot; + file.getName());
		}
	}
	
	public void close() throws CorruptIndexException, IOException {
		
		indexWriter.close();
	}
	
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		
		System.out.println(&quot;start: &quot; + System.currentTimeMillis());
		
		Indexer indexer = new Indexer();
		indexer.index(INDEX_DIR, DATA_DIR);
		indexer.close();
		
		System.out.println(&quot;end: &quot; + System.currentTimeMillis());
	}
}
&lt;/pre&gt;

&lt;h2 id=&quot;part-2-searching-documents&quot;&gt;Part 2: Searching Documents&lt;/h2&gt;

&lt;p&gt;Note that Lucene search through indexes, not the actual documents.&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;package com.crzyjcky.blog;
import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;


public class Searcher {

	private static final String INDEX_DIR = &quot;index&quot;;
	
	private static final int NUM_SEARCH = 10;
	
	public void search(String indexDir, String queryString) throws IOException, ParseException {
		
		Directory dir = FSDirectory.open(new File(INDEX_DIR));
		IndexSearcher indexSearcher = new IndexSearcher(dir);
		
		QueryParser queryParser = new QueryParser(Version.LUCENE_30, &quot;contents&quot;, new StandardAnalyzer(Version.LUCENE_30));
		Query query = queryParser.parse(queryString);
		
		TopDocs hits = indexSearcher.search(query, NUM_SEARCH);
		
		System.out.println(&quot;#hits: &quot; + hits.totalHits);
		
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			
			System.out.print(&quot;scoreDoc.doc: &quot; + scoreDoc.doc + &quot;, score: &quot; + scoreDoc.score + &quot; &quot;);
			Document doc = indexSearcher.doc(scoreDoc.doc);
			System.out.println(&quot;\tfilename: &quot; + doc.get(&quot;filename&quot;));
		}
		
		indexSearcher.close();
	}
	
	/**
	 * @param args
	 * @throws ParseException 
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException, ParseException {
		
		System.out.println(&quot;start: &quot; + System.currentTimeMillis());
		Searcher searcher  = new Searcher();
		
		// put your query here
		String query = &quot;Redistribution&quot;;
		
		searcher.search(INDEX_DIR, query);
		
		System.out.println(&quot;end: &quot; + System.currentTimeMillis());
	}
}
&lt;/pre&gt;

&lt;p&gt;Source code: &lt;a href=&quot;http://crzyjcky.com/2013/01/12/document-search-with-lucene/blog-lucene/&quot; rel=&quot;attachment wp-att-146&quot;&gt;blog-lucene&lt;/a&gt;&lt;/p&gt;
&lt;script charset=&quot;utf-8&quot; type=&quot;text/javascript&quot; src=&quot;http://ws.amazon.com/widgets/q?rt=tf_mfw&amp;#038;ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822/US/crzyjcky-20/8001/e8b36acf-a008-41eb-8ada-8779a74b2e9a&quot;&gt; &lt;/script&gt;

&lt;noscript&gt;
  &lt;a href=&quot;http://ws.amazon.com/widgets/q?rt=tf_mfw&amp;#038;ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822%2FUS%2Fcrzyjcky-20%2F8001%2Fe8b36acf-a008-41eb-8ada-8779a74b2e9a&amp;#038;Operation=NoScript&quot;&gt;Amazon.com Widgets&lt;/a&gt;
&lt;/noscript&gt;
</description>
        <pubDate>Sat, 12 Jan 2013 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2013/01/12/document-search-with-lucene/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2013/01/12/document-search-with-lucene/</guid>
        
        <category>lucene</category>
        
        
        <category>java</category>
        
        <category>lucene</category>
        
      </item>
    
      <item>
        <title>The Magical Bloom Filter</title>
        <description>&lt;h1 id=&quot;what-is-bloom-filter&quot;&gt;What is Bloom Filter?&lt;/h1&gt;

&lt;p&gt;Bloom Filter checks if a key exists or not. It was invented by Burton Bloom (and hence the name) to solve dictionary problem. The Bloom Filter is used to check if the word is in dictionary or not. Computer memory is very limited at that time, and it is impossible to load all the words into memory.&lt;/p&gt;

&lt;p&gt;The uniqueness of Bloom Filter is that it is not a very accurate filter. If it reports false (not exist), the items definitely is not exist. However if it reports true (exist), there are a small chance that it could be false positive result.&lt;/p&gt;

&lt;h1 id=&quot;comparison-with-normal-filter&quot;&gt;Comparison with normal filter&lt;/h1&gt;

&lt;p&gt;To illustrate the benefit of Bloom Filter, we use a normal filter to do comparison. These filter basically do two things, store keys, and check if particular string exists or not.&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;public interface IFilter {

	public void addData(String key);
	public boolean isExist(String key);
}
&lt;/pre&gt;

&lt;p&gt;Snippet 1: IFilter interface contains only 2 operations.&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;public class NormalFilter implements IFilter {

	private HashSet keySet = new HashSet();

	@Override
	public void addData(String key) {

		keySet.add(key);
	}

	@Override
	public boolean isExist(String key) {

		return keySet.contains(key);
	}
}
&lt;/pre&gt;

&lt;p&gt;Snippet 2: Normal Filter store each key, thus it size will increase with the number of keys.&lt;/p&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;public class BloomFilter implements IFilter {

	private int bloomBitArray;

	@Override
	public void addData(String key) {

		int hashKey = hash(key);

		System.out.println(&quot;bloomBitArray (before):\t&quot; + toBinaryString(bloomBitArray));
		System.out.println(&quot;hashKey:\t\t&quot; + toBinaryString(hashKey));

		bloomBitArray = hashKey | bloomBitArray;

		System.out.println(&quot;bloomBitArray (after):\t&quot; + toBinaryString(bloomBitArray));
	}

	@Override
	public boolean isExist(String key) {

		int hashKey = hash(key);

		System.out.println(&quot;bloomBitArray:\t&quot; + toBinaryString(bloomBitArray));
		System.out.println(&quot;hashKey:\t&quot; + toBinaryString(hashKey));

		return (bloomBitArray &amp;amp; hashKey) == hashKey;
	}

	// it can be 1 or more hash functions
	private int hash(String key) {

		// you can use your own hash code, even as simple as modulo hash code,
		// I use Java built-in hashcode to illustrate the purpose.

		// set up 1 bit in the bloomBitArray
		return 1 &amp;lt;&amp;lt; key.hashCode();
	}

	// beautify the result
	private String toBinaryString(int key) {

		return padLeft(Integer.toBinaryString(key));
	}

	// beautify the result
	private String padLeft(String binaryString) {

		return String.format(&quot;%32s&quot;, binaryString).replace(&quot; &quot;, &quot;0&quot;);
	}
}
&lt;/pre&gt;

&lt;p&gt;Snippet 3: Bloom Filter doesn’t store any keys. It only stores combined hash values.&lt;/p&gt;

&lt;div id=&quot;attachment_114&quot; style=&quot;width: 239px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/01/03/the-magical-bloom-filter/bloom-filter-hash/&quot; rel=&quot;attachment wp-att-114&quot;&gt;&lt;img class=&quot;size-full wp-image-114&quot; alt=&quot;Bloom Filter stores combined hash values&quot; src=&quot;http://crzyjcky.com/wp-content/uploads/2013/01/bloom-filter-hash.png&quot; width=&quot;229&quot; height=&quot;435&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Bloom Filter stores combined hash values
  &lt;/p&gt;
&lt;/div&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;public class Main {

	private static IFilter filter = new BloomFilter();
	//private static IFilter filter = new NormalFilter();
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// add as much data as you want here  here

		printAddData(&quot;hello&quot;);
		printAddData(&quot;I&quot;);
		printAddData(&quot;am&quot;);
		printAddData(&quot;happy&quot;);

		System.out.println(&quot;==================================================&quot;);
		System.out.println(&quot;                        RESULT                    &quot;);
		System.out.println(&quot;==================================================&quot;);

		// testing
		printIsExist(&quot;world&quot;);
		printIsExist(&quot;wo&quot;);
		printIsExist(&quot;w&quot;);
		printIsExist(&quot;happy&quot;);
		printIsExist(&quot;hap&quot;);
		printIsExist(&quot;I&quot;);

	}

	private static void printAddData(String key) {

		System.out.println(&quot;---------------------------------&quot;);
		System.out.println(&quot;addData(&quot; + key + &quot;)&quot;);
		filter.addData(key);

	}

	private static void printIsExist(String key) {

		System.out.println(&quot;---------------------------------&quot;);
		System.out.println(&quot;isExist(&quot; + key + &quot;):\t&quot; + filter.isExist(key));
	}
}
&lt;/pre&gt;

&lt;h1 id=&quot;results&quot;&gt;Results&lt;/h1&gt;

&lt;pre class=&quot;brush: java; title: ; notranslate&quot; title=&quot;&quot;&gt;---------------------------------
addData(hello)
bloomBitArray (before):	00000000000000000000000000000000
hashKey:			d	00000000000001000000000000000000
bloomBitArray (after):	00000000000001000000000000000000
---------------------------------
addData(I)
bloomBitArray (before):	00000000000001000000000000000000
hashKey:			d	00000000000000000000001000000000
bloomBitArray (after):	00000000000001000000001000000000
---------------------------------
addData(am)
bloomBitArray (before):	00000000000001000000001000000000
hashKey:			d	00000000000000000001000000000000
bloomBitArray (after):	00000000000001000001001000000000
---------------------------------
addData(happy)
bloomBitArray (before):	00000000000001000001001000000000
hashKey:			d	00000000000000000000000000000001
bloomBitArray (after):	00000000000001000001001000000001
==================================================
                        RESULT
==================================================
---------------------------------
bloomBitArray:	00000000000001000001001000000001
hashKey:		00000000000001000000000000000000
isExist(world):	true
---------------------------------
bloomBitArray:	00000000000001000001001000000001
hashKey:		00000001000000000000000000000000
isExist(wo):	false
---------------------------------
bloomBitArray:	00000000000001000001001000000001
hashKey:		00000000100000000000000000000000
isExist(w):	false
---------------------------------
bloomBitArray:	00000000000001000001001000000001
hashKey:		00000000000000000000000000000001
isExist(happy):	true
---------------------------------
bloomBitArray:	00000000000001000001001000000001
hashKey:		00000000100000000000000000000000
isExist(hap):	false
---------------------------------
bloomBitArray:	00000000000001000001001000000001
hashKey:		00000000000000000000001000000000
isExist(I):	true
&lt;/pre&gt;

&lt;p&gt;Snippet 5: Bloom Filter Test Result&lt;/p&gt;

&lt;p&gt;Note that the first result “world” is not correct. This is the “uniqueness” Bloom Filter (Yea, when we love something, we will call whatever defects as uniqueness :D).&lt;/p&gt;

&lt;p&gt;So the “special” character of Bloom Filter is:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;When it say “wrong”, it is definitely wrong.&lt;/li&gt;
  &lt;li&gt;When it say “right”, it could be right, or it could be wrong (false positive).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;As the result, we can trust the result when it says “something doesn’t exist”. If it reports “yes, it exists”, we will have to check in other way to confirm the result. It seems like problematic, but in fact it is not, because Bloom Filter is normally used as an add-on to speed up query. It doesn’t stand alone.&lt;/p&gt;

&lt;h1 id=&quot;benefits&quot;&gt;Benefits&lt;/h1&gt;

&lt;h2 id=&quot;size-does-matter&quot;&gt;Size does matter&lt;/h2&gt;

&lt;p&gt;As you can see, Bloom Filter stores only hash values. Each has values will be “OR”ed with current bit array in Bloom Filter, as the result, the size of Bloom Filter remains constant, regardless the number of input.&lt;/p&gt;

&lt;div id=&quot;attachment_131&quot; style=&quot;width: 268px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/01/03/the-magical-bloom-filter/bloom-filter-size/&quot; rel=&quot;attachment wp-att-131&quot;&gt;&lt;img class=&quot;size-full wp-image-131&quot; alt=&quot;Bloom Filter size comparison&quot; src=&quot;http://crzyjcky.com/wp-content/uploads/2013/01/bloom-filter-size.png&quot; width=&quot;258&quot; height=&quot;283&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Bloom Filter size comparison
  &lt;/p&gt;
&lt;/div&gt;

&lt;h2 id=&quot;increase-query-speed&quot;&gt;Increase query speed&lt;/h2&gt;

&lt;p&gt;Several NoSQL datastores, namely HBase and Cassandra, have use it to increase query speed.&lt;/p&gt;

&lt;div id=&quot;attachment_132&quot; style=&quot;width: 555px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/01/03/the-magical-bloom-filter/bloom-filter-database/&quot; rel=&quot;attachment wp-att-132&quot;&gt;&lt;img class=&quot;size-full wp-image-132&quot; alt=&quot;Bloom Filter in database&quot; src=&quot;http://crzyjcky.com/wp-content/uploads/2013/01/bloom-filter-database.png&quot; width=&quot;545&quot; height=&quot;326&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Bloom Filter in database
  &lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;Assuming checking with Bloom Filter takes 1 ms, and querying with database takes 100 ms.&lt;/p&gt;

&lt;p&gt;We have 3 cases here.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Case 1: If Bloom Filter reports that the item doesn’t exist, the operation takes 1 ms.&lt;/li&gt;
  &lt;li&gt;Case 2: If Bloom filter reports that the item exists, the request will be sent to database, and database will return the data, the operation takes 1 + 100 ms = 101 ms&lt;/li&gt;
  &lt;li&gt;Case 3: If Bloom filter reports that the item exists, the request will be sent to database, and database will report not found, the operation takes 1 + 100 ms = 101 ms&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Source code: &lt;a href=&quot;http://crzyjcky.com/2013/01/03/the-magical-bloom-filter/blog-bloomfiter/&quot; rel=&quot;attachment wp-att-137&quot;&gt;blog-bloomfiter.zip&lt;/a&gt;&lt;a href=&quot;http://crzyjcky.com/2013/01/03/the-magical-bloom-filter/blog-bloomfiter/&quot; rel=&quot;attachment wp-att-137&quot;&gt;&lt;br /&gt; &lt;/a&gt;&lt;/p&gt;
&lt;script charset=&quot;utf-8&quot; type=&quot;text/javascript&quot; src=&quot;http://ws.amazon.com/widgets/q?rt=tf_mfw&amp;#038;ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822/US/crzyjcky-20/8001/975c5eeb-b11c-4173-be8c-8de8eea4c562&quot;&gt; &lt;/script&gt;

&lt;noscript&gt;
  &lt;a href=&quot;http://ws.amazon.com/widgets/q?rt=tf_mfw&amp;#038;ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822%2FUS%2Fcrzyjcky-20%2F8001%2F975c5eeb-b11c-4173-be8c-8de8eea4c562&amp;#038;Operation=NoScript&quot;&gt;Amazon.com Widgets&lt;/a&gt;
&lt;/noscript&gt;
</description>
        <pubDate>Thu, 03 Jan 2013 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2013/01/03/the-magical-bloom-filter/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2013/01/03/the-magical-bloom-filter/</guid>
        
        <category>bloom-filter</category>
        
        
        <category>big data</category>
        
        <category>distributed system</category>
        
        <category>java</category>
        
        <category>nosql</category>
        
      </item>
    
      <item>
        <title>Relationship among RDMS, NoSQL and MapReduce</title>
        <description>&lt;div id=&quot;attachment_49&quot; style=&quot;width: 730px&quot; class=&quot;wp-caption alignnone&quot;&gt;
  &lt;a href=&quot;http://crzyjcky.com/2013/01/02/relationship-among-rdms-nosql-and-mapreduce/rdms-nosql-mapreduce/&quot; rel=&quot;attachment wp-att-49&quot;&gt;&lt;img class=&quot;size-full wp-image-49&quot; alt=&quot;Relationship among RDMS, NoSQL and MapReduce&quot; src=&quot;http://crzyjcky.com/wp-content/uploads/2013/01/rdms-nosql-mapreduce.png&quot; width=&quot;720&quot; height=&quot;469&quot; /&gt;&lt;/a&gt;
  
  &lt;p class=&quot;wp-caption-text&quot;&gt;
    Relationship among RDMS, NoSQL and MapReduce
  &lt;/p&gt;
&lt;/div&gt;

&lt;h1 id=&quot;for-a-lot-of-data&quot;&gt;For a lot of data&lt;/h1&gt;

&lt;p&gt;RDMS (PostgreSQL, MySQL etc.) can handles storing / retrieval of large data set very well. It also provides basic aggregate operations on the data set to give a summarize reports to the users.&lt;/p&gt;

&lt;h1 id=&quot;for-a-lot-of-8220a-lot-of-data8221&quot;&gt;For a lot of “a lot of data”:&lt;/h1&gt;

&lt;p&gt;When the size of data set increase until RDMS can’t handle it efficiently, we can use NoSQL cluster to store data. In general, most NoSQL store data together in Denormalizated form (very much like OLAP in RDMS). What it does is basically “pre-joined” the different piece of data, thus reducing expensive JOIN operation during run-time and make the reading super fast. However, If users want to do different ways of JOIN operations, or other aggregate functions, the operation become very expensive, because the data store has to run JOIN operation. Worse still, since most NoSQL do not support JOIN natively, this operation will tend to be slower than its RDMS counterpart. One solution is that we could make use of MapReduce function. MapReduce is a programming paradigm that break the huge data set into smaller piece (so it is consumable) and allows data processing in number of nodes in parallel manner. MapReduce functionality can be found in Hadoop. A lot of NoSQL datastores, like MongoDB or Riak, provide certain level of native MapReduce implementation too.&lt;/p&gt;

&lt;script charset=&quot;utf-8&quot; type=&quot;text/javascript&quot; src=&quot;http://ws.amazon.com/widgets/q?rt=tf_mfw&amp;#038;ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822/US/crzyjcky-20/8001/efbdc3bc-fccb-41af-a5b2-371059332e11&quot;&gt; &lt;/script&gt;

&lt;noscript&gt;
  &lt;a href=&quot;http://ws.amazon.com/widgets/q?rt=tf_mfw&amp;#038;ServiceVersion=20070822&amp;#038;MarketPlace=US&amp;#038;ID=V20070822%2FUS%2Fcrzyjcky-20%2F8001%2Fefbdc3bc-fccb-41af-a5b2-371059332e11&amp;#038;Operation=NoScript&quot;&gt;Amazon.com Widgets&lt;/a&gt;
&lt;/noscript&gt;
</description>
        <pubDate>Wed, 02 Jan 2013 00:00:00 +0000</pubDate>
        <link>http://crzyjcky.com/2013/01/02/relationship-among-rdms-nosql-and-mapreduce-3/</link>
        <guid isPermaLink="true">http://crzyjcky.com/2013/01/02/relationship-among-rdms-nosql-and-mapreduce-3/</guid>
        
        <category>mapreduce</category>
        
        <category>nosql</category>
        
        <category>rdms</category>
        
        
        <category>big data</category>
        
        <category>hadoop</category>
        
        <category>nosql</category>
        
      </item>
    
  </channel>
</rss>
