<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <title>A Fuzzy Philosopher</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta name="keywords" content="">
    <meta name="generator" content="JBake">

    <!-- Le styles -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/asciidoctor.css" rel="stylesheet">
    <link href="css/base.css" rel="stylesheet">
    <link href="css/prettify.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="js/html5shiv.min.js"></script>
    <![endif]-->

    <!-- Fav and touch icons -->
    <!--<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">-->
    <link rel="shortcut icon" href="favicon.ico">
  </head>
  <body onload="prettyPrint()">
    <div id="wrap">
   


		<!-- Fixed navbar -->
    <div class="navbar navbar-default navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="notes/about.html">Farley Lai</a>
        </div>
        <div class="navbar-collapse collapse">
          <ul class="nav navbar-nav">
            <li><a href="index.html">Blog</a></li>
            <li><a href="notes/projects.html">Projects</a></li>
            <li><a href="notes/teaching.html">Teaching</a></li>
            <li><a href="notes/research.html">Research</a></li>
            <li><a href="notes/events.html">Events</a></li>
            <li><a href="notes/art.html">Art</a></li>
            <li><a href="archive.html">Archive</a></li>
            <li><a href="feed.xml">Feed</a></li>
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Shortcut <b class="caret"></b></a>
              <ul class="dropdown-menu">
                <li><a href="notes/android.html">Linux</a></li>
                <li><a href="notes/linux.html">Linux</a></li>
                <li><a href="notes/groovy.html">Groovy</a></li>
                <li><a href="notes/tools.html">Tools</a></li>
                <li><a href="notes/resources.html">Resources</a></li>
                <li class="divider"></li>
                <li class="dropdown-header">Android</li>
                <li><a href="notes/android/AndroidStudio.html">Android Studio</a></li>
                <li><a href="notes/android/performance.html">Performance</a></li>
                <li><a href="notes/android/pm.html">Power Management</a></li>
                <li><a href="notes/android/atrace.html">atrace</a></li>
                <li><a href="notes/android/stats.html">stats</a></li>
                <li class="dropdown-header">Compiler</li>
                <li><a href="notes/compiler/DataFlowAnalysis.html">Data-Flow Analsyis</a></li>
                <li><a href="notes/compiler/StaticSingleAssignmentForm.html">Static Single Assignement</a></li>
                <li><a href="notes/compiler/CompilerOptimizations.html">Compiler Optimizations</a></li>
              </ul>
            </li>
          </ul>
          <ul class="nav navbar-nav navbar-right">
            <li><a href="https://github.com/farleylai"><i class="fa fa-github"></i></a></li>
            <li><a href="https://plus.google.com/+FarleyLai/"><i class="fa fa-google-plus"></i></a>
            <li><a href="https://www.linkedin.com/in/farleylai"><i class="fa fa-linkedin"></i></a>
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </div>
    <div class="container">


	<div class="page-header">
		<h1>A Fuzzy Philosopher</h1>
	</div>
	
		<a href="blog/2017/spark-s3.html"><h1>Access S3 Bucket with Apache Spark</h1></a>
		<p>30 March 2017</p>
		<p><div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Assume hadoop-2.7.3 is installed via brew on macOS.
For single machine use, the configurations may be set statically.
For multiple users, the configurations may be set pragmatically.
The latest url scheme to access an S3 bucket begins with <code>s3a://</code>.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_static_configration">Static Configration</h2>
<div class="sectionbody">
<div class="dlist">
<dl>
<dt class="hdlist1">Step1</dt>
<dd>
<p>Tell spark where hadoop configuration files are.</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">/usr/local/Cellar/apache-spark/2.1.0/libexec/conf/spark-env.sh</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">export HADOOP_HOME=/usr/local/Cellar/hadoop/2.7.3/libexec
export HADOOP_CONF_DIR=$HADOOP_HOME/etc/hadoop</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Step2</dt>
<dd>
<p>Set S3 endpoint and access key for Hadoop</p>
</dd>
</dl>
</div>
<div class="listingblock">
<div class="title">/usr/local/Cellar/hadoop/2.7.3/libexec/etc/hadoop/core-site.xml</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-xml" data-lang="xml">&lt;configuration&gt;
    &lt;property&gt;
        &lt;name&gt;fs.s3a.endpoint&lt;/name&gt;
        &lt;description&gt;AWS S3 endpoint to connect to. An up-to-date list is
            provided in the AWS Documentation: regions and endpoints. Without this
            property, the standard region (s3.amazonaws.com) is assumed.
        &lt;/description&gt;
        &lt;value&gt;s3.us-east-2.amazonaws.com&lt;/value&gt;
    &lt;/property&gt;
    &lt;property&gt;
        &lt;name&gt;fs.s3a.impl&lt;/name&gt;
        &lt;value&gt;org.apache.hadoop.fs.s3a.S3AFileSystem&lt;/value&gt;
        &lt;description&gt;The implementation class of the S3A Filesystem&lt;/description&gt;
    &lt;/property&gt;
    &lt;property&gt;
        &lt;name&gt;fs.s3a.access.key&lt;/name&gt;
        &lt;description&gt;AWS access key ID.&lt;/description&gt;
        &lt;value&gt;**********&lt;/value&gt;
    &lt;/property&gt;
    &lt;property&gt;
        &lt;name&gt;fs.s3a.secret.key&lt;/name&gt;
        &lt;description&gt;AWS secret key.&lt;/description&gt;
        &lt;value&gt;**********&lt;/value&gt;
    &lt;/property&gt;
&lt;/configuration&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively, set the access key in the user&#8217;s environment.</p>
</div>
<div class="listingblock">
<div class="title">bash_profile</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">export AWS_ACCESS_KEY_ID=***************
export AWS_SECRET_ACCESS_KEY=************</code></pre>
</div>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Step3</dt>
<dd>
<p>Set CLASSPATH of AWSClient and enable signature version V4 Support through spark-shell</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>The V4 support is for those S3 endpoints such Ohio.</p>
</div>
<div class="listingblock">
<div class="title">bash_profile</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">export HADOOP_HOME=/usr/local/Cellar/hadoop/2.7.3/libexec
export AWS_CLASSPATH="$HADOOP_HOME/share/hadoop/tools/lib/hadoop-aws-2.7.3.jar"
export AWS_CLASSPATH="$AWS_CLASSPATH:$HADOOP_HOME/share/hadoop/tools/lib/aws-java-sdk-1.7.4.jar"
export AWS_CLASSPATH="$AWS_CLASSPATH:$HADOOP_HOME/share/hadoop/tools/lib/guava-11.0.2.jar"
alias spark-shell="spark-shell --driver-class-path="$AWS_CLASSPATH" --driver-java-options "-Dcom.amazonaws.services.s3.enableV4=true""</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_pragmatic_configuration">Pragmatic Configuration</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The <code>AWS_CLASSPATH</code> above still needs to be passed to <code>spark-shell</code>.
Run spark-shell, enable V4 support and set the S3 access/secret key and endpoint as follows.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-scala" data-lang="scala">System.setProperty("com.amazonaws.services.s3.enableV4", "true")
sc.hadoopConfiguration.set("fs.s3a.endpoint", "s3.us-east-2.amazonaws.com")
sc.hadoopConfiguration.set("fs.s3a.access.key", "**********")
sc.hadoopConfiguration.set("fs.s3a.secret.key", "**********")</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_read_rdd_from_s3_bucket">Read RDD from S3 Bucket</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Finally, count a RDD by reading from a created S3 bucket.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-scala" data-lang="scala">val rdd = sc.textFile("s3a://cs5630s17/part00001.gz")
rdd.count</code></pre>
</div>
</div>
</div>
</div></p>
  	
		<a href="blog/2017/uprun.html"><h1>Counting Increasing Runs in Sliding Windows on Spark</h1></a>
		<p>20 March 2017</p>
		<p><div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>Apache Spark hides the underlying dataset partitions for massive data parallelism.
This makes it tricky to compute statistics in sliding windows across partitions.
Though Spark MLlib provides efficient <a href="https://spark.apache.org/docs/2.0.0/api/java/org/apache/spark/mllib/rdd/RDDFunctions.html">sliding window APIs</a>,
pyspark is unable to access the functionality yet.
One way to implement sliding windows is to duplicate data items at positions covered by a sliding window.
Then call groupBy() on RDD to group data items for each sliding window starting at each data item position.
Unfortunately, the performance is insanely slow.
On the other hand, the sliding window provided by RDDFunctions in Scala is fast and handles partitions correctly.
The idea is to collect tail seqences in the following one or more partitions for the current partition to iterate.
The following Python script computes the increasing runs of length <code>K=15</code> in sliding windows of step size 1.
The generated test dataset sequence ranging from 0 to 79.
The number of increasing runs across partitions should be <code>80 - (K-1) = 66</code>.
If the sliding window across partitions are not handled, the results would be zero for partition size <code>80/20=4</code> less than the
sliding window size.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-python" data-lang="python">from pyspark import SparkConf, SparkContext
import subprocess, sys, random
conf = SparkConf()
sc = SparkContext(conf = conf)
logger = sc._jvm.org.apache.log4j
logger.LogManager.getLogger("org"). setLevel( logger.Level.ERROR )
logger.LogManager.getLogger("akka").setLevel( logger.Level.ERROR )

P = 20   # partitions
N = 80   # generated numbers
K = 15   # sliding window size
manual = False
for i in range(len(sys.argv)):
    if(sys.argv[i] == '-p' and i + 1 &lt; len(sys.argv)): P = int(sys.argv[i+1])
    if(sys.argv[i] == '-n' and i + 1 &lt; len(sys.argv)): N = int(sys.argv[i+1])
    if(sys.argv[i] == '-k' and i + 1 &lt; len(sys.argv)): K = int(sys.argv[i+1])
    if(sys.argv[i] == '-m'): manual = True
print '(P, N, K, manual, testing) = ({}, {}, {}, {}, {})'.format(P, N, K, manual, testing)

def toFloat(n):
    try: return float(n)
    except: ValueError
    return 0

def isUp(window):
    return all(x&lt;y for x, y in zip(window, window[1:]))

def toTail(itr):
    # Generate the tail sequence up to the sliding window size - 1
    tail = []
    for x in itr:
        tail.append(x)
        if(len(tail) == K - 1):
            break
    yield tail

def sliding(i, itr):
    # Aggregate the tail for the current partition from the collected tails
    j = i + 1
    tail = []
    while(j &lt; len(tails) and len(tail) &lt; K - 1):
        tail.extend(tails[j][:K - 1 - len(tail)])
        j = j + 1

    # Compose sliding windows including the full tail
    window = []
    for x in itr:
        window.append(x)
        if(len(window) == K):
            yield window
            window.pop(0)
    for x in tail:
        window.append(x)
        if(len(window) == K):
            yield window
            window.pop(0)

# Generate a test dateset of flaots
rdd = sc.parallelize(range(N), P).map(lambda n: toFloat(n))
if(manual):
    # Hand-made sliding windows using groupBy()
    def window(xi, k):
        x, i = xi
        return [(i - offset, i, x) for offset in xrange(k)]
    runs = (rdd.
            zipWithIndex().
            flatMap(lambda xi: window(xi, K)).
            groupBy(lambda ix: ix[0]).
            mapValues(lambda vals: [x for (pos, i, x) in sorted(vals)]).
            sortByKey().
            values().
            filter(lambda x: len(x) == K).
            filter(isUp))
else:
    # Partitions with tails to yield full sliding windows
    tails = rdd.mapPartitions(toTail).collect()
    runs = rdd.mapPartitionsWithIndex(sliding).filter(isUp)

print '######### Up runs[{}] = {} in {} partitions ##########'.format(K, runs.count(), rdd.getNumPartitions())</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_performance_comparison_with_scala">Performance Comparison with Scala</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Apache Spark is maninly implemented in Scala.
Python support is through <a href="http://py4j.org">Py4j</a> binding.
Even though running a Python script on Spark with spark-submit is straightforward,
the performance difference with Scala could be significant when calling groupBy() or join() on RDD.
Here are the benchmark results of counting the number of increasing runs of length 3 in an EEG dataset with 7450336 float numbers on
an 8-core machine with 8GB RAM.
Running a Python script through spark-submit could be faster than running a Scala script through spark-shell by saving
some JVM/Spark startup overhead but growing slower when computing cross-partition operations.
On the other hand, running a packaged Scala app through spark-submit is twice faster than its python counterpart,
making it desirable for production use.
Nonetheless, it takes some prep. work to package a Scala app.</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">Running uprun.py through spark-submit in 4 partitions</dt>
<dd>
<div class="ulist">
<ul>
<li>
<p>Sliding windows with full tails: 18.508s</p>
</li>
<li>
<p>Sliding windows using groupBy(): 10m44.039s</p>
</li>
</ul>
</div>
</dd>
<dt class="hdlist1">Running uprun.scala in a packaged jar through spark-submit in 4 partitions</dt>
<dd>
<div class="ulist">
<ul>
<li>
<p>Sliding windows by RDDFunctions: 9.184s</p>
</li>
<li>
<p>Sliding windows using groupBy(): 3m21.722s</p>
</li>
</ul>
</div>
</dd>
<dt class="hdlist1">Running uprun.scala through spark-shell in 4 partitions</dt>
<dd>
<div class="ulist">
<ul>
<li>
<p>Sliding windows by RDDFunctions: 21.759s</p>
</li>
<li>
<p>Sliding windows using groupBy(): 3m34.009s</p>
</li>
</ul>
</div>
</dd>
</dl>
</div>
<div class="paragraph">
<p>The Scala app counterpart is listed below for completeness.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-scala" data-lang="scala">import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.mllib.rdd.RDDFunctions

object UpRun {
  def main(args: Array[String]) {
      val conf = new SparkConf().setAppName("Up Run Couting")
      val sc = new SparkContext(conf)
      var manual = false
      var testing = false
      var P =  4
      var N = 80
      var K =  3
      for(i &lt;- 0 until args.length) {
          if(args(i) == "-p" &amp;&amp; i+1 &lt; args.length ) P = args(i+1).toInt
          if(args(i) == "-n" &amp;&amp; i+1 &lt; args.length ) N = args(i+1).toInt
          if(args(i) == "-k" &amp;&amp; i+1 &lt; args.length ) K = args(i+1).toInt
          if(args(i) == "-m") manual = true
          if(args(i) == "-t") testing = true
      }
      printf("(P, N, K, manual, testing) = (%d, %d, %d, %s, %s)\n", P, N, K, manual, testing)
      val rdd = if(testing) sc.parallelize(1 to N, P).map(_.toFloat)
                else sc.textFile("/user/hadoop/eegsample", P).flatMap(_.split("\\s+")).map(_.toFloat)
      var count:Long = 0
      if(manual) {
          /* Hand-made sliding windows in Scala */
         count = rdd.zipWithIndex.
                 flatMap { case (x, i) =&gt; (0 until K).map(offset =&gt; (i - offset, i, x)) }.
                 groupBy { case (pos, _, _) =&gt; pos }.
                 mapValues(_.toList.sorted.map { case (_, _, x) =&gt; x }).
                 sortByKey().
                 values.
                 filter(_.size == K).
                 filter(w =&gt; (w zip w.drop(1)).forall { case (v1, v2) =&gt; v1 &lt; v2 }).
                 count
     } else {
         count = RDDFunctions.fromRDD(rdd).
                 sliding(K).
                 filter(w =&gt; (w zip w.drop(1)).forall { case (v1, v2) =&gt; v1 &lt; v2 }).
                 count
     }
     printf("######### Up runs[%d] = %d in %d partitions ##########\n", K, count, rdd.getNumPartitions)
     sc.stop()
  }
}</code></pre>
</div>
</div>
</div>
</div></p>
  	
		<a href="blog/2017/spark-scala.html"><h1>Scripting Scala with Apache Spark</h1></a>
		<p>07 March 2017</p>
		<p><div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>You might be used to running python scripts through the spark-submit command.
It is straightforward for prototyping and testing though running python applications through 'pyspark' is not supported as of Spark 2.0.
On the other hand, Scala scripts may be packaged as standalone applications for spark-submit to accept.
This might be a bit overwhelming for running simple Scala scripts even with build tools such as sbt or Gradle.
It happens the spark-shell provides ways to load and evaluate a Scala script.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_method_1_load_within_the_spark_shell">Method 1: load within the Spark shell</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Type the built-in command starting with ':' to load the Scala script as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-scala" data-lang="scala">scala&gt;:load script.scala</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_method_2_run_spark_shell_with_options_to_specify_script_and_arguements">Method 2: run spark-shell with options to specify script and arguements</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Type the following command line to run a Scala script with command line arguments.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">$&gt; spark-shell -i script.scala --conf spark.driver.args="arg1 arg2 ..."</code></pre>
</div>
</div>
<div class="paragraph">
<p>Option <code>-i</code> specifies the script path.
Option <code>--conf</code> allows to specify parameters to pass to the SparkConf instance.
<code>spark.driver.args</code> is a built-in property that is recognizable for use.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_method_3_define_shell_function_to_run_with_command_line_arguments">Method 3: define shell function to run with command line arguments</h2>
<div class="sectionbody">
<div class="paragraph">
<p>A shortcut to run a Spark script in Scala with command line arguments is through the system shell.
Edit <code>.bash_profile</code> to add function <code>spark-scala</code> to capture the target Scala script with command line arguments as follows.</p>
</div>
<div class="listingblock">
<div class="title">bash_profile</div>
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">function spark-scala {
  spark-shell -i "$0" --conf spark.driver.args="$@"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>The Spark script in Scala then retrieves the command line arguments via the SparkConf property <code>spark.driver.args</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-scala" data-lang="scala">val args = sc.getConf.get("spark.driver.args").split("\\s+")
printf("args=%s\n", args.mkString(", "))
// ...</code></pre>
</div>
</div>
<div class="paragraph">
<p>In this way, the scala script can be executed by <code>spark-shell</code> as a python script submitted by <code>spark-submit</code> with command line
arguments passed.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-bash" data-lang="bash">$&gt; spark-scala script.scala -k 3
args=-k, 3</code></pre>
</div>
</div>
</div>
</div></p>
  	
		<a href="blog/2016/AS2.2.x.html"><h1>Gotcha after Upgrading to Android Studio 2.2.x</h1></a>
		<p>09 November 2016</p>
		<p><div class="paragraph">
<p>There are two issues you may encounter when upgrading from 2.1.x to 2.2.x.
Simply disable and enable the plugins to fix them.
Follow the links for details.</p>
</div>
<div class="ulist">
<ul>
<li>
<p><a href="https://goo.gl/J3WmYa">NPE due to NDK support plugin</a></p>
</li>
<li>
<p><a href="https://goo.gl/qylorJ">Android Updater not enabled by default</a></p>
</li>
</ul>
</div></p>
  	
		<a href="blog/2016/monsoonws.html"><h1>Monsoon Power Tool Web Service for Scripting</h1></a>
		<p>09 November 2016</p>
		<p><div class="imageblock" style="text-align: center">
<div class="content">
<img src="http://farleylai.github.io/images/monsoonpm.jpg" alt="monsoonpm" width="800" height="Monsoon Power Monitor">
</div>
</div>
<div class="paragraph">
<p>Monsoon Power Monitor is commonly used by researchers and engineers to measure energy consumption at high frequency.
However, the lack of support for Mac OS X and Linux is a big turnoff and inconvenient.
The monsoon.py included in AOSP is problematic on Mac OS X. The serial port access over USB blocks indefinitely every so often until reboot.
The official support for Windows only renders virtual machine and web service as alternatives.
Unfortunately, accessing the device through a virtual machine is not guaranteed to work.
For example, the device enumeration API may return nothing, unlike on a real Windows machine.
Therefore, setting up the web service on real Windows for remote scripting would be the expedient solution.</p>
</div>
<div class="imageblock" style="text-align: center">
<div class="content">
<img src="http://farleylai.github.io/images/monsoonws.png" alt="monsoonws" width="640" height="Monsoon Power PowerTool Web Service">
</div>
</div>
<div class="paragraph">
<p>The Monsoon PowerTool Web Service for scripting I created is hosted on <a href="https://github.com/farleylai/MonsoonPowerTool">GitHub</a>.
This project contains the server-side web service in C# and a Java client.
There is also a setup subproject for installation on Windows.
The Java client can be built with Gradle to test the remote web service and shows output as follows.</p>
</div>
<div class="literalblock">
<div class="title">Test Java client output</div>
<div class="content">
<pre>PowerToolServiceTest &gt; testPowerToolServiceSampling STANDARD_OUT
    Found connected Monsoon monitor of serial 6325
        Instant main channel: samples=14355, current=0.248630.2, voltage=3.690500.2
        Instant main channel: samples=24255, current=0.218130.2, voltage=3.690500.2</pre>
</div>
</div>
<div class="paragraph">
<p>View build.gradle for details to set the remote WSDL URL.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
<div class="paragraph">
<p>The Web Service APIs are based on PowerTool 4.0.5.2. while the client APIs depend on the actual stub code generation by Apache CXF.
Refer to the official <a href="http://msoon.github.io/powermonitor">developer&#8217;s guide</a> for the API overview.</p>
</div>
</td>
</tr>
</table>
</div></p>
  	
		<a href="blog/2015/parade.html"><h1>Parade</h1></a>
		<p>15 November 2015</p>
		<p><div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p><a href="http://www.devdraft.com">DevDraft</a> just held the Sept. challenge 2015 with an intriguing algorithmic problem. After days
of contemplation, my solution reaches 100% code correctness and perfect algorithmic problem solving for runtime
efficiency.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_problem">Problem</h2>
<div class="sectionbody">
<div class="paragraph">
<p>A nearby city has recently undergone a massive revitalization effort and, in order to celebrate and attract economic
investment, is going to throw a parade. The mayor plans to deploy a number of security forces for the days leading up to
the parade to keep the parade route free of vandalism. However, the budget is limited, so the mayor wants to make sure
the security is deployed in such a way as to maximize effectiveness.</p>
</div>
<div class="paragraph">
<p>You are given a list of integers representing the threat of vandalism occurring on the city blocks along the parade
route&#8212;&#8203;0 means vandalism will not occur on a block, and greater integers indicate a greater danger of vandalism
occurring. The parade is planned to move in a straight line and pass by every block exactly once. You are also given
several security forces, each of which can patrol a number of adjacent blocks, totally nullifying the threat on the
blocks they patrol. The forces come in different types with different patrol lengths; for example, an officer on bike
can patrol farther than an officer on foot. The forces are represented by a list of pairs of integers, where the first
integer is the number of adjacent blocks a type of force can patrol and the second is how many forces are available of
that type.</p>
</div>
<div class="paragraph">
<p>The number of forces available is limited so you must place them strategically to minimize the sum of threat levels of
all blocks that are not patrolled. Because the minimum threat level may be achieved by multiple arrangements of
security, we ask that you output only the minimum total threat level that can be achieved, and not the positions of the
forces.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_c_implementation">C++ Implementation</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Originally, the implementation is in Groovy but the runtime performance can be 100X slower than its C++ counterpart.
Therefore, I decided to submit the C++ version though many Groovy constructs are not supported by the C++ STL and must
be reimplemented. As expected, the rewards pay off.</p>
</div>
<div class="paragraph">
<p>The following code in C++ implements a branch and bound dynamic programming algorithm to solve the problem. More
information about the solution analysis and complexity is available on the
<a href="https://github.com/farleylai/DevDraft/tree/master/2015/SepChallenge/Part1">repo</a>.</p>
</div>
<script
src="http://gist-it.appspot.com/https://github.com/farleylai/DevDraft/blob/master/2015/SepChallenge/Part1/Parade.cpp"></script>
</div>
</div></p>
  	
	
	<hr />
	
	<p>Older posts are available in the <a href="archive.html">archive</a>.</p>

		</div>
		<div id="push"></div>
    </div>
    
    <div id="footer">
<!--
      <div class="container">
        <p class="muted credit">&copy; 2014 | Mixed with <a href="http://getbootstrap.com/">Bootstrap v3.1.1</a>
         | Baked with <a href="http://jbake.org">JBake v2.5.1</a></p>
      </div>
-->
      <div class="container">
        <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_US">
        <img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-nd/3.0/88x31.png" /></a>
        This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_US">
        Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License</a>.
      </div>
    </div>
    
    <!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="js/jquery-1.11.1.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/prettify.js"></script>
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-15840099-1', 'auto');
      ga('send', 'pageview');
    </script>
  </body>
</html>

