<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title>Rohit Agarwal's Notes</title>
  <subtitle>Hello, I am Rohit Agarwal. I am a software engineer. This is where I note my experiences while playing with new (and old) technologies.</subtitle>
  <link href="http://notes.rohitagarwal.org/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="http://notes.rohitagarwal.org/" rel="alternate" type="text/html"/>
  <updated>2022-02-26T02:54:24+00:00</updated>
  <id>http://notes.rohitagarwal.org/</id>
  <rights>Copyright (c) 2022 - Rohit Agarwal</rights>
  <author>
    <name>Rohit Agarwal</name>
  </author>

  
  <entry>
    <title type="html"><![CDATA[Everything you need to know about using GPUs with Kubernetes]]></title>
    <link href="http://notes.rohitagarwal.org/2018/05/04/everything-you-need-to-know-about-using-gpus-with-kubernetes.html"/>
    <published>2018-05-04T15:40:00+00:00</published>
    <updated>2018-05-04T15:40:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2018/05/04/everything-you-need-to-know-about-using-gpus-with-kubernetes</id>
    <content type="html"><![CDATA[<p>I gave a talk about using GPUs with Kubernetes at KubeCon EU 2018 in Copenhagen.</p>

<p>Here are the <a href="https://speakerdeck.com/mindprince/everything-you-need-to-know-about-using-gpus-with-kubernetes">slides</a>:</p>

<script async="" class="speakerdeck-embed" data-id="48e24caf58e64edfa35860206e7e6661" data-ratio="1.77777777777778" src="//speakerdeck.com/assets/embed.js"></script>

<p>And here’s the <a href="https://www.youtube.com/watch?v=KplFFvj3XRk">video recording</a>:</p>
<iframe width="670" height="377" src="https://www.youtube.com/embed/KplFFvj3XRk?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen=""></iframe>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>I gave a talk about using GPUs with Kubernetes at KubeCon EU 2018 in Copenhagen</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Kubernetes for Data Engineers]]></title>
    <link href="http://notes.rohitagarwal.org/2018/04/13/kubernetes-for-data-engineers.html"/>
    <published>2018-04-13T09:45:00+00:00</published>
    <updated>2018-04-13T09:45:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2018/04/13/kubernetes-for-data-engineers</id>
    <content type="html"><![CDATA[<p>I gave a talk on Kubernetes for Data Engineers at Data Platforms 2018 in Phoenix.</p>

<p>Here are the <a href="https://speakerdeck.com/mindprince/kubernetes-for-data-engineers">slides</a>:</p>

<script async="" class="speakerdeck-embed" data-id="f2420deedb574ea592bf4bf0af5cbad5" data-ratio="1.77777777777778" src="//speakerdeck.com/assets/embed.js"></script>

]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>I gave a talk on Kubernetes for Data Engineers at Data Platforms 2018 in Phoenix</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Dedicated node-pools and ExtendedResourceToleration admission controller]]></title>
    <link href="http://notes.rohitagarwal.org/2017/12/17/dedicated-node-pools-and-ExtendedResourceToleration-admission-controller.html"/>
    <published>2017-12-17T11:43:00+00:00</published>
    <updated>2017-12-17T11:43:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2017/12/17/dedicated-node-pools-and-ExtendedResourceToleration-admission-controller</id>
    <content type="html"><![CDATA[<h3 id="the-problem">The problem</h3>

<p>Let’s say you have a <a href="https://kubernetes.io/">Kubernetes</a> cluster and you added
nodes containing GPUs to the cluster. Since Kubernetes supports scheduling pods
that request GPUs, your data scientists can run ML workloads that need GPUs on
your kubernetes cluster.  Great!</p>

<p>But you have a problem, sometimes your data scientists come to you and say that
their pods requesting GPUs are not getting scheduled. You debug and find out
that some other pods (that didn’t request any GPUs) are scheduled on the nodes
containing GPUs. So, even though all the GPUs are unused, there’s not enough CPU
or memory for the pods requesting GPUs and so they are not getting scheduled.
You somehow evict the non-GPU requesting pods from the nodes containing GPUs and
pacify your data scientists.</p>

<p>You have another problem, sometimes there are not enough workloads requiring
GPUs running on the cluster. Since GPU nodes are the most expensive nodes in
your cluster, you want the <a href="https://github.com/kubernetes/autoscaler/tree/cluster-autoscaler-1.1.0/cluster-autoscaler">cluster
autoscaler</a>
to aggressively downscale these nodes in such a scenario. But that doesn’t seem
to happen. You debug and find out the reason for this is the same, some non-GPU
requesting pods are scheduled on these nodes. You want a permanent automated
solution to this problem.</p>

<h3 id="the-solution">The solution</h3>

<p><a href="https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/#example-use-cases">Taints is the Kubernetes concept to create dedicated
nodes.</a>
Taints allow a node to repel a set of pods. Taints work together with
tolerations to ensure that pods are not scheduled onto inappropriate nodes.
Taints are applied to a node, and mark that the node should not accept any pods
that do not tolerate those taints. Tolerations are applied to pods, and allow
the pods to schedule onto nodes with matching taints.</p>

<p>So, you decide to taint the nodes containing GPUs and ask your data scientists
to modify their GPU pod specs to tolerate that taint. All good? Maybe not.
Asking your data scientists to modify their pod specs doesn’t feel like very
user friendly. You fear the inevitable situations where someone forgets to apply
these tolerations or uses an off-the-shelf manifest that doesn’t have these
tolerations.</p>

<p><a href="https://github.com/kubernetes/kubernetes/pull/55839">ExtendedResourceToleration</a>
is a new admission controller added in Kubernetes 1.9 that is designed to solve
this exact problem.</p>

<p>If you, as a cluster operator or a cloud provider, want to create dedicated node
pools, you are expected to taint the nodes containing <a href="https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/#extended-resources">extended
resources</a>
(like NVIDIA GPUs) with a key equal to the name of the extended resource (like
<code class="language-plaintext highlighter-rouge">nvidia.com/gpu</code>) and effect equal to <code class="language-plaintext highlighter-rouge">NoSchedule</code>. If you do that, only pods
that have a toleration for such a taint can be scheduled on those nodes. To
avoid asking your users to modify their pod specs, you can enable the
<code class="language-plaintext highlighter-rouge">ExtendedResourceToleration</code> admission controller. Then, if your users create a
pod that requests extended resources (like <code class="language-plaintext highlighter-rouge">nvidia.com/gpu</code>), the admission
controller will automatically add a toleration with key equal to the name of the
extended resouce (like <code class="language-plaintext highlighter-rouge">nvidia.com/gpu</code>), operator <code class="language-plaintext highlighter-rouge">Exists</code> and effect
<code class="language-plaintext highlighter-rouge">NoSchedule</code> to the pod.  Because this is happening automatically, this would be
invisbile to your users.  Their existing pod specs will keep on working. Pods
requesting GPUs would not get blocked by non-GPU requesting pods from getting
scheduled on GPU nodes.  When there are not enough GPU workloads, the cluster
autoscaler will downscale GPU nodes (because nothing would be running on them).
Everyone will be happy!</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>This post describes the use case for the ExtendedResourceToleration admission controller in Kubernetes.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Multi-tenant Job History Server for Ephemeral Hadoop and Spark Clusters]]></title>
    <link href="http://notes.rohitagarwal.org/2015/08/28/multi-tenant-job-history-server-for-ephemeral-hadoop-and-spark-clusters.html"/>
    <published>2015-08-28T22:08:28+00:00</published>
    <updated>2015-08-28T22:08:28+00:00</updated>
    <id>http://notes.rohitagarwal.org/2015/08/28/multi-tenant-job-history-server-for-ephemeral-hadoop-and-spark-clusters</id>
    <content type="html"><![CDATA[<p>My post on Qubole’s Engineering Blog about how we brought the convenience of always-on permanent clusters to on-demand ephemeral clusters running in the cloud.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Difference between S3 block filesystem and S3 native filesystem on Hadoop]]></title>
    <link href="http://notes.rohitagarwal.org/2014/08/01/difference-between-s3-block-and-s3-native-filesystem-on-hadoop.html"/>
    <published>2014-08-01T13:20:00+00:00</published>
    <updated>2014-08-01T13:20:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2014/08/01/difference-between-s3-block-and-s3-native-filesystem-on-hadoop</id>
    <content type="html"><![CDATA[<p>Recently, I tried to use Amazon S3 to store input/output files for hadoop jobs
and got confused by the different S3 filesystems available on top of Apache
Hadoop.  Here are some notes which helped me:</p>

<p>The first S3-backed Hadoop filesystem was introduced in Hadoop 0.10.0
(<a href="https://issues.apache.org/jira/browse/HADOOP-574">HADOOP-574</a>). It was called
the <strong>S3 block fileystem</strong> and it was assigned the URI scheme <code class="language-plaintext highlighter-rouge">s3://</code>. In this
implementation, files are stored as blocks, just like they are in HDFS. The
files stored by this filesystem are not interoperable with other S3 tools -
what this means is that if you go to the AWS console and try to look for
files written by this filesystem, you won’t find them - instead you would find
files named something like <code class="language-plaintext highlighter-rouge">block_-1212312341234512345</code> etc. Similarly, this
filesystem won’t be able to read pre-existing files on S3 since it assumes a
block-based format.</p>

<p>To overcome these limitations, another S3-backed filesystem was introduced in
Hadoop 0.18.0 (<a href="https://issues.apache.org/jira/browse/HADOOP-930">HADOOP-930</a>).
It was called the <strong>S3 native filesystem</strong> and it was assigned the URI scheme
<code class="language-plaintext highlighter-rouge">s3n://</code>. This filesystem lets you access files on S3 that were written with
other tools. Conversely, other tools can access files written using Hadoop.
When this filesystem was introduced, S3 had a filesize limit of 5GB and hence
this filesystem could only operate with files less than 5GB. In late 2010,
Amazon S3 <a href="http://aws.amazon.com/blogs/aws/amazon-s3-multipart-upload/">introduced the Multipart Upload API</a>
and <a href="http://aws.amazon.com/blogs/aws/amazon-s3-object-size-limit/">raised the file size limit from 5GB to 5TB</a>.
A lot of Hadoop distributions and HaaS providers added support for this quite
early and it landed in Apache Hadoop in version 2.4.0
(<a href="https://issues.apache.org/jira/browse/HADOOP-9454">HADOOP-9454</a>)</p>

<p>Using the S3 block file system is no longer recommended. Various
Hadoop-as-a-service providers like <a href="http://www.qubole.com">Qubole</a> and
<a href="http://aws.amazon.com/elasticmapreduce/">Amazon EMR</a> go as far as mapping both
the <code class="language-plaintext highlighter-rouge">s3://</code> and the <code class="language-plaintext highlighter-rouge">s3n://</code> URIs to the S3 native filesystem to ensure this.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>This post describes the difference between the S3 block filesystem and the S3 native filesystem on Hadoop. It also discusses which URIs (s3:// and s3n://) map to which filesystem.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Canonicalizing hive queries to find top workloads]]></title>
    <link href="http://notes.rohitagarwal.org/2014/04/25/canonicalizing-hive-queries-to-find-top-workloads.html"/>
    <published>2014-04-25T14:21:24+00:00</published>
    <updated>2014-04-25T14:21:24+00:00</updated>
    <id>http://notes.rohitagarwal.org/2014/04/25/canonicalizing-hive-queries-to-find-top-workloads</id>
    <content type="html"><![CDATA[<p>My first post on Qubole’s Engineering Blog. Many more to come!</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Notes on Apache log4j]]></title>
    <link href="http://notes.rohitagarwal.org/2014/01/04/notes-on-apache-log4j.html"/>
    <published>2014-01-04T12:20:00+00:00</published>
    <updated>2014-01-04T12:20:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2014/01/04/notes-on-apache-log4j</id>
    <content type="html"><![CDATA[<p>Setup a working directory. All the following commands are run from this directory. All relative file locations are relative to this directory.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mkdir log-test
$ cd log-test
</code></pre></div></div>

<p>Create a test java program <code class="language-plaintext highlighter-rouge">com/mindprince/MyLogTest.java</code>.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">com.mindprince</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">org.apache.log4j.Logger</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">MyLogTest</span> <span class="o">{</span>
  <span class="kd">static</span> <span class="nc">Logger</span> <span class="no">LOG</span> <span class="o">=</span> <span class="nc">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="nc">MyLogTest</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">"Enter main method."</span><span class="o">);</span>
    <span class="nc">FooBarBaz</span><span class="o">.</span><span class="na">foo</span><span class="o">();</span>
    <span class="nc">FooBarBaz</span><span class="o">.</span><span class="na">bar</span><span class="o">();</span>
    <span class="nc">FooBarBaz</span><span class="o">.</span><span class="na">baz</span><span class="o">();</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">"Exit main method."</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>

<span class="kd">class</span> <span class="nc">FooBarBaz</span> <span class="o">{</span>
  <span class="kd">static</span> <span class="nc">Logger</span> <span class="no">LOG</span> <span class="o">=</span> <span class="nc">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="nc">FooBarBaz</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">foo</span><span class="o">()</span> <span class="o">{</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">"Enter foo method."</span><span class="o">);</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">info</span><span class="o">(</span><span class="s">"This is information from foo."</span><span class="o">);</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">"Exit foo method."</span><span class="o">);</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">bar</span><span class="o">()</span> <span class="o">{</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">"Enter bar method."</span><span class="o">);</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">warn</span><span class="o">(</span><span class="s">"This is a warning from bar."</span><span class="o">);</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">"Exit bar method."</span><span class="o">);</span>
  <span class="o">}</span>

  <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">baz</span><span class="o">()</span> <span class="o">{</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">"Enter baz method."</span><span class="o">);</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">error</span><span class="o">(</span><span class="s">"This error occurred in baz."</span><span class="o">);</span>
    <span class="no">LOG</span><span class="o">.</span><span class="na">debug</span><span class="o">(</span><span class="s">"Exit baz method."</span><span class="o">);</span>
  <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Compile the program.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ export CLASSPATH=$CLASSPATH:.:/path/to/log4j-1.2.17.jar
$ javac com/mindprince/MyLogTest.java
</code></pre></div></div>

<p>Create a <code class="language-plaintext highlighter-rouge">log4j.properties</code> file in the current working directory (<code class="language-plaintext highlighter-rouge">log-test/</code>). Log4j will automatically pick this up as this directory is in the classpath.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c %x - %m%n
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ java com.mindprince.MyLogTest
2013-12-12 14:41:52 [main] INFO  com.mindprince.FooBarBaz  - This is information from foo.
2013-12-12 14:41:52 [main] WARN  com.mindprince.FooBarBaz  - This is a warning from bar.
2013-12-12 14:41:52 [main] ERROR com.mindprince.FooBarBaz  - This error occurred in baz.
</code></pre></div></div>

<p>Sometimes it is useful to see log4j’s internal debug information.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ java -Dlog4j.debug=true com.mindprince.MyLogTest
log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader@1372a1a.
log4j: Trying to find [log4j.xml] using sun.misc.Launcher$AppClassLoader@1372a1a class loader.
log4j: Trying to find [log4j.xml] using ClassLoader.getSystemResource().
log4j: Trying to find [log4j.properties] using context classloader sun.misc.Launcher$AppClassLoader@1372a1a.
log4j: Using URL [file:/home/rohita/log-test/log4j.properties] for automatic log4j configuration.
log4j: Reading configuration from URL file:/home/rohita/log-test/log4j.properties
log4j: Parsing for [root] with value=[INFO, stdout].
log4j: Level token is [INFO].
log4j: Category root set to INFO
log4j: Parsing appender named "stdout".
log4j: Parsing layout options for "stdout".
log4j: Setting property [conversionPattern] to [%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c %x - %m%n].
log4j: End of parsing for "stdout".
log4j: Parsed "stdout" options.
log4j: Finished configuring.
2013-12-12 14:42:50 [main] INFO  com.mindprince.FooBarBaz  - This is information from foo.
2013-12-12 14:42:50 [main] WARN  com.mindprince.FooBarBaz  - This is a warning from bar.
2013-12-12 14:42:50 [main] ERROR com.mindprince.FooBarBaz  - This error occurred in baz.
</code></pre></div></div>

<p>To log messages to a file instead of the console use the following properties:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Root logger option
log4j.rootLogger=DEBUG, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/path/to/logging.log
log4j.appender.file.MaxFileSize=1MB
# Keep one backup file
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c %x - %m%n
</code></pre></div></div>

<p>You can manually specify the location of your log4j properties file using <code class="language-plaintext highlighter-rouge">-Dlog4j.configuration</code></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ java -Dlog4j.configuration=file:/path/to/log4j-tofile.properties com.mindprince.MyLogTest

$ cat /path/to/logging.log
2013-12-12 14:44:07 [main] DEBUG com.mindprince.MyLogTest  - Enter main method.
2013-12-12 14:44:07 [main] DEBUG com.mindprince.FooBarBaz  - Enter foo method.
2013-12-12 14:44:07 [main] INFO  com.mindprince.FooBarBaz  - This is information from foo.
2013-12-12 14:44:07 [main] DEBUG com.mindprince.FooBarBaz  - Exit foo method.
2013-12-12 14:44:07 [main] DEBUG com.mindprince.FooBarBaz  - Enter bar method.
2013-12-12 14:44:07 [main] WARN  com.mindprince.FooBarBaz  - This is a warning from bar.
2013-12-12 14:44:07 [main] DEBUG com.mindprince.FooBarBaz  - Exit bar method.
2013-12-12 14:44:07 [main] DEBUG com.mindprince.FooBarBaz  - Enter baz method.
2013-12-12 14:44:07 [main] ERROR com.mindprince.FooBarBaz  - This error occurred in baz.
2013-12-12 14:44:07 [main] DEBUG com.mindprince.FooBarBaz  - Exit baz method.
2013-12-12 14:44:07 [main] DEBUG com.mindprince.MyLogTest  - Exit main method.
</code></pre></div></div>

<p>Sometimes it is useful to change the logging behaviour for particular classes:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Root logger option
log4j.rootLogger=DEBUG, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c %x - %m%n

# Print only messages of level WARN or above for FooBarBaz
log4j.logger.com.mindprince.FooBarBaz=WARN
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ java -Dlog4j.configuration=file:/path/to/log4j-selective.properties com.mindprince.MyLogTest
2013-12-12 14:51:36 [main] DEBUG com.mindprince.MyLogTest  - Enter main method.
2013-12-12 14:51:36 [main] WARN  com.mindprince.FooBarBaz  - This is a warning from bar.
2013-12-12 14:51:36 [main] ERROR com.mindprince.FooBarBaz  - This error occurred in baz.
2013-12-12 14:51:36 [main] DEBUG com.mindprince.MyLogTest  - Exit main method.
</code></pre></div></div>

<p>I usually log everything to a file but only log important messages to the console:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Root logger option
log4j.rootLogger=DEBUG, stdout, file

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c %x - %m%n
# Print only messages of level WARN or above on the console.
log4j.appender.stdout.Threshold=WARN

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/path/to/messages.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c %x - %m%n
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ java -Dlog4j.configuration=file:/path/to/log4j-both.properties com.mindprince.MyLogTest
2013-12-12 15:10:31 [main] WARN  com.mindprince.FooBarBaz  - This is a warning from bar.
2013-12-12 15:10:31 [main] ERROR com.mindprince.FooBarBaz  - This error occurred in baz.

$ cat /path/to/messages.log
2013-12-12 15:10:31 [main] DEBUG com.mindprince.MyLogTest  - Enter main method.
2013-12-12 15:10:31 [main] DEBUG com.mindprince.FooBarBaz  - Enter foo method.
2013-12-12 15:10:31 [main] INFO  com.mindprince.FooBarBaz  - This is information from foo.
2013-12-12 15:10:31 [main] DEBUG com.mindprince.FooBarBaz  - Exit foo method.
2013-12-12 15:10:31 [main] DEBUG com.mindprince.FooBarBaz  - Enter bar method.
2013-12-12 15:10:31 [main] WARN  com.mindprince.FooBarBaz  - This is a warning from bar.
2013-12-12 15:10:31 [main] DEBUG com.mindprince.FooBarBaz  - Exit bar method.
2013-12-12 15:10:31 [main] DEBUG com.mindprince.FooBarBaz  - Enter baz method.
2013-12-12 15:10:31 [main] ERROR com.mindprince.FooBarBaz  - This error occurred in baz.
2013-12-12 15:10:31 [main] DEBUG com.mindprince.FooBarBaz  - Exit baz method.
2013-12-12 15:10:31 [main] DEBUG com.mindprince.MyLogTest  - Exit main method.
</code></pre></div></div>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>This post contains some example log4j.properties files which I use most frequently.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to transfer files from Mac to iPad without iTunes]]></title>
    <link href="http://notes.rohitagarwal.org/2013/10/20/how-to-transfer-files-from-mac-to-ipad-without-itunes.html"/>
    <published>2013-10-20T09:36:00+00:00</published>
    <updated>2013-10-20T09:36:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/10/20/how-to-transfer-files-from-mac-to-ipad-without-itunes</id>
    <content type="html"><![CDATA[<p>Usually when I need to transfer files from my Mac to my iPad, I either email them to myself or use Dropbox. But sometimes I don’t want to send some files over the internet. Earlier, in those cases I would connect my iPad to my Mac and then transfer the files via iTunes. Not anymore. There is a really cool way to transfer files from your Mac to your iPad when they are on the same network. Here’s how:</p>

<ol>
  <li>
    <p>Open the terminal.</p>
  </li>
  <li>
    <p>In the termial, go to the folder which contains the files you want to transfer.</p>
  </li>
  <li>
    <p>Enter <code class="language-plaintext highlighter-rouge">python -m SimpleHTTPServer 8000</code>.</p>
  </li>
  <li>
    <p>If the firewall prompts: <em>Do you want the application “python” to accept incoming network connections?</em> Click <em>Allow</em>.</p>
  </li>
  <li>
    <p>Find out the IP address of your Mac using <code class="language-plaintext highlighter-rouge">ifconfig</code>.</p>
  </li>
  <li>
    <p>Go to <code class="language-plaintext highlighter-rouge">http://&lt;your-mac's-ip-address&gt;:8000</code> on your iPad.</p>
  </li>
  <li>
    <p>Done!</p>
  </li>
</ol>

<p>This method is very general. You can use it to transfer files from your Mac or PC to your iPad, iPhone or Android device. The only requirements are that they should be on the same network, the Mac/PC should have python installed and you should have permission to poke holes in your firewall.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>How to transfer files from your Mac/PC to your iPad/iPhone/Android device without iTunes.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Opt-Out]]></title>
    <link href="http://notes.rohitagarwal.org/2013/08/19/opt-out.html"/>
    <published>2013-08-19T04:40:00+00:00</published>
    <updated>2013-08-19T04:40:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/08/19/opt-out</id>
    <content type="html"><![CDATA[<h3 id="online-behavioral-advertising">Online Behavioral Advertising</h3>
<p>A lot of advertisers are part of self-regulatory programs and let you opt-out from receiving interest-based advertising.
The following tools let you find out which advertisers have enabled interest-based ads for your browser and opt-out from them.
These tools use opt-out cookies to store your preferences in your browser.
(Note that if you are running advertising blocking plugins, these tools may not work correctly.)</p>

<p><a href="http://www.aboutads.info/choices/">Digital Advertising Alliance (DAA) opt-out tool</a><br />
<a href="http://www.networkadvertising.org/choices/">Network Advertising Initaitive (NAI) opt-out tool</a><br />
<a href="http://www.youronlinechoices.com/uk/your-ad-choices">EDAA Your Online Choices opt-out tool</a></p>

<p>Since the opt-out preferences are stored as cookies, deleting cookies will remove your opt-out preferences.
You can use the following extensions to preserve the opt-out preferences you have set.</p>

<p><a href="http://www.aboutads.info/PMC">Protect My Choices browser extension</a><br />
<a href="https://code.google.com/p/chrome-opt-out-extension/">Keep My Opt-Outs browser extension</a></p>

<h3 id="analytics">Analytics</h3>
<p>Various analytics services provide ways to opt-out from getting tracked by them.
The following are the opt-out pages of the major analytics providers:</p>

<p><a href="https://tools.google.com/dlpage/gaoptout">Google Analytics Opt-out Browser Add-on</a> [1]<br />
<a href="https://reports.web.analytics.yahoo.com/optout,OptOut.vm">Yahoo Web Analytics Opt-out</a><br />
<a href="https://www.kissmetrics.com/user-privacy">KISSmetrics Opt-out</a> [2]<br />
<a href="https://mixpanel.com/optout/">MixPanel Opt-out</a><br />
<a href="http://www.convertro.com/opt-out">Converto Opt-out</a><br />
<a href="https://ondemand.webtrends.com/support/optout.asp">Webtrends Opt-out</a></p>

<h3 id="all-in-one-browser-extensions">All-in-one Browser Extensions</h3>
<p>The following extensions block tracking requests from analytics services, advertising networks and social networking sites.
They are a more drastic measure for blocking tracking as they can break the functionality of some web pages.
It is recommended that you use only one of these as they interfere with each other’s working.</p>

<p><a href="https://disconnect.me/">Disconnect</a><br />
<a href="http://www.ghostery.com/">Ghostery</a><br />
<a href="http://abine.com/dntdetail.php">Abine DoNotTrackMe</a></p>

<p>[1] This blog uses Google Analytics. I know.<br />
[2] I like how the the opt-out page of KISSmetrics links to the opt-out pages of its competitors.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>How to opt out of tracking by advertising networks, analytics services, and social platforms.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Command-line arguments in Python, Java and C]]></title>
    <link href="http://notes.rohitagarwal.org/2013/06/30/command-line-arguments-in-python-java-and-c.html"/>
    <published>2013-06-30T17:02:00+00:00</published>
    <updated>2013-06-30T17:02:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/06/30/command-line-arguments-in-python-java-and-c</id>
    <content type="html"><![CDATA[<p>Handling command-line arguments is a very <a href="/categories/common-tasks/">common task</a>. Here are snippets of code I use to handle command line arguments in Python, Java and C.</p>

<h3 id="command-line-arguments-in-python">Command-line arguments in Python</h3>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">sys</span>
<span class="c1"># sys.argv is a list of strings.
# argv[0] is the script name
</span><span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">sys</span><span class="p">.</span><span class="n">argv</span><span class="p">:</span>
    <span class="c1"># do something with the argument
</span>    <span class="k">print</span> <span class="n">arg</span>
</code></pre></div></div>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>python cmd_line_args.py Position1 Position2 Position3
<span class="go">cmd_line_args.py
Position1
Position2
Position3
</span><span class="gp">$</span><span class="w"> </span>python cmd_line_args.py <span class="s2">"Position1 Position2 Position3"</span>
<span class="go">cmd_line_args.py
Position1 Position2 Position3
</span></code></pre></div></div>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">sys</span>
<span class="c1"># sys.argv is a list of strings.
# argv[0] is the script name
</span><span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">sys</span><span class="p">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]:</span>
    <span class="c1"># if you are sure that the arguments are integers
</span>    <span class="n">arg_int</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
    <span class="c1"># do something with the argument
</span>    <span class="k">print</span> <span class="n">arg_int</span>
</code></pre></div></div>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>python cmd_line_args.py 2013 6 30
<span class="go">2013
6
30
</span><span class="gp">$</span><span class="w"> </span>python cmd_line_args.py Position1 Position2 Position3
<span class="go">Traceback (most recent call last):
</span><span class="gp">  File "cmd_line_args.py", line 6, in &lt;module&gt;</span><span class="w">
</span><span class="go">    arg_int = int(arg)
ValueError: invalid literal for int() with base 10: 'Position1'
</span></code></pre></div></div>

<p>Reference: <a href="http://docs.python.org/2/tutorial/interpreter.html#argument-passing">Python Tutorial</a>.</p>

<p>For more advanced needs, you can try the <a href="http://docs.python.org/2/howto/argparse.html">argparse module</a>.</p>

<h3 id="command-line-arguments-in-java">Command-line arguments in Java</h3>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">CommandLineArguments</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// args is an array of Strings</span>
        <span class="c1">// You can access various positional arguments using</span>
        <span class="c1">// args[0], args[1], etc. Or you can iterate over them.</span>
        <span class="k">for</span> <span class="o">(</span><span class="nc">String</span> <span class="n">argument</span> <span class="o">:</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
            <span class="c1">// do something with the argument</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">argument</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>javac CommandLineArguments.java 
<span class="gp">$</span><span class="w"> </span>java CommandLineArguments Position1 Position2 Position3
<span class="go">Position1
Position2
Position3
</span><span class="gp">$</span><span class="w"> </span>java CommandLineArguments <span class="s2">"Position1 Position2 Position3"</span>
<span class="go">Position1 Position2 Position3
</span></code></pre></div></div>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="kd">class</span> <span class="nc">CommandLineArgumentsInt</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// args is an array of Strings</span>
        <span class="c1">// You can access various positional arguments using</span>
        <span class="c1">// args[0], args[1], etc. Or you can iterate over them.</span>
        <span class="k">for</span> <span class="o">(</span><span class="nc">String</span> <span class="n">argument</span> <span class="o">:</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
            <span class="c1">// If you are sure that the arguments are integers</span>
            <span class="kt">int</span> <span class="n">arg</span> <span class="o">=</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">parseInt</span><span class="o">(</span><span class="n">argument</span><span class="o">);</span>
            <span class="c1">// do something with the argument</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">arg</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>javac CommandLineArgumentsInt.java 
<span class="gp">$</span><span class="w"> </span>java CommandLineArgumentsInt 2013 6 30
<span class="go">2013
6
30
</span><span class="gp">$</span><span class="w"> </span>java CommandLineArgumentsInt Position1 Position2 Position3
<span class="go">Exception in thread "main" java.lang.NumberFormatException: For input string: "Position1"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
	at java.lang.Integer.parseInt(Integer.java:449)
	at java.lang.Integer.parseInt(Integer.java:499)
	at CommandLineArgumentsInt.main(CommandLineArgumentsInt.java:8)
</span></code></pre></div></div>

<p>Reference: <a href="http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html">The Java Tutorial</a>.</p>

<p>For more advanced needs, see <a href="http://stackoverflow.com/questions/367706/is-there-a-good-command-line-argument-parser-for-java">this Stack Overflow question</a>.</p>

<h3 id="command-line-arguments-in-c">Command-line arguments in C</h3>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include &lt;stdio.h&gt;
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">*</span> <span class="n">argv</span><span class="p">[])</span> <span class="p">{</span>
    <span class="c1">// argc refers to the number of arguments passed.</span>
    <span class="c1">// argv is an array of char pointers which contain the passed arguments.</span>
    <span class="c1">// argv[0] is the path and name of the program itself</span>
    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">argc</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// do something whith the argument</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"%s</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="n">i</span><span class="p">]);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>cc cmd_line_args.c 
<span class="gp">$</span><span class="w"> </span>./a.out Position1 Position2 Position3
<span class="go">./a.out
Position1
Position2
Position3
</span><span class="gp">$</span><span class="w"> </span>./a.out <span class="s2">"Position1 Position2 Position3"</span>
<span class="go">./a.out
Position1 Position2 Position3
</span></code></pre></div></div>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">*</span> <span class="n">argv</span><span class="p">[])</span> <span class="p">{</span>
    <span class="c1">// argc refers to the number of arguments passed.</span>
    <span class="c1">// argv is an array of char pointers which contain the passed arguments.</span>
    <span class="c1">// argv[0] is the path and name of the program itself</span>
    <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">argc</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// If you are sure that the arguments are integers</span>
        <span class="kt">int</span> <span class="n">argument</span> <span class="o">=</span> <span class="n">atoi</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="n">i</span><span class="p">]);</span>

        <span class="c1">// do something whith the argument</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"%d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">argument</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<div class="language-console highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>cc cmd_line_args.c 
<span class="gp">$</span><span class="w"> </span>./a.out 2013 6 30
<span class="go">2013
6
30
</span><span class="gp">$</span><span class="w"> </span>./a.out Position1 Position2 Position3
<span class="go">0
0
0
</span></code></pre></div></div>

<p>For more advanced needs, use <a href="http://www.gnu.org/software/libc/manual/html_node/Getopt.html">getopt</a>.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>How to handle command-line arguments in python, java and c.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[File handling in Python, Java and C]]></title>
    <link href="http://notes.rohitagarwal.org/2013/06/29/file-handling-in-python-java-and-c.html"/>
    <published>2013-06-29T17:30:00+00:00</published>
    <updated>2013-06-29T17:30:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/06/29/file-handling-in-python-java-and-c</id>
    <content type="html"><![CDATA[<p>File handling is a very <a href="/categories/common-tasks/">common task</a>. Here are snippets of code I use to perform various file handling operations in Python, Java and C.</p>

<h3 id="reading-a-file-in-python">Reading a file in Python</h3>

<h4 id="reading-a-file-at-once">Reading a file at once</h4>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">try</span><span class="p">:</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">text</span> <span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="n">read</span><span class="p">()</span>
        <span class="c1"># text is a string which contains all the text in the file.
</span>        <span class="c1"># this may cause problems with very big files.
</span>
        <span class="c1"># do something with text
</span>        <span class="k">print</span> <span class="n">text</span>
<span class="k">except</span> <span class="nb">IOError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">"IOError: %s: %s"</span> <span class="o">%</span> <span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">filename</span><span class="p">,</span> <span class="n">e</span><span class="p">.</span><span class="n">strerror</span><span class="p">)</span>
</code></pre></div></div>

<h4 id="reading-a-file-line-by-line">Reading a file line by line</h4>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">try</span><span class="p">:</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
            <span class="c1"># line is a string
</span>            <span class="c1"># a newline character (\n) is present at the end of the string
</span>            <span class="c1"># and is only omitted on the last line of the file if the
</span>            <span class="c1"># file doesn't end in a newline.
</span>
            <span class="c1"># do something with line
</span>            <span class="k">print</span> <span class="n">line</span>
<span class="k">except</span> <span class="nb">IOError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">"IOError: %s: %s"</span> <span class="o">%</span> <span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">filename</span><span class="p">,</span> <span class="n">e</span><span class="p">.</span><span class="n">strerror</span><span class="p">)</span>
</code></pre></div></div>

<h4 id="reading-a-file-word-by-word">Reading a file word by word</h4>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">try</span><span class="p">:</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
            <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">line</span><span class="p">.</span><span class="n">split</span><span class="p">():</span>
                <span class="c1"># do something with word
</span>                <span class="k">print</span> <span class="n">word</span>
<span class="k">except</span> <span class="nb">IOError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">"IOError: %s: %s"</span> <span class="o">%</span> <span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">filename</span><span class="p">,</span> <span class="n">e</span><span class="p">.</span><span class="n">strerror</span><span class="p">)</span>
</code></pre></div></div>

<h4 id="reading-a-file-character-by-character">Reading a file character by character</h4>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">try</span><span class="p">:</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
            <span class="n">character</span> <span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">character</span><span class="p">:</span>
                <span class="c1"># do something with character
</span>                <span class="k">print</span> <span class="n">character</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="c1"># end-of-file reached
</span>                <span class="k">break</span>
<span class="k">except</span> <span class="nb">IOError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">"IOError: %s: %s"</span> <span class="o">%</span> <span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">filename</span><span class="p">,</span> <span class="n">e</span><span class="p">.</span><span class="n">strerror</span><span class="p">)</span>
</code></pre></div></div>

<h3 id="writing-a-file-in-python">Writing a file in Python</h3>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"w"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="c1"># write to the file using f.write()
</span>    <span class="n">f</span><span class="p">.</span><span class="n">write</span><span class="p">(</span><span class="s">'Whatever you want to write.</span><span class="se">\n</span><span class="s">'</span><span class="p">)</span>
    <span class="n">f</span><span class="p">.</span><span class="n">write</span><span class="p">(</span><span class="s">'Really, anything.</span><span class="se">\n</span><span class="s">'</span><span class="p">)</span>
</code></pre></div></div>

<hr />

<h3 id="reading-a-file-in-java">Reading a file in Java</h3>

<h4 id="reading-a-file-at-once-1">Reading a file at once</h4>
<p><a href="http://stackoverflow.com/questions/3402735/what-is-simplest-way-to-read-a-file-into-string-in-java">This question on Stack Overflow</a> shows various ways to do this.</p>

<h4 id="reading-a-file-line-by-line-1">Reading a file line by line</h4>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">java.io.BufferedReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.FileReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.FileNotFoundException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Scanner</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">FileLL</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">Scanner</span> <span class="n">s</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Scanner</span><span class="o">(</span><span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">FileReader</span><span class="o">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="o">)));</span>
            <span class="k">while</span> <span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">hasNext</span><span class="o">())</span> <span class="o">{</span>
                <span class="nc">String</span> <span class="n">line</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="na">nextLine</span><span class="o">();</span>
                <span class="c1">// line does not contain a newline (\n) at the end.</span>

                <span class="c1">// do something with line</span>
                <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="n">line</span><span class="o">);</span>
            <span class="o">}</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">FileNotFoundException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Can't open input file!"</span><span class="o">);</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">());</span>
        <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
            <span class="k">if</span> <span class="o">(</span><span class="n">s</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
                <span class="n">s</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="reading-a-file-word-by-word-1">Reading a file word by word</h4>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">java.io.BufferedReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.FileReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.FileNotFoundException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Scanner</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">FileWW</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="nc">Scanner</span> <span class="n">s</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">s</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Scanner</span><span class="o">(</span><span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">FileReader</span><span class="o">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="o">)));</span>
            <span class="k">while</span> <span class="o">(</span><span class="n">s</span><span class="o">.</span><span class="na">hasNext</span><span class="o">())</span> <span class="o">{</span>
                <span class="nc">String</span> <span class="n">word</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="na">next</span><span class="o">();</span>

                <span class="c1">// do something with the word</span>
                <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">word</span><span class="o">);</span>
            <span class="o">}</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">FileNotFoundException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Can't open input file!"</span><span class="o">);</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">());</span>
        <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
            <span class="k">if</span> <span class="o">(</span><span class="n">s</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
                <span class="n">s</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h4 id="reading-a-file-character-by-character-1">Reading a file character by character</h4>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">java.io.FileReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.BufferedReader</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.FileNotFoundException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.IOException</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">FileCC</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">IOException</span> <span class="o">{</span>
        <span class="nc">BufferedReader</span> <span class="n">br</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">br</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">FileReader</span><span class="o">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="o">));</span>
            <span class="kt">int</span> <span class="n">ch</span><span class="o">;</span>
            <span class="k">while</span> <span class="o">((</span><span class="n">ch</span> <span class="o">=</span> <span class="n">br</span><span class="o">.</span><span class="na">read</span><span class="o">())</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span><span class="o">)</span> <span class="o">{</span>
                <span class="kt">char</span> <span class="n">character</span> <span class="o">=</span> <span class="o">(</span><span class="kt">char</span><span class="o">)</span> <span class="n">ch</span><span class="o">;</span>

                <span class="c1">// do something with the character.</span>
                <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">print</span><span class="o">(</span><span class="n">character</span><span class="o">);</span>
            <span class="o">}</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">FileNotFoundException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Can't open input file!"</span><span class="o">);</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">err</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">());</span>
        <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
            <span class="k">if</span> <span class="o">(</span><span class="n">br</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
                <span class="n">br</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
            <span class="o">}</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<h3 id="writing-a-file-in-java">Writing a file in Java</h3>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">java.io.FileWriter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.BufferedWriter</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.IOException</span><span class="o">;</span>

<span class="kd">public</span> <span class="kd">class</span> <span class="nc">FileW</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="kd">throws</span> <span class="nc">IOException</span> <span class="o">{</span>
        <span class="nc">BufferedWriter</span> <span class="n">bw</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">BufferedWriter</span><span class="o">(</span><span class="k">new</span> <span class="nc">FileWriter</span><span class="o">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="o">));</span>
        <span class="n">bw</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="s">"Whatever you want to write.\n"</span><span class="o">);</span>
        <span class="n">bw</span><span class="o">.</span><span class="na">write</span><span class="o">(</span><span class="s">"Really, anything.\n"</span><span class="o">);</span>
        <span class="n">bw</span><span class="o">.</span><span class="na">close</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<hr />

<h3 id="reading-a-file-in-c">Reading a file in C</h3>

<h4 id="reading-a-file-at-once-2">Reading a file at once</h4>
<p>I don’t know of a straightforward way to do this. Feel free to chime in the comments if you know one.</p>

<h4 id="reading-a-file-line-by-line-2">Reading a file line by line</h4>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>

    <span class="kt">FILE</span> <span class="o">*</span><span class="n">fp</span> <span class="o">=</span> <span class="n">fopen</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">fp</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Can't open input file!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
        <span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="kt">char</span> <span class="n">line</span><span class="p">[</span><span class="mi">1024</span><span class="p">];</span>
    <span class="c1">// assuming no line in the file is longer than 1024 characters.</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">fgets</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="k">sizeof</span> <span class="n">line</span><span class="p">,</span> <span class="n">fp</span><span class="p">)</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// line contains a newline (\n) at the end</span>
        <span class="c1">// except maybe for the last line of the file</span>
        <span class="c1">// if the file doesn't end with a newline</span>

        <span class="c1">// do something with line</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"%s</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">line</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="n">fclose</span><span class="p">(</span><span class="n">fp</span><span class="p">);</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h4 id="reading-a-file-word-by-word-2">Reading a file word by word</h4>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>

    <span class="kt">FILE</span> <span class="o">*</span><span class="n">fp</span> <span class="o">=</span> <span class="n">fopen</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">fp</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Can't open input file!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
        <span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="kt">char</span> <span class="n">word</span><span class="p">[</span><span class="mi">64</span><span class="p">];</span>
    <span class="c1">// assuming no word in the file is longer than 64 characters.</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">fscanf</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="s">"%64s"</span><span class="p">,</span> <span class="n">word</span><span class="p">)</span> <span class="o">!=</span> <span class="n">EOF</span><span class="p">)</span> <span class="p">{</span>
        <span class="c1">// do something with word</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"%s</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">word</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="n">fclose</span><span class="p">(</span><span class="n">fp</span><span class="p">);</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h4 id="reading-a-file-character-by-character-2">Reading a file character by character</h4>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>

    <span class="kt">FILE</span> <span class="o">*</span><span class="n">fp</span> <span class="o">=</span> <span class="n">fopen</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"r"</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">fp</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Can't open input file!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
        <span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="kt">int</span> <span class="n">ch</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">((</span><span class="n">ch</span> <span class="o">=</span> <span class="n">fgetc</span><span class="p">(</span><span class="n">fp</span><span class="p">))</span> <span class="o">!=</span> <span class="n">EOF</span><span class="p">)</span> <span class="p">{</span>
        <span class="kt">char</span> <span class="n">character</span> <span class="o">=</span> <span class="p">(</span><span class="kt">char</span><span class="p">)</span> <span class="n">ch</span><span class="p">;</span>
        <span class="c1">// do something with character</span>
        <span class="n">printf</span><span class="p">(</span><span class="s">"%c"</span><span class="p">,</span> <span class="n">character</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="n">fclose</span><span class="p">(</span><span class="n">fp</span><span class="p">);</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="writing-a-file-in-c">Writing a file in C</h3>
<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">#include &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span> <span class="p">{</span>

    <span class="kt">FILE</span> <span class="o">*</span><span class="n">fp</span> <span class="o">=</span> <span class="n">fopen</span><span class="p">(</span><span class="s">"/path/to/file/filename.txt"</span><span class="p">,</span> <span class="s">"w"</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">fp</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">"Can't open input file!</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
        <span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="s">"Whatever you want to write.</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">fprintf</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="s">"Really, anything.</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
    <span class="n">fclose</span><span class="p">(</span><span class="n">fp</span><span class="p">);</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>How to perform common file handling tasks in python, java and c.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Sharing an internet connection from your computer to your mobile device]]></title>
    <link href="http://notes.rohitagarwal.org/2013/06/19/sharing-an-internet-connection-from-your-computer-to-your-mobile-device.html"/>
    <published>2013-06-19T00:13:00+00:00</published>
    <updated>2013-06-19T00:13:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/06/19/sharing-an-internet-connection-from-your-computer-to-your-mobile-device</id>
    <content type="html"><![CDATA[<p>Recently, I explored how to share an internet connection from computers running Windows or Mac OS X or Linux to mobile devices running iOS or Android.</p>

<p>Here’s the summary:</p>

<p>Unrooted Android devices don’t support ad-hoc mode <a href="https://code.google.com/p/android/issues/detail?id=82">https://code.google.com/p/android/issues/detail?id=82</a> i.e. they don’t see ad-hoc WiFi networks.</p>

<p>iOS devices support ad-hoc mode i.e. they can see ad-hoc WiFi networks.</p>

<p>Now, if you are on a Mac and you want to share your internet connection, you follow the steps outlined here: <a href="http://support.apple.com/kb/PH3853">http://support.apple.com/kb/PH3853</a>, this creates a WiFi network in Infrastructure mode which is visible to both iOS and Android devices and you can access the internet on these devices using this network.</p>

<p>You can create an ad-hoc network on a Mac by following these steps: <a href="http://support.apple.com/kb/PH3771">http://support.apple.com/kb/PH3771</a>. But this network is not visible to unrooted Android devices and iOS devices were not able to access the internet even after connecting to this network. So, don’t do this.</p>

<p>If you are on a PC (Windows 7 or later), you can use <a href="http://www.connectify.me/hotspot/">Connectify Hotspot</a> to create a hotspot in Access Point Mode which is visible to both Android and iOS devices and access the internet on these devices using this hotspot. However, if you are on Windows XP or Vista, your Connectify hotspot will operate in ad-hoc mode and will not work with unrooted Android devices [<a href="http://support.connectify.me/entries/20307637-Does-Connectify-Hotspot-run-on-Windows-Vista-or-Windows-XP-">1</a>] [<a href="http://support.connectify.me/entries/20316691-access-point-mode-vs-ad-hoc-mode">2</a>].</p>

<p>If you don’t want to use Connectify Hotspot, you can create an ad-hoc network by following these steps: <a href="http://windows.microsoft.com/en-in/windows7/set-up-a-computer-to-computer-ad-hoc-network">http://windows.microsoft.com/en-in/windows7/set-up-a-computer-to-computer-ad-hoc-network</a>. This network is not visible to unrooted Android devices but is visible to iOS devices and they can access the internet using this network.</p>

<p>If you are on a PC running Ubuntu, you can create an ad-hoc network by going to the <code class="language-plaintext highlighter-rouge">Network</code> menu and then clicking <code class="language-plaintext highlighter-rouge">Create New Wireless Network</code>. This network is not visible to unrooted Android devices but is visible to iOS devices and they can access the internet using this network.</p>

<p>I don’t know of a way to create a WiFi network on an Ubuntu machine which is visible to unrooted Android devices.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>How to share an internet connection from a computer running Windows or Mac OS X or Linux to a device running iOS or Android</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Sparse matrix multiplication using SQL]]></title>
    <link href="http://notes.rohitagarwal.org/2013/06/07/sparse-matrix-multiplication-using-sql.html"/>
    <published>2013-06-07T21:57:00+00:00</published>
    <updated>2013-06-07T21:57:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/06/07/sparse-matrix-multiplication-using-sql</id>
    <content type="html"><![CDATA[<p><code class="language-plaintext highlighter-rouge">a</code> and <code class="language-plaintext highlighter-rouge">b</code> are two sparse matrices. We want to perform <code class="language-plaintext highlighter-rouge">a * b</code> as shown below:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0   1   0   0   9                1   0   0                0   0   0
0   0   3   0   0       \ /      0   0   0      -----     0  21   0
0   0   0   2   0        *       0   7   0      -----     0   0   4
0   0   0   0   0       / \      0   0   2                0   0   0
                                 0   0   0
</code></pre></div></div>

<p>We can represent a sparse matrix in a relational database as a table <code class="language-plaintext highlighter-rouge">matrix_name(row_num, col_num, value)</code>.
Each non-zero cell in the matrix is represnted as a record (i, j, value) in the table.</p>

<p>Here’s how to do the multiplication. First, create the tables:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">a</span> <span class="p">(</span>
<span class="n">row_num</span> <span class="nb">INT</span><span class="p">,</span>
<span class="n">col_num</span> <span class="nb">INT</span><span class="p">,</span>
<span class="n">value</span> <span class="nb">INT</span><span class="p">,</span>
<span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">(</span><span class="n">row_num</span><span class="p">,</span> <span class="n">col_num</span><span class="p">)</span>
<span class="p">);</span> 

<span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">b</span> <span class="p">(</span>
<span class="n">row_num</span> <span class="nb">INT</span><span class="p">,</span>
<span class="n">col_num</span> <span class="nb">INT</span><span class="p">,</span>
<span class="n">value</span> <span class="nb">INT</span><span class="p">,</span>
<span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">(</span><span class="n">row_num</span><span class="p">,</span> <span class="n">col_num</span><span class="p">)</span>
<span class="p">);</span> 
</code></pre></div></div>

<p>Next, insert values into the tables:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">INSERT</span> <span class="k">INTO</span> <span class="n">a</span> <span class="k">VALUES</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">9</span><span class="p">),</span>
<span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span>
<span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>

<span class="k">INSERT</span> <span class="k">INTO</span> <span class="n">b</span> <span class="k">VALUES</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">7</span><span class="p">),</span>
<span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>
</code></pre></div></div>

<p>Finally, perform the multiplication using the following query:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">a</span><span class="p">.</span><span class="n">row_num</span><span class="p">,</span> <span class="n">b</span><span class="p">.</span><span class="n">col_num</span><span class="p">,</span> <span class="k">SUM</span><span class="p">(</span><span class="n">a</span><span class="p">.</span><span class="n">value</span><span class="o">*</span><span class="n">b</span><span class="p">.</span><span class="n">value</span><span class="p">)</span>
<span class="k">FROM</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
<span class="k">WHERE</span> <span class="n">a</span><span class="p">.</span><span class="n">col_num</span> <span class="o">=</span> <span class="n">b</span><span class="p">.</span><span class="n">row_num</span>
<span class="k">GROUP</span> <span class="k">BY</span> <span class="n">a</span><span class="p">.</span><span class="n">row_num</span><span class="p">,</span> <span class="n">b</span><span class="p">.</span><span class="n">col_num</span><span class="p">;</span>

<span class="mi">2</span><span class="o">|</span><span class="mi">2</span><span class="o">|</span><span class="mi">21</span>
<span class="mi">3</span><span class="o">|</span><span class="mi">3</span><span class="o">|</span><span class="mi">4</span>
</code></pre></div></div>

<p>To see how this query works, remember the formula for cell (i,j) of the product. It is the sum of a(i,k)*b(k,j) for all k.
The <code class="language-plaintext highlighter-rouge">JOIN</code> condition <code class="language-plaintext highlighter-rouge">a.col_num = b.row_num</code> makes sure that both <code class="language-plaintext highlighter-rouge">a.value</code> and <code class="language-plaintext highlighter-rouge">b.value</code> has the same k.
The <code class="language-plaintext highlighter-rouge">GROUP BY</code> clause makes sure that we sum over all k’s.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>How to multiply two sparse matrices using relational databases and SQL.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Search twitter from command-line]]></title>
    <link href="http://notes.rohitagarwal.org/2013/06/06/search-twitter-from-command-line.html"/>
    <published>2013-06-06T20:55:00+00:00</published>
    <updated>2013-06-06T20:55:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/06/06/search-twitter-from-command-line</id>
    <content type="html"><![CDATA[<p>Recently, I started learning the Twitter API.
Twitter has deprecated <a href="https://dev.twitter.com/docs/api/1">v1</a> of its API, and the <a href="https://dev.twitter.com/docs/api/1.1">v1.1</a> of its API requires the use of <code class="language-plaintext highlighter-rouge">OAuth</code>.</p>

<p>So, the first step is to download an <code class="language-plaintext highlighter-rouge">OAuth</code> library. I am going to use <a href="https://github.com/simplegeo/python-oauth2"><code class="language-plaintext highlighter-rouge">simplegeo/python-oauth2</code></a>.
You can download it from <a href="https://pypi.python.org/pypi/oauth2/">pypi</a> and install it by executing <code class="language-plaintext highlighter-rouge">sudo ./setup.py install</code>.</p>

<p>Here is a script which uses the API to search twitter from the terminal.</p>

<script src="https://gist.github.com/5722371.js?file=twitter_search.py"> </script>

<p>To use this script, you first need to create an application at https://dev.twitter.com/apps</p>

<p>You will get your <code class="language-plaintext highlighter-rouge">consumer_key</code> and <code class="language-plaintext highlighter-rouge">consumer_secret</code> from there.
You will also need to create an access token for your account.
After doing that you will get your <code class="language-plaintext highlighter-rouge">access_token_key</code> and <code class="language-plaintext highlighter-rouge">access_token_secret</code>.</p>

<p>Fill these four values in <code class="language-plaintext highlighter-rouge">twitter_search.py</code> and you are good to go.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>python twitter_search.py SEARCH TERM<span class="o">(</span>S<span class="o">)</span>
</code></pre></div></div>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>Search twitter from command-line using their REST API v1.1.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Octopress and Github: WTF is going on with the branches?]]></title>
    <link href="http://notes.rohitagarwal.org/2013/05/29/octopress-and-github-wtf-is-going-on-with-the-branches.html"/>
    <published>2013-05-29T19:50:00+00:00</published>
    <updated>2013-05-29T19:50:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/05/29/octopress-and-github-wtf-is-going-on-with-the-branches</id>
    <content type="html"><![CDATA[<p>This blog is powered by Octopress and hosted using Github Pages.
When I checked the github repository for this blog, I found that there were two branches: <code class="language-plaintext highlighter-rouge">master</code> and <code class="language-plaintext highlighter-rouge">source</code>.
But locally there was only one: <code class="language-plaintext highlighter-rouge">source</code>.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git branch
* source
</code></pre></div></div>

<p>To understand what was going on, I dug up the <a href="http://octopress.org/docs/deploying/github/">docs</a>.</p>

<p>Initially when you clone the octopress repo from <a href="https://github.com/imathis/octopress">imathis/octopress</a>, the local branch is called <code class="language-plaintext highlighter-rouge">master</code> and the remote <code class="language-plaintext highlighter-rouge">imathis/octopress</code> is called <code class="language-plaintext highlighter-rouge">origin</code>.</p>

<p>The <a href="https://github.com/imathis/octopress/blob/1bd2b62a80f3a7be330cb9600a2206a678e6863d/Rakefile#L315">magic</a> happens when you do <code class="language-plaintext highlighter-rouge">rake setup_github_pages</code>.</p>

<p>It renames the remote pointing to <code class="language-plaintext highlighter-rouge">imathis/octopress</code> from <code class="language-plaintext highlighter-rouge">origin</code> to <code class="language-plaintext highlighter-rouge">octopress</code>; adds your Github Pages repository as the default <code class="language-plaintext highlighter-rouge">origin</code> remote and renames the <code class="language-plaintext highlighter-rouge">master</code> branch to <code class="language-plaintext highlighter-rouge">source</code>.
It then creates a new directory <code class="language-plaintext highlighter-rouge">_deploy/</code> and initializes a new git repository there.
<em>Finally, it adds your Github Pages repository as the default <code class="language-plaintext highlighter-rouge">origin</code> remote for this new repository also.</em></p>

<p>Now, when you do <code class="language-plaintext highlighter-rouge">rake deploy</code>, the <code class="language-plaintext highlighter-rouge">master</code> branch of the git repo in <code class="language-plaintext highlighter-rouge">_deploy/</code> is pushed to the <code class="language-plaintext highlighter-rouge">master</code> branch of your Github Pages repo. And when you push the source repo to github, it becomes the <code class="language-plaintext highlighter-rouge">source</code> branch of your Github Pages repo.</p>

<p>Here are some more details:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd octopress/  # THE_DIRECTORY_WHERE_YOU_CLONED_OCTOPRESS
$ git remote show origin
* remote origin
  Fetch URL: git@github.com:mindprince/mindprince.github.io.git
  Push  URL: git@github.com:mindprince/mindprince.github.io.git
  HEAD branch: master
  Remote branches:
    master new (next fetch will store in remotes/origin)
    source tracked
  Local ref configured for 'git push':
    source pushes to source (up to date)
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd octopress/_deploy/
$ git remote show origin
* remote origin
  Fetch URL: git@github.com:mindprince/mindprince.github.io.git
  Push  URL: git@github.com:mindprince/mindprince.github.io.git
  HEAD branch: master
  Remote branches:
    master tracked
    source new (next fetch will store in remotes/origin)
  Local ref configured for 'git push':
    master pushes to master (up to date)
</code></pre></div></div>

<p>To summarize, the two branches <code class="language-plaintext highlighter-rouge">source</code> and <code class="language-plaintext highlighter-rouge">master</code> on your Github Pages repo correspond to two separate git repositories: one in your <code class="language-plaintext highlighter-rouge">octopress/</code> directory and another in the <code class="language-plaintext highlighter-rouge">octopress/_deploy/</code> directory.</p>

<p>The fact that separate git repositories on your local machine can act as different branches of the same repository on github is interesting. It can probably be misused to host more than five private repositories in <a href="https://github.com/pricing">Github’s Micro plan</a>.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>Understanding the local and remote branches of your octopress blog deployed using github pages.</summary>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Fixing UnicodeDecodeError in Python]]></title>
    <link href="http://notes.rohitagarwal.org/2013/05/28/fixing-unicodedecodeerror-in-python.html"/>
    <published>2013-05-28T21:09:00+00:00</published>
    <updated>2013-05-28T21:09:00+00:00</updated>
    <id>http://notes.rohitagarwal.org/2013/05/28/fixing-unicodedecodeerror-in-python</id>
    <content type="html"><![CDATA[<pre><code class="language-pycon">&gt;&gt;&gt; a = "He said, “Hi, there.” She didn't reply."
&gt;&gt;&gt; type(a)
&lt;type 'str'&gt;
&gt;&gt;&gt; a
"He said, \xe2\x80\x9cHi, there.\xe2\x80\x9d She didn't reply."
&gt;&gt;&gt; print a
He said, “Hi, there.” She didn't reply.
</code></pre>

<p><code class="language-plaintext highlighter-rouge">a</code> is a string encoded in utf-8.</p>

<pre><code class="language-pycon">&gt;&gt;&gt; b = unicode(a)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9: ordinal not in range(128)
</code></pre>

<p>This didn’t work because the default encoding in python in ascii. So, python was not able to decode <code class="language-plaintext highlighter-rouge">a</code> assuming ascii encoding.</p>

<pre><code class="language-pycon">&gt;&gt;&gt; b = unicode(a, "utf-8")
&gt;&gt;&gt; type(b)
&lt;type 'unicode'&gt;
&gt;&gt;&gt; b
u"He said, \u201cHi, there.\u201d She didn't reply."
&gt;&gt;&gt; print b
He said, “Hi, there.” She didn't reply.
</code></pre>

<p><code class="language-plaintext highlighter-rouge">b</code> is not a string. It is a unicode object. I think it has no encoding. You can encode it in different encodings.</p>

<pre><code class="language-pycon">&gt;&gt;&gt; c = b.encode("utf-8")
&gt;&gt;&gt; type(c)
&lt;type 'str'&gt;
&gt;&gt;&gt; c
"He said, \xe2\x80\x9cHi, there.\xe2\x80\x9d She didn't reply."
&gt;&gt;&gt; print c
He said, “Hi, there.” She didn't reply.
</code></pre>

<p><code class="language-plaintext highlighter-rouge">c</code> is now same as <code class="language-plaintext highlighter-rouge">a</code>. It is a string encoded in utf-8. We created it by encoding a unicode object.</p>

<pre><code class="language-pycon">&gt;&gt;&gt; d = a.encode("utf-8")
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9: ordinal not in range(128)
</code></pre>

<p><code class="language-plaintext highlighter-rouge">a</code> is already encoded in utf-8. What happens here is that python first tries to decode <code class="language-plaintext highlighter-rouge">a</code> and then encode <code class="language-plaintext highlighter-rouge">a</code>. But decoding <code class="language-plaintext highlighter-rouge">a</code> fails because default encoding is assume to be ascii.</p>

<pre><code class="language-pycon">&gt;&gt;&gt; e = a.decode("utf-8")
&gt;&gt;&gt; type(e)
&lt;type 'unicode'&gt;
&gt;&gt;&gt; e
u"He said, \u201cHi, there.\u201d She didn't reply."
&gt;&gt;&gt; print e
He said, “Hi, there.” She didn't reply.
</code></pre>

<p>Now, <code class="language-plaintext highlighter-rouge">e</code> is same as <code class="language-plaintext highlighter-rouge">b</code>. It is a unicode object.</p>

<pre><code class="language-pycon">&gt;&gt;&gt; f = a.decode("ascii")
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9: ordinal not in range(128)
</code></pre>

<p>Just to show what we have been saying earlier.</p>

<pre><code class="language-pycon">&gt;&gt;&gt; g = b.encode("ascii")
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 9: ordinal not in range(128)
</code></pre>

<p>Note this is an <code class="language-plaintext highlighter-rouge">UnicodeEncodeError</code> and not a <code class="language-plaintext highlighter-rouge">UnicodeDecodeError</code>. We can’t encode a unicode object which contains characters outside of ascii range to ascii encoding.</p>
]]></content>
    <author>
      <name>Rohit Agarwal</name>
    </author>
    <summary>Understanding unicode, string encodings, utf-8 and ascii in python.</summary>
  </entry>
  
</feed>

