<feed xmlns="http://www.w3.org/2005/Atom">
  <title>A Random Walk</title>
  <link href="https://rrampage.github.io/atom.xml" rel="self"/>
  <link href="https://rrampage.github.io/"/>
  <updated>2025-06-13T19:08:50+05:30</updated>
  <id>https://rrampage.github.io/</id>
  <author>
    <name>Raunak</name>
  </author>
  <generator>Hugo -- gohugo.io</generator>
  <entry>
    <title type="html"><![CDATA[strace tips for better debugging]]></title>
    <link href="https://rrampage.github.io/2025/06/13/strace-tips-for-better-debugging/"/>
    <id>https://rrampage.github.io/2025/06/13/strace-tips-for-better-debugging/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2025-06-13T19:08:50+05:30</published>
    <updated>2025-06-13T19:08:50+05:30</updated>
    
    <content type="html"><![CDATA[<p>Recently, I have been building software without libc to better understand Linux syscalls and internals better. So far, I have built a <a href="https://gist.github.com/rrampage/5046b60ca2d040bcffb49ee38e86041f">minimal shell</a>, <a href="https://gist.github.com/rrampage/2a781662645dc2fcba45784eb584cbdc">terminal Snake game</a>, pure ARM64 assembly <a href="https://gist.github.com/rrampage/d31e75647a77badb3586ebae1e414cb6">HTTP server</a> and <a href="https://gist.github.com/rrampage/43c56d4a56f8f73320d17ff7b3a49be6">threads implementation</a>. I have been using <a href="https://man7.org/linux/man-pages/man1/strace.1.html"><code>strace</code></a> extensively while debugging.</p>
<h2 id="useful-options-and-flags">Useful options and flags</h2>
<p>I use a version of the following command:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">strace -fintrCDTYyy -o strace.log -v -s128 ./binary
</span></span></code></pre></div><p>This looks like an alphabet soup of options! Here&rsquo;s what they do and how they are useful:</p>
<ul>
<li><code>-f</code>: Follow child processes/threads. This is especially useful when dealing with spawning processes or threads as otherwise, strace will only trace the parent process.</li>
<li><code>-v</code>: Print unabbreviated versions of environment, stat, termios and other structs in  syscalls. I found this invaluable in conjunction with <code>-s</code> when doing assembly programming to check if the structs were being initialized correctly and if certain arguments were being sent in little/big endian format</li>
<li><code>-s NUM</code>: Specify the maximum string size to print. Useful for large structs</li>
<li><code>-o</code>: Save strace output to a log file. It is always better to do this to investigate the output of the original process and strace separately without each cluttering the other</li>
<li><code>-yy</code>: Print all available information associated with file descriptors. This is great for expanding the file descriptor to either its full path in case of a file or TCP address in case of sockets</li>
<li><code>-Y</code>: Print command names for PIDs. I found this useful when building the shell to check if the correct program is being executed</li>
<li><code>-t</code>: Print current timestamp in log</li>
<li><code>-T</code>: Show time spent in syscalls. Useful for some basic profiling although strace heavily slows down the process.</li>
<li><code>-r</code>: Print a relative timestamp upon entry to each system call</li>
<li><code>-n</code>: Print syscall number. Great to quickly find out syscall numbers on new architectures.</li>
<li><code>-i</code>: Print instruction pointer at the time of syscall. Found this useful when debugging assembly code to check rough location of errors.</li>
<li><code>-C</code>: Print summary of syscall count, time, errors at the end of regular output</li>
</ul>
<h2 id="print-stack-traces">Print stack traces</h2>
<p>The <code>-k</code> or <code>--stack-trace</code> prints the stacktrace along with the syscall. This is useful if your program is compiled with with <code>-g</code>. <a href="https://shane.ai/posts/backtraces-with-strace/">This post</a> is a good read on using strace to show backtraces for a Golang program compiled with <code>GODEBUG</code>.</p>
<h2 id="selectively-tracing-syscalls">Selectively tracing syscalls</h2>
<p>By default, strace traces all syscalls. We can be very selective in tracing calls by using the <code>-e</code> option. It  allows us to trace families of syscalls e.g <code>-e t=%net</code> will trace all network related syscalls while <code>-e t=%mem</code> will trace memory related syscalls.</p>
<p>We can also trace only syscalls which succeed using <code>-z</code> option or fail using <code>-Z</code> option. Another useful option is <code>-P</code> which can be used to only trace syscalls which access a particular path e.g <code>strace -f -P /usr/bin/ls sh -c ls</code>.</p>
<h2 id="tampering-with-syscalls">Tampering with syscalls!</h2>
<p>strace is very powerful and can do stuff like inject faults for particular syscalls e.g <code>strace -e inject=%file:error=ENOENT:when=3+ ls</code> which fails the all file related syscalls after 2 successful invocations. We can also make syscalls return a particular value using <code>retval</code> or send signal using <code>signal</code> or delay at beginning or end of syscall using <code>delay_enter</code> and <code>delay_exit</code> with <code>-e inject</code>.</p>
<p>I found this useful when debugging failure cases in code for the syscalls. The strace output will have lines like <code>openat(AT_FDCWD, &quot;/lib/libc.so.6&quot;, O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory) (INJECTED)</code> which have <code>INJECTED</code> marked in them. This is useful to differentiate genuine syscall errors from the injected ones.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Bash - Oops I deleted my bin dir challenge]]></title>
    <link href="https://rrampage.github.io/2025/05/20/bash-oops-i-deleted-my-bin-dir-challenge/"/>
    <id>https://rrampage.github.io/2025/05/20/bash-oops-i-deleted-my-bin-dir-challenge/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2025-05-20T14:44:24+05:30</published>
    <updated>2025-05-20T14:44:24+05:30</updated>
    
    <content type="html"><![CDATA[<p><a href="https://oops.cmdchallenge.com">Oops I deleted my bin dir</a> is a fun set of challenges to investigate a &ldquo;rogue&rdquo; process which has been deleting files on the system. It has deleted all programs from the <code>bin</code> directories like <code>ps</code>, <code>htop</code>, <code>lsof</code>. All we have left is a shell prompt&hellip;</p>
<h2 id="bash-built-ins">Bash built-ins</h2>
<p>In the challenge, the shell we are using is <code>bash</code>. Bash has many &ldquo;built-ins&rdquo; which are commands we can run without having to spawn a process and execute a binary i.e they are part of bash itself.</p>
<p>The most useful one right now is <code>help</code> which lists all the bash built-ins and their arguments.
Typing <code>help BUILTIN_NAME</code> will give more details about that built-in command.</p>

<details>
  <summary><h3>List of built-ins</h3></summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">job_spec <span class="o">[</span><span class="p">&amp;</span><span class="o">]</span>                                                                   <span class="nb">history</span> <span class="o">[</span>-c<span class="o">]</span> <span class="o">[</span>-d offset<span class="o">]</span> <span class="o">[</span>n<span class="o">]</span> or <span class="nb">history</span> -anrw <span class="o">[</span>filename<span class="o">]</span> or <span class="nb">history</span> -ps<span class="o">[</span>1/218<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="o">((</span> expression <span class="o">))</span>                                                               <span class="k">if</span> COMMANDS<span class="p">;</span> <span class="k">then</span> COMMANDS<span class="p">;</span> <span class="o">[</span> <span class="k">elif</span> COMMANDS<span class="p">;</span> <span class="k">then</span> COMMANDS<span class="p">;</span> <span class="o">]</span>... <span class="o">[</span> <span class="k">else</span> COM&gt;
</span></span><span class="line"><span class="cl"> . filename <span class="o">[</span>arguments<span class="o">]</span>                                                         <span class="nb">jobs</span> <span class="o">[</span>-lnprs<span class="o">]</span> <span class="o">[</span>jobspec ...<span class="o">]</span> or <span class="nb">jobs</span> -x <span class="nb">command</span> <span class="o">[</span>args<span class="o">]</span>
</span></span><span class="line"><span class="cl"> :                                                                              <span class="nb">kill</span> <span class="o">[</span>-s sigspec <span class="p">|</span> -n signum <span class="p">|</span> -sigspec<span class="o">]</span> pid <span class="p">|</span> jobspec ... or <span class="nb">kill</span> -l <span class="o">[</span>sigs&gt;
</span></span><span class="line"><span class="cl"> <span class="o">[</span> arg... <span class="o">]</span>                                                                     <span class="nb">let</span> arg <span class="o">[</span>arg ...<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="o">[[</span> expression <span class="o">]]</span>                                                               <span class="nb">local</span> <span class="o">[</span>option<span class="o">]</span> name<span class="o">[=</span>value<span class="o">]</span> ...
</span></span><span class="line"><span class="cl"> <span class="nb">alias</span> <span class="o">[</span>-p<span class="o">]</span> <span class="o">[</span>name<span class="o">[=</span>value<span class="o">]</span> ... <span class="o">]</span>                                                 <span class="nb">logout</span> <span class="o">[</span>n<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">bg</span> <span class="o">[</span>job_spec ...<span class="o">]</span>                                                              mapfile <span class="o">[</span>-d delim<span class="o">]</span> <span class="o">[</span>-n count<span class="o">]</span> <span class="o">[</span>-O origin<span class="o">]</span> <span class="o">[</span>-s count<span class="o">]</span> <span class="o">[</span>-t<span class="o">]</span> <span class="o">[</span>-u fd<span class="o">]</span> <span class="o">[</span>-C callb&gt;
</span></span><span class="line"><span class="cl"> <span class="nb">bind</span> <span class="o">[</span>-lpsvPSVX<span class="o">]</span> <span class="o">[</span>-m keymap<span class="o">]</span> <span class="o">[</span>-f filename<span class="o">]</span> <span class="o">[</span>-q name<span class="o">]</span> <span class="o">[</span>-u name<span class="o">]</span> <span class="o">[</span>-r keyseq<span class="o">]</span> <span class="o">[</span>&gt;  <span class="nb">popd</span> <span class="o">[</span>-n<span class="o">]</span> <span class="o">[</span>+N <span class="p">|</span> -N<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">break</span> <span class="o">[</span>n<span class="o">]</span>                                                                      <span class="nb">printf</span> <span class="o">[</span>-v var<span class="o">]</span> format <span class="o">[</span>arguments<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">builtin</span> <span class="o">[</span>shell-builtin <span class="o">[</span>arg ...<span class="o">]]</span>                                              <span class="nb">pushd</span> <span class="o">[</span>-n<span class="o">]</span> <span class="o">[</span>+N <span class="p">|</span> -N <span class="p">|</span> dir<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">caller</span> <span class="o">[</span>expr<span class="o">]</span>                                                                  <span class="nb">pwd</span> <span class="o">[</span>-LP<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="k">case</span> WORD in <span class="o">[</span>PATTERN <span class="o">[</span><span class="p">|</span> PATTERN<span class="o">]</span>...<span class="o">)</span> COMMANDS <span class="p">;;</span><span class="o">]</span>... <span class="k">esac</span>                     <span class="nb">read</span> <span class="o">[</span>-ers<span class="o">]</span> <span class="o">[</span>-a array<span class="o">]</span> <span class="o">[</span>-d delim<span class="o">]</span> <span class="o">[</span>-i text<span class="o">]</span> <span class="o">[</span>-n nchars<span class="o">]</span> <span class="o">[</span>-N nchars<span class="o">]</span> <span class="o">[</span>-p pro&gt;
</span></span><span class="line"><span class="cl"> <span class="nb">cd</span> <span class="o">[</span>-L<span class="p">|</span><span class="o">[</span>-P <span class="o">[</span>-e<span class="o">]]</span> <span class="o">[</span>-@<span class="o">]]</span> <span class="o">[</span>dir<span class="o">]</span>                                                   readarray <span class="o">[</span>-d delim<span class="o">]</span> <span class="o">[</span>-n count<span class="o">]</span> <span class="o">[</span>-O origin<span class="o">]</span> <span class="o">[</span>-s count<span class="o">]</span> <span class="o">[</span>-t<span class="o">]</span> <span class="o">[</span>-u fd<span class="o">]</span> <span class="o">[</span>-C cal&gt;
</span></span><span class="line"><span class="cl"> <span class="nb">command</span> <span class="o">[</span>-pVv<span class="o">]</span> <span class="nb">command</span> <span class="o">[</span>arg ...<span class="o">]</span>                                               <span class="nb">readonly</span> <span class="o">[</span>-aAf<span class="o">]</span> <span class="o">[</span>name<span class="o">[=</span>value<span class="o">]</span> ...<span class="o">]</span> or <span class="nb">readonly</span> -p
</span></span><span class="line"><span class="cl"> <span class="nb">compgen</span> <span class="o">[</span>-abcdefgjksuv<span class="o">]</span> <span class="o">[</span>-o option<span class="o">]</span> <span class="o">[</span>-A action<span class="o">]</span> <span class="o">[</span>-G globpat<span class="o">]</span> <span class="o">[</span>-W wordlist<span class="o">]</span> <span class="o">[</span>&gt;  <span class="k">return</span> <span class="o">[</span>n<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">complete</span> <span class="o">[</span>-abcdefgjksuv<span class="o">]</span> <span class="o">[</span>-pr<span class="o">]</span> <span class="o">[</span>-DEI<span class="o">]</span> <span class="o">[</span>-o option<span class="o">]</span> <span class="o">[</span>-A action<span class="o">]</span> <span class="o">[</span>-G globpat<span class="o">]</span> <span class="o">[</span>&gt;  <span class="k">select</span> NAME <span class="o">[</span>in WORDS ... <span class="p">;</span><span class="o">]</span> <span class="k">do</span> COMMANDS<span class="p">;</span> <span class="k">done</span>
</span></span><span class="line"><span class="cl"> compopt <span class="o">[</span>-o<span class="p">|</span>+o option<span class="o">]</span> <span class="o">[</span>-DEI<span class="o">]</span> <span class="o">[</span>name ...<span class="o">]</span>                                       <span class="nb">set</span> <span class="o">[</span>-abefhkmnptuvxBCHP<span class="o">]</span> <span class="o">[</span>-o option-name<span class="o">]</span> <span class="o">[</span>--<span class="o">]</span> <span class="o">[</span>arg ...<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="k">continue</span> <span class="o">[</span>n<span class="o">]</span>                                                                   <span class="nb">shift</span> <span class="o">[</span>n<span class="o">]</span>
</span></span><span class="line"><span class="cl"> coproc <span class="o">[</span>NAME<span class="o">]</span> <span class="nb">command</span> <span class="o">[</span>redirections<span class="o">]</span>                                           <span class="nb">shopt</span> <span class="o">[</span>-pqsu<span class="o">]</span> <span class="o">[</span>-o<span class="o">]</span> <span class="o">[</span>optname ...<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">declare</span> <span class="o">[</span>-aAfFgiIlnrtux<span class="o">]</span> <span class="o">[</span>-p<span class="o">]</span> <span class="o">[</span>name<span class="o">[=</span>value<span class="o">]</span> ...<span class="o">]</span>                               <span class="nb">source</span> filename <span class="o">[</span>arguments<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">dirs</span> <span class="o">[</span>-clpv<span class="o">]</span> <span class="o">[</span>+N<span class="o">]</span> <span class="o">[</span>-N<span class="o">]</span>                                                         <span class="nb">suspend</span> <span class="o">[</span>-f<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">disown</span> <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-ar<span class="o">]</span> <span class="o">[</span>jobspec ... <span class="p">|</span> pid ...<span class="o">]</span>                                      <span class="nb">test</span> <span class="o">[</span>expr<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">echo</span> <span class="o">[</span>-neE<span class="o">]</span> <span class="o">[</span>arg ...<span class="o">]</span>                                                          <span class="nb">time</span> <span class="o">[</span>-p<span class="o">]</span> pipeline
</span></span><span class="line"><span class="cl"> <span class="nb">enable</span> <span class="o">[</span>-a<span class="o">]</span> <span class="o">[</span>-dnps<span class="o">]</span> <span class="o">[</span>-f filename<span class="o">]</span> <span class="o">[</span>name ...<span class="o">]</span>                                   <span class="nb">times</span>
</span></span><span class="line"><span class="cl"> <span class="nb">eval</span> <span class="o">[</span>arg ...<span class="o">]</span>                                                                 <span class="nb">trap</span> <span class="o">[</span>-lp<span class="o">]</span> <span class="o">[[</span>arg<span class="o">]</span> signal_spec ...<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">exec</span> <span class="o">[</span>-cl<span class="o">]</span> <span class="o">[</span>-a name<span class="o">]</span> <span class="o">[</span><span class="nb">command</span> <span class="o">[</span>argument ...<span class="o">]]</span> <span class="o">[</span>redirection ...<span class="o">]</span>                <span class="nb">true</span>
</span></span><span class="line"><span class="cl"> <span class="nb">exit</span> <span class="o">[</span>n<span class="o">]</span>                                                                       <span class="nb">type</span> <span class="o">[</span>-afptP<span class="o">]</span> name <span class="o">[</span>name ...<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">export</span> <span class="o">[</span>-fn<span class="o">]</span> <span class="o">[</span>name<span class="o">[=</span>value<span class="o">]</span> ...<span class="o">]</span> or <span class="nb">export</span> -p                                   <span class="nb">typeset</span> <span class="o">[</span>-aAfFgiIlnrtux<span class="o">]</span> <span class="o">[</span>-p<span class="o">]</span> name<span class="o">[=</span>value<span class="o">]</span> ...
</span></span><span class="line"><span class="cl"> <span class="nb">false</span>                                                                          <span class="nb">ulimit</span> <span class="o">[</span>-SHabcdefiklmnpqrstuvxPT<span class="o">]</span> <span class="o">[</span>limit<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">fc</span> <span class="o">[</span>-e ename<span class="o">]</span> <span class="o">[</span>-lnr<span class="o">]</span> <span class="o">[</span>first<span class="o">]</span> <span class="o">[</span>last<span class="o">]</span> or <span class="nb">fc</span> -s <span class="o">[</span><span class="nv">pat</span><span class="o">=</span>rep<span class="o">]</span> <span class="o">[</span>command<span class="o">]</span>               <span class="nb">umask</span> <span class="o">[</span>-p<span class="o">]</span> <span class="o">[</span>-S<span class="o">]</span> <span class="o">[</span>mode<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">fg</span> <span class="o">[</span>job_spec<span class="o">]</span>                                                                  <span class="nb">unalias</span> <span class="o">[</span>-a<span class="o">]</span> name <span class="o">[</span>name ...<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="k">for</span> NAME <span class="o">[</span>in WORDS ... <span class="o">]</span> <span class="p">;</span> <span class="k">do</span> COMMANDS<span class="p">;</span> <span class="k">done</span>                                   <span class="nb">unset</span> <span class="o">[</span>-f<span class="o">]</span> <span class="o">[</span>-v<span class="o">]</span> <span class="o">[</span>-n<span class="o">]</span> <span class="o">[</span>name ...<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="k">for</span> <span class="o">((</span> exp1<span class="p">;</span> exp2<span class="p">;</span> exp3 <span class="o">))</span><span class="p">;</span> <span class="k">do</span> COMMANDS<span class="p">;</span> <span class="k">done</span>                                  <span class="k">until</span> COMMANDS<span class="p">;</span> <span class="k">do</span> COMMANDS<span class="p">;</span> <span class="k">done</span>
</span></span><span class="line"><span class="cl"> <span class="k">function</span> name <span class="o">{</span> COMMANDS <span class="p">;</span> <span class="o">}</span> or name <span class="o">()</span> <span class="o">{</span> COMMANDS <span class="p">;</span> <span class="o">}</span>                         variables - Names and meanings of some shell variables
</span></span><span class="line"><span class="cl"> <span class="nb">getopts</span> optstring name <span class="o">[</span>arg ...<span class="o">]</span>                                               <span class="nb">wait</span> <span class="o">[</span>-fn<span class="o">]</span> <span class="o">[</span>-p var<span class="o">]</span> <span class="o">[</span>id ...<span class="o">]</span>
</span></span><span class="line"><span class="cl"> <span class="nb">hash</span> <span class="o">[</span>-lr<span class="o">]</span> <span class="o">[</span>-p pathname<span class="o">]</span> <span class="o">[</span>-dt<span class="o">]</span> <span class="o">[</span>name ...<span class="o">]</span>                                      <span class="k">while</span> COMMANDS<span class="p">;</span> <span class="k">do</span> COMMANDS<span class="p">;</span> <span class="k">done</span>
</span></span><span class="line"><span class="cl"> <span class="nb">help</span> <span class="o">[</span>-dms<span class="o">]</span> <span class="o">[</span>pattern ...<span class="o">]</span>                                                      <span class="o">{</span> COMMANDS <span class="p">;</span> <span class="o">}</span>
</span></span></code></pre></div></details>

<h2 id="challenge-1---print-the-current-working-directory">Challenge 1 - print the current working directory</h2>
<details>
  <summary>
    
    
    <h3>Solution</h3>
  </summary>
  <div>
    
The `pwd` built-in shows the *p*resent *w*orking *d*irectory


  </div>
</details>
<h2 id="challenge-2---list-all-files-in-the-current-working-directory">Challenge 2 - List all files in the current working directory</h2>
<p>We can not use <code>ls</code> as it is gone&hellip; Which built-in can help us?</p>

<details>
  <summary><h3>Solution</h3></summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">echo</span> *
</span></span></code></pre></div><p>This works because <code>echo</code> prints all its arguments to stdout. The <code>*</code> character is a wildcard character which makes <code>bash</code> perform <a href="https://www.man7.org/linux/man-pages/man7/glob.7.html">glob expansion</a>. This will expand the <code>*</code> to match all files in the directory.</p>
</details>

<h2 id="challenge-3---display-contents-of-a-file">Challenge 3 - Display contents of a file</h2>
<p>No <code>cat</code>! We can still use <code>echo</code> to print stuff to stdout. How do we pass the file contents to <code>echo</code>?</p>

<details>
  <summary><h3>Solution</h3></summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;</span><span class="k">$(</span>&lt;file_name<span class="k">)</span><span class="s2">&#34;</span>
</span></span></code></pre></div><ul>
<li><code>&lt;file_name</code> redirects the file contents to stdin.</li>
<li><code>$(&lt;file_name)</code> is <a href="https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html">command substitution</a> which means that bash executes the command in a sub-shell and substitutes the command with stdout of the command</li>
<li><code>&quot;$(&lt;file_name)&quot;</code> - we wrap this in double quotes to prevent bash from expanding newlines and spaces</li>
<li>Finally, we pass the whole string to <code>echo</code></li>
</ul>
</details>

<h2 id="challenge-4---print-the-name-of-the-running-processes">Challenge 4 - Print the name of the running processes</h2>
<p>We can not use <code>ps</code>. <a href="https://www.man7.org/linux/man-pages/man5/proc.5.html"><code>/proc</code></a> can be used as it is just a file system which can be read similar to how we displayed file contents earlier</p>

<details>
  <summary><h3>Solution</h3></summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="k">for</span> f in /proc/*/cmdline<span class="p">;</span> <span class="k">do</span> <span class="nb">echo</span> <span class="k">$(</span>&lt;<span class="nv">$f</span><span class="k">)</span><span class="p">;</span> <span class="k">done</span>
</span></span></code></pre></div><ul>
<li><code>/proc</code> has directories for each <code>pid</code>. In the <code>pid</code> directory for each process, there will be files for:
<ul>
<li><code>cmdline</code>: this shows the command line arguments passed by Linux to the process</li>
<li><code>comm</code>: name of the process</li>
<li><code>cwd</code>: current working directory of the process i.e where it was started</li>
<li><code>exe</code>: symlink to the actual location of the binary being executed by the process</li>
<li><code>status</code>: More details about the process like memory usage, signal handlers, etc</li>
<li><code>syscall</code>: system call number and argument registers for the system call currently being executed by the process, followed by the values of the stack pointer and program counter registers</li>
</ul>
</li>
<li><code>/proc/*/cmdline</code> will get <code>cmdline</code> file for all running processes</li>
<li><code>for f in /proc/*/cmdline</code>: run a <code>for</code> loop with loop variable <code>f</code> for all the args in <code>/proc/*/cmdline</code></li>
<li><code>echo $(&lt;$f)</code>: echo the value in <code>$f</code></li>
</ul>
<p>This is a nice combination of a one line for loop, globbing, command substitution and input redirection.</p>
</details>

<h2 id="challenge-5---kill-the-rogue-process">Challenge 5 - Kill the rogue process!</h2>
<p>Now that we know which process is causing havoc, it is time to kill it before it does more damage!</p>

<details>
  <summary><h3>Solution</h3></summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">kill</span> -9 PID
</span></span></code></pre></div><ul>
<li><code>kill</code> is a bash built-in. It passes a signal to the process. In this case, we need to pass the SIGKILL signal.</li>
<li>Running <code>kill -l</code> lists all signals with their numbers.</li>
<li><code>kill -NUM PID</code> or <code>kill -SIGNAME PID</code> will send the signal to the process</li>
</ul>
</details>

<h2 id="summary">Summary</h2>

<details>
  <summary><h3>All answers</h3></summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"> <span class="c1"># List bash builtins help</span>
</span></span><span class="line"><span class="cl"> <span class="nb">help</span>
</span></span><span class="line"><span class="cl"> <span class="c1"># List current directory</span>
</span></span><span class="line"><span class="cl"> <span class="nb">pwd</span>
</span></span><span class="line"><span class="cl"> <span class="c1"># List files in pwd</span>
</span></span><span class="line"><span class="cl"> <span class="nb">echo</span> *
</span></span><span class="line"><span class="cl"> <span class="c1"># Read file contents</span>
</span></span><span class="line"><span class="cl"> <span class="nb">echo</span> <span class="s2">&#34;</span><span class="k">$(</span>&lt;file_name<span class="k">)</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl"> <span class="c1"># Read cmdline of all running processes in proc</span>
</span></span><span class="line"><span class="cl"> <span class="k">for</span> f in /proc/*/cmdline<span class="p">;</span> <span class="k">do</span> <span class="nb">echo</span> <span class="k">$(</span>&lt;<span class="nv">$f</span><span class="k">)</span><span class="p">;</span> <span class="k">done</span>
</span></span><span class="line"><span class="cl"> <span class="c1"># Kill process</span>
</span></span><span class="line"><span class="cl"> <span class="nb">kill</span> -9 PID
</span></span></code></pre></div></details>

]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[HTML toggle headings using Details Summary element and some CSS]]></title>
    <link href="https://rrampage.github.io/2025/03/06/html-toggle-headings-using-details-summary-element-and-some-css/"/>
    <id>https://rrampage.github.io/2025/03/06/html-toggle-headings-using-details-summary-element-and-some-css/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2025-03-06T14:40:15+05:30</published>
    <updated>2025-03-06T14:40:15+05:30</updated>
    
    <content type="html"><![CDATA[<h2 id="overview-of-the-html-details-tag">Overview of the HTML <code>details</code> tag</h2>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details"><code>details</code> tag</a> creates a toggleable element which we can use to hide sensitive information like spoilers. It has a <code>summary</code> attribute which is visible to the reader and a button which they can click to show then content.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-html" data-lang="html"><span class="line"><span class="cl"><span class="p">&lt;</span><span class="nt">details</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="p">&lt;</span><span class="nt">summary</span><span class="p">&gt;</span>Spoilers!<span class="p">&lt;/</span><span class="nt">summary</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  Lot of sensitive information!
</span></span><span class="line"><span class="cl"><span class="p">&lt;/</span><span class="nt">details</span><span class="p">&gt;</span>
</span></span></code></pre></div><h2 id="creating-toggle-headings-using-summary-and-html-heading-tags">Creating Toggle Headings using <code>summary</code> and HTML heading tags</h2>
<p>Since <code>summary</code> is an HTML element, we can nest other HTML elements in it. If we want to create something like Notion&rsquo;s toggle headings (<code>/toggleh1</code>), we can do something like</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-html" data-lang="html"><span class="line"><span class="cl"><span class="p">&lt;</span><span class="nt">details</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  <span class="p">&lt;</span><span class="nt">summary</span><span class="p">&gt;&lt;</span><span class="nt">h3</span><span class="p">&gt;</span>Spoilers!<span class="p">&lt;/</span><span class="nt">h3</span><span class="p">&gt;&lt;/</span><span class="nt">summary</span><span class="p">&gt;</span>
</span></span><span class="line"><span class="cl">  Spoilers
</span></span><span class="line"><span class="cl"><span class="p">&lt;/</span><span class="nt">details</span><span class="p">&gt;</span>
</span></span></code></pre></div><p>This shows the <code>&lt;h3&gt;</code> header but below the taggle i.e not inline. See <a href="https://jsfiddle.net/3ht4n0jm/">this fiddle</a> for the minimal example. Searching for this led me to this <a href="https://css-tricks.com/two-issues-styling-the-details-element-and-how-to-solve-them/">article</a> which suggested this CSS fix to the problem</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-css" data-lang="css"><span class="line"><span class="cl"><span class="nt">details</span> <span class="nt">summary</span> <span class="o">&gt;</span> <span class="o">*</span> <span class="p">{</span> 
</span></span><span class="line"><span class="cl">  <span class="k">display</span><span class="p">:</span> <span class="kc">inline</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>This CSS snippet inlines all children of the <code>details summary</code> element.</p>
<p>Here&rsquo;s the <a href="https://jsfiddle.net/0yjpcLef/">fix</a> in action!</p>
<h2 id="using-the-details-element-in-hugo-markdown">Using the <code>details</code> element in Hugo markdown</h2>
<p>Since version 0.140, Hugo has supported <code>details</code> as a <a href="https://gohugo.io/shortcodes/details/">shortcode</a>. We can put arbitrary HTML in the summary e.g</p>
<p>{{&lt; details summary=&quot;&lt;h3&gt;Major Spoilers!&lt;/h3&gt;&quot; &gt;}}<br>
{{&lt; /details &gt;}}</p>
<h2 id="using-a-custom-hugo-shortcodes-to-generate-toggle-headings">Using a custom Hugo Shortcodes to generate toggle headings</h2>
<p>I created a custom shortcode called <code>tog</code> with <code>tag</code> and <code>summary</code> attributes to support toggle headers. Here it is in action! Also linked is a <a href="https://gist.github.com/rrampage/66af5cb88147bd07cb79cb1b3c8ba46b">gist</a> with the minimal necessary HTML + CSS to create and use toggle headings in Hugo.</p>
<details>
  <summary>
    
    
    <h3>Shortcode HTML</h3>
  </summary>
  <div>
    


Create the following HTML in `tog.html` in the `layouts/shortcodes` directory

&lt;details><br>
  &lt;summary><br>
    {{ $tag := .Get "tag" | default "h3" }}<br>
    {{ $heading := printf "<%s>%s</%s>" $tag (.Get "summary") $tag | safeHTML }}<br>
    {{ $heading }}<br>
  &lt;/summary><br>
  &lt;div><br>
    {{ .Inner }}
  &lt;/div><br>
&lt;/details><br>

  </div>
</details>
<details>
  <summary>
    
    
    <h4>Usage</h4>
  </summary>
  <div>
    <br>
{{&lt; tog tag="h4" summary="Usage" >}}<br>
{{&lt; /tog >}}<br>

  </div>
</details>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[An APL a day! - Caesar Salad]]></title>
    <link href="https://rrampage.github.io/2025/02/24/an-apl-a-day-caesar-salad/"/>
    <id>https://rrampage.github.io/2025/02/24/an-apl-a-day-caesar-salad/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2025-02-24T02:15:00+05:30</published>
    <updated>2025-02-24T02:15:00+05:30</updated>
    
    <content type="html"><![CDATA[<p>Today&rsquo;s problem - <a href="https://apl.quest/psets/2023.html?goto=P3_Caesar_Salad">Caesar Salad</a></p>
<p>A Caesar cipher, also known as a shift cipher, is one of the simplest encryption techniques. In a Caesar cipher, each letter in the plaintext is replaced by a letter some fixed number of positions away in the alphabet, effectively &ldquo;shifting&rdquo; the alphabet.</p>
<p>Write a function that:</p>
<pre><code>takes a single integer left argument representing the size of the shift
takes a character vector right argument representing the plaintext message
returns a result with the same shape as the right argument representing the encrypted message
</code></pre>
<p>Notes:</p>
<pre><code>Use ' ',⎕A as the alphabet
You can assume that the plaintext message will contain only characters found in the alphabet.
</code></pre>
<p>Hint: The rotate function ⌽ could be helpful in solving this problem.</p>
<h2 id="examples">Examples</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-apl" data-lang="apl"><span class="line"><span class="cl">      <span class="m">4</span> <span class="nv">caesar</span> <span class="s1">&#39;HELLO WORLDS&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">LIPPSD</span> <span class="nv">SVPHW</span>
</span></span><span class="line"><span class="cl">    
</span></span><span class="line"><span class="cl">      <span class="m">¯4</span> <span class="nv">caesar</span> <span class="s1">&#39;HELLO WORLDS&#39;</span> <span class="c1">⍝ negative shifts are okay</span>
</span></span><span class="line"><span class="cl"><span class="nv">DAHHKWSKNH</span> <span class="nv">O</span> 
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="m">0</span> <span class="nv">caesar</span> <span class="s1">&#39;HELLO WORLDS&#39;</span> <span class="c1">⍝ no shift is okay</span>
</span></span><span class="line"><span class="cl"><span class="nv">HELLO</span> <span class="nv">WORLDS</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="m">27</span> <span class="nv">caesar</span> <span class="s1">&#39;HELLO WORLDS&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nv">HELLO</span> <span class="nv">WORLDS</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="m">¯10</span> <span class="nv">caesar</span> <span class="s1">&#39;&#39;</span> <span class="c1">⍝ returns an empty vector</span>
</span></span></code></pre></div><h2 id="solution">Solution</h2>

<details>
  <summary><h3>See the solution</h3></summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-apl" data-lang="apl"><span class="line"><span class="cl"><span class="kt">{</span><span class="p">(</span><span class="bp">⍺</span><span class="o">⌽</span><span class="s1">&#39; &#39;</span><span class="o">,</span><span class="nf">⎕A</span><span class="p">)</span><span class="sr">[</span><span class="p">(</span><span class="s1">&#39; &#39;</span><span class="o">,</span><span class="nf">⎕A</span><span class="p">)</span> <span class="o">⍸</span><span class="bp">⍵</span><span class="sr">]</span><span class="kt">}</span>
</span></span></code></pre></div><p>Breaking it down:</p>
<ul>
<li><strong>1. Define the alphabet:</strong> <code>' ',⎕A</code> creates our alphabet consisting of a space followed by the uppercase letters A-Z.</li>
<li><strong>2. Find positions in the alphabet:</strong> <code>(' ',⎕A) ⍸⍵</code> uses the index-of (⍸) function to find the positions of each character in the input string (⍵) within our alphabet.</li>
<li><strong>3. Create the shifted alphabet:</strong> <code>⍺⌽' ',⎕A</code> rotates our alphabet by the shift amount (⍺). The rotate function (⌽) shifts the entire alphabet by the specified number of positions.</li>
<li><strong>4. Map to the new characters:</strong> Using the positions found in step 2, we index into the shifted alphabet: <code>(⍺⌽' ',⎕A)[...]</code> to get our encrypted message.</li>
</ul>
</details>

]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[An APL a day! - Put It In Reverse]]></title>
    <link href="https://rrampage.github.io/2025/02/21/an-apl-a-day-put-it-in-reverse/"/>
    <id>https://rrampage.github.io/2025/02/21/an-apl-a-day-put-it-in-reverse/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2025-02-21T16:13:02+05:30</published>
    <updated>2025-02-21T16:13:02+05:30</updated>
    
    <content type="html"><![CDATA[<p>Without much ado, today&rsquo;s problem - <a href="https://apl.quest/psets/2023.html?goto=P2_Put_It_In_Reverse">Put it in Reverse</a></p>
<p>The find function X⍷Y identifies the beginnings of occurrences of array X in array Y.</p>
<p>In this problem, you&rsquo;re asked to return a result that identifies the endings of occurrences of array X in array Y. To keep things simple, X and Y will be at most rank 1, meaning they&rsquo;ll either be vectors or scalars.</p>
<p>Write a function that:</p>
<ul>
<li>takes a scalar or vector left argument</li>
<li>takes a scalar or vector right argument</li>
<li>returns a Boolean result that is the same shape as the right argument where 1&rsquo;s mark the ends of occurrences of the left argument in the right argument</li>
</ul>
<h2 id="examples">Examples:</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-apl" data-lang="apl"><span class="line"><span class="cl">      <span class="s1">&#39;abra&#39;</span> <span class="nv">findEnd</span> <span class="s1">&#39;abracadabra&#39;</span>
</span></span><span class="line"><span class="cl"><span class="m">0</span> <span class="m">0</span> <span class="m">0</span> <span class="m">1</span> <span class="m">0</span> <span class="m">0</span> <span class="m">0</span> <span class="m">0</span> <span class="m">0</span> <span class="m">0</span> <span class="m">1</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="s1">&#39;issi&#39;</span> <span class="nv">findEnd</span> <span class="s1">&#39;Mississippi&#39;</span>
</span></span><span class="line"><span class="cl"><span class="m">0</span> <span class="m">0</span> <span class="m">0</span> <span class="m">0</span> <span class="m">1</span> <span class="m">0</span> <span class="m">0</span> <span class="m">1</span> <span class="m">0</span> <span class="m">0</span> <span class="m">0</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="s1">&#39;bb&#39;</span> <span class="nv">findEnd</span> <span class="s1">&#39;bbb bbb&#39;</span>
</span></span><span class="line"><span class="cl"><span class="m">0</span> <span class="m">1</span> <span class="m">1</span> <span class="m">0</span> <span class="m">0</span> <span class="m">1</span> <span class="m">1</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="p">(</span><span class="o">,</span><span class="m">42</span><span class="p">)</span> <span class="nv">findEnd</span> <span class="m">42</span>
</span></span><span class="line"><span class="cl"><span class="m">0</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="m">42</span> <span class="nv">findEnd</span> <span class="m">42</span>
</span></span><span class="line"><span class="cl"><span class="m">1</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="p">(</span><span class="o">,</span><span class="m">42</span><span class="p">)</span> <span class="nv">findEnd</span> <span class="o">,</span><span class="m">42</span>
</span></span><span class="line"><span class="cl"><span class="m">1</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="s1">&#39;are&#39;</span> <span class="s1">&#39;aquatic&#39;</span> <span class="nv">findEnd</span> <span class="s1">&#39;ducks&#39;</span> <span class="s1">&#39;are&#39;</span> <span class="s1">&#39;aquatic&#39;</span> <span class="s1">&#39;avians&#39;</span> 
</span></span><span class="line"><span class="cl"><span class="m">0</span> <span class="m">0</span> <span class="m">1</span> <span class="m">0</span>
</span></span></code></pre></div><h2 id="solution">Solution</h2>

<details>
  <summary>See the solution</summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-apl" data-lang="apl"><span class="line"><span class="cl"><span class="kt">{</span><span class="o">⌽</span><span class="p">(</span><span class="o">⌽</span><span class="bp">⍺</span><span class="p">)</span><span class="o">⍷⌽</span><span class="bp">⍵</span><span class="kt">}</span>
</span></span></code></pre></div><ul>
<li>We use ⍷ to find beginning of reversed array <code>⌽⍺</code> in <code>⌽⍵</code></li>
<li>We reverse this to get the ending of ⍺ in ⍵</li>
</ul>
<p>Taking example <code>'abra' {⌽(⌽⍺)⍷⌽⍵} 'abracadabra'</code></p>
<ul>
<li>For <code>'abra' ⍷ 'abracadabra'</code>, we get <code>1 0 0 0 0 0 0 1 0 0 0</code> as <code>'abra</code> matches twice at index 1 and 8</li>
<li>When we reverse &lsquo;abra&rsquo; and &lsquo;abracadabra&rsquo; and do a find, we get start index of &lsquo;arba&rsquo; in &lsquo;arbadacarba&rsquo; i.e <code>1 0 0 0 0 0 0 1 0 0 0</code></li>
<li>Finally, when we reverse this array, we get end index of &lsquo;abra&rsquo; in &lsquo;abracadabra&rsquo; i.e <code>0 0 0 1 0 0 0 0 0 0 1</code></li>
</ul>
</details>

]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[An APL a day! - Elimination Sort]]></title>
    <link href="https://rrampage.github.io/2025/02/20/an-apl-a-day-elimination-sort/"/>
    <id>https://rrampage.github.io/2025/02/20/an-apl-a-day-elimination-sort/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2025-02-20T22:38:33+05:30</published>
    <updated>2025-02-20T22:38:33+05:30</updated>
    
    <content type="html"><![CDATA[<p>I&rsquo;ve started dabbling with APL. It has been a lot of fun solving the <a href="https://challenge.dyalog.com/">current batch of challenges</a>. <a href="https://web.archive.org/web/20250210194607/https://challenge.dyalog.com/?goto=welcome">Archive</a>. I loved how each challenge focuses on a small set of operators and makes us use them in various (devious!) combinations to solve the problems. I&rsquo;m going through some of the older challenges to learn about more operators.</p>
<p>The past challenges can be found at <a href="https://apl.quest/">APL Quest</a>. Today, we&rsquo;ll be solving the first problem from the 2023 challenge. Use <a href="https://tryapl.org/">tryapl.org</a> as an online interactive REPL.</p>
<h1 id="elimination-sort"><a href="https://apl.quest/psets/2023.html?goto=P1_Elimination_Sort">Elimination Sort</a></h1>
<p>An &ldquo;Elimination Sort&rdquo; is a somewhat farcical sorting algorithm which starts with the leftmost element and keeps subsequent elements that are at least as large as the previous kept element, discarding all other elements. For example:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-apl" data-lang="apl"><span class="line"><span class="cl"><span class="nv">EliminationSort</span> <span class="m">1</span> <span class="m">3</span> <span class="m">7</span> <span class="m">3</span> <span class="m">5</span> <span class="m">8</span> <span class="m">5</span> <span class="m">8</span> <span class="m">1</span> <span class="m">6</span> <span class="m">1</span> <span class="m">8</span> <span class="m">1</span> <span class="m">10</span> <span class="m">8</span> <span class="m">4</span> <span class="m">3</span> <span class="m">4</span> <span class="m">1</span> <span class="m">4</span>
</span></span><span class="line"><span class="cl"><span class="m">1</span> <span class="m">3</span> <span class="m">7</span> <span class="m">8</span> <span class="m">8</span> <span class="m">8</span> <span class="m">10</span> 
</span></span></code></pre></div><p>Write a function that:</p>
<ul>
<li>takes a non-empty numeric vector right argument</li>
<li>returns an &ldquo;Elimination-sorted&rdquo; vector of the right argument</li>
</ul>
<p>Hint: The progressive-maxima idiomatic phrase ⌈, the greater or equal function ≥, and the replicate function / could be helpful in solving this problem.</p>
<h2 id="examples">Examples</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-apl" data-lang="apl"><span class="line"><span class="cl">      <span class="nv">EliminationSort</span> <span class="o">⍳</span><span class="m">10</span>
</span></span><span class="line"><span class="cl"><span class="m">1</span> <span class="m">2</span> <span class="m">3</span> <span class="m">4</span> <span class="m">5</span> <span class="m">6</span> <span class="m">7</span> <span class="m">8</span> <span class="m">9</span> <span class="m">10</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="nv">EliminationSort</span> <span class="m">2</span> <span class="m">1</span> <span class="m">4</span> <span class="m">3</span> <span class="m">6</span> <span class="m">5</span> <span class="m">8</span> <span class="m">7</span> <span class="m">10</span> <span class="m">9</span>
</span></span><span class="line"><span class="cl"><span class="m">2</span> <span class="m">4</span> <span class="m">6</span> <span class="m">8</span> <span class="m">10</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="nv">EliminationSort</span> <span class="m">1000</span> <span class="m">2500</span> <span class="m">1333</span> <span class="m">1969</span> <span class="m">3141</span> <span class="m">2345</span> <span class="m">3141</span> <span class="m">4291.9</span> <span class="m">4291.8</span> <span class="m">4292</span>
</span></span><span class="line"><span class="cl"><span class="m">1000</span> <span class="m">2500</span> <span class="m">3141</span> <span class="m">3141</span> <span class="m">4291.9</span> <span class="m">4292</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">      <span class="nv">EliminationSort</span> <span class="m">1</span> <span class="m">3</span> <span class="m">7</span> <span class="m">3</span> <span class="m">5</span> <span class="m">8</span> <span class="m">5</span> <span class="m">8</span> <span class="m">1</span> <span class="m">6</span> <span class="m">1</span> <span class="m">8</span> <span class="m">1</span> <span class="m">10</span> <span class="m">8</span> <span class="m">4</span> <span class="m">3</span> <span class="m">4</span> <span class="m">1</span> <span class="m">4</span>
</span></span><span class="line"><span class="cl"><span class="m">1</span> <span class="m">3</span> <span class="m">7</span> <span class="m">8</span> <span class="m">8</span> <span class="m">8</span> <span class="m">10</span>
</span></span></code></pre></div><h2 id="solution">Solution</h2>

<details>
  <summary>See the solution</summary>
  <div class="highlight"><pre tabindex="0" class="chroma"><code class="language-apl" data-lang="apl"><span class="line"><span class="cl"><span class="kt">{</span><span class="p">(</span><span class="bp">⍵</span><span class="o">=⌈</span><span class="na">\</span><span class="bp">⍵</span><span class="p">)</span><span class="na">/</span><span class="bp">⍵</span><span class="kt">}</span>
</span></span></code></pre></div><ul>
<li><code>⌈\⍵</code> to generate a <code>scan</code> of running maximum
<ul>
<li>e.g for <code>⌈\2 1 4 3 6 5 8 7 10 9</code> gives <code>2 2 4 4 6 6 8 8 10 10</code></li>
</ul>
</li>
<li>Compare with ⍵ to only get those indices where the actual element exists
<ul>
<li><code>{(⍵=⌈\⍵)} 2 1 4 3 6 5 8 7 10 9</code> gives <code>1 0 1 0 1 0 1 0 1 0</code></li>
</ul>
</li>
<li>Finally, <a href="https://aplwiki.com/wiki/Replicate">replicate</a> (/) to get only the required elements
<ul>
<li><code>{(⍵=⌈\⍵)/⍵} 2 1 4 3 6 5 8 7 10 9</code> gives <code>2 4 6 8 10</code></li>
</ul>
</li>
</ul>
</details>

]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Re-learning Lua]]></title>
    <link href="https://rrampage.github.io/2021/12/04/relearning-lua/"/>
    <id>https://rrampage.github.io/2021/12/04/relearning-lua/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2021-12-04T00:00:00+05:30</published>
    <updated>2021-12-04T00:00:00+05:30</updated>
    
    <content type="html"><![CDATA[<h2 id="lua---basics">Lua - Basics</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-lua" data-lang="lua"><span class="line"><span class="cl"><span class="kr">for</span> <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">1</span> <span class="kr">do</span> <span class="n">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="kr">end</span> <span class="c1">-- for loop with range and step. step if not given is assumed to be 1</span>
</span></span><span class="line"><span class="cl"><span class="c1">-- Tables are the soul of Lua. They double up as arrays and hashes</span>
</span></span><span class="line"><span class="cl"><span class="n">a</span> <span class="o">=</span> <span class="p">{}</span>
</span></span><span class="line"><span class="cl"><span class="n">b</span> <span class="o">=</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">3</span><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="c1">-- b[1] will return 1 as indexing for arrays is from 1</span>
</span></span><span class="line"><span class="cl"><span class="n">c</span> <span class="o">=</span> <span class="p">{[</span><span class="mi">0</span><span class="p">]</span><span class="o">=</span><span class="p">{</span><span class="mi">123</span><span class="p">,</span><span class="mi">3</span><span class="p">},[</span><span class="s2">&#34;a&#34;</span><span class="p">]</span><span class="o">=</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">3</span><span class="p">},</span><span class="n">v</span><span class="o">=</span><span class="p">{</span><span class="mi">2</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">7</span><span class="p">}}</span>
</span></span><span class="line"><span class="cl"><span class="c1">-- We can have a &#34;0&#34;th index by adding the 1st element as [0]=value</span>
</span></span><span class="line"><span class="cl"><span class="c1">-- Adding keys which are not valid identifiers in Lua needs to be done by wrapping key in []</span>
</span></span><span class="line"><span class="cl"><span class="c1">-- If a key is a valid identifier, we can access using `.` e.g c.a for above code vs c[0]</span>
</span></span><span class="line"><span class="cl"><span class="kr">for</span> <span class="n">k</span><span class="p">,</span><span class="n">v</span> <span class="kr">in</span> <span class="n">pairs</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="kr">do</span> <span class="n">print</span><span class="p">(</span><span class="n">type</span><span class="p">(</span><span class="n">k</span><span class="p">))</span> <span class="kr">end</span> <span class="c1">-- iterates through k/v in table and prints type of key</span>
</span></span></code></pre></div><h3 id="print-a-table-as-valid-lua-code">Print a table as valid Lua code</h3>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-lua" data-lang="lua"><span class="line"><span class="cl"><span class="kr">function</span> <span class="nf">printTable</span><span class="p">(</span><span class="n">tbl</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">		<span class="c1">-- Specify function vars as local else they become global</span>
</span></span><span class="line"><span class="cl">        <span class="kd">local</span> <span class="n">s</span> <span class="o">=</span> <span class="s2">&#34;{&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="kd">local</span> <span class="n">fst</span> <span class="o">=</span> <span class="kc">true</span>
</span></span><span class="line"><span class="cl">        <span class="kr">for</span> <span class="n">k</span><span class="p">,</span><span class="n">v</span> <span class="kr">in</span> <span class="n">pairs</span><span class="p">(</span><span class="n">tbl</span><span class="p">)</span> <span class="kr">do</span>
</span></span><span class="line"><span class="cl">        	    <span class="kd">local</span> <span class="n">tk</span> <span class="o">=</span> <span class="n">type</span><span class="p">(</span><span class="n">k</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">        	    <span class="kd">local</span> <span class="n">tv</span> <span class="o">=</span> <span class="n">type</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">                <span class="kr">if</span> <span class="ow">not</span> <span class="n">fst</span> <span class="kr">then</span>
</span></span><span class="line"><span class="cl">                        <span class="n">s</span> <span class="o">=</span> <span class="n">s</span> <span class="o">..</span> <span class="s2">&#34;,&#34;</span>
</span></span><span class="line"><span class="cl">                <span class="kr">else</span>
</span></span><span class="line"><span class="cl">                        <span class="n">fst</span> <span class="o">=</span> <span class="kc">false</span>
</span></span><span class="line"><span class="cl">                <span class="kr">end</span>
</span></span><span class="line"><span class="cl">                
</span></span><span class="line"><span class="cl">                <span class="kr">if</span> <span class="n">tk</span> <span class="o">==</span> <span class="s2">&#34;number&#34;</span> <span class="ow">or</span> <span class="n">tk</span> <span class="o">==</span> <span class="s2">&#34;boolean&#34;</span> <span class="kr">then</span>
</span></span><span class="line"><span class="cl">                        <span class="n">s</span> <span class="o">=</span> <span class="n">s</span> <span class="o">..</span> <span class="s2">&#34;[&#34;</span> <span class="o">..</span> <span class="n">tostring</span><span class="p">(</span><span class="n">k</span><span class="p">)</span> <span class="o">..</span> <span class="s2">&#34;]=&#34;</span>
</span></span><span class="line"><span class="cl">                <span class="kr">else</span>
</span></span><span class="line"><span class="cl">                        <span class="n">s</span> <span class="o">=</span> <span class="n">s</span> <span class="o">..</span> <span class="s1">&#39;[&#34;&#39;</span> <span class="o">..</span> <span class="n">k</span> <span class="o">..</span> <span class="s1">&#39;&#34;]=&#39;</span>
</span></span><span class="line"><span class="cl">                <span class="kr">end</span>
</span></span><span class="line"><span class="cl">                
</span></span><span class="line"><span class="cl">                <span class="kr">if</span> <span class="n">tv</span> <span class="o">==</span> <span class="s2">&#34;table&#34;</span> <span class="kr">then</span>
</span></span><span class="line"><span class="cl">                    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span> <span class="o">..</span> <span class="n">printTable</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">                <span class="kr">elseif</span> <span class="n">tv</span> <span class="o">==</span> <span class="s2">&#34;number&#34;</span> <span class="ow">or</span> <span class="n">tv</span> <span class="o">==</span> <span class="s2">&#34;boolean&#34;</span> <span class="kr">then</span>
</span></span><span class="line"><span class="cl">                    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span> <span class="o">..</span> <span class="n">tostring</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">                <span class="kr">elseif</span> <span class="n">tv</span> <span class="o">==</span> <span class="s2">&#34;string&#34;</span> <span class="kr">then</span>
</span></span><span class="line"><span class="cl">                    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span> <span class="o">..</span> <span class="s1">&#39;&#34;&#39;</span> <span class="o">..</span> <span class="n">v</span> <span class="o">..</span> <span class="s1">&#39;&#34;&#39;</span>
</span></span><span class="line"><span class="cl">                <span class="kr">else</span>
</span></span><span class="line"><span class="cl">                	<span class="n">s</span> <span class="o">=</span> <span class="n">s</span> <span class="o">..</span> <span class="n">vt</span>
</span></span><span class="line"><span class="cl">                <span class="kr">end</span>
</span></span><span class="line"><span class="cl">        <span class="kr">end</span>
</span></span><span class="line"><span class="cl">        <span class="n">s</span> <span class="o">=</span> <span class="n">s</span> <span class="o">..</span> <span class="s2">&#34;}&#34;</span>
</span></span><span class="line"><span class="cl">        <span class="kr">return</span> <span class="n">s</span>
</span></span><span class="line"><span class="cl"><span class="kr">end</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">sv</span> <span class="o">=</span> <span class="n">printTable</span><span class="p">({[</span><span class="mi">0</span><span class="p">]</span><span class="o">=</span><span class="p">{</span><span class="mi">123</span><span class="p">,</span><span class="mi">3</span><span class="p">},[</span><span class="s2">&#34;a&#34;</span><span class="p">]</span><span class="o">=</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">3</span><span class="p">},</span><span class="n">v</span><span class="o">=</span><span class="p">{</span><span class="mi">2</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">7</span><span class="p">},[</span><span class="kc">true</span><span class="p">]</span><span class="o">=</span><span class="mi">123</span><span class="p">})</span>
</span></span><span class="line"><span class="cl"><span class="n">print</span><span class="p">(</span><span class="n">sv</span><span class="p">)</span>
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-lua" data-lang="lua"><span class="line"><span class="cl"><span class="c1">-- posts.lua (saved table) can be read from another lua file as posts=require(&#34;posts&#34;)</span>
</span></span><span class="line"><span class="cl"><span class="kr">return</span> <span class="p">{[</span><span class="mi">0</span><span class="p">]</span><span class="o">=</span><span class="p">{[</span><span class="mi">1</span><span class="p">]</span><span class="o">=</span><span class="mi">123</span><span class="p">,[</span><span class="mi">2</span><span class="p">]</span><span class="o">=</span><span class="mi">3</span><span class="p">},[</span><span class="s2">&#34;v&#34;</span><span class="p">]</span><span class="o">=</span><span class="p">{[</span><span class="mi">1</span><span class="p">]</span><span class="o">=</span><span class="mi">2</span><span class="p">,[</span><span class="mi">2</span><span class="p">]</span><span class="o">=</span><span class="mi">6</span><span class="p">,[</span><span class="mi">3</span><span class="p">]</span><span class="o">=</span><span class="mi">7</span><span class="p">},[</span><span class="s2">&#34;a&#34;</span><span class="p">]</span><span class="o">=</span><span class="p">{[</span><span class="mi">1</span><span class="p">]</span><span class="o">=</span><span class="mi">1</span><span class="p">,[</span><span class="mi">2</span><span class="p">]</span><span class="o">=</span><span class="mi">2</span><span class="p">,[</span><span class="mi">3</span><span class="p">]</span><span class="o">=</span><span class="mi">3</span><span class="p">},[</span><span class="kc">true</span><span class="p">]</span><span class="o">=</span><span class="mi">123</span><span class="p">}</span>
</span></span></code></pre></div>]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[S3 Game]]></title>
    <link href="https://rrampage.github.io/2020/06/04/s3-game/"/>
    <id>https://rrampage.github.io/2020/06/04/s3-game/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2020-06-04T16:09:34+00:00</published>
    <updated>2020-06-04T16:09:34+00:00</updated>
    
    <content type="html"><![CDATA[<h2 id="introduction">Introduction</h2>
<p>The best way to learn a skill is through deliberate practice!
<a href="http://s3game-level1.s3-website.us-east-2.amazonaws.com/">S3 Game</a> is an awesome game made by <a href="https://www.linkedin.com/in/vpantyukhin/">Vasily Pantyukhin</a> which walks you through various features of S3 from beginner to fairly advanced.</p>
<h3 id="what-you-will-need">What you will need:</h3>
<ul>
<li>A browser</li>
<li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">aws cli</a></li>
</ul>
<h3 id="click"><strong>CLICK <a href="http://s3game-level1.s3-website.us-east-2.amazonaws.com/">HERE</a> TO PLAY!</strong></h3>
<p>Each level consists of finding a &ldquo;treasure&rdquo; object and getting to the next level using the secret code in the &ldquo;treasure&rdquo;.</p>
<p>Go ahead and play this game. Each level contains multiple hints with links to S3 API documentation.</p>
<p>Below is a walk through you can refer to if you are stuck on any level. Make sure that you try for a bit before seeing here :)</p>
<h2 id="walk-through-spoilers">Walk through (Spoilers)</h2>

<details>
  <summary>See the solution</summary>
  <h3 id="level-1"><a href="http://s3game-level1.s3-website.us-east-2.amazonaws.com/level1.html">Level 1</a></h3>
<h4 id="solution">Solution:</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># List the objects in bucket</span>
</span></span><span class="line"><span class="cl">aws s3 ls s3://s3game-level1
</span></span></code></pre></div><p>Visit the <a href="http://s3game-level1.s3-website.us-east-2.amazonaws.com/treasure1">treasure object</a></p>
<h3 id="level-2"><a href="https://s3game-level2.s3.us-east-2.amazonaws.com/level2-748l6b6xwzl6.html">Level 2</a></h3>
<h4 id="solution-1">Solution:</h4>
<p>Just get the treasure2 object either using browser or aws s3 : <a href="https://s3game-level2.s3.us-east-2.amazonaws.com/treasure2">https://s3game-level2.s3.us-east-2.amazonaws.com/treasure2</a>
Make sure to save the Access and Secret key somewhere</p>
<h3 id="level-3"><a href="https://s3game-level3.s3.us-east-2.amazonaws.com/level3-76qp7mlpzyg1.html">Level 3</a></h3>
<p>Create an AWS profile &ldquo;tmp&rdquo; with the access and secret key obtained from previous level. You will need to use this for almost every level from here on.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">aws configure --profile tmp
</span></span><span class="line"><span class="cl">&gt; AWS Access Key ID
</span></span><span class="line"><span class="cl">&gt; AWS Secret Access Key
</span></span><span class="line"><span class="cl">&gt; Default region name - us-east-2
</span></span></code></pre></div><h4 id="solution-2">Solution:</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">aws s3 ls s3://s3game-level3 --profile tmp
</span></span><span class="line"><span class="cl">aws s3 cp s3://s3game-level3/treasure3_has_no_secret_code . --profile tmp
</span></span><span class="line"><span class="cl">cat treasure3_has_no_secret_code
</span></span><span class="line"><span class="cl"><span class="c1"># The object data itself does not have the secret code. It is present in the metadata</span>
</span></span><span class="line"><span class="cl">aws s3api head-object --bucket s3game-level3 --key treasure3_has_no_secret_code --profile tmp
</span></span></code></pre></div><h3 id="level-4"><a href="https://s3game-level4-k73045aztqln.s3.us-east-2.amazonaws.com/level4.html">Level 4</a></h3>
<ul>
<li><a href="https://s3game-level4-k73045aztqln.s3.us-east-2.amazonaws.com/level4-hint2.html">Hint</a></li>
</ul>
<h4 id="solution-3">Solution:</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># List the bucket ..</span>
</span></span><span class="line"><span class="cl"><span class="c1"># get the file</span>
</span></span><span class="line"><span class="cl">aws s3 cp s3://s3game-level4-k73045aztqln/treasure4_also_has_no_secret_code . --profile tmp
</span></span><span class="line"><span class="cl"><span class="c1"># looks like the data is empty</span>
</span></span><span class="line"><span class="cl">aws s3api head-object --bucket s3game-level4-k73045aztqln --profile tmp --key treasure4_also_has_no_secret_code
</span></span><span class="line"><span class="cl"><span class="c1"># ... so is the metadata. Let&#39;s try object tags as mentioned in hint</span>
</span></span><span class="line"><span class="cl">aws s3api get-object-tagging --bucket s3game-level4-k73045aztqln --profile tmp --key treasure4_also_has_no_secret_code
</span></span></code></pre></div><h4 id="takeaway">Takeaway:</h4>
<blockquote>
<p>Object in S3, including its metadata, is immutable. When you edit object&rsquo;s metadata, you are actually overwriting the object with a copy of itself, with its metadata modified.
In contrast, tags are subresources. They are managed separately and can be modified without modifying the object itself.</p></blockquote>
<h3 id="level-5"><a href="https://s3game-level5-8v95e5rv7z4i.s3.us-east-2.amazonaws.com/level5.html">Level 5</a></h3>
<ul>
<li><a href="https://s3game-level5-8v95e5rv7z4i.s3.us-east-2.amazonaws.com/level5-hint2.html">Hint</a></li>
<li><a href="https://s3game-level5-8v95e5rv7z4i.s3.us-east-2.amazonaws.com/level5-hint3.html">Hint</a></li>
<li><a href="https://s3game-level5-8v95e5rv7z4i.s3.us-east-2.amazonaws.com/level5-hint4.html">Hint</a></li>
</ul>
<h4 id="solution-4">Solution</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># We are listing all versions of objects as the hint says that the object is not present in its current version</span>
</span></span><span class="line"><span class="cl">aws s3api list-object-versions --bucket s3game-level5-8v95e5rv7z4i --profile tmp
</span></span><span class="line"><span class="cl"><span class="c1"># Get the specific version of treasure5_is_deleted using version-id from previous call</span>
</span></span><span class="line"><span class="cl">aws s3api get-object --bucket <span class="s1">&#39;s3game-level5-8v95e5rv7z4i&#39;</span> --key treasure5_is_deleted --version-id <span class="s1">&#39;344PQOyFqocF0TI66MbLynNNdQqHfBz3&#39;</span> --profile tmp treasure5_is_deleted
</span></span></code></pre></div><h4 id="takeaway-1">Takeaway</h4>
<blockquote>
<p>S3 versioning keeps multiple variants of an object in the same bucket.
If you enable versioning for a bucket, S3 automatically generates a unique version ID for the object being stored.
In one bucket you can have two objects with the same key, but different version IDs.
Check if versioning is enabled using: <code>aws s3api get-bucket-versioning --bucket my-bucket</code></p></blockquote>
<h3 id="level-6"><a href="https://s3game-level6-vjv45x1gux81.s3.us-east-2.amazonaws.com/level6.html">Level 6</a></h3>
<ul>
<li><a href="https://s3game-level6-vjv45x1gux81.s3.us-east-2.amazonaws.com/level6-hint2.html">Hint</a></li>
</ul>
<h4 id="solution-5">Solution</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># We need to get a gzipped object using S3 select</span>
</span></span><span class="line"><span class="cl">aws s3api list-objects --bucket s3game-level6-vjv45x1gux81 --profile tmp
</span></span><span class="line"><span class="cl"><span class="c1"># Now, do the select on s3select.csv.gz</span>
</span></span><span class="line"><span class="cl">aws s3api <span class="k">select</span>-object-content --bucket s3game-level6-vjv45x1gux81 --key s3select.csv.gz --expression <span class="s2">&#34;SELECT s.Answer FROM s3object s WHERE Category = &#39;TREASURE&#39;&#34;</span> --expression-type sql --input-serialization <span class="s1">&#39;{&#34;CSV&#34;: {&#34;FileHeaderInfo&#34;: &#34;USE&#34;, &#34;FieldDelimiter&#34;: &#34;;&#34;}, &#34;CompressionType&#34;: &#34;GZIP&#34;}&#39;</span> --output-serialization <span class="s1">&#39;{&#34;CSV&#34;: {}}&#39;</span> --profile tmp treasure6
</span></span></code></pre></div><h3 id="level-7"><a href="https://s3game-level7-zhovpo4j8588.s3.us-east-2.amazonaws.com/level7.html">Level 7</a></h3>
<ul>
<li><a href="https://s3game-level7-zhovpo4j8588.s3.us-east-2.amazonaws.com/level7-hint2.html">Hint</a></li>
</ul>
<h4 id="solution-6">Solution</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Get &#39;somethingstrange&#39; from the bucket</span>
</span></span><span class="line"><span class="cl">aws s3api get-object --bucket s3game-level7-zhovpo4j8588 --key somethingstrange --profile tmp t7
</span></span><span class="line"><span class="cl">cat t7
</span></span><span class="line"><span class="cl"><span class="c1"># Visit the pre-signed URL in the file to get URL for next level</span>
</span></span></code></pre></div><h4 id="takeaway-2">Takeaway</h4>
<p>Pre-signed URLs are a powerful feature of S3. From the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html">docs</a>:</p>
<blockquote>
<p>A presigned URL is generated by an AWS user who has access to the object. The generated URL is then given to the unauthorized user. The presigned URL can be entered in a browser or used by a program or HTML webpage. The credentials used by the presigned URL are those of the AWS user who generated the URL.</p>
<p>A presigned URL remains valid for a <strong>limited period of time</strong> which is specified when the URL is generated.</p></blockquote>
<h3 id="level-8"><a href="https://s3game-level8-v6g8tp7ra2ld.s3.us-east-2.amazonaws.com/level8.html">Level 8</a></h3>
<h4 id="solution-7">Solution</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># List objects</span>
</span></span><span class="line"><span class="cl">aws s3api list-objects --bucket s3game-level8-v6g8tp7ra2ld --profile tmp
</span></span><span class="line"><span class="cl"><span class="c1"># Visit the treasure file using the cloudfront URL</span>
</span></span><span class="line"><span class="cl">curl <span class="s1">&#39;https://d2suiw06vujwz3.cloudfront.net/treasure8_CDN&#39;</span>
</span></span></code></pre></div><h4 id="takeaway-3">Takeaway</h4>
<ul>
<li>You can easily create a Cloudfront distribution backed by an S3 bucket</li>
<li>In such cases, you can restrict public access for the objects in the bucket as they can be accessed using Cloudfront</li>
<li>Ensure that your bucket does not allow unprivileged users to list all objects in the bucket</li>
</ul>
<h3 id="level-9"><a href="https://s3game-level9-781xtls2quvy.s3.us-east-2.amazonaws.com/level9.html">Level 9</a></h3>
<ul>
<li><a href="https://s3game-level9-781xtls2quvy.s3.us-east-2.amazonaws.com/level9-hint2.html">Hint</a></li>
</ul>
<p>The bucket has a policy which checks that any request for &ldquo;arn:aws:s3:::s3game-level9-781xtls2quvy/treasure9_referer&rdquo; has the referer string &ldquo;<a href="http://s3game.treasure">http://s3game.treasure</a>&rdquo;</p>
<h4 id="solution-8">Solution</h4>
<p>All we need to do is curl with a &ndash;refer given in policy
curl &lsquo;<a href="https://s3game-level9-781xtls2quvy.s3.us-east-2.amazonaws.com/treasure9_referer'">https://s3game-level9-781xtls2quvy.s3.us-east-2.amazonaws.com/treasure9_referer'</a> &ndash;refer &lsquo;<a href="http://s3game.treasure">http://s3game.treasure</a>&rsquo;</p>
<h3 id="level-10"><a href="https://s3game-level10-gac6tf83erp6.s3.us-east-2.amazonaws.com/level10.html">Level 10</a></h3>
<p>Here, we need to fetch an object which is in Infrequent Access storage.</p>
<h4 id="solution-9">Solution</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># We can use the powerful query param of aws cli to just fetch those objects which are in infrequent access storgae</span>
</span></span><span class="line"><span class="cl">aws s3api list-objects --bucket s3game-level10-gac6tf83erp6 --query <span class="s1">&#39;Contents[?StorageClass == `STANDARD_IA`]&#39;</span> --profile tmp
</span></span></code></pre></div><h4 id="takeaway-4">Takeaway</h4>
<blockquote>
<p>Amazon S3 offers a range of storage classes designed for different use cases:</p>
<ul>
<li>Standard for general-purpose storage of frequently accessed data</li>
<li>Intelligent-Tiering for data with unknown or changing access patterns</li>
<li>Standard-Infrequent Access (Standard-IA) and One Zone-Infrequent Access (One Zone-IA) for long-lived, but less frequently accessed data</li>
<li>Glacier and Glacier Deep Archive for long-term archive</li>
</ul></blockquote>
<h3 id="level-11"><a href="https://s3game-level11-djq30a807iyq.s3.us-east-2.amazonaws.com/level11.html">Level 11</a></h3>
<p>Here we need to fetch an object which has been encrypted using client side encryption and uploaded to S3. This means that we can not fetch the object unless we have the encryption key.</p>
<h4 id="solution-10">Solution</h4>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># The encryption key is given in the hint</span>
</span></span><span class="line"><span class="cl">aws s3 cp --sse-c <span class="s1">&#39;AES256&#39;</span> --sse-c-key <span class="s1">&#39;UkXp2s5v8y/B?E(H+MbPeShVmYq3t6w9&#39;</span> <span class="s1">&#39;s3://s3game-level11-djq30a807iyq/treasure11_encryption&#39;</span> --profile tmp .
</span></span><span class="line"><span class="cl"><span class="c1"># Alternate way using aws s3api. Here we also need to give md5 of encryption key as additional integrity check</span>
</span></span><span class="line"><span class="cl">aws s3api get-object --bucket s3game-level11-djq30a807iyq --key treasure11_encryption --sse-customer-key <span class="s1">&#39;UkXp2s5v8y/B?E(H+MbPeShVmYq3t6w9&#39;</span> --sse-customer-algorithm AES256 --profile tmp treasure11_encryption
</span></span></code></pre></div><h4 id="takeaway-5">Takeaway</h4>
<p>S3 supports both <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html">server side</a> and <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingClientSideEncryption.html">client side encryption</a>.</p>
<h3 id="victory---level-12">VICTORY! - <a href="https://s3game-level12-bk0m5ax5n92o.s3.us-east-2.amazonaws.com/level12.html">Level 12</a></h3>
<p>Congrats! You have cleared the game!</p>
</details>

]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[NPM and Node tips to make your dev machine (slightly) safer]]></title>
    <link href="https://rrampage.github.io/2020/05/28/npm-and-node-tips-to-make-your-dev-machine-slightly-safer/"/>
    <id>https://rrampage.github.io/2020/05/28/npm-and-node-tips-to-make-your-dev-machine-slightly-safer/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2020-05-28T10:42:07+00:00</published>
    <updated>2020-05-28T10:42:07+00:00</updated>
    
    <content type="html"><![CDATA[<p>NPM is used as a convenient cross-platform package manager for <a href="https://hackernoon.com/the-best-of-npm-install-g-9ab9d749eeb1">a lot of developer tools</a>. For many tools, the defacto way to install is <strong><code>npm install -g $TOOL</code></strong>. But installing anything via npm allows it to run untrusted code on your machine.</p>
<p>Here are a few tips to minimize the risk:</p>
<h2 id="1-never-run-npm-as-sudoroot">1. NEVER run npm as sudo/root</h2>
<p><a href="https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally">Node&rsquo;s official documentation</a> recommends not installing global packages as sudo/root. If you have already installed node through <code>nvm</code> ignore this step. If you use a system installed <code>node</code> e.g using Ubuntu&rsquo;s apt-get, read through <strong><a href="https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md">this guide</a></strong> for Linux/Mac or <a href="https://github.com/glenpike/npm-g_nosudo">npm-g-nosudo</a> which is a shell script for Linux.</p>
<h3 id="if-you-are-lazy-like-me-heres-a-summary-from-the-linked-guide">If you are lazy (like me), here&rsquo;s a summary from the linked guide:</h3>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">mkdir -p <span class="s2">&#34;</span><span class="si">${</span><span class="nv">HOME</span><span class="si">}</span><span class="s2">/.npm-packages&#34;</span> <span class="o">&amp;&amp;</span> npm config <span class="nb">set</span> prefix <span class="s2">&#34;</span><span class="si">${</span><span class="nv">HOME</span><span class="si">}</span><span class="s2">/.npm-packages&#34;</span>
</span></span></code></pre></div><p>Add this to your <code>.bashrc</code> or <code>.zshrc</code>:</p>
<pre tabindex="0"><code>NPM_PACKAGES=&#34;${HOME}/.npm-packages&#34;
export PATH=&#34;$PATH:$NPM_PACKAGES/bin&#34;
# Preserve MANPATH if you already defined it somewhere in your config.
# Otherwise, fall back to `manpath` so we can inherit from `/etc/manpath`.
export MANPATH=&#34;${MANPATH-$(manpath)}:$NPM_PACKAGES/share/man&#34;
</code></pre><h2 id="2-installuse-node-using-nvm-or-asdf">2. Install/Use node using <code>nvm</code> or <code>asdf</code></h2>
<p><a href="https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally">Node&rsquo;s official documentation</a> recommends installing node as an unprivileged user using a node version manager.</p>
<p>Here are the steps:</p>
<ul>
<li>Install <a href="https://github.com/nvm-sh/nvm">nvm</a>. This does not work for Windows, use <a href="https://github.com/coreybutler/nvm-windows">nvm-windows</a> which is a totally different project from nvm.
<ul>
<li>Unfortunately, <code>nvm</code> suffers from the curl pipe to bash install as its main way to install.</li>
<li>If you have git installed on your machine, you can also directly clone it using the following steps:
<ul>
<li><code>cd &quot;$HOME&quot; &amp;&amp; git clone https://github.com/nvm-sh/nvm.git .nvm</code></li>
<li><code>cd &quot;$HOME/.nvm&quot; &amp;&amp; git checkout v0.35.3 &amp;&amp; . nvm.sh</code></li>
<li>Add to your .bashrc or .zshrc:</li>
</ul>
</li>
</ul>
</li>
</ul>
<pre tabindex="0"><code>export NVM_DIR=&#34;$HOME/.nvm&#34;
[ -s &#34;$NVM_DIR/nvm.sh&#34; ] &amp;&amp; \. &#34;$NVM_DIR/nvm.sh&#34;  # This loads nvm
[ -s &#34;$NVM_DIR/bash_completion&#34; ] &amp;&amp; \. &#34;$NVM_DIR/bash_completion&#34;  # This loads nvm bash_completion
</code></pre><ul>
<li><code>nvm install --lts</code> or whichever version of node you need.</li>
<li><code>nvm use node</code></li>
<li>To use a node version by default, <code>echo &quot;lts/*&quot; &gt; &quot;$HOME/.nvmrc&quot;</code></li>
</ul>
<h2 id="3-list-all-your-globally-installed-npm-packages-and-remove-any-unnecessary-ones">3. List all your globally installed npm packages and remove any unnecessary ones</h2>
<p>Listing global packages is done with <strong><code>npm ls -g --depth 0</code></strong>
Remove any unnecessary packages with <strong><code>npm uninstall -g $TOOL</code></strong>
You can check your shell history/scripts folders to see if you actually use many of the global packages.</p>
<h2 id="4-audit-your-packages">4. Audit your packages</h2>
<p>Run <strong><code>npm audit</code></strong> in your project regularly to see if <a href="https://docs.npmjs.com/auditing-package-dependencies-for-security-vulnerabilities">any dependencies are vulnerable</a>. This only works for your development projects, not global packages.</p>
<h3 id="a-hacky-way-to-npm-audit--global-packages"><a href="https://stackoverflow.com/a/53619858">A (hacky) way</a> to <code>npm audit</code>  global packages:</h3>
<ul>
<li>Run <code>npm</code>. The last line will show the folder of the global npm packages e.g <code>$HOME/.npm-packages/lib/node_modules/npm</code></li>
<li>Go to <code>$HOME/.npm-packages/lib</code> and run <code>npm init -y</code> and then run <code>npm i --package-lock-only</code>. These steps are required as <code>npm audit</code> checks for <code>package.json</code> and <code>package-lock.json</code></li>
<li>Now run <code>npm audit</code>. Remove any dependencies which have high or too many moderate vulnerabilities. These could either be malicious or unmaintained tools.</li>
<li>Remove the <code>package.json</code> and <code>package-lock.json</code> after the audit</li>
</ul>
<h2 id="5-use-npx-to-run-executables">5. Use <code>npx</code> to run executables</h2>
<p>Many times, it is not necessary to have a tool installed globally e.g <code>create-react-app</code>. Node 6+ comes with <code>npx</code> which allows you to temporarily download and run scripts. The benefits of using <code>npx</code> over <code>npm install -g</code> are beautifully explained in <a href="https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b">this post</a>.</p>
<p>A gist of the article:</p>
<blockquote>
<p>Calling npx <command> when <command> isn’t already in your $PATH will automatically install a package with that name from the npm registry for you, and invoke it. When it’s done, the installed package won’t be anywhere in your globals, so you won’t have to worry about pollution in the long-term.</p></blockquote>
<blockquote>
<p>This feature is ideal for things like generators, too. Tools like yeoman or create-react-app only ever get called once in a blue moon. <strong>By the time you run them again, they’ll already be far out of date, so you end up having to run an install every time you want to use them anyway.</strong></p></blockquote>
<h2 id="bonus--use-deno-for-developer-tools">Bonus : Use Deno for developer tools</h2>
<p>I think a project like <a href="https://deno.land/">deno</a> with good sandbox capabilities and <a href="https://deno.land/manual/getting_started/permissions">limited permisisons</a> is the best choice for a lot of developer tools currently made using Node. Read <a href="https://www.jeremymorgan.com/blog/programming/what-is-deno/">this post</a> for more details on why everyone is talking about Deno.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Does this solve all security issues of <code>node</code>/<code>npm</code> on your machine? No! There are a <a href="https://blog.npmjs.org/post/180565383195/details-about-the-event-stream-incident">lot</a> <a href="https://blog.npmjs.org/post/185397814280/plot-to-steal-cryptocurrency-foiled-by-the-npm">of</a> <a href="https://blog.npmjs.org/post/175824896885/incident-report-npm-inc-operations-incident-of">ways</a> in which a malicious attacker can compromise your machine/project. This only prevents a bad npm tool from getting root access and removes globally installed npm tools with known insecure dependencies.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Webhook to auto-deploy on git push to Github]]></title>
    <link href="https://rrampage.github.io/2020/05/25/webhook-to-auto-deploy-on-git-push-to-github/"/>
    <id>https://rrampage.github.io/2020/05/25/webhook-to-auto-deploy-on-git-push-to-github/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2020-05-25T17:32:54+00:00</published>
    <updated>2020-05-25T17:32:54+00:00</updated>
    
    <content type="html"><![CDATA[<h2 id="what-is-a-webhook">What is a webhook?</h2>
<p>A <a href="https://en.wikipedia.org/wiki/Webhook">webhook</a> is an endpoint on your server which allows you to execute a particular task. Webhooks are usually triggered by some event. A good use-case for a webhook is running tests on a dedicated test server or deploying your latest <code>master</code> branch to staging/production.</p>
<p><a href="https://developer.github.com/webhooks/">Github</a> / <a href="https://docs.gitlab.com/ee/user/project/integrations/webhooks.html">Gitlab</a> / Bitbucket allow you to specify a webhook URL in your repository settings. Github triggers the webhook which sends the event data on every push.</p>
<h2 id="webhook-server"><a href="https://github.com/adnanh/webhook">Webhook</a> server</h2>
<p><a href="https://github.com/adnanh/webhook">Webhook</a> is a very useful golang project which runs any script you specify when a particular endpoint is hit.</p>
<p>Download and extract the binary for your operating system from the <a href="https://github.com/adnanh/webhook/releases">releases page</a>. For Linux, it is <a href="https://github.com/adnanh/webhook/releases/download/2.7.0/webhook-linux-amd64.tar.gz">here</a>.</p>
<p>The program takes as config a <strong><code>hooks.json</code></strong> file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">[</span>
</span></span><span class="line"><span class="cl">  <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;id&#34;</span><span class="p">:</span> <span class="s2">&#34;hello-world&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;execute-command&#34;</span><span class="p">:</span> <span class="s2">&#34;/home/user/scripts/hello.sh&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;command-working-directory&#34;</span><span class="p">:</span> <span class="s2">&#34;/home/user/webhook&#34;</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">]</span>
</span></span></code></pre></div><p>Replace <code>user</code> with the username of your linux user.</p>
<p>The <code>hello.sh</code> script.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="cp">#!/bin/bash
</span></span></span><span class="line"><span class="cl"><span class="cp"></span><span class="nb">echo</span> <span class="s1">&#39;Hello!&#39;</span>
</span></span></code></pre></div><p>Make the script executable by running <strong><code>chmod +x hello.sh</code></strong></p>
<p>Start webhook server as <strong><code>webhook -hooks hooks.json -hotreload -logfile webhooks.log</code></strong>. The server will run on port 9000 by default. You can check if everything is working by running <strong><code>curl http://localhost:9000/hooks/hello-world</code></strong>. This will print &ldquo;Hello!&rdquo; in the log file.</p>
<h2 id="deploy-script">Deploy script</h2>
<p>For the purpose of this post, I&rsquo;ll assume the script is called <strong><code>deploy</code></strong> and is at location <code>/home/user/scripts/deploy</code>. This script will vary depending on your tech stack and the complexity of your CI process.</p>
<p>A simple example <code>deploy</code> script:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="cp">#!/bin/bash
</span></span></span><span class="line"><span class="cl"><span class="cp"></span><span class="c1"># If you have a build server which creates binary/jar/artifact</span>
</span></span><span class="line"><span class="cl">wget <span class="s1">&#39;ARTIFACT_URL&#39;</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Else, git pull and build on the server itself</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Assuming this script stops old instance of your code and starts a new instance with latest artifact </span>
</span></span><span class="line"><span class="cl">restart-service.sh
</span></span></code></pre></div><h3 id="configuration-to-run-deploy-script">Configuration to run deploy script</h3>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-json" data-lang="json"><span class="line"><span class="cl"><span class="p">[</span>
</span></span><span class="line"><span class="cl">  <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;id&#34;</span><span class="p">:</span> <span class="s2">&#34;deploy-from-git&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;execute-command&#34;</span><span class="p">:</span> <span class="s2">&#34;/home/user/scripts/deploy&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;command-working-directory&#34;</span><span class="p">:</span> <span class="s2">&#34;/home/user/scripts&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="nt">&#34;trigger-rule&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="p">{</span>
</span></span><span class="line"><span class="cl">      <span class="nt">&#34;and&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">      <span class="p">[</span>
</span></span><span class="line"><span class="cl">        <span class="p">{</span>
</span></span><span class="line"><span class="cl">          <span class="nt">&#34;match&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">          <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;payload-hash-sha1&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;secret&#34;</span><span class="p">:</span> <span class="s2">&#34;MyTotallySecretString&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;parameter&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="p">{</span>
</span></span><span class="line"><span class="cl">              <span class="nt">&#34;source&#34;</span><span class="p">:</span> <span class="s2">&#34;header&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">              <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;X-Hub-Signature&#34;</span>
</span></span><span class="line"><span class="cl">            <span class="p">}</span>
</span></span><span class="line"><span class="cl">          <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="p">},</span>
</span></span><span class="line"><span class="cl">        <span class="p">{</span>
</span></span><span class="line"><span class="cl">          <span class="nt">&#34;match&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">          <span class="p">{</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;type&#34;</span><span class="p">:</span> <span class="s2">&#34;value&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;value&#34;</span><span class="p">:</span> <span class="s2">&#34;refs/heads/master&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">            <span class="nt">&#34;parameter&#34;</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">            <span class="p">{</span>
</span></span><span class="line"><span class="cl">              <span class="nt">&#34;source&#34;</span><span class="p">:</span> <span class="s2">&#34;payload&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">              <span class="nt">&#34;name&#34;</span><span class="p">:</span> <span class="s2">&#34;ref&#34;</span>
</span></span><span class="line"><span class="cl">            <span class="p">}</span>
</span></span><span class="line"><span class="cl">          <span class="p">}</span>
</span></span><span class="line"><span class="cl">        <span class="p">}</span>
</span></span><span class="line"><span class="cl">      <span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">]</span>
</span></span></code></pre></div><p>The <strong>trigger-rule</strong> in config above will ensure that the script is only triggered when header from Github request contains <strong>&ldquo;X-Hub-Signature&rdquo;</strong> with a secret string and the push has occured in master branch.</p>
<p>Make sure that the secret string (&ldquo;secret&rdquo; : &ldquo;MyTotallySecretString&rdquo;) is randomly generated. This secret will need to be entered in Github settings as well.</p>
<p>For Gitlab and Bitbucket, example hook config can be found on repo page <a href="https://github.com/adnanh/webhook/blob/master/docs/Hook-Examples.md">here</a></p>
<h2 id="expose-your-webhook-server-safely-to-the-internet">Expose your webhook server safely to the internet</h2>
<p>There are 2 ways of exposing the webhook server to github:</p>
<ul>
<li>Proxy using Nginx</li>
<li>Via a tunnel e.g by downloading <a href="https://ngrok.com/product">ngrok</a> and then running <code>ngrok http 9000</code></li>
</ul>
<h3 id="nginx-configuration">Nginx configuration</h3>
<p>Preferably use HTTPS for your domain with Nginx. A good tutorial <a href="https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04">here</a>.</p>
<p>Example Nginx config (HTTPS):</p>
<pre tabindex="0"><code>upstream webhook {
    server localhost:9000;
}

server {
	listen 443 ssl http2;
        server_name YOUR.DOMAIN.COM;
	ssl_certificate YOUR_CERT_CHAIN; # e.g /etc/letsencrypt/live/DOMAIN/fullchain.pem;
	ssl_certificate_key YOUR_CERT_KEY; # e.g /etc/letsencrypt/live/DOMAIN/privkey.pem;
	include /etc/nginx/options-ssl-nginx.conf;
	ssl_dhparam /etc/nginx/ssl-dhparams.pem;
        location ~ ^/hooks/(.+)$ {
		proxy_pass http://webhook;
	}
}
</code></pre><h2 id="add-your-webhook-url-to-github">Add your webhook URL to Github</h2>
<p>Go to the settings page of your Github repo then click on Webhook. Enter the URL of your webhook server. If using Nginx, it should be something like <code>https://YOUR.DOMAIN.COM/hooks/deploy-from-git</code>. Make sure you select content type as <code>application/json</code> and secret to the secret you generated earlier.</p>
<h2 id="bonus-create-a-systemd-user-service-for-webhook-linux">Bonus: Create a systemd user service for webhook (Linux)</h2>
<p>Create a systemd unit file with path <strong>/home/user/.config/systemd/user/webhook.service</strong> . This service does not require sudo/root permissions and can be run by the unprivileged user.</p>
<pre tabindex="0"><code>[Unit]
AssertPathExists=/home/user/scripts

[Service]
WorkingDirectory=/home/user/scripts
ExecStart=/home/user/scripts/webhook -hooks hooks.json -hotreload -logfile webhooks.log
Restart=always
PrivateTmp=true
NoNewPrivileges=true

[Install]
WantedBy=default.target
</code></pre><p>Do <code>systemctl --user daemon-reload</code> and <code>systemctl --user start webhook.service</code>. You can <code>systemctl --user enable webhook.service</code> to ensure that the service always runs when your machine is booted.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Bash function to add TILs]]></title>
    <link href="https://rrampage.github.io/2020/05/23/bash-function-to-add-tils/"/>
    <id>https://rrampage.github.io/2020/05/23/bash-function-to-add-tils/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2020-05-23T12:42:20+00:00</published>
    <updated>2020-05-23T12:42:20+00:00</updated>
    
    <content type="html"><![CDATA[<h2 id="til-snippet"><code>til</code> snippet</h2>
<p>Here&rsquo;s a snippet I use in my <strong><code>.bashrc</code></strong> file to quickly write down and review TILs (Today I learned):</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nv">TIL_FILE</span><span class="o">=</span><span class="s2">&#34;</span><span class="nv">$HOME</span><span class="s2">/my-notes-repo/til.md&#34;</span>
</span></span><span class="line"><span class="cl">til <span class="o">()</span> 
</span></span><span class="line"><span class="cl"><span class="o">{</span> 
</span></span><span class="line"><span class="cl">    <span class="c1"># checks if the function has been called without any argument</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="o">[[</span> -z <span class="nv">$1</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># opens the file in my editor, setting the cursor to the last line</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># useful to review latest entries or to write a longer entry</span>
</span></span><span class="line"><span class="cl">        vim + <span class="s2">&#34;</span><span class="nv">$TIL_FILE</span><span class="s2">&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="k">else</span>
</span></span><span class="line"><span class="cl">        <span class="c1"># adds a line with today&#39;s date, a TAB and all arguments supplied (&#34;$@&#34;)</span>
</span></span><span class="line"><span class="cl">        <span class="nb">echo</span> -e <span class="s2">&#34;- </span><span class="k">$(</span> date <span class="s1">&#39;+%F&#39;</span> <span class="k">)</span><span class="s2">:\t</span><span class="nv">$@</span><span class="s2">&#34;</span> &gt;&gt; <span class="s2">&#34;</span><span class="nv">$TIL_FILE</span><span class="s2">&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="k">fi</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></div><h2 id="how-to-use">How to use:</h2>
<ul>
<li><strong><code>til</code></strong> to open the file. I use this to review what I learned today  or if I need to write a longer, multiline entry</li>
<li><strong><code>til CONTENT</code></strong> to append a line to the file
<ul>
<li>e.g <code>til grep --line-buffered to immediately print especially when tailing files</code> will add this: <code>- 2020-05-23:   grep --line-buffered to immediately print especially when tailing files</code></li>
</ul>
</li>
</ul>
<h3 id="explanation-on-the-function">Explanation on the function</h3>
<p>In case you missed the comments in the function, here&rsquo;s an explanation of what the various lines do:</p>
<ul>
<li><strong><code>if [[ -z $1 ]];</code></strong> checks if the function has been called without any arguments</li>
<li><strong><code>vim + &quot;$TIL_FILE&quot;</code></strong> opens the file in vim (my preferred editor), setting the cursor to the last line of the file.</li>
<li><strong><code>echo -e &quot;- $tdate:\t$@&quot; &gt;&gt; &quot;$TIL_FILE&quot;;</code></strong> adds a line with today&rsquo;s date, a TAB and all arguments supplied (&quot;$@&quot;) to <code>til</code></li>
</ul>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Setting display brightness on Linux from the command line]]></title>
    <link href="https://rrampage.github.io/2020/05/19/setting-display-brightness-on-linux-from-the-command-line/"/>
    <id>https://rrampage.github.io/2020/05/19/setting-display-brightness-on-linux-from-the-command-line/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2020-05-19T16:10:26+00:00</published>
    <updated>2020-05-19T16:10:26+00:00</updated>
    
    <content type="html"><![CDATA[<h2 id="setting-display-brightness-using-xrandr">Setting display brightness using <code>xrandr</code></h2>
<p>I auto-adjust the brightness on my display using a <a href="https://en.wikipedia.org/wiki/Cron">cron</a> which runs at 7 pm everyday.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">xrandr --output eDP-1 --brightness 0.9
</span></span></code></pre></div><p>This sets the brightness to 90% of maximum brightness.</p>
<h2 id="working-with-linux-display-environments-in-a-cron">Working with Linux Display environments in a cron</h2>
<p>The above command works when run from my terminal. But when run on a cron, it does not produce any effect. We need to explicitly mention the &ldquo;display number&rdquo; as an environment variable <code>DISPLAY</code>.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="m">8</span> <span class="m">19</span> * * * <span class="nv">DISPLAY</span><span class="o">=</span>:0 xrandr --verbose --output eDP-1 --brightness 0.9
</span></span></code></pre></div><h3 id="how-to-get-the-display-number-of-your-monitor">How to get the display number of your monitor?</h3>
<p>Running <code>xrandr</code> will give you a lot of output like</p>
<pre tabindex="0"><code>Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 16384 x 16384
eDP-1 connected primary 1920x1080+0+0 (normal left inverted right x axis y axis)
</code></pre><p>In my case, the display number is <code>:0</code></p>
<h3 id="adjusting-backlight-brightness-vs-perceived-brightness">Adjusting backlight brightness vs perceived brightness</h3>
<p>If <code>xrandr</code> is unable to find backlight, it only changes &ldquo;perceived&rdquo; brightness i.e it does <a href="https://wiki.archlinux.org/index.php/backlight#Color_correction">software color correction</a>. If we want to save battery, we will need to reduce the backlight brightness.</p>
<p>In Linux, the backlights can be found in <code>/sys/class/backlight</code>. In my case, it was <code>/sys/class/backlight/intel_backlight</code>. In this folder, there are many files like</p>
<pre tabindex="0"><code>actual_brightness
max_brightness
brightness
</code></pre><p><code>max_brightness</code> shows highest possible level of brightness for the display. We can adjust the value in <code>brightness</code> file to reduce backlight brightness.
Here&rsquo;s what I do to adjust it: <code>echo 1800 &gt; /sys/class/backlight/intel_backlight/brightness</code> (in root crontab)</p>
<p>Unlike the xrandr command, this does not require setting any DISPLAY variable in the cron file.</p>
<h2 id="other-tools">Other tools</h2>
<ul>
<li><a href="https://github.com/Hummer12007/brightnessctl">brightnessctl</a> is an easy to use tool which integrates well with systemd. It is also available in the package managers of various distributions like Debian, Ubuntu, Arch Linux.</li>
</ul>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Easy VPN using Wireguard]]></title>
    <link href="https://rrampage.github.io/2018/12/14/easy-vpn-using-wireguard/"/>
    <id>https://rrampage.github.io/2018/12/14/easy-vpn-using-wireguard/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-12-14T11:48:44+00:00</published>
    <updated>2018-12-14T11:48:44+00:00</updated>
    
    <content type="html"><![CDATA[<h2 id="why-wireguard-and-how-does-it-work">Why Wireguard and How does it work?</h2>
<ul>
<li>Simple (one config file on server and client and one command to run)</li>
<li>Small codebase (5000 LOC) unlike OpenVPN and IPSEC</li>
<li>Scheduled to be merged into Linux kernel soon</li>
</ul>
<p>Wireguard works by creating a tunnel to the server using a separate network interface on your machine.
You do not need to worry about Proxy settings and all your applications will work without issue.</p>
<h2 id="installation-and-key-generation">Installation and Key Generation</h2>
<p>Do this on both server and client machines</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1">#Installation: For both machines</span>
</span></span><span class="line"><span class="cl">sudo apt install wireguard wireguard-tools openresolv
</span></span><span class="line"><span class="cl"><span class="c1"># openresolv is in case you are using systemd-resolved which is default for DNS resolution on Ubuntu</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Generate private and public key pair : For both machines</span>
</span></span><span class="line"><span class="cl"><span class="nb">umask</span> <span class="m">077</span>
</span></span><span class="line"><span class="cl">wg genkey <span class="p">|</span> tee privatekey <span class="p">|</span> wg pubkey &gt; publickey
</span></span></code></pre></div><h2 id="configure-server">Configure Server</h2>
<p>Create file called <code>/etc/wireguard/wg0.conf</code></p>
<pre tabindex="0"><code>[Interface]
PrivateKey = &lt;Private Key&gt;
ListenPort = &lt;UDP Port to listen on, by default it is 51820&gt;
Address = 192.168.2.1/24, fd86:ea04:1115::1/64
ListenPort = 51820
PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE; ip6tables -A FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE; ip6tables -D FORWARD -i wg0 -j ACCEPT; ip6tables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
SaveConfig = true

[Peer]
PublicKey = &lt;Client Public Key&gt;
AllowedIPs = 192.168.2.2/32
</code></pre><p>Note that you have to paste the <strong>contents</strong> of the private key in the conf file, not the path.
The <strong>PostUp</strong> sets up forwarding rules when the wiregaurd interface is started. <strong>PostDown</strong> deletes the rules when the interface is shutdown.
Packet forwarding is essential if you want to use your server as a VPN to the general internet. Enable it on your server by adding the following to <code>/etc/sysctl.conf</code> and run <code>sudo sysctl -p</code> to reload the configuration changes.</p>
<pre tabindex="0"><code># Add to end of /etc/sysctl.conf
net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding=1
</code></pre><p>Whitelist the UDP port so that it is reachable by client</p>
<pre tabindex="0"><code>sudo ufw allow 51820/udp
sudo ufw enable
</code></pre><h2 id="configure-client">Configure Client</h2>
<p>Create file called <code>/etc/wireguard/wg0.conf</code></p>
<pre tabindex="0"><code>[Interface]
PrivateKey = &lt;Private Key&gt;
Address = 192.168.2.2/32
SaveConfig = true

[Peer]
PublicKey = &lt;Server Public Key&gt;
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = &lt;Server Public IP: Port e.g 23.23.23.23:2323&gt;
</code></pre><p>Note that the <strong>Address</strong> in interface part of client must be within range of <strong>AllowedIPs</strong> in server&rsquo;s config.
If you are not using the server as a VPN, you can restrict the <strong>AllowedIPs</strong> section of client.</p>
<h2 id="start-server-and-client">Start Server and Client</h2>
<p>Run <code>sudo wg-quick up wg0</code>
Enable it to run as service on system startup using <code>sudo systemctl enable wg-quick@wg0</code>
If you want to stop, use <code>sudo wg-quick down wg0</code></p>
<h2 id="test-connection">Test connection</h2>
<pre tabindex="0"><code># Ping Google
ping -c3 8.8.8.8
sudo wg # shows tyou status of the wireguard connection
</code></pre><h2 id="resources">Resources</h2>
<ul>
<li><a href="https://www.wireguard.com/papers/wireguard.pdf">Whitepaper</a></li>
<li><a href="https://www.digitalocean.com/community/tutorials/how-to-create-a-point-to-point-vpn-with-wireguard-on-ubuntu-16-04">Adapted from</a></li>
<li><a href="https://www.timdoug.com/log/2018/08/04/#wireguard_macos">OSX</a></li>
<li><a href="https://play.google.com/store/apps/details?id=com.wireguard.android&amp;hl=en_US">Android client</a></li>
<li><a href="https://www.wireguard.com/install/">More platforms</a></li>
</ul>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Git Tagging Tutorial]]></title>
    <link href="https://rrampage.github.io/2018/11/22/git-tagging-tutorial/"/>
    <id>https://rrampage.github.io/2018/11/22/git-tagging-tutorial/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-11-22T10:44:36+00:00</published>
    <updated>2018-11-22T10:44:36+00:00</updated>
    
    <content type="html"><![CDATA[<p>I read a post on <a href="https://dev.to/zellwk/git-tags--37a">dev.to</a> which shows how to create git tags using GUI-based git clients. I think that tags are useful to know even when using the git cli.</p>
<h2 id="what-are-tags">What are tags</h2>
<p>Tags are specific points in your code history which are useful to re-visit later e.g
you just released a new version of your app. You can tag the commit as <code>v1.0</code> using <strong><code>git tag v1.0</code></strong>. Anytime you want to reproduce bugs encountered on that version,  simply do <strong><code>git checkout v1.0</code></strong> and investigate.</p>
<h2 id="how-to-use-git-tag-better">How to use <code>git tag</code> better</h2>
<h3 id="checkout-code-to-the-tag">Checkout code to the tag</h3>
<p>The tag is linked to the specific commit and not to a branch. When you checkout the tag, git tells you that you are in &ldquo;detached HEAD&rdquo; state. Do not worry, all it means is that you need to create a new branch if you want to retain any changes you make after checking out the tag.</p>
<p>Create a new branch exactly at the commit of the tag using <strong><code>git checkout -b BRANCH_NAME TAG_NAME</code></strong></p>
<h3 id="make-your-tag-more-informational">Make your tag more informational!</h3>
<p>You can add more information using <strong><code>git tag -a TAG_NAME -m 'MESSAGE'</code></strong>
The tag information can be viewed without having to checkout the tag using <strong><code>git show TAG_NAME</code></strong>.</p>
<h3 id="create-tag-at-a-particular-commit">Create tag at a particular commit</h3>
<p>You do not always have to be at the HEAD or in the tip of the branch to create a tag. If you want to create tag say 5 commits before HEAD, you can use <code>git log</code> to get the correct commit hash e.g <strong><code>git log --pretty=oneline -10</code></strong> which shows the last 10 commits on the current branch.</p>
<p>Then, create tag using <strong><code>git tag -a TAG_NAME -m 'MESSAGE' COMMIT_HASH</code></strong></p>
<h3 id="list-and-delete-tags">List and Delete tags</h3>
<p>Listing all tags is simply: <strong><code>git tag</code></strong>
Similarly, delete a tag using <strong><code>git tag -d TAG_NAME</code></strong></p>
<h3 id="share-your-tag-with-others">Share your tag with others!</h3>
<p>The tag created is not pushed to remote automatically. If you want your tags to be used by other contributors too, you need to push them using <strong><code>git push origin TAG_NAME</code></strong></p>
<h3 id="sign-your-tags">Sign your tags!</h3>
<p>If you are working on a major project and want to show without any doubt that you have worked on the release, you can sign it using your GPG private key as <strong><code>git tag -s TAG_NAME -m 'MESSAGE'</code></strong>. Anyone who runs <strong><code>git show TAG_NAME</code></strong> on the tag will also see your public key signature along with the tag information.</p>
<p>They can additionally verify the tag using <strong><code>git tag -v TAG_NAME</code></strong>. This checks using your public key whether the signature is indeed yours.</p>
<h2 id="tags-vs-branches">Tags vs Branches</h2>
<p>Why use tags when you have branches? Because branches can change and tags are linked to a specific commit. Thus, marking releases with a tag will give you the state of code when the particular software release was done.</p>
<h2 id="summary">Summary</h2>
<ul>
<li>Tags are great way to remember specific commits</li>
<li>It is good to add a message to the tag so that people can easily see why you tagged a particular commit</li>
</ul>
<h2 id="references">References</h2>
<p>The Git book chapters:</p>
<ul>
<li><a href="https://git-scm.com/book/en/v2/Git-Basics-Tagging">Tagging</a></li>
<li><a href="https://git-scm.com/book/en/v2/Git-Tools-Signing-Your-Work">Signing</a></li>
</ul>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Bash Command Completion - Finding all the cats in your $PATH!]]></title>
    <link href="https://rrampage.github.io/2018/11/15/bash-command-completion-finding-all-the-cats-in-your-path/"/>
    <id>https://rrampage.github.io/2018/11/15/bash-command-completion-finding-all-the-cats-in-your-path/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-11-15T09:39:37+00:00</published>
    <updated>2018-11-15T09:39:37+00:00</updated>
    
    <content type="html"><![CDATA[<p>Today, I was curious to find out <strong>how many programs ending with <code>cat</code></strong> I had on my system. I remember using <code>cat</code>, <code>zcat</code> and wanted to know if there are similar programs. Pressing TAB after <code>cat</code> only gives programs which start with <code>cat</code>.</p>
<h2 id="1-apropos">1. <code>apropos</code></h2>
<p>In my <a href="https://dev.to/rrampage/getting-help-in-the-terminal-4cmo">last post</a>, I had mentioned that apropos is a way to search for what programs are available on your system. The search string for <code>apropos</code> can be any regex. So, <code>apropos 'cat$'</code> should solve the problem. <code>cat$</code> means all words ending with &lsquo;cat&rsquo;</p>
<p>The output has</p>
<pre tabindex="0"><code>STAILQ_CONCAT (3)     - implementations of singly-linked lists, singly-linked tail queues, lists and tail queues
OPENSSL_strlcat (3ssl) - Memory allocation functions
..
bzcat (1)            - decompresses files to stdout
cat (1)              - concatenate files and print on the standard output
fc-cat (1)           - read font information cache files
gencat (1)           - Generate message catalog
</code></pre><p>Clearly, the top 2 do not look like programs. Why is <code>apropos</code> then returning them?
Let&rsquo;s have a look at the <code>apropos</code> manual</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">man apropos
</span></span><span class="line"><span class="cl"><span class="c1"># apropos - search the manual page names and descriptions</span>
</span></span></code></pre></div><p>So <code>apropos</code> searches the <code>man</code> pages. And looks like there are <code>man</code> pages for other things and not just programs&hellip;</p>
<p>Digging deeper, let&rsquo;s try manual for the <code>man</code> pages!</p>
<pre tabindex="0"><code>man man
# The table below shows the section numbers of the manual followed by the types of pages they contain.
#       1   Executable programs or shell commands
#       2   System calls (functions provided by the kernel)
#       3   Library calls (functions within program libraries)
#       4   Special files (usually found in /dev)
#       5   File formats and conventions eg /etc/passwd
#       6   Games
#       7   Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7)
#       8   System administration commands (usually only for root)
#       9   Kernel routines [Non standard]
</code></pre><p>Ok. We are interested in are executable programs i.e section 1 of the man pages. <code>apropos</code> has a way to limit which sections we search using<code>-s</code> flag.
<strong><code>apropos -s 1 'cat$'</code></strong> gives us all programs ending with name <code>cat</code> which have an entry in the man pages but it does not show us any programs which do not have a man page.</p>
<h2 id="2-list-all-programs-on-your-path">2. List all programs on your path</h2>
<p>The way Bash knows which programs can be called directly by their name (e.g <code>ls</code>) and not by their full path (e.g <code>/usr/bin/ls</code>) is by looking at the <code>$PATH</code> environment variable.</p>
<p>** Listing all executable files on path **</p>
<p>Here&rsquo;s a small bash snippet which lists the executable files in PATH (let&rsquo;s call it <code>paths.sh</code>)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="cp">#!/bin/bash
</span></span></span><span class="line"><span class="cl"><span class="cp"></span><span class="c1"># The directories in $PATH are separated by &#34;:&#34;, so we split by it to get individual directories</span>
</span></span><span class="line"><span class="cl"><span class="k">for</span> pdir in <span class="k">$(</span><span class="nb">echo</span> <span class="s2">&#34;</span><span class="nv">$PATH</span><span class="s2">&#34;</span> <span class="p">|</span> tr <span class="s2">&#34;:&#34;</span> <span class="s2">&#34;\n&#34;</span><span class="k">)</span>
</span></span><span class="line"><span class="cl"><span class="k">do</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># We `find` all files in the directory which are executable and print the filename</span>
</span></span><span class="line"><span class="cl">    find <span class="s2">&#34;</span><span class="nv">$pdir</span><span class="s2">&#34;</span> -maxdepth <span class="m">1</span> -executable -type f -printf <span class="s2">&#34;%f\n&#34;</span>
</span></span><span class="line"><span class="cl"><span class="k">done</span>
</span></span></code></pre></div><p>If you prefer Python, here&rsquo;s a small Python program for the same (let&rsquo;s call it <code>paths.py</code>)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">itertools</span> <span class="kn">import</span> <span class="n">chain</span>
</span></span><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">os</span>
</span></span><span class="line"><span class="cl"><span class="n">path_dirs</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s1">&#39;PATH&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;:&#39;</span><span class="p">)</span> <span class="c1"># Split PATH by &#39;:&#39;</span>
</span></span><span class="line"><span class="cl"><span class="nb">print</span><span class="p">(</span><span class="n">path_dirs</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="n">all_files</span> <span class="o">=</span> <span class="n">chain</span><span class="p">(</span><span class="o">*</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="n">p</span><span class="p">)</span> <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">path_dirs</span><span class="p">))</span> <span class="c1"># Iterable of all files in the directories contained in PATH</span>
</span></span><span class="line"><span class="cl"><span class="n">is_exec</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span> <span class="p">:</span> <span class="n">os</span><span class="o">.</span><span class="n">access</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">X_OK</span><span class="p">)</span> <span class="c1"># Function to check if a filename is executable</span>
</span></span><span class="line"><span class="cl"><span class="n">execs</span> <span class="o">=</span> <span class="n">chain</span><span class="p">(</span><span class="o">*</span><span class="p">([</span><span class="n">f</span> <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">fs</span> <span class="k">if</span> <span class="n">is_exec</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">r</span><span class="p">,</span><span class="n">f</span><span class="p">))]</span> <span class="k">for</span> <span class="n">r</span><span class="p">,</span><span class="n">_</span><span class="p">,</span><span class="n">fs</span> <span class="ow">in</span> <span class="n">all_files</span><span class="p">))</span>
</span></span><span class="line"><span class="cl"><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">execs</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">    <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</span></span></code></pre></div><p>Running either our Bash or Python scripts will give us the correct output!</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">sh paths.sh <span class="p">|</span> grep <span class="s1">&#39;cat$&#39;</span>
</span></span><span class="line"><span class="cl">python3 paths.py <span class="p">|</span> grep <span class="s1">&#39;cat$&#39;</span>
</span></span></code></pre></div><h2 id="3-power-of-bash-completion">3. Power of Bash Completion!</h2>
<p>When I press TAB TAB after typing a letter, I get a list of suggestions. How does Bash do that? The <a href="https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html">Bash manual</a> says that it uses <code>complete</code> and <code>compgen</code> built-ins for suggesting completions.</p>
<p><code>compgen</code> generates completions using a list of words (-W) or list of commands (-c). The latter is of particular interest to us. <code>compgen -c</code> prints every executable on our path and all shell built-ins and shell-functions.</p>
<p><code>compgen --help</code> prints following message:
<code>compgen: compgen [-abcdefgjksuv] [-o option] [-A action] [-G globpat] [-W wordlist]  [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word] Display possible completions depending on the options.</code></p>
<p>The options stand for:</p>
<ul>
<li>a : aliases</li>
<li>b : shell builtins</li>
<li><strong>c : executable commands</strong></li>
<li>d : directories in current directory</li>
<li>e : <strong>export</strong> variables</li>
<li>f : files in current directory</li>
<li>g : groups in system</li>
<li>j : pending jobs (in background / stopped)</li>
<li>k : Bash <strong>keywords</strong></li>
<li>s : System services</li>
<li>u : users</li>
<li>v : All shell variables</li>
</ul>
<p>So <strong><code>compgen -c | grep 'cat$'</code></strong> should give us every single executable ending with <code>cat</code>.</p>
<h2 id="epilogue">Epilogue</h2>
<p>Diving into this rabbit-hole has given me a better understanding of how Bash completion works, how apropos finds relevant programs and why man pages are organized into various sections.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Command-line productivity tips : Getting help in the terminal]]></title>
    <link href="https://rrampage.github.io/2018/11/11/command-line-productivity-tips-getting-help-in-the-terminal/"/>
    <id>https://rrampage.github.io/2018/11/11/command-line-productivity-tips-getting-help-in-the-terminal/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-11-11T17:30:30+00:00</published>
    <updated>2018-11-11T17:30:30+00:00</updated>
    
    <content type="html"><![CDATA[<p>The command-line is often a daunting place for beginners. With nothing but a blinking cursor and an unfriendly dark screen staring back at you, despair sets in.</p>
<p>Here are a few things to do if you are stuck:</p>
<h2 id="1-how-to-find-programs-for-specific-tasks">1. How to find programs for specific tasks</h2>
<p>Many times, you want to do a particular task but you do not remember the name of the program which does that. Many shell utilities are not easy to remember at first with their cryptic 2 letter names.</p>
<p>Worry not, there is a command called <strong><code>apropos</code></strong> to help you out!</p>
<p>For example, you want to <strong>show a file with line numbers</strong>. You know that there is a program but have forgotten its name. You can just type <code>apropos -a line number</code> to get a list of programs. We use <code>-a</code> flag so that <code>apropos</code> will only return those programs which have the words <strong><code>line</code> AND <code>number</code></strong> in their description.</p>
<p>On my computer, it gives the following output:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">apropos -a line number
</span></span><span class="line"><span class="cl"><span class="c1"># Output:</span>
</span></span><span class="line"><span class="cl">addr2line <span class="o">(</span>1<span class="o">)</span>        - convert addresses into file names and line numbers.
</span></span><span class="line"><span class="cl">nl <span class="o">(</span>1<span class="o">)</span>               - number lines of files
</span></span><span class="line"><span class="cl">x86_64-linux-gnu-addr2line <span class="o">(</span>1<span class="o">)</span> - convert addresses into file names and line numbers.
</span></span></code></pre></div><p>There are 3 programs which have something to do with numbering lines. Let&rsquo;s find out what each of these programs does.</p>
<h2 id="2-find-out-what-a-program-does">2. Find out what a program does</h2>
<p>Let&rsquo;s have a look at our first candidate <code>addr2line</code>. <strong>Typing <code>--help</code> after the command is one way of finding out what a program does</strong>. It is a convention for command-line programs to print a small help message when you call them with <code>--help</code>. Some programs also allow do the same on calling with <code>-h</code>.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">addr2line --help
</span></span><span class="line"><span class="cl"><span class="c1"># Output:</span>
</span></span><span class="line"><span class="cl">Usage: addr2line <span class="o">[</span>option<span class="o">(</span>s<span class="o">)]</span> <span class="o">[</span>addr<span class="o">(</span>s<span class="o">)]</span>
</span></span><span class="line"><span class="cl"> Convert addresses into line number/file name pairs.
</span></span><span class="line"><span class="cl"> If no addresses are specified on the <span class="nb">command</span> line, they will be <span class="nb">read</span> from stdin
</span></span><span class="line"><span class="cl">....
</span></span></code></pre></div><p>Ok. This does program does something with <code>addresses</code>, not what we are looking for. Moving on to the next in our list: <code>nl</code></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">nl --help
</span></span><span class="line"><span class="cl"><span class="c1"># Output:</span>
</span></span><span class="line"><span class="cl">Usage: nl <span class="o">[</span>OPTION<span class="o">]</span>... <span class="o">[</span>FILE<span class="o">]</span>...
</span></span><span class="line"><span class="cl">Write each FILE to standard output, with line numbers added.
</span></span><span class="line"><span class="cl">...
</span></span></code></pre></div><p>Looks like we found our program. Let&rsquo;s try it out. This is our file <code>foo.txt</code></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">cat foo.txt
</span></span><span class="line"><span class="cl"><span class="c1"># Output:</span>
</span></span><span class="line"><span class="cl">one
</span></span><span class="line"><span class="cl">two
</span></span><span class="line"><span class="cl">three
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">four
</span></span><span class="line"><span class="cl">five
</span></span></code></pre></div><div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">nl foo.txt
</span></span><span class="line"><span class="cl"><span class="c1"># Output:</span>
</span></span><span class="line"><span class="cl">     <span class="m">1</span>  one
</span></span><span class="line"><span class="cl">     <span class="m">2</span>  two
</span></span><span class="line"><span class="cl">     <span class="m">3</span>  three
</span></span><span class="line"><span class="cl">       
</span></span><span class="line"><span class="cl">     <span class="m">4</span>  four
</span></span><span class="line"><span class="cl">     <span class="m">5</span>  five
</span></span></code></pre></div><p>It works ok but why is it not numbering blank lines?</p>
<h2 id="3-getting-detailed-information-about-a-program">3. Getting detailed information about a program</h2>
<p>The <code>--help</code> messages are very concise. If we want to know in detail what a program does, we need to consult the manual or <code>man</code> pages. These pages are very detailed documentation of what a program does, all its possible options and arguments. Type <code>man nl</code> and have a look at the information&hellip;</p>
<p>Woah! The terminal screen is filled with information!. You can navigate up and down using the arrow keys and press <code>q</code> to quit.</p>
<p>We can see the following in the output:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">.
</span></span><span class="line"><span class="cl">.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">-b, --body-numbering<span class="o">=</span>STYLE
</span></span><span class="line"><span class="cl">              use STYLE <span class="k">for</span> numbering body lines
</span></span><span class="line"><span class="cl">.
</span></span><span class="line"><span class="cl">.
</span></span><span class="line"><span class="cl">STYLE is one of:
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">       a      number all lines
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">       t      number only nonempty lines
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">       n      number no lines
</span></span></code></pre></div><p>So, <strong><code>nl -b a foo.txt</code></strong> will number <strong>all</strong> lines in foo.txt which is what we want.</p>
<pre tabindex="0"><code>nl -b a foo.txt
# Output:
     1  one
     2  two
     3  three
     4
     5  four
     6  five
</code></pre><p>That seems to solve our problem.</p>
<p>There is also <code>info</code> command which gives even more detailed usage information. You can try it out using <strong><code>info nl</code></strong>.</p>
<h2 id="4-getting-examples-for-using-a-program">4. Getting examples for using a program</h2>
<p>But what if we just quickly want to get our command to work without having to read a huge wall of text?</p>
<p>Turns out, there is a nifty utility you can install called <strong><code>tldr</code></strong>. If you use <code>node</code> or <code>python</code> you can install using <code>npm install -g tldr</code> or <code>pip install tldr</code> respectively. The <a href="https://tldr.sh/">tldr page</a> has a list of other installation options. After installing it, just try out <code>tldr nl</code> in your terminal</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">tldr nl
</span></span><span class="line"><span class="cl"><span class="c1"># Output:</span>
</span></span><span class="line"><span class="cl">nl
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  A utility <span class="k">for</span> numbering lines, either from a file, or from standard input.
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  - Number non-blank lines in a file:
</span></span><span class="line"><span class="cl">    nl file
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">....
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">  - Number all lines including blank lines:
</span></span><span class="line"><span class="cl">    nl -b a file
</span></span></code></pre></div><p>There! We can see the example with easy to understand description.</p>
<p><code>tldr</code> is community-driven! People contribute examples for various commands. If your favorite command does not have an entry, you can submit a <a href="https://github.com/tldr-pages/tldr">pull request</a>.</p>
<h2 id="recap">Recap</h2>
<p>To recap, we can:</p>
<ul>
<li>Find out possible programs which do particular tasks using <strong><code>apropos</code></strong></li>
<li>Get help information for <strong><code>$program</code></strong> using <strong><code>$program --help</code></strong> or <strong><code>man $program</code></strong></li>
<li>Get examples using <strong><code>tldr $program</code></strong></li>
</ul>
<h3 id="ps-what-if-we-are-not-able-to-find-programs-for-our-tasks">PS: What if we are not able to find programs for our tasks</h3>
<p>In Section 1, we assume that we will be able to find programs for our task. But many times, we may not have it installed. In such cases, we can search our distribution&rsquo;s package manager e.g <code>apt-get</code> for Ubuntu or <code>yum</code> or <code>dnf</code> for CentOS / Fedora.</p>
<p>In Ubuntu, we can search all available packages in the repositories using <code>apt-cache search $KEYWORD</code>.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Git: How to keep your fork updated with remote repository]]></title>
    <link href="https://rrampage.github.io/2018/11/09/git-how-to-keep-your-fork-updated-with-remote-repository/"/>
    <id>https://rrampage.github.io/2018/11/09/git-how-to-keep-your-fork-updated-with-remote-repository/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-11-09T12:50:54+00:00</published>
    <updated>2018-11-09T12:50:54+00:00</updated>
    
    <content type="html"><![CDATA[<p>This is useful when you have forked a repository (repo), cloned it to your local machine and want to keep it in sync with the original repo.</p>
<h2 id="adding-the-remote-repo">Adding the remote repo</h2>
<p>We can list the remote repositories for our repo with <strong><code>git remote -v</code></strong> and add the original repo as follows:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">git remote add upstream LINK_TO_ORIGINAL_REPO
</span></span></code></pre></div><p>Note that it is merely a convention to call it <strong><code>upstream</code></strong>. You can give any name you want.</p>
<p>Check that the repo is added to your remote using <strong><code>git remote -v</code></strong>.</p>
<h2 id="sync-with-remote">Sync with remote</h2>
<ul>
<li>Check if there are any changes in remote not on your fork using <strong><code>git fetch upstream</code></strong></li>
<li>Checkout whichever branch you are interested ( <strong><code>git checkout $BRANCH</code></strong>)</li>
<li>Merge with upstream using: <strong><code>git merge upstream/$BRANCH</code></strong></li>
<li>Push your changes to origin if needed: <strong><code>git push origin $BRANCH</code></strong></li>
</ul>
<h2 id="removing-the-remote-repo">Removing the remote repo</h2>
<p>If you no longer want to get changes from the remote repo, it is easy to remove it using <strong><code>git remote remove upstream</code></strong></p>
<h2 id="references">References</h2>
<p>Github&rsquo;s <a href="https://help.github.com/articles/syncing-a-fork/">help page</a></p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Ensuring that a shell script runs exactly once]]></title>
    <link href="https://rrampage.github.io/2018/11/06/ensuring-that-a-shell-script-runs-exactly-once/"/>
    <id>https://rrampage.github.io/2018/11/06/ensuring-that-a-shell-script-runs-exactly-once/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-11-06T18:53:23+00:00</published>
    <updated>2018-11-06T18:53:23+00:00</updated>
    
    <content type="html"><![CDATA[<p>Many times, we have shell scripts which perform some important stuff like inserting into database, mailing reports, etc which we want to run exactly one instance of.</p>
<h2 id="enter-locks">Enter locks!</h2>
<p>A simple solution is to create a &ldquo;lock file&rdquo; and check if the file exists when the script starts. If the file is already created, it means another instance of that program is running, so we can fail with message &ldquo;Try again later!&rdquo;. Once the script completes running, it will clean-up and delete the lock file.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nv">LOCK_FILE</span><span class="o">=</span>a.lock
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="o">[</span> -f <span class="s2">&#34;</span><span class="nv">$LOCK_FILE</span><span class="s2">&#34;</span> <span class="o">]</span><span class="p">;</span> <span class="k">then</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Lock file already exists, exit the script</span>
</span></span><span class="line"><span class="cl">    <span class="nb">echo</span> <span class="s2">&#34;An instance of this script is already running&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="nb">exit</span> <span class="m">1</span>
</span></span><span class="line"><span class="cl"><span class="k">fi</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Create the lock file</span>
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;Locked&#34;</span> &gt; <span class="s2">&#34;</span><span class="nv">$LOCK_FILE</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Do the normal stuff</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># clean-up before exit</span>
</span></span><span class="line"><span class="cl">rm <span class="s2">&#34;</span><span class="nv">$LOCK_FILE</span><span class="s2">&#34;</span>
</span></span></code></pre></div><p>This looks promising but there are issues with this approach. What happens if the script does not end correctly i.e it exits because of some failure before it reaches the clean-up part of the code? Or if it gets forcibly terminated with <code>Ctrl+C</code> or <code>kill</code> command? In both these cases, the created lock file will not be deleted. So next time you run the script, you will always get an error and will have to manually delete the file.</p>
<p>There is another, more subtle error with the above code. A race condition. If two instances of scripts are started around the same time, it is possible that both of them get past the <code>if [ -f &quot;$LOCK_FILE&quot; ]</code> because the second instance may reach that part of the code before the first instance is able to create the lock file. Thus, we have more than one instance running.</p>
<h2 id="a-better-lock">A better lock!</h2>
<p>Is there a way to create a lock file which is more robust to race conditions and non-standard termination (<code>Ctrl+C</code>, <code>kill</code> command, etc)? Linux offers <code>flock</code> a utility to manage locks from shell scripts. Using <code>flock</code>, we can rewrite the above snippet as follows:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nv">LOCK_FILE</span><span class="o">=</span>a.lock
</span></span><span class="line"><span class="cl"><span class="nb">exec</span> 99&gt;<span class="s2">&#34;</span><span class="nv">$LOCK_FILE</span><span class="s2">&#34;</span>
</span></span><span class="line"><span class="cl">flock -n <span class="m">99</span> <span class="o">||</span> <span class="nb">exit</span> <span class="m">1</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Do stuff and exit!</span>
</span></span></code></pre></div><p>The <code>exec 99&gt;&quot;$LOCK_FILE&quot;</code> creates a file descriptor numbered 99 and assigns it to <code>LOCK_FILE</code>. <a href="https://en.wikipedia.org/wiki/File_descriptor">File descriptors (fd)</a>  0, 1, 2 are for <code>stdin</code>, <code>stdout</code>, <code>stderr</code> respectively. We are creating new fd with a high number to ensure that it does not clash with numbered fds opened later-on by script.</p>
<p><code>flock -n 99 || exit 1</code> does 2 things. Firstly, it acquires an <code>exclusive</code> lock on the file descriptor 99 which refers to our <code>LOCK_FILE</code>. This operation is guaranteed by the linux kernel to be atomic. Secondly, if it fails to acquire the lock, it exits with return code 1. We do not need to worry about any clean up. <code>flock</code> will automatically release the lock when the script exits regardless of how it terminates. This solves our problem!</p>
<p>What if I wanted to add a more informational message instead of exiting directly on failure to acquire lock? We can change the line <code>flock -n 99 || exit 1</code> as follows:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">flock -n <span class="m">99</span>
</span></span><span class="line"><span class="cl"><span class="nv">RC</span><span class="o">=</span><span class="nv">$?</span>
</span></span><span class="line"><span class="cl"><span class="k">if</span> <span class="o">[</span> <span class="s2">&#34;</span><span class="nv">$RC</span><span class="s2">&#34;</span> !<span class="o">=</span> <span class="m">0</span> <span class="o">]</span><span class="p">;</span> <span class="k">then</span>
</span></span><span class="line"><span class="cl">    <span class="c1"># Send message and exit</span>
</span></span><span class="line"><span class="cl">    <span class="nb">echo</span> <span class="s2">&#34;Already running script. Try again after sometime&#34;</span>
</span></span><span class="line"><span class="cl">    <span class="nb">exit</span> <span class="m">1</span>
</span></span><span class="line"><span class="cl"><span class="k">fi</span>
</span></span></code></pre></div><p>The flock <a href="http://man7.org/linux/man-pages/man1/flock.1.html">man page</a> has an example which you can use to add an exclusive lock to start of any shell script:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="o">[</span> <span class="s2">&#34;</span><span class="si">${</span><span class="nv">FLOCKER</span><span class="si">}</span><span class="s2">&#34;</span> !<span class="o">=</span> <span class="s2">&#34;</span><span class="nv">$0</span><span class="s2">&#34;</span> <span class="o">]</span> <span class="o">&amp;&amp;</span> <span class="nb">exec</span> env <span class="nv">FLOCKER</span><span class="o">=</span><span class="s2">&#34;</span><span class="nv">$0</span><span class="s2">&#34;</span> flock -en <span class="s2">&#34;</span><span class="nv">$0</span><span class="s2">&#34;</span> <span class="s2">&#34;</span><span class="nv">$0</span><span class="s2">&#34;</span> <span class="s2">&#34;</span><span class="nv">$@</span><span class="s2">&#34;</span> <span class="o">||</span> :
</span></span></code></pre></div><p>This boilerplate uses the script file itself as a lock. It works by setting an environment variable <code>$FLOCKER</code> to script file name and executing the script with its original parameters after acquiring the lock. On failure however, it does not print anything and silently exits.</p>
<p><code>$0</code> here stands for name of the script. <code>$@</code> stands for all arguments passed to the script when it was called.</p>
<h2 id="use-case-for-me">Use case for me</h2>
<p>My team uses a test machine where we deploy multiple branches of a code-base. We need to make sure that exactly one person is building the project at a particular time. The deploy script pulls the specified branch of code from <code>git</code> and builds the project, deploys the main service and starts ancillary services. The script takes sometime to execute. If someone tries to deploy another branch while a build is ongoing, both can fail.</p>
<p>With the above snippet, calling the script more than once shows the current branch being built and exits with failure.</p>
<h2 id="further-reading">Further reading</h2>
<ul>
<li>Flock <a href="http://man7.org/linux/man-pages/man1/flock.1.html">man page</a></li>
<li><a href="http://mywiki.wooledge.org/BashFAQ/045">Pitfalls of creating a lock file</a> like in our initial snippet</li>
</ul>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Surviving the Linux OOM Killer]]></title>
    <link href="https://rrampage.github.io/2018/10/04/surviving-the-linux-oom-killer/"/>
    <id>https://rrampage.github.io/2018/10/04/surviving-the-linux-oom-killer/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-10-04T15:48:41+00:00</published>
    <updated>2018-10-04T15:48:41+00:00</updated>
    
    <content type="html"><![CDATA[<p>When your Linux machine runs out of memory, <strong>Out of Memory (OOM) killer</strong> is called by kernel to free some memory. It is often encountered on servers which have a number of memory intensive processes running. In this post, we dig a little deeper into when does OOM killer get called, how it decides which process to kill and if we can prevent it from killing important processes like databases.</p>
<h2 id="how-does-oom-killer-choose-which-process-to-kill">How does OOM Killer choose which process to kill?</h2>
<p>The Linux kernel gives a score to each running process called <code>oom_score</code> which shows how likely it is to be terminated in case of low available memory. The score is proportional to the amount of memory used by the process. The score is <code>10 x percent of memory used by process</code>. So the maximum score is 100% x 10 = 1000. In addition, if a process is running as a <strong>privileged user</strong>, it gets a <strong>slightly lower oom_score</strong> as compared to same memory usage by a normal user process. In earlier versions of Linux ( v2.6.32 kernel), there was a more elaborate heuristic which calculated this score.</p>
<p>The <code>oom_score</code> of a process can be found in the <code>/proc</code> directory. Let&rsquo;s say that the process id (pid) of your process is 42, <code>cat /proc/42/oom_score</code> will give you the process&rsquo; score.</p>
<h2 id="can-i-ensure-some-important-processes-do-not-get-killed-by-oom-killer">Can I ensure some important processes do not get killed by OOM Killer?</h2>
<p>Yes! The OOM killer checks <code>oom_score_adj</code> to adjust its final calculated score. This file is present in <code>/proc/$pid/oom_score_adj</code>. You can add a large negative score to this file to ensure that your process gets a lower chance of being picked and terminated by OOM killer. The <code>oom_score_adj</code> can vary from -1000 to 1000. If you assign -1000 to it, it can use 100% memory and still avoid getting terminated by OOM killer. On the other hand, if you assign 1000 to it, the Linux kernel will keep killing the process even when it uses minimal memory.</p>
<p>Let&rsquo;s go back to our process with pid 42. Here is how you can change its <code>oom_score_adj</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-shell" data-lang="shell"><span class="line"><span class="cl"><span class="nb">echo</span> -200 <span class="p">|</span> sudo tee - /proc/42/oom_score_adj
</span></span></code></pre></div><p>We need to do this as <code>root</code> user or <code>sudo</code> because Linux does not allow normal users to reduce the OOM score. You can increase the OOM score as a normal user without any special permissions. e.g <code>echo 100 &gt; /proc/42/oom_score_adj</code></p>
<p>There is also another, less fine-grained score called <code>oom_adj</code> which varies from -16 to 15. It is similar to <code>oom_score_adj</code>. In fact, when you set <code>oom_score_adj</code>, the kernel automatically scales it down and calculates <code>oom_adj</code>. <code>oom_adj</code> has a magic value of -17 which indicates that the given process should never be killed by OOM killer.</p>
<h2 id="display-oom-scores-of-all-running-processes">Display OOM scores of all running processes</h2>
<p>This script displays the OOM score and OOM adjusted score of all running processes, in descending order of OOM score</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-shell" data-lang="shell"><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1">#!/bin/bash</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Displays running processes in descending order of OOM score</span>
</span></span><span class="line"><span class="cl"><span class="nb">printf</span> <span class="s1">&#39;PID\tOOM Score\tOOM Adj\tCommand\n&#39;</span>
</span></span><span class="line"><span class="cl"><span class="k">while</span> <span class="nb">read</span> -r pid comm<span class="p">;</span> <span class="k">do</span> <span class="o">[</span> -f /proc/<span class="nv">$pid</span>/oom_score <span class="o">]</span> <span class="o">&amp;&amp;</span> <span class="o">[</span> <span class="k">$(</span>cat /proc/<span class="nv">$pid</span>/oom_score<span class="k">)</span> !<span class="o">=</span> <span class="m">0</span> <span class="o">]</span> <span class="o">&amp;&amp;</span> <span class="nb">printf</span> <span class="s1">&#39;%d\t%d\t\t%d\t%s\n&#39;</span> <span class="s2">&#34;</span><span class="nv">$pid</span><span class="s2">&#34;</span> <span class="s2">&#34;</span><span class="k">$(</span>cat /proc/<span class="nv">$pid</span>/oom_score<span class="k">)</span><span class="s2">&#34;</span> <span class="s2">&#34;</span><span class="k">$(</span>cat /proc/<span class="nv">$pid</span>/oom_score_adj<span class="k">)</span><span class="s2">&#34;</span> <span class="s2">&#34;</span><span class="nv">$comm</span><span class="s2">&#34;</span><span class="p">;</span> <span class="k">done</span> &lt; &lt;<span class="o">(</span>ps -e -o <span class="nv">pid</span><span class="o">=</span> -o <span class="nv">comm</span><span class="o">=)</span> <span class="p">|</span> sort -k 2nr
</span></span></code></pre></div><h2 id="check-if-any-of-your-processes-have-been-oom-killed">Check if any of your processes have been OOM-killed</h2>
<p>The easiest way is to <code>grep</code> your system logs. In Ubuntu: <code>grep -i kill /var/log/syslog</code>. If a process has been killed, you may get results like <code>my_process invoked oom-killer: gfp_mask=0x201da, order=0, oom_score_adj=0</code></p>
<h2 id="caveats-of-adjusting-oom-scores">Caveats of adjusting OOM scores</h2>
<p>Remember that OOM is a symptom of a bigger problem - low available memory. The best way to solve it is by either increasing the available memory (e.g better hardware) or moving some programs to other machines or by reducing memory consumption of programs (e.g allocate less memory where possible).</p>
<p>Too much tweaking of the OOM adjusted score will result in random processes getting killed and not being able to free enough memory.</p>
<h2 id="references">References</h2>
<ol>
<li><a href="http://man7.org/linux/man-pages/man5/proc.5.html">proc</a> man page</li>
<li><a href="https://askubuntu.com/questions/60672/how-do-i-use-oom-score-adj/">https://askubuntu.com/questions/60672/how-do-i-use-oom-score-adj/</a></li>
<li><a href="https://linux-mm.org/OOM_Killer">Walkthrough</a> on which part of Linux code is called</li>
<li>Classic <a href="https://lwn.net/Articles/317814/">LWN article</a> (a bit dated)</li>
<li><a href="https://www.lynxbee.com/how-to-invoke-oom-killer-manually-for-understanding-which-process-gets-killed-first/">Invoking the OOM killer manually</a></li>
</ol>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Algorithms: Gray Binary Code]]></title>
    <link href="https://rrampage.github.io/2018/08/18/algorithms-gray-binary-code/"/>
    <id>https://rrampage.github.io/2018/08/18/algorithms-gray-binary-code/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-08-18T17:52:23+00:00</published>
    <updated>2018-08-18T17:52:23+00:00</updated>
    
    <content type="html"><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Gray_code">Gray binary code</a> is a way of expressing binary numbers such that consecutive numbers differ in exactly 1 digit.
For example, in our conventional binary system, the numbers are</p>
<ul>
<li>000</li>
<li>001</li>
<li>010</li>
<li>011</li>
<li>100</li>
<li>101</li>
<li>110</li>
<li>111 and so on</li>
</ul>
<p>In Gray, they are:</p>
<ul>
<li>000</li>
<li>001</li>
<li>011</li>
<li>010</li>
<li>110</li>
<li>111</li>
<li>101</li>
<li>100 and so on</li>
</ul>
<p>In first system, when we go from &lsquo;001&rsquo; to &lsquo;010&rsquo;, there are 2 changes namely the unit&rsquo;s place becomes &lsquo;0&rsquo; from &lsquo;1&rsquo; and the next digit becomes &lsquo;1&rsquo; from &lsquo;0&rsquo;.
But in Gray&rsquo;s system, &lsquo;001&rsquo; becomes &lsquo;011&rsquo; where there is only 1 change (that of 2nd digit).</p>
<p>Gray codes are used in error correction in communication.</p>
<h3 id="generating-gray-codes-of-length-n">Generating Gray codes of length n</h3>
<p>Is there a property we can use for easily generating the Gray codes of a given length? Yes! In our previous example, we generated all the Gray codes for n=3. Ignoring the most significant bit (<strong>MSB</strong>), notice how the 4th and 5th numbers are equal in their first 2 digits, as are the 3rd and 6th, 2nd and 7th and 1st and 8th. The last 4 numbers are <strong>reflection</strong> of the first 4 if we ignore the last digit. But the last digit is 0 for the 1st 4 numbers and 1 for the last 4&hellip; We have a recursive formulation.</p>
<p>R(0) = []
R(n+1) = 0R(n) + 1R&rsquo;(n)   (R&rsquo;(n) = reverse of R(n))
For n=0, we have an empty list.
For n+1, we take R(n), prepend 0 to all elements and to this sequence, we add reverse of R(n) prepended with 1.</p>
<p>This can be succinctly expressed in Python as:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">gray_code</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">n</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="p">[]</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="p">[</span><span class="s1">&#39;0&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">    <span class="n">res</span> <span class="o">=</span> <span class="n">gray_code</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="p">[</span><span class="s1">&#39;0&#39;</span><span class="o">+</span><span class="n">s</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">res</span><span class="p">]</span> <span class="o">+</span> <span class="p">[</span><span class="s1">&#39;1&#39;</span><span class="o">+</span><span class="n">s</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">res</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]]</span>
</span></span></code></pre></div><p>The above function returns in correct order all the 2^n Gray codes of length n.
We had to add a case for <code>n==1</code> because we are treating the numbers as strings so we can prepend &lsquo;0&rsquo; or &lsquo;1&rsquo;. As n=0 is an empty list, we need another case where we first add the strings.</p>
<h3 id="converting-a-binary-number-to-gray-code">Converting a binary number to Gray code</h3>
<p>How do we convert a binary number to Gray code e.g what is Gray code equivalent of 7 (111 in binary)? From our earlier example, it is 100 = 4. So we need a function which takes an integer and returns the equivalent Gray code as integer.</p>
<p>We can use our recursive formulation from earlier to arrive at an algorithm. Let n = 2^a + b. Here, a is the MSB of n. G(n) is the Gray code of n. From our earlier formula, G(n) = 2^a + G(2^a-1-b) .. because of the reflection property. Thus, we know the value of G(n) at ath digit. We can keep iterating to get the other digits of G(n).</p>
<p>Our pseudo-code:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">bin_to_gray</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="mi">0</span>
</span></span><span class="line"><span class="cl">    <span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
</span></span><span class="line"><span class="cl">        <span class="k">return</span> <span class="mi">1</span>
</span></span><span class="line"><span class="cl">    <span class="n">a</span> <span class="o">=</span> <span class="n">MSB</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="c1"># Assume MSB function exists. It finds most significant bit of n</span>
</span></span><span class="line"><span class="cl">    <span class="n">b</span> <span class="o">=</span> <span class="n">n</span> <span class="o">-</span> <span class="mi">2</span><span class="o">**</span><span class="n">a</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="mi">2</span><span class="o">**</span><span class="n">a</span> <span class="o">+</span> <span class="n">bin_to_gray</span><span class="p">(</span><span class="mi">2</span><span class="o">**</span><span class="n">a</span><span class="o">-</span><span class="mi">1</span><span class="o">-</span><span class="n">b</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="n">log2</span> <span class="k">as</span> <span class="n">l2</span>
</span></span><span class="line"><span class="cl"><span class="c1"># A simple way to find MSB</span>
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">MSB</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="nb">int</span><span class="p">(</span><span class="n">l2</span><span class="p">(</span><span class="n">n</span><span class="p">))</span>
</span></span></code></pre></div><h4 id="an-even-faster-way">An even faster way:</h4>
<p>It turns out that there is an even faster way of getting the nth Gray code from n.
G(n) = n xor n/2</p>
<p>In C, Java or Python, this is expressed as:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">return</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">^</span><span class="w"> </span><span class="p">(</span><span class="n">n</span><span class="w"> </span><span class="o">&gt;&gt;</span><span class="w"> </span><span class="n">1</span><span class="p">)</span><span class="w">
</span></span></span></code></pre></div><h4 id="addendum--generating-all-gray-codes-knuth-style">Addendum : Generating all Gray codes Knuth style!</h4>
<p>The legendary <a href="https://www-cs-faculty.stanford.edu/~knuth/taocp.html">Donald Knuth</a> uses this algorithm to generate all the tuples in his Art of Computer Programming Vol 4A:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">gen_gray_bin_taocp</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">n</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kt">boolean</span><span class="w"> </span><span class="n">p</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kc">false</span><span class="p">;</span><span class="w"> </span><span class="c1">// parity bit</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kt">byte</span><span class="o">[]</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="kt">byte</span><span class="o">[</span><span class="n">n</span><span class="o">]</span><span class="p">;</span><span class="w"> </span><span class="c1">// each bit is an element in this array</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kt">int</span><span class="w"> </span><span class="n">j</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="kc">true</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="n">Arrays</span><span class="p">.</span><span class="na">toString</span><span class="p">(</span><span class="n">a</span><span class="p">));</span><span class="w"> </span><span class="c1">// Will print the number in reverse order</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">p</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="o">!</span><span class="n">p</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">p</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">j</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">else</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="n">j</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">1</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="c1">// Find min j so that a[j-1] = 1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">            </span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="n">j</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">n</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="o">[</span><span class="n">j</span><span class="o">-</span><span class="n">1</span><span class="o">]</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">1</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                    </span><span class="k">break</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="n">j</span><span class="o">++</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">j</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">n</span><span class="p">)</span><span class="w"> </span><span class="c1">// Termination condition</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">                    </span><span class="k">return</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">a</span><span class="o">[</span><span class="n">j</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">(</span><span class="kt">byte</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="n">1</span><span class="o">-</span><span class="n">a</span><span class="o">[</span><span class="n">j</span><span class="o">]</span><span class="p">);</span><span class="w"> </span><span class="c1">// We flip the element at j</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div>]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[100 Days Of Code]]></title>
    <link href="https://rrampage.github.io/2018/08/13/100-days-of-code/"/>
    <id>https://rrampage.github.io/2018/08/13/100-days-of-code/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-08-13T13:40:27+00:00</published>
    <updated>2018-08-13T13:40:27+00:00</updated>
    
    <content type="html"><![CDATA[<p>I have started the <a href="https://www.100daysofcode.com/">100 days of code challenge</a>.
I intend to use this time to check out new languages and frameworks and solve some fun problems.</p>
<p>I will update this post with my logs.</p>
<p><strong>Aug 13 2018 D0</strong> : Algorithms for calculating number of combinations and generating them in a lexicographical increasing order. <a href="https://dev.to/rrampage/algorithms-generating-combinations-100daysofcode-4o0a">Blog</a></p>
<p><strong>Aug 14 2018 D1</strong> : Working on algorithm for generating all permutations. First I managed to generate all possible <code>r</code> repetitions of <code>n</code> i.e <code>n^r</code>. Next, I read up and wrote code on Heap&rsquo;s algorithm. I am still not sure of the intuition behind the algorithm. Also, it does not generate the permutations in lexicographical increasing order.</p>
<p><strong>Aug 15 2018 D2</strong> : Learned and implemented an algorithm that generates all permutations in a lexicographical order. It is not as efficient as Heap&rsquo;s algorithm.</p>
<p><strong>Aug 16 2018 D3</strong> : Stumbled across the game of <a href="https://www.nytimes.com/crosswords/game/set">Set</a>. Wrote a small python script which generates all solutions of any given game.</p>
<p><strong>Aug 17 2018 D4</strong> : Learning to use <a href="https://pptr.dev/">Puppeteer.js</a> along with <a href="https://cloud.google.com/functions">Google Cloud Functions</a>. This <a href="https://dev.to/_mertsimsek/to-use-google-cloud-function-as-google-chrome-3e7e">dev.to post</a> was very useful in getting me started.</p>
<p><strong>Aug 18 2018 D5</strong> : Read about Gray Codes, an alternative way of ordering binary numbers in TAOCP Vol 4. Wrote <a href="https://dev.to/rrampage/algorithms-gray-binary-code---a-different-way-of-ordering-numbers-14e3">a blog post</a> exploring some of their properties and how to generate them.</p>
<p><strong>Aug 19 2018 D6</strong> : Wrote a script which calculates iterations for <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway&rsquo;s Game of Life</a></p>
<p><strong>Aug 20 2018 D7</strong> : Went through some Dynamic programming problems. Staircase problem is a good example of DP.</p>
<p><strong>Aug 21 2018 D8</strong>: More recursion and DP. Towers of Hanoi and Longest unique sub-string problem.</p>
<p><strong>Aug 24 2018 D9</strong>: After 2 days break due to travel, got back to C and linked lists. I am working through <a href="http://cslibrary.stanford.edu/105/LinkedListProblems.pdf">Stanford&rsquo;s Linked List problems</a>.</p>
<p><strong>Aug 25 2018 D10</strong> Working on a Sudoku solver. Made some more progress on the linked list problems from yesterday.</p>
<p><strong>Aug 26 2018 D11</strong> My sudoku solver can solve easy sudokus from <a href="https://www.codewars.com/kata/sudoku-solver/python">Code Wars</a></p>
<p><a href="https://gist.github.com/rrampage/ddc6f6fdaa0911493d2edec5cc303271">Gist</a></p>
<p><strong>Aug 27 2018 D12</strong> Reading up on back-tracking and n-queens problem.</p>
<p><strong>Aug 28 2018 D13</strong> Some fun with numpy and pandas and setting up virtualenvs.</p>
<p><strong>Aug 29 2018 D14</strong> Solved <a href="https://www.codewars.com/kata/compress-slash-encode-a-message-with-rle-run-length-encoding/train/python">Run Length Encoding problem</a> recursively</p>
<p><strong>Aug 30 2018 D15</strong> Data visualization using matplotlib in Python</p>
<p><strong>Aug 31 2018 D16</strong> 1D Cellular Automata in Java</p>
<p><strong>Sep 1 2018 D17</strong> Solved some regex golf problems</p>
<p><strong>Sep 2 2018 D18</strong> Played around with TMDB API using Python</p>
<p><strong>Sep 3 2018 D19</strong> Some interactive graph visualizations using Gephi</p>
<p><strong>Sep 4 2018 D20</strong> Implemented Tries in Java</p>
<p><strong>Sep 5 2018 D21</strong> Codewars kata on displaying a Tic-tac-toe board in C</p>
<p><strong>Sep 6 2018 D22</strong> Dynamic programming - Coin change problem!</p>
<p><strong>Sep 7 2018 D23</strong> Data cleaning using OpenRefine</p>
<p><strong>Sep 8 2018 D24</strong> Using SQLite for importing tabular data</p>
<p><strong>Sep 9 2018 D25</strong> SQLite window functions</p>
<p><strong>Sep 13 2018 D26</strong> After 3 day break because of job interviews and travel, a simple Python problem on moving 0s to the end of list on <a href="https://www.codewars.com/kata/52597aa56021e91c93000cb0">Codewars</a></p>
<p><strong>Sep 14 2018 D27</strong> Full-text search using SQLite (FTS4 and FTS5 engines)</p>
<p><strong>Sep 15 2018 D28</strong> n-Queens in Python using backtracking in just 20 lines! Code here: <a href="https://gist.github.com/rrampage/8f7fb7e0a53b1a5ec0161386ded429cc">gist</a></p>
<p><strong>Sep 16 2018 D29</strong> Playing around with D3.js for data visualization</p>
<p><strong>Sep 17 2018 D30</strong> Creating SVGs of various shapes in HTML. Awesome guide <a href="http://svgpocketguide.com/book/">here</a></p>
<p><strong>Sep 18 2018 D31</strong> Befunge interpreter on <a href="https://www.codewars.com/kata/befunge-interpreter/">Codewars</a></p>
<p><strong>Sep 19 2018 D32</strong> Learned more about JS <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">Array.reduce</a></p>
<p><strong>Sep 20 2018 D33</strong> Learned more about git branching and detaching from HEAD commit</p>
<p><strong>Sep 21 2018 D34</strong> Learned to use <a href="http://www.grymoire.com/Unix/Sed.html">sed</a> <a href="https://likegeeks.com/sed-linux/">effectively</a></p>
<p><strong>Sep 22 2018 D35</strong> <code>os.walk</code> in Python is very nifty for crawling the filesystem!</p>
<p><strong>Sep 23 2018 D36</strong> More d3.js, visualizations using choropleths for maps</p>
<p><strong>Sep 24 2018 D37</strong> Learned how OOM killer works on Linux. Wrote an article <a href="https://dev.to/rrampage/surviving-the-linux-oom-killer-2ki9">here</a></p>
<p>Have started working once again. I am putting this on hiatus till I find more time. Meanwhile, I will continue posting blog posts on my learning.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Algorithms: Generating Combinations]]></title>
    <link href="https://rrampage.github.io/2018/08/12/algorithms-generating-combinations/"/>
    <id>https://rrampage.github.io/2018/08/12/algorithms-generating-combinations/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-08-12T20:20:11+00:00</published>
    <updated>2018-08-12T20:20:11+00:00</updated>
    
    <content type="html"><![CDATA[<p>In how many different ways can we select <code>r</code> objects from a collection of <code>n</code> objects? In mathematics, this is called <a href="https://en.wikipedia.org/wiki/Combination">combinations</a>.</p>
<p><img loading="lazy" src="https://thepracticaldev.s3.amazonaws.com/i/w8utl55xbryxdvolbkdx.jpg" alt="Combinations of 5 objects, taken 2 at a time"  />
</p>
<p>The formula for the number of combinations is:
<img loading="lazy" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/813f7124a61dac205542db3f8491b36cb306453a" alt=""  />

where, <code>n!</code> denotes the factorial of a number that is the product of all numbers from 1 to n (inclusive).</p>
<h3 id="prelude--a-function-for-calculating-factorial-of-a-number">Prelude : A function for calculating factorial of a number</h3>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="nf">factorial</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">n</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kt">long</span><span class="w"> </span><span class="n">res</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">1L</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">&lt;=</span><span class="w"> </span><span class="n">n</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">res</span><span class="w"> </span><span class="o">*=</span><span class="w"> </span><span class="n">i</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">return</span><span class="w"> </span><span class="n">res</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><h3 id="calculating-combinations">Calculating Combinations</h3>
<p>That was simple! Let us now move on to calculating the number of combinations given <code>n</code> and <code>r</code></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">long</span><span class="w"> </span><span class="nf">combinations</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">n</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">r</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">r</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">0</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="kt">long</span><span class="w"> </span><span class="n">res</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">1L</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">r</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">r</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">r</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">r</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">r</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">res</span><span class="w"> </span><span class="o">*=</span><span class="w"> </span><span class="p">(</span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">i</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">res</span><span class="w"> </span><span class="o">/=</span><span class="w"> </span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">1</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">return</span><span class="w"> </span><span class="n">res</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>What does this algorithm do? Recall that we need to find <code>n!/r!(n-r)!</code> which will be of the form <code>n(n-1)...(n-r+1)/1.2...r</code>. Similar to <code>factorial</code>, we initialize the result as <code>1</code> and multiply by <code>n-i</code> and divide by <code>i+1</code>. Will this result in a fractional number? No. This is because first, we multiply by <code>n</code> and divide by <code>1</code>. Next, we multiply by <code>n-1</code> and divide by <code>2</code>. Now, either <code>n</code> or <code>n-1</code> have to be even (as they are consecutive numbers). Similarly, next when we divide by 3, one of <code>n</code>,<code>n-1</code> and <code>n-2</code> must be divisible by 3.</p>
<p>In the above code, we also make use of the mathematical property that <code>combinations(n,r) = combinations(n,n-r)</code>. This way, we can do less number of operations for calculating the combinations.</p>
<h3 id="generating-the-combinations">Generating the combinations</h3>
<p>Counting the number of combinations was not so hard! Now, let&rsquo;s generate all the combinations.</p>
<ul>
<li>Given <code>n</code> and <code>r</code>, we will print out all the combinations.</li>
<li>For the <code>n</code> objects, we will use the numbers from 0 to (n-1).</li>
<li>Additionally, we will generate them in a <strong>lexicographical</strong> order which is math speak for sorted order.</li>
<li>Finally, in a combination containing a and b, if a &lt; b, we will print <code>a b</code> instead of <code>b a</code>. Formally stated, if a[k] and a[k+1] are the kth and (k+1)th elements in a generated combination, a[k] &lt; a[k+1] for all k</li>
</ul>
<p>For example, given n = 4, r = 2, we have:</p>
<pre tabindex="0"><code>0 1
0 2
0 3
1 2
1 3
2 3
</code></pre><p>i.e 6 combinations.</p>
<p>Notice that we have <code>0 1</code> and not <code>1 0</code>. This is because we are generating each combination in lexicographical order and we take the minimum for each combination.</p>
<h4 id="generating-for-a-specific-value-of-r-r--2">Generating for a specific value of <code>r</code> (r = 2)</h4>
<p>If we have a specific value of <code>r</code> say 2, the code will involve 2 <code>for</code> loops like:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">n</span><span class="o">-</span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">j</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">i</span><span class="o">+</span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="n">j</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">n</span><span class="p">;</span><span class="w"> </span><span class="n">j</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">println</span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="s">&#34; &#34;</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">j</span><span class="p">);</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>In the code above, our first loop variable <code>i</code> goes from 0 to n-2 and the next variable <code>j</code> goes from <code>i+1</code> to n-1. Why so? This is because we have a requirement for taking the lexicographical minimum combination, so <code>i &lt; j</code> from our constraints.</p>
<p>If value of <code>r</code> is fixed, we can simply create r <code>for</code> loops. But it is not fixed&hellip;</p>
<h4 id="generalizing">Generalizing!</h4>
<p>Now, let&rsquo;s move on to the main goal - generate combinations of <code>n</code> numbers taken <code>r</code> at a time. <em>This section will be a little verbose as I have outlined how I arrived at the correct code. If you are interested in just the algorithm, feel free to skip to the bottom of the article</em></p>
<p>If we notice our previous code for <code>r = 2</code>, our first combination is always <code>0 1</code> as <code>i = 0, j = 1</code>. Similarly, if <code>r</code> was 3, our first combination would be <code>0 1 2</code>. There is a pattern!</p>
<p><strong>By creating an array <code>a</code> of size <code>r</code>, we can generate the first combination as <code>0 1 2 .. r-1</code>.</strong> We have the first combination ready. What about the rest? Somehow, if we increment elements in this array, we will generate the combinations&hellip;</p>
<p>Again, looking at the <code>r = 2</code> case, notice that the <strong>last</strong> combination is <code>n-2 n-1</code>. Similarly, for <code>r = 3</code>, it is <code>n-3 n-2 n-1</code>. Thus, for <code>r</code> elements, it will be <code>n-r+1 n-r+2 .. n-1</code>. There is one more insight - <strong>there is exactly one combination which starts with <code>n-r+1</code></strong>. If our array&rsquo;s first element reaches <code>n-r+1</code>, we are done!</p>
<p><strong>We now have a termination condition for our function: <code>a[0] == n-r+1</code></strong></p>
<p>The code we have so far will look like:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kt">int</span><span class="w"> </span><span class="n">n</span><span class="p">;</span><span class="w"> </span><span class="c1">// Given</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kt">int</span><span class="w"> </span><span class="n">r</span><span class="p">;</span><span class="w"> </span><span class="c1">// Given</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kt">int</span><span class="o">[]</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="kt">int</span><span class="o">[</span><span class="n">r</span><span class="o">]</span><span class="p">;</span><span class="w"> </span><span class="c1">// Initialize array of size r</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">r</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">i</span><span class="p">;</span><span class="w"> </span><span class="c1">// Initialize array with first combination</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="o">[</span><span class="n">0</span><span class="o">]</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">n</span><span class="o">-</span><span class="n">r</span><span class="o">+</span><span class="n">1</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// Our termination condition</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// DO SOMETHING!</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>We have a <code>while</code> loop that checks for termination condition. For the loop to terminate, we need to steadily progress from our first combination to the last combination. As we are generating elements in lexicographical order, the last element of the array must be incremented first. Then the second from last element and so on.</p>
<p>In our earlier example of <code>n = 4, r = 2</code>, we had</p>
<pre tabindex="0"><code>0 1
0 2
0 3
1 2
1 3
2 3
</code></pre><p>After <code>0 3</code>, we get <code>1 2</code>. This means once the <code>r-1</code> element (last element) reaches its maximum, we increment <code>r-2</code> element from 0 to 1 and also reset the value of <code>r-1</code> element to <code>a[r-2]+1</code> as it must always be at least 1 greater than the <code>r-2</code> element (from our constraints). Moving to our pseudo-code, let&rsquo;s add this to the <code>while</code> loop</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">r</span><span class="o">-</span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="c1">// variable i keeps track of which element in array we are incrementing</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="o">[</span><span class="n">0</span><span class="o">]</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">n</span><span class="o">-</span><span class="n">r</span><span class="o">+</span><span class="n">1</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="c1">// Our termination condition</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="n">0</span><span class="w"> </span><span class="o">&amp;&amp;</span><span class="w"> </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">n</span><span class="o">-</span><span class="n">r</span><span class="o">+</span><span class="n">1</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">i</span><span class="o">-</span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="c1">//If a[i] has reached the max allowable value, decrement i and move to next element in array</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">printArray</span><span class="p">(</span><span class="n">a</span><span class="p">);</span><span class="w"> </span><span class="c1">// pseudo-code to print out the combination</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]+</span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="c1">// increment</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">r</span><span class="o">-</span><span class="n">1</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">+</span><span class="n">1</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]+</span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="c1">// Reset `i+1` element as previous element + 1, according to our constraints</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">i</span><span class="o">+</span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="c1">// Once you have reset the i+1 element, it is no longer &lt; n-r+i and hence, we can move it back to old value</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>We have an index variable <code>i</code> which we use to check which is the element in the array to be incremented. In the first <code>if</code> in above code, we check if the <code>a[i]</code> has reached its maximum value of <code>n-r+i</code>. If yes, we decrement <code>i</code> as <code>a[i]</code> can no longer be incremented. Moving out of <code>if</code>, we then print the combination and increment <code>a[i]</code>. Now, if <code>i</code> is no longer <code>r-1</code> i.e it is no longer last element of <code>a</code>, we must reset it to <code>r-1</code> and also set the value of <code>a[r-1]</code> as <code>a[r-2]+1</code>. This works for <code>r=2</code>. Hooray! We have abstracted out the <code>for</code> loop in the earlier section into a <code>while</code> loop with a few conditionals.</p>
<p>But does this work for <code>r &gt; 2</code>? No&hellip; We need a minor change to make it work! Change the <code>if</code> statements inside the loop to <code>while</code> loops and we are done! In case of first loop, we need to find the maximum <code>i</code> which is less than <code>n+r-i</code>. For example <code>n=5, r=3</code> we have:</p>
<pre tabindex="0"><code>0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
</code></pre><p>As we move from <code>0 3 4</code> to <code>1 2 3</code>, both <code>i = 2</code> (a[2] = 4) and <code>i = 1</code> (a[1] = 3) are at their maximum. We need to move to <code>i = 0</code>. Similarly, the second <code>if</code> must be a <code>while</code> loop because once we have incremented the a[i] for minimum <code>i</code>, we need to reset the outer elements of array to maintain our constraints.</p>
<h3 id="our-final-code">Our final code:</h3>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kt">int</span><span class="o">[]</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="kt">int</span><span class="o">[</span><span class="n">r</span><span class="o">]</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// initialize first combination</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">0</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">r</span><span class="p">;</span><span class="w"> </span><span class="n">i</span><span class="o">++</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">i</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">r</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">1</span><span class="p">;</span><span class="w"> </span><span class="c1">// Index to keep track of maximum unsaturated element in array</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="c1">// a[0] can only be n-r+1 exactly once - our termination condition!</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="o">[</span><span class="n">0</span><span class="o">]</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">r</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">1</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// If outer elements are saturated, keep decrementing i till you find unsaturated element</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="n">0</span><span class="w"> </span><span class="o">&amp;&amp;</span><span class="w"> </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="n">n</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">r</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">i</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">i</span><span class="o">--</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">printArray</span><span class="p">(</span><span class="n">a</span><span class="p">);</span><span class="w"> </span><span class="c1">// pseudo-code to print array as space separated numbers</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]++</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// Reset each outer element to prev element + 1</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">while</span><span class="w"> </span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">r</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="n">1</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">1</span><span class="o">]</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">a</span><span class="o">[</span><span class="n">i</span><span class="o">]</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">1</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="n">i</span><span class="o">++</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><h4 id="proof-of-termination">Proof of termination</h4>
<p>Now that we have our algorithm, how can we show that it terminates? In each iteration of our outer while loop, we increment the element of the array with maximum index i which has not reached value <code>n-r+i</code> while maintaining our constraints. <strong>Due to the lexicographical ordering, our previous combination is always lesser than our currently generated combination.</strong> As there are only a finite number of combinations till we reach our &ldquo;last&rdquo; combination, we can say that our algorithm will terminate.</p>
<h3 id="meta">Meta:</h3>
<p>I began my 100 days of code challenge today with this problem. I will create a separate post explaining my motivations and plans.</p>
<p>Regarding this problem statement of generating combinations, I had some trouble initially moving from <code>r=2</code> case to the general one. It took me some time to find the correct termination condition. I am happy that the final algorithm is relatively compact. I also want to do a proof of correctness for this algorithm later.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Awk - A useful little language]]></title>
    <link href="https://rrampage.github.io/2018/05/26/awk-a-useful-little-language/"/>
    <id>https://rrampage.github.io/2018/05/26/awk-a-useful-little-language/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-05-26T13:58:58+00:00</published>
    <updated>2018-05-26T13:58:58+00:00</updated>
    
    <content type="html"><![CDATA[<p>Awk is a small but capable programming language which is used for processing text. It was developed by Aho, Weinberger, Kerninghan at Bell Labs.</p>
<p><a href="https://twitter.com/b0rk">Julia Evans</a> made an awesome Awk <a href="https://wizardzines.com/comics/awk/">comic</a>:

  <img src="https://wizardzines.com/images/uploads/awk.png" alt="AWK comic"/>
</p>
<p>Awk scans input file as a sequence of lines and splits each line into fields. The field separator is usually whitespace but you can customize it to any character.</p>
<p>An <code>awk</code> program is a sequence of <strong>pattern-action</strong> pairs i.e for each line, it checks if it matches the pattern and if yes, it performs the associated action on the line. Awk can be used interactively or to run saved programs.</p>
<p>Here is what Awk does written in Python-like pseudocode:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="n">initialize</span><span class="p">()</span> <span class="c1"># Initializes variables in BEGIN block</span>
</span></span><span class="line"><span class="cl"><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">input_lines</span><span class="p">:</span> <span class="c1"># Awk divides file / input into a list of lines</span>
</span></span><span class="line"><span class="cl">    <span class="k">for</span> <span class="n">condition</span><span class="p">,</span> <span class="n">action</span> <span class="ow">in</span> <span class="n">conditions</span><span class="p">:</span> <span class="c1"># A program is a list of condition-action pairs</span>
</span></span><span class="line"><span class="cl">        <span class="k">if</span> <span class="n">condition</span><span class="p">(</span><span class="n">line</span><span class="p">):</span> <span class="c1">#match line against condition</span>
</span></span><span class="line"><span class="cl">            <span class="n">action</span><span class="p">()</span> <span class="c1">#perform action on match </span>
</span></span></code></pre></div><p>Here are some small snippets of Awk:</p>
<h2 id="example---hello-world">Example - Hello World!</h2>
<p>You can run <code>awk</code> programs inline or through a file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-shell" data-lang="shell"><span class="line"><span class="cl">awk <span class="s1">&#39;BEGIN{ print &#34;Hello, World!&#34;}&#39;</span>
</span></span></code></pre></div><p>Alternatively, you can save this to a file <code>hello.awk</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-awk" data-lang="awk"><span class="line"><span class="cl"><span class="nb">BEGIN</span><span class="p">{</span> <span class="kr">print</span> <span class="s2">&#34;Hello, World!&#34;</span><span class="p">}</span>
</span></span></code></pre></div><p>Then run it as <code>awk -f hello.awk</code></p>
<h2 id="example---reading-a-csv-and-printing-a-specific-column">Example - Reading a CSV and printing a specific column</h2>
<p>Let&rsquo;s now do something useful! Download this <a href="https://data.lacity.org/api/views/nxs9-385f/rows.csv">csv</a> which is 2010 census data by zip code in Los Angeles city.</p>
<p>Read the first 3 lines from csv: <code>head -3 2010_Census_Populations_by_Zip_Code.csv</code></p>
<pre tabindex="0"><code>Zip Code,Total Population,Median Age,Total Males,Total Females,Total Households,Average Household Size
91371,1,73.5,0,1,1,1
90001,57110,26.6,28468,28642,12971,4.4
</code></pre><p>We will print just the total column using <code>awk -F, '{print $2}' 2010_Census_Populations_by_Zip_Code.csv</code></p>
<p>The <code>-F,</code> sets the field separator to comma as we need to split by commas for getting fields in a CSV file. <code>$n</code> allows you to use the value in the nth column.</p>
<h2 id="example---computing-some-statistics">Example - Computing some statistics</h2>
<p>Awk allows the use of variables and functions. Let&rsquo;s see how to use them by computing the total population in the entire city.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-awk" data-lang="awk"><span class="line"><span class="cl"><span class="c1"># total.awk</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span><span class="nx">s</span> <span class="o">+=</span> <span class="o">$</span><span class="mi">2</span><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="nb">END</span> <span class="p">{</span><span class="kr">print</span> <span class="s2">&#34;Total population:&#34;</span><span class="p">,</span> <span class="nx">s</span><span class="p">}</span>
</span></span></code></pre></div><p>Variables are by default initialized to 0. Here, we use a variable <code>s</code> to hold the total.</p>
<p>Running this script as <strong><code>awk -F, -f total.awk 2010_Census_Populations_by_Zip_Code.csv</code></strong>, we get output: <code>Total population: 10603988</code></p>
<h2 id="special-variables-and-built-in-functions">Special variables and built-in functions</h2>
<p>Awk uses some special variables and functions to make your programs more compact:</p>
<ul>
<li><strong>NF</strong> : Number of fields in a line</li>
<li><strong>NR</strong> : Line number</li>
<li><strong>$0</strong> : The entire input line</li>
<li><strong>length</strong> : gives number of characters in a string</li>
</ul>
<p>Now, we will compute the average household size which is total population divided by total households. The columns of interest are $2 and $6.
We also want the average population per zip code. Our script:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-awk" data-lang="awk"><span class="line"><span class="cl"><span class="c1"># stats.awk</span>
</span></span><span class="line"><span class="cl"><span class="p">{</span> <span class="nx">s</span> <span class="o">+=</span> <span class="o">$</span><span class="mi">2</span><span class="p">;</span> <span class="nx">h</span> <span class="o">+=</span> <span class="o">$</span><span class="mi">6</span><span class="p">;}</span>
</span></span><span class="line"><span class="cl"><span class="nb">END</span> <span class="p">{</span><span class="kr">print</span> <span class="s2">&#34;Total population:&#34;</span><span class="p">,</span> <span class="nx">s</span><span class="p">,</span> <span class="s2">&#34;\nTotal households:&#34;</span><span class="p">,</span> <span class="nx">h</span><span class="p">,</span> <span class="s2">&#34;\nAverage household size:&#34;</span><span class="p">,</span> <span class="nx">s</span><span class="o">/</span><span class="nx">h</span><span class="p">,</span> <span class="s2">&#34;\nAverage population per zip code:&#34;</span><span class="p">,</span> <span class="nx">s</span><span class="o">/</span><span class="nb">NR</span><span class="p">}</span>
</span></span></code></pre></div><p><code>NR</code> gives us the total number of lines. But we do not want the header line. We can use <code>tail</code> command to skip the 1st line as <code>tail -n +2</code>. Running <strong><code>tail -n +2 2010_Census_Populations_by_Zip_Code.csv | awk -F, -f total.awk</code></strong> gives us :</p>
<pre tabindex="0"><code>Total population: 10603988
Total households: 3497698
Average household size: 3.0317
Average population per zip code: 33241.3
</code></pre><h2 id="example---pattern-matching">Example - Pattern matching</h2>
<p>We have done some useful things with awk so far, but we have ignored its biggest strength - pattern matching. We can match based on field values, regexes, line numbers.</p>
<ul>
<li>Print every 2nd line : <strong><code>NR%2 == 0 {print $0}</code></strong>. Here $0 stands for the entire line.</li>
<li>Print all zip codes with population &gt; 100,000 : <strong><code>$2 &gt; 100000 {print $1}</code></strong></li>
<li>Print all zip codes with population &gt; 10,000 and average household size &gt; 4 : <strong><code>$2 &gt; 10000 &amp;&amp; $7 &gt; 4 { print $1}</code></strong>. We can combine conditions using <code>&amp;&amp;</code> and <code>||</code> which stand for logical <strong>and</strong> and <strong>or</strong> respectively.</li>
</ul>
<h2 id="further-reading">Further reading</h2>
<p>There is a lot more to Awk. Here are some references:</p>
<ul>
<li>
<p>The best resource for learning Awk is <a href="https://ia802309.us.archive.org/25/items/pdfy-MgN0H1joIoDVoIC7/The_AWK_Programming_Language.pdf">The AWK programming language</a> written by the same trio. This book goes over and beyond a typical programming language tutorial and teaches you how to use your Awk superpowers to build versatile systems like a relational database, a parser, an interpreter, etc.</p>
</li>
<li>
<p>The <a href="https://web.archive.org/web/20090410021611/http://www.gnu.org:80/software/gawk/manual/gawk.html">GNU Awk Manual for Effective Awk Programming</a> is a thorough reference.</p>
</li>
</ul>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[JVM Primer Part 2 - Debugging memory issues]]></title>
    <link href="https://rrampage.github.io/2018/05/16/jvm-primer-part-2-debugging-memory-issues/"/>
    <id>https://rrampage.github.io/2018/05/16/jvm-primer-part-2-debugging-memory-issues/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-05-16T11:53:42+00:00</published>
    <updated>2018-05-16T11:53:42+00:00</updated>
    
    <content type="html"><![CDATA[<p>This is part 2 of my series on JVM Memory management and debugging.
Read part 1 <a href="https://dev.to/rrampage/a-primer-on-jvm-memory-management-and-troubleshooting---1-12b6">here</a></p>
<p>In this post, we will cover symptoms of memory issues for JVM-based applications, which tools we can use to diagnose them and how we can fix them.</p>
<h2 id="symptoms">Symptoms</h2>
<p>Here are a few symptoms of memory issues:</p>
<ol>
<li>Poor application performance</li>
<li>Abnormal memory usage</li>
<li>OutOfMemory errors (OOME)</li>
</ol>
<h3 id="poor-application-performance">Poor Application Performance</h3>
<ol>
<li>Application not performing to expected level</li>
<li>Long response times</li>
<li>Dropping client requests</li>
<li>Stuck threads</li>
<li>Service unavailability</li>
<li>Large gaps in timestamps in application logs</li>
</ol>
<h3 id="causes-of-memory-problems">Causes of memory problems:</h3>
<ol>
<li>Misconfigured memory
<ul>
<li><strong>Old generation</strong> memory space is sized smaller than live-set of objects. This triggers a major garbage collection (GC), resulting in larger pauses.</li>
<li><strong>Code cache</strong> is smaller than generated compiled code footprint</li>
<li><strong>Young generation</strong> is not sized appropriately leading to premature promotion of objects</li>
<li><strong>PermGen / Metaspace</strong> not sized correctly leading to full GC</li>
</ul>
</li>
<li>Memory leaks - Unintentional retention of objects in memory spaces
<ul>
<li>Unintentional references to set of objects in heap</li>
<li>Not dereferencing classloader instances appropriateky</li>
<li>Not releasing native resources appropriately</li>
</ul>
</li>
<li>Excessive use of <strong>finalizers</strong>
<ul>
<li>Objects with finalizers may delay their own GC</li>
<li>Finalizer thread needs to invoke finalize() method of the instances before reclaiming them</li>
<li>There can only be 1 Finalizer thread. If it does not keep up with rate at which objects become available for finalization, JVM fails with OOME</li>
<li>Pending finalizer objects are essentially accumulated garbage</li>
<li>Finalizers deprecated in Java 9</li>
</ul>
</li>
<li>Explicit GC calls
<ul>
<li><strong><code>System.gc()</code></strong> and diagnostic data collections can cause long pauses</li>
<li><strong><code>-XX:+DisableExplicitGC</code></strong> can disable System.gc() calls</li>
<li><strong><code>-XX:+PrintClassHistogram</code></strong> also calls an explicit GC when receiving <code>kill -3</code> signal</li>
</ul>
</li>
</ol>
<h3 id="outofmemoryerror">OutOfMemoryError</h3>
<ul>
<li>Hierarchy : <code>Throwable</code> -&gt; <code>Error</code> -&gt; <code>VirtualMachineError</code> -&gt; <code>OutOfMemoryError</code> (Unchecked exception)</li>
<li>Thrown when JVM runs out of space in various memory spaces or cannot proceed further with process execution. Some of the possibilities:
<ul>
<li>Heap space full
<ul>
<li>JVM already invoked full GC but could not free up space</li>
<li>Heap may be sized smaller than app footprint or app is unnecessarily holding on to some set of objects in heap</li>
</ul>
</li>
<li>GC overhead limit exceeded
<ul>
<li>Too many GCs with very less space claimed</li>
<li>Application threads not getting any CPU cycles</li>
</ul>
</li>
<li>Requested array size exceeds VM limit</li>
<li>PermGen space / Metaspace / compressed class space
<ul>
<li>Full GC invoked but unable to free space in Metaspace and application is attempting to load more classes</li>
<li>Metaspace by default &ldquo;unlimited&rdquo; but can be controlled by MaxMetaspaceSize. By default, 1 GB reserved for compressed class space</li>
<li>Make sure that -Xnoclassgc is not in use as it prevents unloading of classes</li>
</ul>
</li>
<li>Native memory - out of swap space / stack trace with native method
<ul>
<li>Native space used for Java thread stacks, loaded jars, zips, native libraries, native resources like files; mem allocated from native code</li>
<li>Unable to allocate more native memory or to create new threads or native memory leaks</li>
<li>Running 32 bit JVM on 64 bit machine puts 4 GB limit on process size</li>
<li>Position of Java heap can put a cap on max size of native heap. Can be controlled by option -XX:HeapBaseMinAddress=n to specify address native heap should be based at</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="codecache-warnings">CodeCache warnings</h3>
<ul>
<li>warning message printed by JVM saying CodeCache full, compiler has been disabled.</li>
<li><strong>No OOME when code cache is full</strong></li>
<li>Emergency cleanup undertaken by Sweeper. This may discard compiled code and JIT may need to perform optimizations again</li>
<li>Ensure appropriate size of CC using <strong><code>ReservedCodeCacheSize</code></strong> option</li>
</ul>
<h3 id="direct-buffer-memory">Direct Buffer Memory</h3>
<ul>
<li><strong><code>ByteBuffer.allocateDirect(N)</code></strong> : Direct buffers which are garbage collected using phantom references and a reference queue</li>
<li>Unlimited memory by default but can be controlled by -XX:MaxDirectMemorySize=n</li>
<li>Used by <strong>Java NIO</strong>. Heap ByteBuffer for I/O uses temporary direct ByteBuffer</li>
</ul>
<h2 id="diagnostic-data-data-collection-and-analysis-tools">Diagnostic Data, Data Collection and Analysis Tools</h2>
<h3 id="troubleshooting-memory-leaks">Troubleshooting Memory leaks</h3>
<ol>
<li>
<p><strong>Confirm memory leak</strong></p>
<ul>
<li>Monitor heap usage over time</li>
<li>If full GCs unable to claim space in OldGen, could be config issue</li>
<li>Heap size may be too small -&gt; Increase heap size and monitor! If issue persists, it could be a memory leak</li>
<li><code>-XX:+GCTimeLimit</code> sets upper limit on amount of time GCs can spend in percent of total time, default 98%</li>
<li><code>-XX:+GCHeapFreeLimit</code> sets lower limit on amount of space that should be freed by a GC, represented as % of max heap, default is 2%</li>
<li><code>OutOfMemoryError</code> is thrown after a full GC if previous 5 consecutive GCs were not able to keep the GC cost below <code>GCTimeLimit</code> or free up at least <code>GCHeapFreeLimit</code> space</li>
<li><code>PermGen</code>/<code>Metaspace</code> may be too small if frequent Full GCs do not claim any space</li>
</ul>
</li>
<li>
<p><strong>Diagnostic data and analysis</strong></p>
<ul>
<li><strong>GC logs</strong> are helpful for determining heap requirements, finding out excessive GCs and long GC pauses and in configuration of memory spaces
<ul>
<li>For Java 9+, G1 options are: <code>-Xlog:gc*,gc+phases=debug:file=gc.log . For non G1, -Xlog:gc*:file=gc.log</code>. For older JVMs, <code>-XX:+PrintGCDetails, -XX:+PrintGCTimeStamps, -XX:+PrintGCDateStamps, -Xloggc:gc.log</code></li>
<li>For checking metaspace, <code>-verbose:class</code> or <code>-XX:+TraceClassLoading , -XX:+TraceClassUnloading</code></li>
<li>We can analyse logs through manual inspection, <a href="https://sourceforge.net/projects/gcviewer/">GCViewer</a>, <a href="https://github.com/jewes/gchisto">GCHisto</a>, <a href="http://gceasy.io/">gceasy.io</a></li>
</ul>
</li>
<li><strong>Heap dumps</strong> help determine unexpected memory growth and memory leaks.
<ul>
<li>We can take heap dumps in follwing ways:
<ul>
<li>jcmd pid GC.heap_dump heapdump.dmp</li>
<li>jmap -dump:format=b,file=snapshot.jmap pid</li>
<li>JConsole or Java Mission Control using MBean HotSpotDiagnostic</li>
<li>JVM option heap dump on OOM error : -XX:+HeapDumpOnOutOfMemoryError . Frequent full GCs can delay collection of heap dump and restart of the process</li>
</ul>
</li>
<li><strong>Eclipse Memory Analyzer Tool (MAT)</strong> shows leak suspects, histograms, unreachable objects, duplicate classes, reference chains to GC roots, allows using <a href="https://en.wikipedia.org/wiki/Object_Query_Language">OQL</a> to explore heap dumps.</li>
<li><strong>JOverFlow for JMC</strong> and <strong>Java VisualVM</strong>, <strong>YourKit</strong> (a commercial profiler) can all take heap dumps.</li>
</ul>
</li>
<li><strong>Heap histograms</strong> - quick view of objects in heap
<ul>
<li>Collect using:
<ul>
<li><code>-XX:+PrintClassHistogram</code> and <code>SIGQUIT</code> on Posix and <code>SIGBREAK</code> on Windows</li>
<li><code>jcmd pid GC.class_histogram filename=histo</code></li>
<li><code>jmap -histo pid core_file</code></li>
<li><code>jhsdb jmap</code> (Java 9)</li>
</ul>
</li>
</ul>
</li>
<li><strong>Java flight recordings</strong> - unexpected memory growth and memory leaks, GC events
<ul>
<li>Enable Heap Statistics. Can introduce additional performance overhead</li>
<li>To create a flight recording : <code>-XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:StartFlightRecording=delay=20s,duration=60s,name=Rec,filename=lol.jfr,settings=profile</code></li>
<li><strong>Flight recordings can find out type of leaking objects but you need heap dumps to find out what is causing the objects to leak</strong></li>
</ul>
</li>
<li><strong>Finalizers</strong>
<ul>
<li>Collect data using JConsole, jmap</li>
<li>Analyse using Eclipse MAT / Visual VM using heap dumps</li>
</ul>
</li>
<li>Native Memory
<ul>
<li>Native Memory Tracker output - tracks native memory used internally by JVM, not for external libraries. Start JVM with <strong><code>NativeMemoryTracking</code></strong> option</li>
<li><strong><code>pmap</code></strong>, <strong><code>libumem</code></strong>, <strong><code>valgrind</code></strong>, core files</li>
</ul>
</li>
</ul>
</li>
</ol>
<h2 id="conclusion">Conclusion</h2>
<p>In this series, we have taken a look at how the JVM manages memory and how the garbage collection process works. We have also gone through how to diagnose memory issues, which tools to use to collect and analyze diagnostic information and some JVM options which can affect application performance.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[A Primer on JVM Memory Management and Troubleshooting - 1]]></title>
    <link href="https://rrampage.github.io/2018/05/15/a-primer-on-jvm-memory-management-and-troubleshooting-1/"/>
    <id>https://rrampage.github.io/2018/05/15/a-primer-on-jvm-memory-management-and-troubleshooting-1/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-05-15T14:14:49+00:00</published>
    <updated>2018-05-15T14:14:49+00:00</updated>
    
    <content type="html"><![CDATA[<p>This series is a summary of Oracle&rsquo;s <a href="https://apexapps.oracle.com/pls/apex/f?p=44785:149:105166169953256::NO:RP,149:P149_EVENT_ID:5552">JVM troubleshooting course</a> which gives an overview on JVM memory management, Hotspot VM&rsquo;s garbage collection options, various memory errors and how to troubleshoot them.</p>
<p>In this post (part 1), we will have a look at how JVM manages memory and its different garbage collectors.</p>
<p>You can find Part 2 <a href="https://dev.to/rrampage/jvm-primer-part-2---debugging-performance-issues-1od">here</a></p>
<h3 id="jvm-memory-management-overview">JVM Memory Management Overview</h3>
<p>The JVM provides automatic memory management to free the programmer from manually managing memory. New objects are allocated on heap memory. A <strong>root set</strong> consists of pointers to external memory, static variables, threads, <a href="https://en.wikipedia.org/wiki/Java_Native_Interface">JNI</a> references and internal JVM structures. Objects directly reachable from the root set must be kept in heap. Objects reachable from any of the reachable objects must also be in heap. This group of objects are the only ones which can be used by a program. The unreachable objects (garbage) are removed using a process called <strong>garbage collection (GC)</strong>. Reachable objects are <strong>compacted</strong> i.e moved to contiguous space in heap. This is important as otherwise, the heap will become <a href="https://en.wikipedia.org/wiki/Fragmentation_(computing)">fragmented</a>.</p>
<h3 id="generational-gc-and-memory-spaces-in-hotspot">Generational GC and Memory Spaces in Hotspot</h3>
<p>When the JVM starts, it requests some memory from the OS. This memory is divided into various spaces.</p>
<p><img loading="lazy" src="https://www.ibm.com/support/knowledgecenter/SS3JSW_5.2.0/com.ibm.help.performance_mgmt.doc/SIPM_HotSpotMemory.jpg" alt="Memory spaces in Hotspot"  title="Memory spaces in Hotspot VM"  />

Memory spaces in JVM prior to JDK 8</p>
<ul>
<li>Separate pools hold objects of diff age ranges</li>
<li>JVM&rsquo;s GC is <strong>generational</strong> and is based on the hypothesis that:
<ul>
<li>Most objects die young</li>
<li>Few references from older to younger objects</li>
</ul>
</li>
<li>There are 2 generations of objects:
<ul>
<li>young : small and collected frequently (minor collection). Objects which survive a threshold number of GCs move to old generation.</li>
<li>old : large, collected infrequently (major collection = Full GC)</li>
</ul>
</li>
<li>Prior to JDK 8, there was also a <strong>permanent generation</strong> which was for storing class representations and metadata, interned strings and class statics. This was replaced by meta-space in JDK 8 and later.</li>
<li><strong>Meta-space</strong> is allocated in native memory. It is managed through JVM options <strong>MetaspaceSize</strong> for initial size and <strong>MaxMetaspaceSize</strong> for maximum.
<ul>
<li>If <strong>UseCompressedClassPointers</strong> is enabled, 2 areas of memory are used for storing classes and their metadata - <strong>meta-space</strong> and <strong>compressed class space</strong>. 64 bit class pointers represented with 32 bit offsets to save space. Class metadata is referenced by 32 bit offsets stored in compressed class space. By default, compressed class space is 1 GB.</li>
</ul>
</li>
<li>Code cache is used to store compiled code generated by JIT (Just in time optimizer), allocated out of native memory and managed by Code Cache Sweeper</li>
</ul>
<h3 id="garbage-collectors-in-hotspot-jvm">Garbage Collectors in Hotspot JVM</h3>
<p>The JVM has different garbage collection methods for different generations of objects. Some of them are described below:</p>
<ul>
<li>Young generation collection
<ul>
<li>Serial - Stop-the-world (STW), copying collector, single threaded</li>
<li>ParNew - STW, copying collector, multiple GC threads</li>
<li>Parallel Scavenge - STW, copying collector, multiple GC threads</li>
</ul>
</li>
<li>Old generation collection
<ul>
<li>Serial Old - STW, mark-sweep-compact collector, single threaded</li>
<li>CMS - Mostly concurrent, low pause</li>
<li>Parallel Old - compacting collector, multiple GC threads</li>
</ul>
</li>
<li>G1 : designed for large heaps and offers predictable short pauses.
<ul>
<li>Has different memory layout for generations</li>
<li>Same collector for all generations</li>
</ul>
</li>
</ul>
<h3 id="gc-options-for-jdk">GC options for JDK</h3>
<p>These are the option flags passed to JVM for specifying which GC to use:</p>
<ul>
<li>UseSerialGC : Serial + SerialOld</li>
<li>UseParNewGC : ParNew + SerialOld . In JDK 9, uses CMS for old gen</li>
<li>UseConcMarkSweepGC : ParNew + CMS + SerialOld
<ul>
<li>CMS used most of time to collect old generation. SerialOld used when concurrent mode failure occurs.</li>
<li>CMS performs most work in concurrent with application threads.</li>
<li>No heap compaction leads to fragmentation. Has floating garbage and requires larger heap sizes.</li>
<li>Free space maintained as linked lists. Allocation expensive compared to bump-the-pointer allocations.</li>
<li>Additional overhead on young collections</li>
<li>Deprecated in JDK 9</li>
</ul>
</li>
<li>UseParallelGC : Parallel Scavenge + Parallel Old.
<ul>
<li>Maximizes throughput.</li>
<li>Default GC till JDK 9</li>
</ul>
</li>
<li>UseG1GC - G1 for both generations
<ul>
<li>Server style GC for multi-core machines with large memory</li>
<li>Low GC pauses with high probability while trying for high throughput</li>
<li>Compacting collector. Low pauses without fragmentation</li>
<li>Better GC ergonomics. Parallel threads and some tasks are concurrent with application threads</li>
<li>Available since JDK 7u4 and default in JDK 9</li>
</ul>
</li>
</ul>
<p>For more detailed information on tuning the garbage collector, read the official <a href="https://docs.oracle.com/javase/9/gctuning/toc.htm">GC Tuning Guide</a></p>
<h4 id="minor-gc-or-how-young-generation-is-collected">Minor GC or How young generation is collected:</h4>
<ol>
<li>When Eden space in young gen is full, reachable objects are marked and moved to the ToSurvivorSpace</li>
<li>Objects in FromSurvivor space that are reachable are moved to ToSurvivorSpace</li>
<li>Objects in FromSurvivor space that have crossed the threshold are promoted to the old generation</li>
<li>Eden becomes empty and is ready for new allocations</li>
<li>To and From Survivor Spaces are switched</li>
</ol>
<h4 id="notes-on-mark-sweep-compact-collector-serial-old">Notes on Mark-Sweep-Compact collector (Serial Old):</h4>
<ul>
<li>Mark phase : marks all live objects</li>
<li>Sweep phase : sweeps over heap identifying garbage</li>
<li>Slide phase : GC performs a sliding compaction by sliding live objects to the start of the heap</li>
</ul>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Snake case to camel case and back using regular expressions and Python]]></title>
    <link href="https://rrampage.github.io/2018/05/09/snake-case-to-camel-case-and-back-using-regular-expressions-and-python/"/>
    <id>https://rrampage.github.io/2018/05/09/snake-case-to-camel-case-and-back-using-regular-expressions-and-python/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-05-09T00:10:00+05:30</published>
    <updated>2018-05-09T00:10:00+05:30</updated>
    
    <content type="html"><![CDATA[<p><a href="https://en.wikipedia.org/wiki/Snake_case">Snake case</a> and <a href="https://en.wikipedia.org/wiki/Camel_case">Camel case</a> are conventions of naming variables, functions and classes. Most teams and projects prescribe a particular case in their style guides.</p>
<p>Examples of camel case:</p>
<pre tabindex="0"><code>MyClass
MyClassFactory
MyClassFactoryBuilder
MyClassFactoryBuilderImpl
myInstance
myInstance2
abc
patternMatcher
</code></pre><p>Examples of snake case:</p>
<pre tabindex="0"><code>add
matrix_add
diagonal_matrix_add
pseudo_inverse
</code></pre><p>If we want to convert back and forth between these cases, we must look for the points of interest - the word boundaries. Camel case boundaries have the first letter capitalized while the snake case word boundaries have an <strong><code>_</code></strong>.</p>
<h3 id="snake-case-to-camel-case">Snake case to camel case</h3>
<p>Here is a regular expression for finding out the <strong><code>_</code></strong> and the first letter in the next word:</p>
<pre tabindex="0"><code class="language-regex" data-lang="regex">(.*?)_([a-zA-Z])
</code></pre><p>This regex has 2 parts:</p>
<ol>
<li>
<p><strong><code>(.*?)</code></strong> finds everything upto the <strong><code>_</code></strong>.</p>
<ul>
<li>The &lsquo;.&rsquo; means any character.</li>
<li>&lsquo;*&rsquo; stands for match 0 or more instances</li>
<li>&lsquo;?&rsquo; stands for non-greedy match. We must use &lsquo;?&rsquo; in the pattern because the regex engine will try to match as much as possible by default. So, if we use just <strong><code>(.*)</code></strong>, the whole word will be consumed and nothing will be left for the rest of the pattern.</li>
<li>&lsquo;()&rsquo; stand for a group. A group is a way of saving a part of the match for later.</li>
<li>Together, they mean that find all characters upto the first &lsquo;_&rsquo; and capture them in a group.</li>
</ul>
</li>
<li>
<p><strong><code>([a-zA-Z])</code></strong> finds the first alphabet after the <strong><code>_</code></strong>. We need this to convert to upper case for Camel case.</p>
</li>
</ol>
<p>The Python code below converts words which are in snake case to camel case:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">re</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">REG</span> <span class="o">=</span> <span class="sa">r</span><span class="s2">&#34;(.*?)_([a-zA-Z])&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">camel</span><span class="p">(</span><span class="k">match</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="k">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="k">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">camel_upper</span><span class="p">(</span><span class="k">match</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="k">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span> <span class="o">+</span> <span class="k">match</span><span class="o">.</span><span class="n">group</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="o">+</span> <span class="k">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">words</span> <span class="o">=</span> <span class="s2">&#34;&#34;&#34;add
</span></span></span><span class="line"><span class="cl"><span class="s2">matrix_add
</span></span></span><span class="line"><span class="cl"><span class="s2">diagonal_matrix_add
</span></span></span><span class="line"><span class="cl"><span class="s2">pseudo_inverse&#34;&#34;&#34;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">results</span> <span class="o">=</span> <span class="p">[</span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">REG</span><span class="p">,</span> <span class="n">camel</span><span class="p">,</span> <span class="n">w</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="nb">print</span><span class="p">(</span><span class="n">results</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Output:</span>
</span></span><span class="line"><span class="cl"><span class="c1"># [&#39;add&#39;, &#39;matrixAdd&#39;, &#39;diagonalMatrixAdd&#39;, &#39;pseudoInverse&#39;]</span>
</span></span></code></pre></div><p>We use the regex we constructed earlier and the <a href="https://docs.python.org/3/library/re.html#re.sub"><strong><code>re.sub</code></strong></a> method to substitute our matched words. We pass a method called <code>camel</code> as an argument. This method allows us to change the case of the letter in the second group and keep the first group unchanged. Notice that the first letter can be either lower or upper depending on whether it is a variable or method (lower) or a class (upper). The <code>camel_upper</code> method can be used for class names.</p>
<h3 id="camel-case-to-snake-case">Camel case to snake case</h3>
<p>Similarly, for converting from camel to snake case, the regex is:</p>
<pre tabindex="0"><code class="language-regex" data-lang="regex">(.+?)([A-Z])
</code></pre><p>And the Python code :</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">import</span> <span class="nn">re</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">REG</span> <span class="o">=</span> <span class="sa">r</span><span class="s2">&#34;(.+?)([A-Z])&#34;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">def</span> <span class="nf">snake</span><span class="p">(</span><span class="k">match</span><span class="p">):</span>
</span></span><span class="line"><span class="cl">    <span class="k">return</span> <span class="k">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span> <span class="o">+</span> <span class="s2">&#34;_&#34;</span> <span class="o">+</span> <span class="k">match</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">words</span> <span class="o">=</span> <span class="s2">&#34;&#34;&#34;MyClass
</span></span></span><span class="line"><span class="cl"><span class="s2">MyClassFactory
</span></span></span><span class="line"><span class="cl"><span class="s2">MyClassFactoryBuilder
</span></span></span><span class="line"><span class="cl"><span class="s2">MyClassFactoryBuilderImpl
</span></span></span><span class="line"><span class="cl"><span class="s2">myInstance
</span></span></span><span class="line"><span class="cl"><span class="s2">myInstance2
</span></span></span><span class="line"><span class="cl"><span class="s2">abc
</span></span></span><span class="line"><span class="cl"><span class="s2">patternMatcher&#34;&#34;&#34;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">results</span> <span class="o">=</span> <span class="p">[</span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">REG</span><span class="p">,</span> <span class="n">snake</span><span class="p">,</span> <span class="n">w</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">]</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="nb">print</span><span class="p">(</span><span class="n">results</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="c1"># Output</span>
</span></span><span class="line"><span class="cl"><span class="c1"># [&#39;my_class&#39;, &#39;my_class_factory&#39;, &#39;my_class_factory_builder&#39;, &#39;my_class_factory_builder_impl&#39;, &#39;my_instance&#39;, &#39;my_instance2&#39;, &#39;abc&#39;, &#39;pattern_matcher&#39;]</span>
</span></span></code></pre></div>]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Cargo refused to build my project - A Rust debugging story!]]></title>
    <link href="https://rrampage.github.io/2018/05/09/cargo-refused-to-build-my-project-a-rust-debugging-story/"/>
    <id>https://rrampage.github.io/2018/05/09/cargo-refused-to-build-my-project-a-rust-debugging-story/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-05-09T00:00:00+05:30</published>
    <updated>2018-05-09T00:00:00+05:30</updated>
    
    <content type="html"><![CDATA[<h3 id="background">Background</h3>
<p>Today, I resumed a <code>rust</code> project of mine after a long time. In order to check my last working code, I ran <code>cargo run</code>. But it refused to run with error message:</p>
<pre tabindex="0"><code>....&#34;-Wl,-Bdynamic&#34; &#34;-l&#34; &#34;dl&#34; &#34;-l&#34; &#34;rt&#34; &#34;-l&#34; &#34;pthread&#34; &#34;-l&#34; &#34;pthread&#34; &#34;-l&#34; &#34;gcc_s&#34; &#34;-l&#34; &#34;c&#34; &#34;-l&#34; &#34;m&#34; &#34;-l&#34; &#34;rt&#34; &#34;-l&#34; &#34;pthread&#34; &#34;-l&#34; &#34;util&#34; &#34;-l&#34; &#34;util&#34;
= note: /usr/bin/ld: cannot find Scrt1.o: No such file or directory
          collect2: error: ld returned 1 exit status
</code></pre><h3 id="linker-issues">Linker Issues!</h3>
<p><code>ld</code> is used to link libraries. So, the error was not in the code but in the linking phase. I googled the error and the solution was to have <code>build-essential</code> package installed. But the package was already installed on my machine (it is one of the first packages I install on any development machine).</p>
<p>Some more googling revealed that <code>cargo</code> uses the system <code>cc</code> linker to link to the C runtime. Running <code>which cc</code> gave me <code>$HOME/anaconda3/bin/cc</code>. This <code>cc</code> is part of my Anaconda root environment. (Anaconda is a package manager for scientific computing packages. It is a convenient way for installing multiple versions of packages in different environments).</p>
<p>On Linux, the linker knows where to find the required libraries using the shared library cache. I ran <code>ldconfig -v</code> to refresh it and then try again. Same error!</p>
<p>It is possible to explicitly list directories to include using <code>LD_LIBRARY_PATH</code> environment variable. I tried setting the <code>LD_LIBRARY_PATH</code> to point to the required directory and then run cargo as <code>LD_LIBRARY_PATH=DIR cargo build -v</code>. But it gave the same error.</p>
<p>I thought that <code>cargo</code> must be setting the linker value somewhere, so instead let me try directly compiling with <code>rustc</code>. Even that gave the same error. With this, I eliminated the possibility of some environment variable only affecting <code>cargo</code>.</p>
<h3 id="more-googling">More googling!</h3>
<p>Further searching for the error with &ldquo;rust&rdquo; added showed me results of people having trouble cross-compiling. From this, I learned that cargo has different targets i.e different instruction sets (e,g x86-64, arm, x86, mips), different OSs (e.g linux, windows, freebsd) and different C runtimes (e.g glibc, musl, msvc). The Rust documentation on cargo mentioned that this is called a target triple. The <a href="https://doc.rust-lang.org/cargo/reference/"><strong>Cargo book</strong></a> mentioned that you can direct cargo to explicitly use a particular linker using RUSTFLAGS environment variable.</p>
<p>Since I am only building for my machine, I had to find out the exact value of the target. Rust gives an exhaustive list of all supported targets by running <code>rustc --print target-list</code>. My target was <code>x86_64-unknown-linux-gnu</code>.</p>
<p>It is possible to pass a linker to <code>cargo</code> explicitly as <code>RUSTFLAGS=&quot;-C linker=x86_64-unknown-linux-gnu&quot; cargo build -v</code>. It worked!</p>
<h3 id="all-time-fix">All-time fix!</h3>
<p>I do not want to do this every time I run <code>cargo</code>. The Cargo book says that cargo uses a global config file in <code>$HOME/.cargo/config</code>.</p>
<p>I added the following to the file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-toml" data-lang="toml"><span class="line"><span class="cl"><span class="c"># Specify which linker to use for this target</span>
</span></span><span class="line"><span class="cl"><span class="p">[</span><span class="nx">target</span><span class="p">.</span><span class="nx">x86_64-unknown-linux-gnu</span><span class="p">]</span>
</span></span><span class="line"><span class="cl"><span class="nx">linker</span> <span class="p">=</span> <span class="s2">&#34;x86_64-linux-gnu-gcc&#34;</span>
</span></span></code></pre></div><p>Now, <code>cargo build</code> works without issues.</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Disk Space Debugging Checklist]]></title>
    <link href="https://rrampage.github.io/2018/05/04/disk-space-debugging-checklist/"/>
    <id>https://rrampage.github.io/2018/05/04/disk-space-debugging-checklist/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2018-05-04T00:00:00+05:30</published>
    <updated>2018-05-04T00:00:00+05:30</updated>
    
    <content type="html"><![CDATA[<p>Many times, smoothly running processes stop working mysteriously. You open the logs and see what is happening, only to find that even the logs have stopped updating. But the process itself is running. You SSH to the server and type cd TAB. Bash weeps &ldquo;Unable to create temporary file&rdquo;. The machine is out of disk space&hellip;</p>
<p>Here is a checklist to make disk space debugging easier, using standard Linux utilities so you can get started without having to install anything extra:</p>
<ol>
<li><strong><code>df -h</code></strong> command gives you an overview in a readable format about the number of disks mounted and their total and available capacities.</li>
<li>To get an idea of which folders/directories are eating up the maximum space, try out <strong><code>du -ch / | sort -h | tail -n 30</code></strong>. This gives you the 30 most space consuming directories. If you already know which directories generate maximum disk output e.g logs and temp files, you can replace the &lsquo;/&rsquo; with your directory (DIR) and run the command as <strong><code>du -ch DIR | sort -h | tail -n 30</code></strong></li>
<li>Now that we have identified the directories with maximum space consumed, we may need to delete some files and get our process going again. The <strong><code>rm</code></strong> command is your friend here. You can delete old logs and temporary files to free up space.</li>
<li>Many times, the culprit is a single large file which is already in use by a program e.g <code>catalina.out</code> by Apache Tomcat. If you want to free up space without shutting down the process, the <strong><code>truncate</code></strong> command will help you out. Example: <strong><code>truncate -s0 BIG_LOG.log</code></strong>. This will truncate the file to 0 bytes and still allow the other process to use it without issues (standard Unix permissions apply)</li>
<li>Sometimes, you delete files and still, the space does not seem to be recovered. This can be because some process is still holding on to the file descriptor of the deleted file. Once these processes are stopped, the space will be recovered. The <strong><code>lsof</code></strong> command will help you out here. It stands for <em>list open files</em>. You can find out which processes are using deleted files as follows: <code>lsof | grep deleted | grep OLD_FILENAME</code>. The lsof command gives you the process name and the process id so you can run <code>kill</code> on the process. If you do not know the name of the deleted file, you can still run <code>lsof | grep deleted</code> and see the output to check for any familiar file / process.</li>
</ol>
<p>Finally, keep in mind that disk space is one of the metrics you should monitor on your server. This checklist must be used in a pinch. If you find yourself constantly having disk space issues, the solution is to set up periodic deletion/rotation of old log files, alerts when the disk space reaches a particular threshold or to increase the disk size if your processes require a lot of disk space e.g Kafka, MySQL and other databases.</p>
<p>Let me know if there are some other tools I am missing out on and your experiences dealing with disk space issues!</p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Markdown (and some Hugo) Tutorial]]></title>
    <link href="https://rrampage.github.io/2017/08/20/markdown-and-some-hugo-tutorial/"/>
    <id>https://rrampage.github.io/2017/08/20/markdown-and-some-hugo-tutorial/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2017-08-20T00:00:00+00:00</published>
    <updated>2017-08-20T00:00:00+00:00</updated>
    
    <content type="html"><![CDATA[<h1 id="markdown-basics">Markdown Basics</h1>
<p>You can write regular <a href="http://markdowntutorial.com/">markdown</a> here and Jekyll will automatically convert it to a nice webpage.  I strongly encourage you to <a href="http://markdowntutorial.com/">take 5 minutes to learn how to write in markdown</a> - it&rsquo;ll teach you how to transform regular text into bold/italics/headings/tables/etc.</p>
<p><strong>Here is some bold text</strong></p>
<h2 id="here-is-a-secondary-heading">Here is a secondary heading</h2>
<p>Here&rsquo;s a useless table:</p>
<table>
  <thead>
      <tr>
          <th style="text-align: left">Number</th>
          <th style="text-align: left">Next number</th>
          <th style="text-align: left">Previous number</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td style="text-align: left">Five</td>
          <td style="text-align: left">Six</td>
          <td style="text-align: left">Four</td>
      </tr>
      <tr>
          <td style="text-align: left">Ten</td>
          <td style="text-align: left">Eleven</td>
          <td style="text-align: left">Nine</td>
      </tr>
      <tr>
          <td style="text-align: left">Seven</td>
          <td style="text-align: left">Eight</td>
          <td style="text-align: left">Six</td>
      </tr>
      <tr>
          <td style="text-align: left">Two</td>
          <td style="text-align: left">Three</td>
          <td style="text-align: left">One</td>
      </tr>
  </tbody>
</table>
<p>How about a yummy crepe?</p>
<p><img loading="lazy" src="http://s3-media3.fl.yelpcdn.com/bphoto/cQ1Yoa75m2yUFFbY2xwuqw/348s.jpg" alt="Crepe"  />
</p>
<h1 id="code-and-syntax-highlighting">Code and Syntax highlighting</h1>
<p>The following are two code samples using syntax highlighting.</p>
<p>The following is a code sample using triple backticks ( ``` ) code fencing provided in Hugo. This is client side highlighting and does not require any special installation.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-javascript" data-lang="javascript"><span class="line"><span class="cl">    <span class="kd">var</span> <span class="nx">num1</span><span class="p">,</span> <span class="nx">num2</span><span class="p">,</span> <span class="nx">sum</span>
</span></span><span class="line"><span class="cl">    <span class="nx">num1</span> <span class="o">=</span> <span class="nx">prompt</span><span class="p">(</span><span class="s2">&#34;Enter first number&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nx">num2</span> <span class="o">=</span> <span class="nx">prompt</span><span class="p">(</span><span class="s2">&#34;Enter second number&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nx">sum</span> <span class="o">=</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">num1</span><span class="p">)</span> <span class="o">+</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">num2</span><span class="p">)</span> <span class="c1">// &#34;+&#34; means &#34;add&#34;
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="nx">alert</span><span class="p">(</span><span class="s2">&#34;Sum = &#34;</span> <span class="o">+</span> <span class="nx">sum</span><span class="p">)</span>  <span class="c1">// &#34;+&#34; means combine into a string
</span></span></span></code></pre></div><p>The following is a code sample using the &ldquo;highlight&rdquo; shortcode provided in Hugo. This is server side highlighting and requires Python and Pygments to be installed.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-javascript" data-lang="javascript"><span class="line"><span class="cl">    <span class="kd">var</span> <span class="nx">num1</span><span class="p">,</span> <span class="nx">num2</span><span class="p">,</span> <span class="nx">sum</span>
</span></span><span class="line"><span class="cl">    <span class="nx">num1</span> <span class="o">=</span> <span class="nx">prompt</span><span class="p">(</span><span class="s2">&#34;Enter first number&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nx">num2</span> <span class="o">=</span> <span class="nx">prompt</span><span class="p">(</span><span class="s2">&#34;Enter second number&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="cl">    <span class="nx">sum</span> <span class="o">=</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">num1</span><span class="p">)</span> <span class="o">+</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">num2</span><span class="p">)</span> <span class="c1">// &#34;+&#34; means &#34;add&#34;
</span></span></span><span class="line"><span class="cl"><span class="c1"></span>    <span class="nx">alert</span><span class="p">(</span><span class="s2">&#34;Sum = &#34;</span> <span class="o">+</span> <span class="nx">sum</span><span class="p">)</span>  <span class="c1">// &#34;+&#34; means combine into a string
</span></span></span></code></pre></div>
<p>And here is the same code with line numbers:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-javascript" data-lang="javascript"><span class="line"><span class="ln">1</span><span class="cl">    <span class="kd">var</span> <span class="nx">num1</span><span class="p">,</span> <span class="nx">num2</span><span class="p">,</span> <span class="nx">sum</span>
</span></span><span class="line"><span class="ln">2</span><span class="cl">    <span class="nx">num1</span> <span class="o">=</span> <span class="nx">prompt</span><span class="p">(</span><span class="s2">&#34;Enter first number&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="ln">3</span><span class="cl">    <span class="nx">num2</span> <span class="o">=</span> <span class="nx">prompt</span><span class="p">(</span><span class="s2">&#34;Enter second number&#34;</span><span class="p">)</span>
</span></span><span class="line"><span class="ln">4</span><span class="cl">    <span class="nx">sum</span> <span class="o">=</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">num1</span><span class="p">)</span> <span class="o">+</span> <span class="nb">parseInt</span><span class="p">(</span><span class="nx">num2</span><span class="p">)</span> <span class="c1">// &#34;+&#34; means &#34;add&#34;
</span></span></span><span class="line"><span class="ln">5</span><span class="cl"><span class="c1"></span>    <span class="nx">alert</span><span class="p">(</span><span class="s2">&#34;Sum = &#34;</span> <span class="o">+</span> <span class="nx">sum</span><span class="p">)</span>  <span class="c1">// &#34;+&#34; means combine into a string
</span></span></span></code></pre></div>
<h1 id="math-and-katex">Math and KaTeX</h1>
<p>KaTeX can be used to generate complex math formulas server-side.</p>
<p>$$
\phi = \frac{(1+\sqrt{5})}{2} = 1.6180339887\cdots
$$</p>
<p>Additional details can be found on <a href="https://github.com/Khan/KaTeX">GitHub</a> or on the <a href="http://tiddlywiki.com/plugins/tiddlywiki/katex/">Wiki</a>.</p>
<p>To load KaTeX on markdown pages, add <code>math: true</code> in front-matter of post. Read <a href="https://mertbakir.gitlab.io/hugo/math-typesetting-in-hugo/">this post</a> for more information</p>
<!--more-->
<h3 id="example-1">Example 1</h3>
<p>If the text between $$ contains newlines it will rendered in display mode:</p>
<pre tabindex="0"><code>$$
f(x) = \int_{-\infty}^\infty\hat f(\xi)\,e^{2 \pi i \xi x}\,d\xi
$$
</code></pre><p>$$
f(x) = \int_{-\infty}^\infty\hat f(\xi),e^{2 \pi i \xi x},d\xi
$$</p>
<h3 id="example-2">Example 2</h3>
<pre tabindex="0"><code>$$
\frac{1}{\Bigl(\sqrt{\phi \sqrt{5}}-\phi\Bigr) e^{\frac25 \pi}} = 1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}} {1+\frac{e^{-8\pi}} {1+\cdots} } } }
$$
</code></pre><p>​​$$
\frac{1}{\Bigl(\sqrt{\phi \sqrt{5}}-\phi\Bigr) e^{\frac25 \pi}} = 1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}} {1+\frac{e^{-8\pi}} {1+\cdots} } } }
$$
​​</p>
<h3 id="example-3">Example 3</h3>
<pre tabindex="0"><code>$$
1 +  \frac{q^2}{(1-q)}+\frac{q^6}{(1-q)(1-q^2)}+\cdots = \prod_{j=0}^{\infty}\frac{1}{(1-q^{5j+2})(1-q^{5j+3})}, \quad\quad \text{for }\lvert q\rvert&lt;1.
$$
</code></pre><p>$$
1 +  \frac{q^2}{(1-q)}+\frac{q^6}{(1-q)(1-q^2)}+\cdots = \prod_{j=0}^{\infty}\frac{1}{(1-q^{5j+2})(1-q^{5j+3})}, \quad\quad \text{for }\lvert q\rvert&lt;1.
$$</p>]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Hello World]]></title>
    <link href="https://rrampage.github.io/2014/03/03/hello-world/"/>
    <id>https://rrampage.github.io/2014/03/03/hello-world/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>2014-03-03T22:38:33+05:30</published>
    <updated>2014-03-03T22:38:33+05:30</updated>
    
    <content type="html"><![CDATA[<p><strong>Hello World!</strong></p>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[About]]></title>
    <link href="https://rrampage.github.io/about/"/>
    <id>https://rrampage.github.io/about/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>0001-01-01T00:00:00+00:00</published>
    <updated>0001-01-01T00:00:00+00:00</updated>
    
    <content type="html"><![CDATA[<h4 id="about-this-blog">About this blog:</h4>
<ul>
<li>the delights and frustrations of programming</li>
<li>new things I learn/stumble across while coding</li>
<li>interesting concepts/resources I come across</li>
<li>trying to explain a few topics</li>
</ul>
<h4 id="about-me">About Me</h4>
<p>I am a software developer. I work on mostly backend stuff.
I blog occasionally <a href="https://rrampage.github.io">here</a> or crosspost to <a href="https://dev.to/rrampage">dev.to</a>.</p>
<h4 id="-ask-me-about-">💬 Ask me about &hellip;</h4>
<ul>
<li>Bash, sed, awk, GNU Make, jq</li>
<li>Linux</li>
<li>Postgres/MySQL/SQLite</li>
<li>Java/Kotlin, JOOQ, Dropwizard</li>
<li>Solr &amp; Elasticsearch</li>
<li>ArangoDB</li>
<li>Nginx &amp; Openresty</li>
<li>State machines, Regexes, State charts</li>
</ul>
<h4 id="-how-to-reach-me">📫 How to reach me:</h4>
<ul>
<li><a href="https://hachyderm.io/@bit">Mastodon</a></li>
<li><a href="https://in.linkedin.com/in/raunak1">LinkedIn</a></li>
<li><a href="https://bsky.app/profile/rrampage.bsky.social">Bluesky</a></li>
</ul>
<h4 id="software-powering-this-blog">Software powering this blog:</h4>
<ul>
<li><a href="https://gohugo.io/">Hugo</a>
<ul>
<li>Modified version of <a href="https://github.com/adityatelange/hugo-PaperMod/">PaperMod</a> theme</li>
</ul>
</li>
<li><a href="https://github.com/rrampage/rrampage.github.io">Github pages</a></li>
</ul>
]]></content>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[APL Scrapbook]]></title>
    <link href="https://rrampage.github.io/misc/apl-scrapbook/"/>
    <id>https://rrampage.github.io/misc/apl-scrapbook/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>0001-01-01T00:00:00+00:00</published>
    <updated>0001-01-01T00:00:00+00:00</updated>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Archive]]></title>
    <link href="https://rrampage.github.io/archives/"/>
    <id>https://rrampage.github.io/archives/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>0001-01-01T00:00:00+00:00</published>
    <updated>0001-01-01T00:00:00+00:00</updated>
    
  </entry>
  <entry>
    <title type="html"><![CDATA[Search]]></title>
    <link href="https://rrampage.github.io/search/"/>
    <id>https://rrampage.github.io/search/</id> 
    <author>
      <name>Raunak</name>
    </author>
    <published>0001-01-01T00:00:00+00:00</published>
    <updated>0001-01-01T00:00:00+00:00</updated>
    
  </entry>
</feed>