<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Backpacking Dream]]></title><description><![CDATA[Welcome to my blog, where I lies my journey backpacking through terrains of the physical and digital realms. I write about technical things like programming lan]]></description><link>https://hashnode.king-11.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 15 May 2026 03:24:29 GMT</lastBuildDate><atom:link href="https://hashnode.king-11.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Cloudflare Integration]]></title><description><![CDATA[I recently tried to move all my DNS records for web resources deployed over the internet to the unified network of cloudflare as they are just great at what they do with all the services and network protection.
I will walk through the setup cloudflar...]]></description><link>https://hashnode.king-11.dev/cloudflare-integration</link><guid isPermaLink="true">https://hashnode.king-11.dev/cloudflare-integration</guid><category><![CDATA[cloudflare]]></category><category><![CDATA[networking]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Thu, 31 Oct 2024 06:08:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730352660880/858bc302-e61c-4908-86fd-2aa5b4c9710e.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently tried to move all my <strong>DNS</strong> records for web resources deployed over the internet to the unified network of <code>cloudflare</code> as they are just great at what they do with all the services and network protection.</p>
<p>I will walk through the setup <code>cloudflare</code> to use as <a target="_blank" href="/posts/cloudflare-integration/#nameserver">nameserver</a>, DNS record management, and <strong>SSL/TLS</strong> setup. There is plenty more at <code>cloudflare</code> like <a target="_blank" href="https://blog.king-11.dev/posts/rate-limiting/">rate limiting</a> as well.</p>
<p>Let’s get this out of the way first Domain Name System (<code>DNS</code>) is a way to translate domain names like <a target="_blank" href="https://blog.king-11.dev">blog.king-11.dev</a> to its IP Address.</p>
<pre><code class="lang-bash">host blog.king-11.dev
blog.king-11.dev has address 172.67.164.94
blog.king-11.dev has address 104.21.66.209
blog.king-11.dev has IPv6 address 2606:4700:3033::6815:42d1
blog.king-11.dev has IPv6 address 2606:4700:3032::ac43:a45e
</code></pre>
<p>The resources I moved from multiple different providers included:</p>
<ul>
<li><p>Custom Domain</p>
</li>
<li><p>Static <code>Github</code> Pages Website</p>
</li>
<li><p>Dynamic <code>NextJS</code> Website</p>
</li>
<li><p>Home Server Network Tunnel</p>
</li>
</ul>
<p>Let’s dive into how my late night network shenanigans went.</p>
<h2 id="heading-custom-domain">Custom Domain</h2>
<p>I had a great time just using <a target="_blank" href="github.io">github.io</a>, <a target="_blank" href="vercel.app">vercel.app</a> and <a target="_blank" href="netlify.app">netlify.app</a>. These service providers are amazing and offer you a lot for free. But there were primarily two reason for my switch:</p>
<ul>
<li><p>I wanted to setup a <a target="_blank" href="/posts/cloudflare-integration/#cloudflare-tunnel">cloudflare tunnel</a> for my <code>jellyfin</code> server at flat so that I can binge watch my series and movies from anywhere in the world</p>
</li>
<li><p>Having everything under a single umbrella helps in developing the brand as people remember it easily so why not?</p>
</li>
</ul>
<h3 id="heading-purchasing-domain">Purchasing Domain</h3>
<p>So after asking people what top level domain (<code>TLD</code>) should I buy and thinking a little about getting free ones. I unloaded my pockets and got myself <a target="_blank" href="king-11.dev"><strong>king-11.dev</strong></a> from <a target="_blank" href="namecheap.com"><strong>Namecheap</strong></a>.</p>
<p>The only issue was they didn’t provide <code>INR</code> payment options just like <code>cloudflare</code> so I had to use my <a target="_blank" href="https://www.getonecard.app/"><strong>OneCard</strong></a> as that provides a good <strong>forex</strong> rate of <strong>1%</strong> only.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730354804661/da816c41-c2de-4e85-92e5-89f63fa9cbc2.webp" alt class="image--center mx-auto" /></p>
<p>I could have bought the domain from <code>cloudflare</code> too they are the most transparent in terms of domain registration as they only ask for the registration charges and nothing else. But their <code>paypal</code> integration wasn’t working for me and <code>namecheap</code> was cheaper so went with it.</p>
<h3 id="heading-nameserver">Nameserver</h3>
<p><strong>Nameserver</strong> is the server which contain <code>DNS</code> records for your domain. Think of it like a phonebook which contains your addresses, there can be many phonebooks but only one some will contain your details.</p>
<pre><code class="lang-mermaid">graph LR
  B[Browser] --&gt;|domain| N[Nameserver] --&gt; |ip address| B
</code></pre>
<p>To manage my custom domain on cloudflare I had to update my nameservers on namecheap and point them to the ones that cloudflare provided me.</p>
<p>To verify that nameserver is set properly we can use <code>dig</code> command</p>
<pre><code class="lang-bash">dig king-11.dev NS +short
mark.ns.cloudflare.com. ollie.ns.cloudflare.com.
</code></pre>
<p>Now the domain is in hands of <code>cloudflare</code> it can now easily create new DNS records for my domain name.</p>
<h2 id="heading-security-settings">Security Settings</h2>
<p>We can do additional setup to ensure that the content is transferred securely between all involved entities. To do this will enable full SSL (Secure Socket Layer)/TLS (Transport Layer Security). Under websites -&gt; king-11.dev -&gt; SSL/TLS, we would set my encryption mode to <code>Full</code>.</p>
<pre><code class="lang-mermaid">graph LR
  B(Browser) --&gt;|🔒| C(Cloudflare) --&gt;|🔒| O(Origin Server)
</code></pre>
<p>Furthermore, I can upgrade all the <code>HTTP</code> connection to <code>HTTPS</code> which returns content to user over a secure transport channel.</p>
<ol>
<li><p>Under the SSL/TLS section, there is option of <em>Edge Certificates</em></p>
</li>
<li><p>Under Edge Certificates, we can enable “<em>Always Use HTTPS”</em></p>
</li>
</ol>
<pre><code class="lang-mermaid">graph TD
  B(Browser) --&gt;|HTTP Connection| C(Cloudflare)
  C --&gt;|307 Internal Redirect| B
  B --&gt;|Connection Redirect| B
  B --&gt;|HTTPS Connection| C
</code></pre>
<h2 id="heading-github-pages">Github Pages</h2>
<p>I have been using github pages to deploy my static sites which included my <a target="_blank" href="github.com/king-11/blog">blog</a> repository. It uses a <a target="_blank" href="https://github.com/king-11/blog/blob/main/.github/workflows/hugo.yaml#L36"><strong>github action</strong></a> to build and then publish my <a target="_blank" href="https://gohugo.io/"><strong>hugo</strong></a> based site onto github pages.</p>
<p>The change I needed to make here was</p>
<ol>
<li><p>Add the custom domain in Settings -&gt; Pages section.</p>
</li>
<li><p>Create DNS entry in cloudflare to point <a target="_blank" href="blog.king-11.dev">blog.king-11.dev</a> towards a github server.</p>
</li>
</ol>
<p>But I don’t know the server neither does cloudflare’s nameserver and given I am no more using <a target="_blank" href="king-11.github.io/blog">king-11.github.io/blog</a> that entry would just redirect to my custom domain. So who will find me the ip address for my site?</p>
<h3 id="heading-cname-entry">CNAME Entry</h3>
<p>Given github is the only one aware about the IP Address of my server, cloudflare needs to add a mapping such that dns resolution for my subdomain is offloaded to github.</p>
<p>This is exactly what CNAME records provide a DNS level redirection, they map one domain to another domain where both can be handled by different nameservers.</p>
<pre><code class="lang-mermaid">graph LR
  B[(Browser)] --&gt;|blog.king-11.dev| C[(Cloudflare)]
  C --&gt;|blog.king-11.dev| G[(Github)]
</code></pre>
<p>So in the above case when users asks cloudflare for blog site it redirects user to github which given the custom domain configuration settings know which server this domain points to and can provide user the result i.e. an A Name Record (domain -&gt; IP).</p>
<p>To see this in line action we can use the command</p>
<pre><code class="lang-bash">dig blog.king-11.dev +trace
</code></pre>
<h3 id="heading-mixed-content-bug">Mixed Content Bug</h3>
<p>After all this process it started to happen that the cover of my blogs wasn’t visible anymore. Checking the console of browser the issue was that</p>
<blockquote>
<p>Mixed Content: The page at ‘<a target="_blank" href="https://blog.king-11.dev/posts/memory-management/'">https://blog.king-11.dev/posts/memory-management/'</a> was loaded over HTTPS, but requested an insecure image ‘<a target="_blank" href="http://blog.king-11.dev/posts/memory-management/cover_hu3f9b19c18b96efe8ccfa749888a579de_415626_720x0_resize_q75_h2_box_2.webp'">http://blog.king-11.dev/posts/memory-management/cover_hu3f9b19c18b96efe8ccfa749888a579de_415626_720x0_resize_q75_h2_box_2.webp'</a>. This request has been blocked; the content must be served over HTTPS.</p>
</blockquote>
<p>So browsers don’t allow accessing any HTTP (insecure) resource from an HTTPS (secure) page. But why was it using <code>http</code>?</p>
<p>I tried setting <code>cloudflare</code> to redirect <code>http</code> to <code>https</code> itself but browser was already blocking any <code>http</code> connection before even going out of the browser. I checked the generated html of my blog page to find the image component as</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">loading</span>=<span class="hljs-string">"lazy"</span> <span class="hljs-attr">srcset</span>=<span class="hljs-string">"http://blog.king-11.dev/posts/memory-management/cover_hu3f9b19c18b96efe8ccfa749888a579de_415626_360x0_resize_
q75_h2_box_2.webp 360w ,http://blog.king-11.dev/posts/memory-management/cover_hu3f9b19c18b96efe8ccfa749888a579de_415626_480x0_resize_q75_
h2_box_2.webp 480w ,http://blog.king-11.dev/posts/memory-management/cover_hu3f9b19c18b96efe8ccfa749888a579de_415626_720x0_resize_q75_h2_b
ox_2.webp 720w ,http://blog.king-11.dev/posts/memory-management/cover_hu3f9b19c18b96efe8ccfa749888a579de_415626_1080x0_resize_q75_h2_box_
2.webp 1080w ,http://blog.king-11.dev/posts/memory-management/cover.webp 1080w"</span> <span class="hljs-attr">sizes</span>=<span class="hljs-string">"(min-width: 768px) 720px, 100vw"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://blog
.king-11.dev/posts/memory-management/cover.webp"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> <span class="hljs-attr">width</span>=<span class="hljs-string">"1080"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"1080"</span>&gt;</span>
</code></pre>
<p>So, the <code>src</code> tag is correct but image is loaded using <code>srcset</code> (due to precedence) whose urls are prefixed with <code>http</code>. Now I updated my <code>baseURL</code> in hugo <a target="_blank" href="https://github.com/king-11/blog/blob/main/config.yml#L1">config</a> file but still nothing was happening generated html was still using <code>http</code> only.</p>
<p>So I checked further <code>github</code> without information that SSL/TLS is enabled on my system was passing <code>http://blog.king-11.dev</code> to my github action which wasn’t using <code>baseURL</code> set in <code>config</code> file. Finally, it made sense leading to a final commit with the following diff</p>
<pre><code class="lang-diff">     run: |
       hugo \
         --gc \
<span class="hljs-deletion">-        --minify \</span>
<span class="hljs-deletion">-        --baseURL "${{ steps.pages.outputs.base_url }}/"</span>
<span class="hljs-addition">+        --minify</span>
   - name: Upload artifact
</code></pre>
<h2 id="heading-vercel-redirection">Vercel Redirection</h2>
<p>After going through github vercel setup was a breeze. Again given vercel deploys my site it has the <em>A Name Record</em> for it. So on cloudflare I just need to add a CNAME record pointing my root to vercel’s cname domain and rest vercel handles on its own.</p>
<p>Two key things useful for vercel is:</p>
<ul>
<li><p>Set SSL/TLS encryption to Full mode initially it is flexible, which can lead to <a target="_blank" href="https://vercel.com/guides/resolve-err-too-many-redirects-when-using-cloudflare-proxy-with-vercel">ERR_TOO_MANY_REDIRECTS</a></p>
</li>
<li><p>Enabling <code>Always Use HTTPS</code> allows ACME protocol used to validate the domain ownership to <a target="_blank" href="https://vercel.com/docs/integrations/external-platforms/cloudflare#troubleshooting">bypass restrictions</a> and use <code>http</code>.</p>
</li>
</ul>
<p>What came in handy here is vercel has a great documentation for bugs, troubleshooting and setup 🎉.</p>
<h2 id="heading-cloudflare-tunnel">Cloudflare Tunnel</h2>
<p>So this all started from cloudflare tunnels. I have added details in my post <a target="_blank" href="https://blog.king-11.dev/posts/living-hacker/#self-hosting">The Hacker Way of Living</a> about how I use self hosting to keep a personal library of movies and series, downloaded using torrent and hosted on my raspberry pi 4 using <a target="_blank" href="https://jellyfin.org/">jellyfin</a> media server.</p>
<p>To access it <a target="_blank" href="https://umbrel.com/">umbrel</a> provides <strong>tor</strong> based access which is very slow so I needed a faster solution. There was <a target="_blank" href="https://tailscale.com/">Tailscale VPN</a> which wasn’t working so the other option was <a target="_blank" href="https://www.cloudflare.com/en-in/products/tunnel/">cloudflare tunnel</a>.</p>
<pre><code class="lang-mermaid">graph LR
    B((Browser)) --&gt;|jellyfin.king-11.dev| C[(Cloudflare)]
    O[(Origin Server)] --- D[cloudflared]
    D --&gt; C
    M((👨‍💻)) --x D
</code></pre>
<p>So while there is a connection between <code>cloudflare</code> and <code>cloudflared</code> (d is for daemon process) on my raspberry pi, no other user can access it. I can then use <code>cloudflare</code> to serve it on a custom domain which I purchased.</p>
<p>We can go on our dashboard, Zero Trust -&gt; Networks -&gt; Tunnels to create a new tunnel. Now to expose it or even multiple other endpoints we need to add our public ip and what it internally maps to on the origin server.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>So the idea was for me to easily access my jellyfin from anywhere in the world while my raspberry pi 4 easily sits at my flat. Sadly, my flatmate unplugged it and forgot to plug it back.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347470149/4499b49b-79d0-4f63-84c8-e7ad1c718a8c.gif" alt="unplug" /></p>
<p>Screams!, first of all you never unplug a server without properly shutting it down it will lead to data corruption. And secondly the server always stays plugged in. I need to set some new flat rules and setup warnings signs. Alexa play “<em>new rules</em>” because I don’t have tickets to go and see dua lipa 😭.</p>
<p>That was all for this time, it was quite some learning about <strong>networks</strong> that my computer science course didn’t even care to touch. I hope when you try to setup your own custom domain or self host things this blog would come handy. Thanks for reading see you next time after my next trip :P.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347471545/c624913a-d88d-4b0d-baad-64c7e028cb20.gif" alt="thank you merci" /></p>
]]></content:encoded></item><item><title><![CDATA[Memory Management]]></title><description><![CDATA[Modern programming languages that we work with these days have made memory management simpler that ever, they manage it on their own using things like garbage collectors, smart pointers, ownership, etc.
Creating an empty vector is as simple as
let em...]]></description><link>https://hashnode.king-11.dev/memory-management</link><guid isPermaLink="true">https://hashnode.king-11.dev/memory-management</guid><category><![CDATA[operating system]]></category><category><![CDATA[Computer Science]]></category><category><![CDATA[memory-management]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Sat, 07 Sep 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730383841573/6815a4b4-473e-489f-97cf-71ba0e99c76b.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Modern programming languages that we work with these days have made memory management simpler that ever, they manage it on their own using things like garbage collectors, smart pointers, ownership, etc.</p>
<p>Creating an empty vector is as simple as</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> empty_vec: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = <span class="hljs-built_in">Vec</span>::new();
</code></pre>
<p>But some questions remain unanswered if you haven’t tried manually doing memory operations like:</p>
<ul>
<li><p>how is a sized vector created using <code>Vec::with_capacity</code>?</p>
</li>
<li><p>how is a vector resized on calling <code>pop_back</code> or <code>push_back</code>?</p>
</li>
<li><p>and finally how is the memory freed when vector goes out of scope?</p>
</li>
</ul>
<p>Let’s engage in old god <code>C</code> as its closest we get to actual system calls and try to figure out these question <strong>inside out</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347489930/7619300f-959e-4225-a76e-f64e8b83a830.gif" alt="memory inside out" /></p>
<h2 id="heading-memory-allocation">Memory Allocation</h2>
<p>To store a vector or object we need a backing address in the physical memory of our system. We use <code>malloc</code> to ask operating system for more memory which looks something like below.</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span>* numbers = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">malloc</span>(<span class="hljs-number">8</span> * <span class="hljs-number">42</span>);
</code></pre>
<p>In above code we are trying to create an array of numbers or more pedantically a <code>pointer</code> to integer which is the starting point of our array.</p>
<p>The parameter to <code>malloc</code> is the number of bytes we want to allocate. Given on a <strong>64 bit</strong> system an integer takes <strong>8 bytes</strong> so we are allocating for <code>42</code> integers.</p>
<p><code>malloc</code> returns a <code>void *</code> which is <code>C</code>’s way of saying it can be anything so we have to <em>type cast</em> it based on our requirement and understanding.</p>
<h3 id="heading-dynamic-sizing">Dynamic Sizing</h3>
<p>Generally we can’t rely on hard coding the size of objects integers might be simple but can still vary on a <strong>32 bit</strong> machine. A more complex thing like a struct of multiple values will vary even more.</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">foo</span>
{</span>
  <span class="hljs-keyword">int</span> element;
  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">foo</span> *<span class="hljs-title">next</span>;</span>
};
</code></pre>
<p>So its better to use a utility function <code>sizeof</code> for calculating size of our type.</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span>* numbers = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>) * <span class="hljs-number">42</span>);
</code></pre>
<p>In case you are running on <strong>512 MB</strong> system and system runs out of memory <code>malloc</code> will return <code>NULL</code> value.</p>
<blockquote>
<p>It’s not the <code>null</code> you see in <code>Java</code> and other garbage collected languages, <code>NULL</code> means a zero value something like <code>(void *)0</code> whereas the other keyword is used to identify a variable as not having any reference.</p>
</blockquote>
<h3 id="heading-pointer-inside-pointer">Pointer inside Pointer</h3>
<p>How about we handle an even more complex scenario</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">wallet</span> {</span>
    <span class="hljs-keyword">int</span> version;
    <span class="hljs-keyword">int</span> *notes;
};
</code></pre>
<p>Now we have a dynamic array inside of a dynamic struct which we have to allocate memory for, using just <code>sizeof</code> will give an empty array to us and it will <strong>segfault</strong> if you try to access array’s memory.</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">wallet</span>* <span class="hljs-title">w</span> = (<span class="hljs-title">struct</span> <span class="hljs-title">wallet</span> *)<span class="hljs-title">malloc</span>(<span class="hljs-title">sizeof</span>(<span class="hljs-title">struct</span> <span class="hljs-title">wallet</span>));</span>
<span class="hljs-comment">// this will segfault</span>
<span class="hljs-comment">// w-&gt;notes[0] = 42;</span>
</code></pre>
<p>So we have to allocate memory of the <code>array</code> of integers inside of our <code>wallet</code>.</p>
<pre><code class="lang-c">wallet-&gt;notes = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>) * <span class="hljs-number">42</span>);
</code></pre>
<h3 id="heading-zeroing-memory">Zeroing Memory</h3>
<p>If you use <code>malloc</code> the memory is allocated to us but its never zeroed out before we get it. It can have <strong>garbage values</strong> which if not cleaned can cause your program to behave in unexpected ways.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347491917/9364d350-0289-47dd-8c5e-04fe076e399d.gif" alt="cleaning dirty" /></p>
<p>The solution for this is to use one shot allocation and memory zeroing using <code>calloc</code>.</p>
<pre><code class="lang-c">w-&gt;notes = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">calloc</span>(<span class="hljs-number">4</span>, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>));
</code></pre>
<p><code>calloc</code> allocates an array of size <code>4</code> where size of each element is <code>sizeof(int)</code>. The returned memory is set to zero.</p>
<p>Now the question arises why not always use <code>calloc</code>:</p>
<ul>
<li><p>First it only works for <strong>array</strong> allocation so you can’t allocate a <code>struct</code> using it.</p>
</li>
<li><p>It is <strong>slow</strong>, in case you don’t need to zero memory out and pass the buffer to some other function which maybe reads the file or does some other <code>io</code> just use the big brother <code>malloc</code>.</p>
</li>
</ul>
<h2 id="heading-resizing">Resizing</h2>
<p>To answer the next question that we had in regard of a <code>vector</code> is basically related to allocating more memory and de-allocating extra memory. We do that using <code>realloc</code> function.</p>
<p>We will declare our vector struct as below it will track backing store, current position and total size of store.</p>
<pre><code class="lang-c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vector</span> {</span>
  <span class="hljs-keyword">int</span> *backing_store;
  <span class="hljs-keyword">int</span> current_position;
  <span class="hljs-keyword">int</span> backing_store_size;
};
</code></pre>
<p>When we call <code>push_back</code> the vector checks whether the size of its backing store is sufficient or not. If not, it allocates a backing store of <strong>double size</strong> using <code>realloc</code> and the places the element there. The newly allocated memory will be <strong>uninitialised</strong>.</p>
<pre><code class="lang-c"><span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">push_back</span><span class="hljs-params">(struct <span class="hljs-built_in">vector</span> *v, <span class="hljs-keyword">int</span> element)</span> </span>{
  <span class="hljs-keyword">if</span> (v-&gt;backing_store_size &lt;= v-&gt;current_position) {
    v-&gt;backing_store_size = v-&gt;backing_store_size * <span class="hljs-number">2</span>;
    v-&gt;backing_store = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">realloc</span>(v-&gt;backing_store, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>) * v-&gt;backing_store_size);
  }
  v-&gt;backing_store[v-&gt;current_position] = element;
  v-&gt;current_position = v-&gt;current_position + <span class="hljs-number">1</span>;
}
</code></pre>
<p>Similarly, we can handle <code>pop_back</code>, just one crucial optimisation we won’t reduce to half but instead if current position is less that <code>1/4th</code> of backing store size then we reduce the backing store to <strong>quarter</strong> of its previous size.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730383929746/f51d0cdd-9777-4b03-ba91-8f04d6f27de7.webp" alt /></p>
<p>All the functions above return a <code>NULL</code> value in case of error and set <code>errno</code> which is <code>C</code>s way of communicating error kind.</p>
<h2 id="heading-freeing">Freeing</h2>
<p>It’s also important that we keep our memory usage in check otherwise it can <strong>exceed</strong> the physical memory <strong>capacity</strong> really fast. We have to <code>free</code> unused memory and return it back to the operating system.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347493308/a7808572-cecc-43e5-8165-72681d96e01e.gif" alt="be free" /></p>
<p>It’s done using <code>free</code> function call, you pass in the pointer where memory is allocated and it will return it back to the system.</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span>* numbers = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>) * <span class="hljs-number">42</span>);
<span class="hljs-built_in">free</span>(numbers);
</code></pre>
<h2 id="heading-common-errors">Common Errors</h2>
<p>The rise of <strong>RUST</strong> memory safe languages, paradigm like <a target="_blank" href="https://en.cppreference.com/book/intro/smart_pointers">smart pointers</a> in C++ and system like <a target="_blank" href="https://en.cppreference.com/w/cpp/language/raii">RAII</a> is because of the reason that there are so many memory issues that keep happening in systems.</p>
<p>The recent <a target="_blank" href="https://www.youtube.com/watch?v=H9RSeDUdkCA">Crowd Strike</a> one was also a memory issue where <a target="_blank" href="https://x.com/Perpetualmaniac/status/1814376668095754753">invalid memory buffer</a> was being accessed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347494367/2dc4d78a-caa2-4b9c-bb90-72b85afbc745.gif" alt="blue screen of death" /></p>
<p>Let’s go over some common gotchas that you have to keep in mind while managing memory.</p>
<h3 id="heading-invalid-free">Invalid Free</h3>
<p>Accessing a memory which was already <strong>freed</strong> will cause <strong>SEGFAULT</strong> and trying to free (double free) it again is an <strong>undefined</strong> behaviour you might not wanna encounter.</p>
<p>Free expects a pointer from the result of call to <code>malloc</code> passing anything else will also result in erroneous program execution.</p>
<h3 id="heading-less-allocation">Less Allocation</h3>
<p>It’s possible you might have allocated less memory than required or no memory at all for an operation in which case <strong>buffer overflow</strong> will happen or <strong>SEGFAULT</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730383947033/65860d43-3472-4b2f-84bf-41cceb630448.webp" alt /></p>
<blockquote>
<p>It is one of the <code>binary exploitation</code> ways <a target="_blank" href="https://owasp.org/www-community/vulnerabilities/Buffer_Overflow">hackers</a> use and will probably cost your service a lot of secret credentials.</p>
</blockquote>
<pre><code class="lang-c"><span class="hljs-keyword">char</span> *src = <span class="hljs-string">"hello world"</span>;
<span class="hljs-keyword">char</span> *dst = (<span class="hljs-keyword">char</span> *)<span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">char</span>) * <span class="hljs-number">4</span>);
<span class="hljs-comment">// dst has size 4 while required is strlen(src) + 1</span>
<span class="hljs-built_in">strcpy</span>(dst, src);
</code></pre>
<blockquote>
<p>In above example we could have probably used <code>strdup</code>.</p>
</blockquote>
<h3 id="heading-garbage-values">Garbage Values</h3>
<p>Accessing <strong>garbage</strong> or <strong>uninitialised</strong> value without clearing your memory will result in undefined behaviour of your program. It’s sometimes good to use <code>calloc</code> or clear memory on your own.</p>
<h3 id="heading-memory-leak">Memory Leak</h3>
<p>Allocated memory is returned back to operating system when program dies even if you don’t call <code>free</code> on your own.</p>
<p>But that’s only in case of short running processes, in case of long ones like <strong>databases</strong> and <strong>servers</strong> if you don’t free unused memory, the memory allocated to program will keep increasing and finally your system will run out of available memory leading to <strong>crash.</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347495792/523f9f45-36d2-4508-955a-e0ea8bd7435b.gif" alt="no memory" /></p>
<h2 id="heading-finding-memory-issues">Finding memory issues</h2>
<p><a target="_blank" href="https://www.usenix.org/legacy/publications/library/proceedings/usenix05/tech/general/full_papers/seward/seward.pdf">valgrind</a> is one of the tools we can use to identify memory related issues. It can tell us about:</p>
<ul>
<li><p>uninitialised reads</p>
</li>
<li><p>invalid memory read/write</p>
</li>
<li><p>memory leak</p>
</li>
<li><p>invalid free, and a lot more</p>
</li>
</ul>
<p>For a buggy program like this</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> *data = (<span class="hljs-keyword">int</span> *)<span class="hljs-built_in">malloc</span>(<span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">int</span>) * <span class="hljs-number">100</span>);
data[<span class="hljs-number">100</span>] = <span class="hljs-number">42</span>;
</code></pre>
<p>It will tell us about the invalid write if you run it through and also about the lack of a <code>free</code> call.</p>
<pre><code class="lang-bash">gcc -g test.c -o <span class="hljs-built_in">test</span>
valgrind --leak-check=yes ./<span class="hljs-built_in">test</span>
<span class="hljs-comment"># Invalid write of size 4</span>
<span class="hljs-comment"># 400 bytes in 1 blocks are definitely lost in loss record 1 of 1</span>
</code></pre>
<p>In case we try to access uninitialised memory and run it through <code>valgrind</code> it will let us know</p>
<pre><code class="lang-c"><span class="hljs-built_in">printf</span>(<span class="hljs-string">"value at index 11"</span>, data[<span class="hljs-number">11</span>]);
# Use of uninitialised value of size <span class="hljs-number">8</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Knowing about memory management is very crucial to build <strong>safe</strong> and <strong>performance</strong> critical software which basically is every software.</p>
<p>Offloading tasks to garbage collectors in programming languages with automatic memory management does make it easy but things like memory leak can still happen there so you should know what’s happening in your program otherwise <strong>AI replacement</strong> is coming for you :P.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347496836/8ae83d99-f7cb-47d9-997e-3c0dfd80f0d9.gif" alt="ai destroy humans" /></p>
<p>That was all for this week, I wrote this piece after reading through <a target="_blank" href="https://pages.cs.wisc.edu/~remzi/OSTEP/">Operating System: Three Easy Pieces</a> its a very nice book with <em>exercises</em> and <em>references</em> to research papers I am enjoying reading it will keep sharing my learning from it as I try to complete it fingers crossed.</p>
<p>You can read more of my articles on my <a target="_blank" href="https://blog.king-11.dev">blog</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Rate Limiting]]></title><description><![CDATA[Why to Rate Limit?
Rate Limiting is a crucial part of designing any API it maybe private or public. A rate limiter caps how many requests a sender can issue in a specific window of time. A rate limiter provides following features:

Defense against a ...]]></description><link>https://hashnode.king-11.dev/rate-limiting</link><guid isPermaLink="true">https://hashnode.king-11.dev/rate-limiting</guid><category><![CDATA[System Design]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Sat, 10 Feb 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730375179386/e0cdb838-c105-48f7-90c3-4bf1d5d68516.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-why-to-rate-limit">Why to Rate Limit?</h2>
<p>Rate Limiting is a crucial part of designing any API it maybe private or public. A rate limiter caps how many requests a sender can issue in a specific window of time. A rate limiter provides following features:</p>
<ul>
<li><p>Defense against a Denial of Service from malicious actors trying to pull down the service.</p>
</li>
<li><p>Ensures the load on servers is always under maintainable state by discarding too many requests.</p>
</li>
<li><p>Prevent broke developers from receiving an unexpectedly large bill in today’s auto scalable cloud service offerings.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347569041/bc07062c-4276-4958-8907-b1c139ef3f01.gif" alt="broke girls meme gif" /></p>
<p><em>I can relate with you Max :’(</em></p>
<h2 id="heading-algorithms">Algorithms</h2>
<p>Rate Limiting implementation can use different algorithms based on the requirement of our applications. Two key parameters are how we define our user (ip address, user id, device, etc.) and the second being our time window (1 minute, 1 hour, etc.)</p>
<h3 id="heading-token-bucket">Token Bucket</h3>
<p>In token bucket algorithm we have a fixed size bucket which keeps getting filled by tokens at a uniform rate. When a new request arrives it is only processed if we have at-least one token in the bucket, otherwise the request is dropped.</p>
<pre><code class="lang-mermaid">flowchart LR
    r(Request)
    t[[tap]]
    b[(Bucket)]
    c[/count &gt; 0/]
    p((Process))
    d((Drop))

    r --&gt; c
    t --&gt; b
    b &lt;--&gt; c
    c --&gt;|true| p
    c --&gt;|false| d
</code></pre>
<h3 id="heading-leaky-bucket">Leaky Bucket</h3>
<p>In leaky bucket algorithm there is a fixed size queue where new requests are queued. These requests are then consumed at a uniform rate. A new request is dropped if bucket is a it’s capacity.</p>
<pre><code class="lang-mermaid">flowchart LR
    r(Request)
    b[(Queue)]
    c[/!capacityFull/]
    p((process))
    d((drop))

    r --&gt; c
    c --&gt;|true| b
    c --&gt;|false| d
    b --&gt; p
</code></pre>
<p>Leaky and Token bucket algorithm are relatively simple to implement but on the downside it’s difficult to find the right value for bucket size and token generation/request consumption rate.</p>
<h3 id="heading-fixed-window-counter">Fixed Window Counter</h3>
<p>In fixed window counter we keep track of number of requests within a fixed time range e.g. a minute or 30 seconds etc. We only process a limited number of requests within the time window beyond which the requests are dropped (red ones).</p>
<pre><code class="lang-mermaid">gantt
    title Requests v/s Time
    dateFormat m:ss
    axisFormat %M:%S
    tickInterval 10second
    R1 :0:00,10s
    R2 :10s
    R3 :0:25,10s
    R4 :crit,0:40,10s
    R5 :crit,0:45,10s
</code></pre>
<p>The issue with fixed window counter comes around when there are requests coming near the boundary of two windows. In such a scenario we actually end up processing more request within time window than set parameter.</p>
<pre><code class="lang-mermaid">gantt
    title Requests v/s Time
    dateFormat m:ss
    axisFormat %M:%S
    tickInterval 10second

    R3 :0:30,10s
    R4 :0:40,10s
    R5 :0:45,10s
    R6 :1:00,10s
    R7 :1:00,10s
    R8 :1:20,10s
</code></pre>
<p>In the above example within time range of 00:30 - 01:30 instead of 3 the rate limiter allowed 6 requests which is double of what was expected of it to allow in a minute. O(2*n)</p>
<h3 id="heading-sliding-window-log">Sliding Window Log</h3>
<p>Sliding Window log is a dynamic one which handles the previous faults in fixed window counter by keeping track of requests in the current time window which is updated with every new request. It also uses a log to keep track of current requests.</p>
<p>Whenever a new request arrives</p>
<ul>
<li><p>We delete all the entries older than current time window.</p>
</li>
<li><p>Now request’s timestamp is added to our log which now represents all the requests made in current time window.</p>
</li>
<li><p>If the <code>len(log) &lt;= rate</code> then we process the request else its dropped</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730375273874/2cac83c6-e8e1-4520-8d1e-3bf788c266a6.webp" alt /></p>
<p>Generally redis sorted sets are the used to keep track of timestamps in an efficient data structure which allows easy querying and updates.</p>
<p>Even with all its goodness its a little flawed due to the high memory usage. In case of a DoS attack we can have thousands of these log entries leading to huge memory usage and no valid requests will be processed in this duration these drawbacks lead us to the last algorithm.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730375280592/e99e60de-1b4b-4c48-97ef-bb7004eba719.webp" alt /></p>
<h3 id="heading-sliding-window-counter">Sliding Window Counter</h3>
<p>It is a hybrid approach inspired from fixed window counter and sliding window log. It takes the best part of both and combines them <strong>sliding window log + fixed window counter</strong>.</p>
<p>To fix the flaws of fixed window counter it uses a <strong>weighted counter</strong> to smooth out burst around window boundaries which takes previous and present window requests into account.</p>
<pre><code class="lang-python">percent = (cur_time - start_time_cur_window) / window_size

weighted_counter = requests_prev_window * (<span class="hljs-number">1.0</span> - percent) + requests_cur_window * percent
</code></pre>
<p>Liked sliding window log we need to use memory for keeping track of history. To count requests from each sender we will use multiple fixed time windows 1/60th the size of our rate limit’s time window like <a target="_blank" href="https://www.figma.com/blog/an-alternative-approach-to-rate-limiting/">figma</a> does. This remedies the memory footprint issue limiting it to just 60 values for every user.</p>
<pre><code class="lang-bash">4 bytes per counter * 60 counters * 100,000 users = 24,000,000 bytes OR 24MB
</code></pre>
<p>To reduce our memory footprint, we can store counters in a Redis hash which are highly efficient in their <a target="_blank" href="https://redis.io/topics/memory-optimization">storage usage</a>. Each new request which increments the counter it can set the expiry for it based on our time window but still there is a possibility of DoS attack to remedy this we should clean up hashes at regular intervals if they are rapidly increasing.</p>
<pre><code class="lang-mermaid">flowchart LR
    r[request]
    i(increment counter)
    c[/weighted counter &lt; limit/]
    re[(Redis)]
    p((process))
    d(drop)

    r --&gt; i
    i --&gt; c
    c &lt;--&gt; re
    c --&gt; p
    c --&gt; d
</code></pre>
<h2 id="heading-http-response">HTTP Response</h2>
<p>Now that we have rate limited user its also important to convey it back to the end user. HTTP 429 - Too Many Requests is the status code which is created for this purpose. We can add in more details in HTTP Headers as well</p>
<ul>
<li><p>X-Ratelimit-Remaining</p>
</li>
<li><p>X-Ratelimit-Limit</p>
</li>
<li><p>X-Ratelimit-Retry-After</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347570910/bcb4cf08-41ff-447f-9808-7658765258a0.gif" alt="thank you modi ji" /></p>
<p>I wrote this blog to better my <strong>understanding</strong> as am currently reading the holy grail of system design: <a target="_blank" href="https://www.goodreads.com/book/show/54109255-system-design-interview-an-insider-s-guide">The System Design Interview Book</a>. I was never rate limited before but recently when I unfollowed over <strong>1k</strong> people on <em>Instagram</em> it rate limited me.</p>
<p>I made use of <a target="_blank" href="https://mermaid.js.org/">mermaid diagrams</a> for the first time in my blog compared to using <a target="_blank" href="https://excalidraw.com/">excalidraw</a>. Mermaid is pretty cool, easy to use, keeps me inside the markdown and its just text so very easily transferable.</p>
<p>I hope I was able to share my understanding with you, <strong>thanks</strong> for your support till here. If you’ve enjoyed this read, please share it, to help others find it as well. Also, feel free ping me up for any comment on <a target="_blank" href="https://twitter.com/1108king">@1108King</a>😁</p>
]]></content:encoded></item><item><title><![CDATA[VLS - Summer of Bitcoin 2023]]></title><description><![CDATA[I had previously completed Google Summer of Code | 2021 and Linux Foundation Mentorship | 2021 two highly renowned open source programs which paved my path towards excellence as a software developer. I chose open source for reasons I have highlighted...]]></description><link>https://hashnode.king-11.dev/vls-summer-of-bitcoin-2023</link><guid isPermaLink="true">https://hashnode.king-11.dev/vls-summer-of-bitcoin-2023</guid><category><![CDATA[Open Source]]></category><category><![CDATA[Bitcoin]]></category><category><![CDATA[Rust]]></category><category><![CDATA[Summer of Bitcoin]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Sun, 04 Feb 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355982542/2e4d75ce-fabb-4949-9c41-6e06c3b08670.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I had previously completed <a target="_blank" href="https://king-11.github.io/blog/posts/gsoc-report/">Google Summer of Code | 2021</a> and <a target="_blank" href="https://king-11.github.io/blog/posts/lfx-report/">Linux Foundation Mentorship | 2021</a> two highly renowned open source programs which paved my path towards excellence as a software developer. I chose open source for reasons I have highlighted in <a target="_blank" href="https://king-11.github.io/blog/posts/collab-to-top/">Collaboration not Competition</a> but it brought so many other good things along with it like <strong>learning</strong>, <strong>friends</strong>, <strong>experience</strong>, <strong>connections</strong>, etc.</p>
<p>There was one space which was left for me to explore with open source, <strong>Bitcoin</strong>. Summer of Bitcoin started when I did my <strong>GSoC</strong> and the next summer (2022) again I didn’t apply because I was focused on my internship at <strong>Microsoft</strong> to grab that <strong>P.P.O.</strong> and chill for final year.</p>
<p>I was by no chance a bitcoin <strong>supporter</strong> I had heard news about <strong>bubble</strong> crash, people losing so much <strong>money</strong> including my own maternal uncle, the <strong>energy</strong> consumption for mining activities and then the associated <strong>latency</strong> of transactions. The idea seemed innovative but <strong>not</strong> at all <strong>practical</strong> to me.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347544427/181ed9d5-4a62-452c-9a17-6b7d39f34a82.gif" alt="bitcoin explain meme" /></p>
<p>I even jotted my thoughts and posted on whatsapp status. Two people (<strong>Nishant Kumar</strong> and <strong>Aditya Sharma</strong>) I vividly remember came to help me understand Bitcoin better and work towards getting a better understanding of its internals before making random claims. So that’s what I aimed to do with summer of bitcoin grab <strong>understanding</strong> of bitcoin better and completing the <strong>holy grail of open source programs</strong> before ending my college journey.</p>
<h1 id="heading-application-process">Application Process</h1>
<p>I went ahead and applied on <a target="_blank" href="https://www.summerofbitcoin.org/">website</a> for summer 2023 very <strong>late</strong> as I was engaged with <strong>Inter IIT Tech 11.0</strong>. Before getting entry on the discord server for proposal round we had to complete two bitcoin courses by <a target="_blank" href="https://learn.saylor.org/course/PRDV151">saylor</a> this included going through all the content and then giving a final exam. With whatever minimal understanding I had and internet resources, I gave the test after it was done I was on the SOB discord server.</p>
<h2 id="heading-project-selection">Project Selection</h2>
<p>With my new found love for rust I wanted to apply into a project which was written in rust. To my surprise <strong>rust</strong> was amongst the <strong>predominant</strong> technology being used in bitcoin which speaks a lot about the intent to make sure bitcoin and its associated projects are <strong>secure software</strong> to use.</p>
<p>While most projects were already flooded with applicants <a target="_blank" href="https://vls.tech">VLS</a> caught my eye as there weren’t many people engaged so I went with it. I was welcomed by <strong>Ken</strong> who is such a humble individual with so much knowledge and experience.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356007186/edc3393c-5d27-4cd8-afeb-f72bfbd2fd46.webp" alt /></p>
<h2 id="heading-competency-test">Competency Test</h2>
<p>Every project in the organisation had an associated competency test. We had to build the software and like every new software I couldn’t at first. It’s generally because I use bleeding edge linux like <strong>fedora</strong> and <strong>manjaro</strong> (in past) while it takes sometime for packages to catch upto them.</p>
<pre><code class="lang-bash">make build-experimental
<span class="hljs-comment"># error: not a problem with poetry but with grpcio (1.47.0)</span>
<span class="hljs-comment"># latest gcc wasn't yet ready to work with grpcio</span>
</code></pre>
<p>I didn’t want to setup a virtual machine as they are very slow. Also I didn’t want to shift to ubuntu whose operations were working fine. So I created a <strong>ubuntu container</strong> and tried running vls tests inside it. I encountered some errors related to lowdown which ken helped me resolve.</p>
<p>Again I couldn’t do this because containers don’t support <strong>systemd</strong>.</p>
<pre><code class="lang-mermaid">flowchart LR
    s[systemd]
    sn[snapd]
    btc[bitcoind]
    s --&gt; sn
    sn --&gt; btc
</code></pre>
<p>I think I tried <strong>WSL</strong> but systemd isn’t directly supported there as well. I was only able to make VLS work on WSL later around August and documented my journey with WSL in a <a target="_blank" href="https://github.com/king-11/dotrc/issues/3">github issue</a></p>
<p>Finally I made some space and <strong>triple booted</strong> my beast of a laptop. So I had <strong>Ubuntu 22</strong>, <strong>Fedora 35</strong> and <strong>Windows 10</strong> on the same device now. Finally I completed competency test which was to find the time taken by some of the operations by wrapping function calls in <code>Instant::now()</code> and <code>elapsed()</code> on certain tests.</p>
<pre><code class="lang-bash">Time elapsed <span class="hljs-keyword">in</span> sign_counterparty_commitment_tx_phase2() is: 1.430216ms
Time elapsed <span class="hljs-keyword">in</span> validate_commitment_tx() is: 30.734µs
</code></pre>
<p>There was only one project for VLS. The bench-marking one:</p>
<blockquote>
<p>The project aims to benchmark and improve the performance of the Validating Lightning Signer.</p>
</blockquote>
<p>I clarified on the expectations of project from ken and devrandom:</p>
<ol>
<li><p><strong>Identifying</strong> main operations for benchmarking</p>
</li>
<li><p><strong>Benchmarking</strong> the main operations of a node running against the VLS</p>
</li>
<li><p>Identifying <strong>bottlenecks</strong> causing latency for different configurations</p>
</li>
<li><p><strong>Updating</strong> the code base to handle those bottlenecks</p>
</li>
</ol>
<p>I covered details about two options for creating bench-marking tests <code>criterion</code> and <code>test</code>. Listed down ways we can do <strong>optimisation algorithmic, config, inlining functions,</strong> etc. During phase of proposal submission I started helping other beginner contributors as much as I can while trying to understand the project.</p>
<h3 id="heading-last-minute-submission">Last Minute Submission</h3>
<p>I <strong>delayed</strong> the whole writing of proposal till very late. I don’t remember why I did it but it was probably because it was my <strong>final semester</strong> in college and I wanted to leave no stone un-turned explore everything, hangout with friends, work for council and clubs, etc.</p>
<p>The deadline for submission was <strong>16th April, 7:30AM</strong> and I began writing my proposal after coming from Shubhanshu and Yamini’s birthday party on <strong>15th April</strong> at <strong>11:50PM</strong>. I somehow kept myself awake through the process of writing proposal and submitted the proposal. With no expectation of getting selected or not I was at peace.</p>
<h2 id="heading-selection">Selection</h2>
<p>Jack contacted me while they were checking my application to know about when do I start with Microsoft. I misread and talked about my internship experience instead, he told me they had submitted results and Adi will reach out to us.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356055548/bfeb4d49-1f6e-459e-bdec-ccac2a19e1f6.webp" alt /></p>
<h1 id="heading-summer-of-bitcoin">Summer of Bitcoin</h1>
<p>I had the onboarding call with <strong>ken</strong>, <strong>devrandom</strong> and <strong>jack</strong>. There was one more fellow intern with me dhruv. The team liked both of our applications and hence decided to increase the slots and create one more project for memory usage bench-marking as well. I took the time latency and dhruv memory.</p>
<p>The team got us to buy <code>STM32F413H</code> devices which would come in handy for our projects.</p>
<h2 id="heading-merge-requets">Merge Requets</h2>
<blockquote>
<p>“Talk is cheap. Show me the code.” - Linus Torvalds</p>
</blockquote>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Title</td><td>Link</td><td>Type</td></tr>
</thead>
<tbody>
<tr>
<td>cln testnet service (!431)</td><td><a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/442">https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/442</a></td><td>DOC</td><td>FIX</td></tr>
<tr>
<td>add gawk for one-time (!442)</td><td><a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/442">https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/442</a></td><td>DOC</td><td>FIX</td></tr>
<tr>
<td>dont print error on help (!444)</td><td><a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/444">https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/444</a></td><td>FEATURE</td><td>FIX</td></tr>
<tr>
<td>transaction operations benchmark tests (!487)</td><td><a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/487">https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/487</a></td><td>TEST</td></tr>
<tr>
<td>fedora setup (!474)</td><td><a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/474">https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/474</a></td><td>DOC</td><td>FEATURE</td></tr>
<tr>
<td>persister bench (!492)</td><td><a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/492">https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/492</a></td><td>TEST</td></tr>
<tr>
<td>update nightly vls-signer-stm32 (!507)</td><td><a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/507">https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/507</a></td><td>DOC</td><td>FIX</td></tr>
<tr>
<td>bench crypto ops stm (!508)</td><td><a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/508">https://gitlab.com/lightning-signer/validating-lightning-signer/-/merge_requests/508</a></td><td>TEST</td></tr>
</tbody>
</table>
</div><h2 id="heading-documentation">Documentation</h2>
<p><strong>Documentation</strong>: Apart from this I worked towards fixing documentation which is the first part any developer encounters making it easy so that others don’t face the issues I did. There were changes in packages, nightly version to use for STM and minor things.</p>
<p><strong>Fedora Setup</strong>: The first thing I did as part of project was to make life easier by working out details on how to make vls work again on fedora linux. I added the details for the same into our updated documentation.</p>
<h2 id="heading-operation-latency">Operation Latency</h2>
<p>We started with our decided plans of first doing the operations (keysend, pay, etc.) and checking their latency with multiple configurations of device (socket server/stm32) and logging modes (debug/info).</p>
<p>Below is the flow when any operations happen on a lightning node with VLS.</p>
<pre><code class="lang-mermaid">sequenceDiagram
    participant SignerA
    participant NodeA
    participant NodeB
    participant SignerB

    activate NodeA
    NodeA-&gt;&gt;+SignerA: SignCounterpartyCommitment(m+1)
    SignerA--&gt;&gt;-NodeA: ack

    NodeA-&gt;&gt;+NodeB: commitment_signed(m+1)

    NodeB-&gt;&gt;+SignerB: ValidateHolderCommitment(m+1)
    SignerB--&gt;&gt;-NodeB: ack

    NodeB-&gt;&gt;+SignerB: RevokeHolderCommitment(m)
    SignerB--&gt;&gt;-NodeB: ack

    NodeB-&gt;&gt;-NodeA: revoke_and_ack(m)

    NodeA-&gt;&gt;+SignerA: ValidateCounterpartyRevocation(m)
    SignerA--&gt;&gt;-NodeA: ack

    deactivate NodeA
</code></pre>
<p>For running the operations using <strong>socket server</strong> I had setup a testnet node on my laptop which was connected to ken’s node. I had to manually go through the <strong>logs</strong> and ask ken to provide me the same using which I created <strong>diagrams</strong> with time for each operation.</p>
<p>Like a regular programmer who denies any form of <strong>manual labour</strong> I tried automating the task and making my life a little easier using <strong>scripts</strong> which used to:</p>
<ul>
<li><p>copy the vls log file and then truncate it to <code>0</code></p>
</li>
<li><p>do the operation of keysend and pay</p>
</li>
<li><p>wait for sometime after the operation is done</p>
</li>
<li><p>copy the log file again into current directory.</p>
</li>
</ul>
<p>This helped reduce the manual labour somewhat by getting logs for precisely the time of operation.</p>
<p>I also did the <a target="_blank" href="https://gitlab.com/lightning-signer/validating-lightning-signer/uploads/0b70cff01d6e364213a57a7ea3b5b0e9/signer-info.png">operations</a> for STM but instead of doing them with an external node I utilised the <strong>system tests</strong> which create temporary nodes on the same system.</p>
<h2 id="heading-benchmarking-tests">Benchmarking Tests</h2>
<p>After we had done these operations for sufficient time and were happy with the results. I started working on writing benchmark our three major operations.</p>
<ul>
<li><p>Sign Remote Commitment</p>
</li>
<li><p>Validate Holder Commitment</p>
</li>
<li><p>Validate Revocation</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356259315/bb2f0415-6c8e-4878-baac-76c5f4396ced.webp" alt class="image--center mx-auto" /></p>
<p>I also added in benchmarks for our <code>secp256k1</code> since we have a lot of activities using its functions. Finally we had a good overview on our operation latency.</p>
<pre><code class="lang-bash">7609 bench INFO - Bench: Sign ECDSA, 200 iterations <span class="hljs-keyword">in</span> 3360ms, each 16.8ms
12941 bench INFO - Bench: Verify ECDSA, 200 iterations <span class="hljs-keyword">in</span> 3521ms, each 17.605ms
12966 bench INFO - Bench: SHA256, 200 iterations <span class="hljs-keyword">in</span> 16ms, each 0.08ms
17941 bench INFO - Bench: Secp256k1 Create, 200 iterations <span class="hljs-keyword">in</span> 3316ms, each 16.58ms
</code></pre>
<h3 id="heading-sled-issue">Sled Issue</h3>
<p>During the testing <code>devrandom</code> found it odd that even on a rotating disk the performance tests for persister were running really fast. Going further it was realised that it was issue of our key-value store <code>sled</code>. It was not have been syncing to disk correctly.</p>
<p>Sled uses <code>sync_file_range</code> for flushes, which does not guarantee durable writes, except on specialised hardware (e.g. battery backed-up HD cache). Hence, we decided to move away from <code>sled</code> to <code>redb</code>.</p>
<h1 id="heading-takeaways">Takeaways</h1>
<p>The biggest key thing for me was I understood <strong>bitcoin</strong> why it was <strong>created</strong>, how will it go <strong>further</strong> and what will take it go further. I poured all my understanding into this blog <a target="_blank" href="https://king-11.github.io/blog/posts/bitcoin-financial-system/">Bitcoin, the Financial System</a>.</p>
<p>Along the way I got to interact with highly skilled and amazing mentors <strong>Ken</strong> and <strong>Devrandom</strong>. By reviewing my MRs and having <strong>discussion</strong> with me around them they helped me get a better perspective on <strong>software development, testing, security</strong> etc.</p>
<p>I have continued contributing to <strong>VLS</strong> even became one of the <strong>core contributors</strong> with <strong>ownership</strong> of the <a target="_blank" href="https://gitlab.com/lightning-signer/vls-container">VLS Container</a> project. I have been invited to <a target="_blank" href="https://btcplusplus.dev/conf/atx24">bitcoin++ austin!</a> as a <strong>speaker</strong>, I am finding it hard to get a <strong>US Visa</strong> but hopefully I might get a chance to visit there, if you know someone who can help please do reach out to me.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347548471/fb781eee-9b18-41ac-815a-34da888ada8a.gif" alt="bitcoin cheers" /></p>
<p>Thanks for reading like always I am starting to get back in the routine of writing one blog per week hoping to write more and learn more.</p>
]]></content:encoded></item><item><title><![CDATA[Union/Sum Type]]></title><description><![CDATA[Let’s take an example of operating system information as a data structure to better understand sum types.
Struct
Our bare minimum struct to represent an operating system contains a few common fields that would exist in each of the operating system.
t...]]></description><link>https://hashnode.king-11.dev/unionsum-type</link><guid isPermaLink="true">https://hashnode.king-11.dev/unionsum-type</guid><category><![CDATA[C#]]></category><category><![CDATA[Java]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Fri, 19 Jan 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730374743685/47446b89-b94a-459a-a8d5-0f94a213dc89.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let’s take an example of operating system information as a data structure to better understand sum types.</p>
<h2 id="heading-struct">Struct</h2>
<p>Our bare minimum struct to represent an operating system contains a few common fields that would exist in each of the operating system.</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  <span class="hljs-keyword">char</span> organization[];
  <span class="hljs-keyword">int</span> releaseYear;
  <span class="hljs-keyword">float</span> version;
  <span class="hljs-keyword">int</span> is_opensource;
} os;
</code></pre>
<p>It’s missing one thing though the <strong>type of operating system</strong> like <code>macOS</code>, <code>linux</code>, <code>windows</code>, etc.</p>
<h2 id="heading-enum">Enum</h2>
<p>We will add in a new field into our structure to represent the type of operating system by using an <code>enum</code>.</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-keyword">enum</span>
{
  Linux,
  Windows,
  MacOS
} os_type_enum;

<span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  ...
  os_type_enum os_type;
} os;
</code></pre>
<h2 id="heading-more-data-fields">More Data Fields</h2>
<p>Consider the case of Linux, there are many distributions like <code>Manjaro</code>, <code>Fedora</code>, <code>Ubuntu</code>, <code>Zorin</code>, etc. we want to store this data as well.</p>
<p>So what can we do now with our struct and enum combination is we can create a new field which will be <code>nullptr</code> in case of <code>MacOS</code> and <code>Windows</code> and in case of <code>Linux</code> it will hold data.</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  ...
  <span class="hljs-keyword">char</span> distribution[];
} os;
</code></pre>
<p>Now it comes down to <strong>user</strong> to manage this <strong>logic</strong> properly the language won’t provide support for anything. But there is a better way to handle such things we can use <code>union</code>.</p>
<h2 id="heading-union">Union</h2>
<p><strong>C language</strong>, yes the elder one has features for us to easily create sum type by using <code>union</code> keyword. And you thought your new and shiny language has an advantage over it <em>“much to learn you still have”</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347587906/8cb4d0bd-aec2-4c4b-bb71-4c8e4f083a42.gif" alt="yoda telling you to appreciate C language" /></p>
<p>We will create three new structs each representing meta details about each operating system. In case of <code>macOS</code> and <code>Windows</code> these would be empty structs but in case of <code>linux</code> will have a data field.</p>
<pre><code class="lang-c"><span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  <span class="hljs-keyword">char</span> distribution[];
} linux_details;

<span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>} mac_os_details;
<span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>} windows_details;

<span class="hljs-keyword">union</span> os_details_union {
  linux_details linux;
  mac_os_details mac_os;
  windows_details windows;
};

<span class="hljs-keyword">typedef</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>
  ...
  os_details_union os_details;
} os;
</code></pre>
<p><strong>Union</strong> forms the basis for sum types which is actually a <strong>mathematical concept</strong> represented by <code>A U B</code> where A and B are individual types.</p>
<p>The opposite of sum type is <strong>product type</strong>, which is represented in programming languages by a normal <code>class</code> or <code>struct</code>. An <code>interface</code> represents an <strong>intersection</strong> in mathematical terms.</p>
<h3 id="heading-memory-requirements">Memory Requirements</h3>
<p>A union variable will always be the size of its largest element. So even if I have some fields in the other two structures as well it still won’t be an addition of individual struct size but instead a max.</p>
<pre><code class="lang-c"><span class="hljs-keyword">int</span> struct_memory = <span class="hljs-keyword">sizeof</span>(linux_details) + <span class="hljs-keyword">sizeof</span>(mac_os_details) + <span class="hljs-keyword">sizeof</span>(windows_details)
<span class="hljs-keyword">int</span> union_memory = max(<span class="hljs-keyword">sizeof</span>(linux_details), max(<span class="hljs-keyword">sizeof</span>(mac_os_details), <span class="hljs-keyword">sizeof</span>(windows_details)))
</code></pre>
<p>While writing this blog I came to know about this benefit which is utilized in low resource devices.</p>
<h3 id="heading-pros-and-cons">Pros and Cons</h3>
<p>Now the union logic isn’t on user but instead on the language runtime itself to manage. It brings in <strong>safety</strong> and <strong>clarity</strong> of usage to the end user of language i.e. the programmer but it also adds in <strong>un-safety</strong> around same <strong>memory</strong> utilization for all the fields.</p>
<p>What do I mean by memory un-safety? let’s consider below example of memory overwrite.</p>
<pre><code class="lang-c"><span class="hljs-keyword">union</span> random_data {
  <span class="hljs-keyword">int</span> happiness_index;
  <span class="hljs-keyword">int</span> sadness_index;
} data_holder;

data_holder.happiness_index = <span class="hljs-number">5</span>;
<span class="hljs-comment">// below assignment will override happiness_index</span>
data_holder.sadness_index = <span class="hljs-number">2</span>;
<span class="hljs-built_in">printf</span>(<span class="hljs-string">"happiness_index is %d and sadness_index is %d"</span>, data_holder.happiness_index, data_holder.sadness_index)
<span class="hljs-comment">// happiness_index is 2 and sadness_index is 2</span>
</code></pre>
<p>As we can see a wrong usage of union can cause <strong>loss of data</strong> as only <em>one field can exist in the union</em> because they share <strong>same memory space</strong>. This is a simple example of memory <strong>overwrite</strong>, in a mix of structs and primitive data types we face a even bigger threat.</p>
<h2 id="heading-safe-sum">Safe Sum</h2>
<p>There are other languages as well which provide union/sum types with <strong>memory safety</strong> like <code>Haskell</code>, <code>OCaml</code>, etc. but I would like to go with <strong>Rust</strong> here as am familiar with it.</p>
<p>In rust there is no special <code>union</code> type instead <code>enum</code> values can hold the data we need and it make our lives easy.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">OsTypeEnum</span></span> {
  Windows,
  Linux(<span class="hljs-built_in">String</span>),
  MacOS,
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Os</span></span> {
  os_type: OsTypeEnum,
  organization: <span class="hljs-built_in">String</span>,
  release_year: <span class="hljs-built_in">i32</span>,
  version: <span class="hljs-built_in">f32</span>,
  opensource: <span class="hljs-built_in">bool</span>,
}
</code></pre>
<p>That’s it so simple so elegant just looking like a wow.</p>
<h2 id="heading-pattern-matching">Pattern Matching</h2>
<p>While in <code>C</code> even with union type we still had to rely on the <code>os_type_enum</code> to check what operating is the <code>os</code> struct representing and a <strong>user error</strong> there would result in memory issues.</p>
<p>Modern languages have <strong>pattern matching</strong> which allows them to match against the <strong>structure of types</strong>, both complex and simple in a very clean manner.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">match</span> os_type {
  OsTypeEnum::Windows =&gt; <span class="hljs-built_in">print!</span>(<span class="hljs-string">"Hail Microsoft!"</span>),
  OsTypeEnum::MacOS =&gt; <span class="hljs-built_in">print!</span>(<span class="hljs-string">"richie rich :P"</span>),
  OsTypeEnum::Linux(description) =&gt; <span class="hljs-built_in">print!</span>(<span class="hljs-string">"never ending suffering {}"</span>, description)
}
</code></pre>
<p>In rust we can pattern match against things like:</p>
<ul>
<li><p>Literals</p>
</li>
<li><p>Destructured arrays, enums, structs, or tuples</p>
</li>
<li><p>Variables</p>
</li>
<li><p>Wildcards</p>
</li>
<li><p>Placeholders</p>
</li>
</ul>
<p>You can read more about the capabilities of rust specific pattern matching in <a target="_blank" href="https://doc.rust-lang.org/book/ch18-00-patterns.html">the rust book</a>.</p>
<h2 id="heading-other-languages">Other Languages</h2>
<p>Not every language has sum type or pattern matching but most of the languages are moving towards enabling it, not in a true manner but something is better than nothing coughs in golang.</p>
<h3 id="heading-c-sharp">C Sharp</h3>
<p>It has become a language that I have started <strong>liking a lot</strong>. C# has no <strong>true equivalent</strong> to union type like <strong>C</strong> or <strong>Rust</strong> but we can provide similar feature using <strong>inheritance</strong> and pattern matching.</p>
<p>I took reference from a <a target="_blank" href="https://spencerfarley.com/2021/03/26/unions-in-csharp/">blog</a> which goes in detail about <em>improvements</em> made till <strong>C#9</strong> to allow below example with a very clean syntax.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">record</span> <span class="hljs-title">OsType</span> {
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Windows</span> : <span class="hljs-title">OsType</span>;
  <span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Linux</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> distro</span>) : OsType</span>;
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">MacOS</span> : <span class="hljs-title">OsType</span>;
  <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">OsType</span>(<span class="hljs-params"></span>)</span> { } <span class="hljs-comment">// private constructor can prevent derived cases from being defined elsewhere</span>
}
</code></pre>
<p>C Hash Sharp also provides pattern matching abilities using the <code>switch</code> statement but it won’t be able to do an exhaustive match.</p>
<pre><code class="lang-csharp">osType <span class="hljs-keyword">switch</span> {
  OsType.Windows windows =&gt; <span class="hljs-string">"its updating"</span>,
  OsType.Linux linux =&gt; <span class="hljs-string">$"where are the display drivers: <span class="hljs-subst">{linux.distro}</span>"</span>,
  OsType.MacOS macOS =&gt; <span class="hljs-string">"flexing that half eaten apple"</span>,
  _ =&gt; <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(message: <span class="hljs-string">"invalid OsType value"</span>, paramName: <span class="hljs-keyword">nameof</span>(osType)),
};
</code></pre>
<h3 id="heading-java">Java</h3>
<p>In Java we have <strong>records</strong>, <strong>pattern matching</strong> and <strong>sealed interfaces</strong> as part of <strong>Java17</strong> which can allow us to implement union types.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> sealed <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">OsType</span> </span>{}
<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Linux</span><span class="hljs-params">(String Distribution)</span> implements OsType </span>{}
<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">MacOS</span><span class="hljs-params">()</span> implements OsType </span>{}
<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Windows</span><span class="hljs-params">()</span> implements OsType </span>{}
</code></pre>
<p>For pattern matching we can use the <code>switch</code> and <code>isInstanceOf</code> to do exhaustive matching with a sealed interface.</p>
<pre><code class="lang-java"><span class="hljs-keyword">switch</span> (osType) {
  <span class="hljs-keyword">case</span> LinuxInformation linux -&gt; <span class="hljs-string">"I use arch btw"</span>;
  <span class="hljs-keyword">case</span> MacOS macOS -&gt; <span class="hljs-string">"loan installment pending"</span>;
  <span class="hljs-keyword">case</span> Windows windows -&gt; <span class="hljs-string">"even dad can use it"</span>;
}
</code></pre>
<h3 id="heading-kotlin">Kotlin</h3>
<p>My new found <strong>love</strong> does union types mostly like java but instead of interface we use a <strong>sealed class</strong>, <strong>data objects</strong> and <strong>data classes</strong>. Data Class seems <strong>superior</strong> to Java records as they can extend other classes whereas a record can’t.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">sealed</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OsType</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">constructor</span></span>() {
  <span class="hljs-keyword">data</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Linux</span></span>(<span class="hljs-keyword">val</span> distribution: String) : OsType()
  <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> MacOS : OsType()
  <span class="hljs-keyword">data</span> <span class="hljs-keyword">object</span> Windows : OsType()
}
</code></pre>
<p>The pattern matching happens using <code>when</code></p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">when</span> (os) {
  <span class="hljs-comment">// smart casting happening here</span>
  <span class="hljs-keyword">is</span> Os.Linux -&gt; <span class="hljs-string">"mr. robot uses $(os.distribution)"</span>
  <span class="hljs-keyword">is</span> Os.MacOS -&gt; <span class="hljs-string">"no more space left"</span>
  <span class="hljs-keyword">is</span> Os.Windows -&gt; <span class="hljs-string">"its AI everywhere"</span>
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p><strong>Union/Sum Types</strong> are <strong>concrete types</strong> even in the face of diverse options. <code>C</code> introduced it to us long back when it was a <strong>crude mathematical model</strong> and it has been improved thoroughly now with time and is visible in <strong>modern languages</strong> like <code>Rust</code>, <code>OCaml</code>, <code>Scala</code>, etc.</p>
<p>The old gods like <code>C#</code>, <code>Java</code>, etc. are trying to keep up with <em>trendy types</em> by adding more new feature but it just <strong>doesn’t feel as good</strong>. I was even planning to show example for doing it with <code>Go</code> but it just can’t do that in a <em>humanely readable way</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347589299/daf7f0b1-bcca-4c60-90dd-4e38bca73077.gif" alt="jai shree ram" /></p>
<p>That was all for this week, thanks for reading, stay tuned on the <a target="_blank" href="https://king-11.github.io/blog/">Backpacking Dream</a> and <strong>Jai Shree Ram!!</strong>.</p>
]]></content:encoded></item><item><title><![CDATA[Kotlin Coroutines]]></title><description><![CDATA[Coroutine
A coroutine is an instance of a suspend-able computation. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works concurrently with the rest of the code.
However, a coroutine is not bound to any ...]]></description><link>https://hashnode.king-11.dev/kotlin-coroutines</link><guid isPermaLink="true">https://hashnode.king-11.dev/kotlin-coroutines</guid><category><![CDATA[Kotlin]]></category><category><![CDATA[Computer Science]]></category><category><![CDATA[coroutines]]></category><category><![CDATA[Threads]]></category><category><![CDATA[concurrency]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Sat, 13 Jan 2024 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356945386/0ccae399-2b65-47f6-b5ea-0eb5bb419fbb.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-coroutine">Coroutine</h1>
<p>A <code>coroutine</code> is an instance of a <strong>suspend-able computation</strong>. It is conceptually similar to a thread, in the sense that it takes a block of code to run that works <strong>concurrently</strong> with the rest of the code.</p>
<p>However, a coroutine is not <em>bound</em> to any particular user level thread. It may suspend its execution in one thread and resume in another one. This scheduling of coroutines is handled by the Kotlin <code>dispatchers</code> similar to <a target="_blank" href="https://king-11.github.io/blog/posts/goroutines/#go-runtime-components">go runtime</a></p>
<p>Coroutines are <strong>less resource-intensive</strong> than JVM threads. Code that exhausts the JVM’s available <strong>memory</strong> when using threads can be expressed using coroutines without hitting resource limits.</p>
<h2 id="heading-suspending-function">Suspending Function</h2>
<p>Suspending functions are at the heart of coroutines. They can <strong>use other suspending functions</strong> (like delay in this example) to <strong>suspend</strong> execution of a coroutine and free the thread for useful computation by other coroutines.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">doWorld</span><span class="hljs-params">()</span></span> {
    delay(<span class="hljs-number">1000L</span>)
    println(<span class="hljs-string">"World!"</span>)
}
</code></pre>
<h2 id="heading-coroutine-builders">Coroutine Builders</h2>
<p>To actually build a coroutine we need to use coroutine builders which cater to multiple different scenarios where coroutines can be used.</p>
<h3 id="heading-launch">Launch</h3>
<p>A <code>launch</code> coroutine builder returns a <code>Job</code> object that is a handle to the launched coroutine and can be used to explicitly wait for its completion.</p>
<pre><code class="lang-kotlin">launch { <span class="hljs-comment">// launch a new coroutine</span>
    delay(<span class="hljs-number">1000L</span>) <span class="hljs-comment">// non-blocking delay for 1 second (default time unit is ms)</span>
    println(<span class="hljs-string">"World!"</span>) <span class="hljs-comment">// print after delay</span>
}
</code></pre>
<h3 id="heading-coroutinescope">CoroutineScope</h3>
<p>A <code>coroutineScope</code> builder can be used inside any suspending function to perform multiple concurrent operations</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// Concurrently executes both sections</span>
<span class="hljs-keyword">suspend</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">doWorld</span><span class="hljs-params">()</span></span> = coroutineScope { <span class="hljs-comment">// this: CoroutineScope</span>
    launch {
        delay(<span class="hljs-number">2000L</span>)
        println(<span class="hljs-string">"World 2"</span>)
    }
    launch {
        delay(<span class="hljs-number">1000L</span>)
        println(<span class="hljs-string">"World 1"</span>)
    }
    println(<span class="hljs-string">"Hello"</span>)
}
</code></pre>
<p>The main difference from <code>runBlocking</code> method is that it <strong>blocks</strong> the current thread for waiting, while <code>coroutineScope</code> just <strong>suspends</strong>, releasing the underlying thread for other usages. Because of that difference, <code>runBlocking</code> is a regular function and <code>coroutineScope</code> is a suspending function.</p>
<h3 id="heading-produce">Produce</h3>
<p>We can also use <code>produce</code> builder where a coroutine is producing a <strong>sequence/stream</strong> of elements (very common in <em>producer consumer patterns</em>)</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// infinite stream of integers starting from 1</span>
<span class="hljs-function"><span class="hljs-keyword">fun</span> CoroutineScope.<span class="hljs-title">produceNumbers</span><span class="hljs-params">()</span></span> = produce&lt;<span class="hljs-built_in">Int</span>&gt; {
    <span class="hljs-keyword">var</span> x = <span class="hljs-number">1</span>
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) send(x++)
}
</code></pre>
<blockquote>
<p><strong>Note:</strong> All functions that create coroutines are defined as extensions on CoroutineScope, so that we can rely on <a target="_blank" href="https://kotlinlang.org/docs/composing-suspending-functions.html#structured-concurrency-with-async">structured concurrency</a> to make sure that we don’t have lingering global coroutines in our application.</p>
</blockquote>
<h3 id="heading-async">Async</h3>
<p>There is another builder, <code>async</code> it is quite similar to <code>launch</code>. It creates a single coroutine but instead of forgetting about return value like the case with <code>launch</code> returned <code>Job</code>, <code>async</code> returns a <code>Deferred</code> (non-blocking future) that represents a promise to provide result using <code>.await()</code>.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> one = async { doSomethingUsefulOne() }
println(<span class="hljs-string">"The answer is <span class="hljs-subst">${one.await()}</span>"</span>)
</code></pre>
<p>Optionally, we can make <code>async</code> lazy as follows:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() }
one.start() <span class="hljs-comment">// start lazily</span>
</code></pre>
<p>Now that we have a concurrent environment where multiple coroutines are working simultaneously, we need mechanisms to synchronize data access/communication.</p>
<h1 id="heading-channels">Channels</h1>
<p>Channels are <strong>communication primitives</strong> that allow data to be passed between coroutines. One coroutine can <em>send</em> some information to a channel, while another can <em>receive</em> that information from it in a <strong>thread safe manner</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730357041136/4a686683-6066-47b8-a219-8e6684ff02f5.webp" alt /></p>
<p><code>Channel</code> is represented by three different interfaces: <code>SendChannel</code>, <code>ReceiveChannel</code>, and <code>Channel</code>, with the latter extending the first two.</p>
<p>There are multiple kinds of channels:</p>
<ul>
<li><p>Unlimited Channel</p>
</li>
<li><p>Buffered Channel</p>
</li>
<li><p>Rendezvous Channel</p>
</li>
<li><p>Conflated Channel</p>
<p>  val rendezvousChannel = Channel() val bufferedChannel = Channel(10) val conflatedChannel = Channel(CONFLATED) val unlimitedChannel = Channel(UNLIMITED)</p>
</li>
</ul>
<p><strong><em>Note</em></strong>: Both <code>Channel</code> factory function and <a target="_blank" href="/posts/kotlin-coroutines/#produce">produce</a> builder take an optional <code>capacity</code> parameter to specify <em>buffer size</em>.</p>
<h2 id="heading-sending-and-receiving">Sending and Receiving</h2>
<p>A Channel is conceptually very similar to <code>BlockingQueue</code>, except that its methods aren’t blocking and instead of <strong>suspending</strong> nature.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Blocking</td><td>Suspending</td></tr>
</thead>
<tbody>
<tr>
<td>put</td><td>send</td></tr>
<tr>
<td>take</td><td>receive</td></tr>
</tbody>
</table>
</div><pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> channel = Channel&lt;<span class="hljs-built_in">Int</span>&gt;()
launch {
    <span class="hljs-comment">// this might be heavy CPU-consuming computation or async logic, we'll just send five squares</span>
    <span class="hljs-keyword">for</span> (x <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>..<span class="hljs-number">5</span>) channel.send(x * x)
}
<span class="hljs-comment">// here we print five received integers:</span>
repeat(<span class="hljs-number">5</span>) { println(channel.receive()) }
println(<span class="hljs-string">"Done!"</span>)
</code></pre>
<blockquote>
<p>Channel <code>send</code> or <code>receive</code> functions can suspend when the channel is <strong>full</strong> or <strong>empty</strong> respectively. The channel can be <strong>full</strong> if the channel size has an upper bound.</p>
</blockquote>
<h2 id="heading-closing">Closing</h2>
<p>The producer can close a channel to indicate that no more elements are coming. Conceptually, a <a target="_blank" href="https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-send-channel/close.html">close</a> is like sending a special close token to the channel.</p>
<p>A receiver iterating on channel stops as soon as this close token is received, so there is a guarantee that all previously sent elements before the close are received.</p>
<pre><code class="lang-kotlin">launch {
    <span class="hljs-keyword">for</span> (x <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>..<span class="hljs-number">5</span>) channel.send(x * x)
    channel.close() <span class="hljs-comment">// we're done sending</span>
}
<span class="hljs-comment">// here we print received values using `for` loop (until the channel is closed)</span>
<span class="hljs-keyword">for</span> (y <span class="hljs-keyword">in</span> channel) println(y)
</code></pre>
<h1 id="heading-patterns">Patterns</h1>
<p>We can use the channel data structure to implement multiple concurrency patterns frequently used in concurrent/parallel programming.</p>
<h2 id="heading-producer-consumer">Producer-Consumer</h2>
<p>Channels simplify implementation of <em>producer consumer pattern</em> in kotlin to a large extent with a large set of easy to use functions. We can use the <code>produce</code> builder on producer side and an extension function <code>consumeEach</code>, that replaces a <code>for</code> loop on the consumer side.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// producer builder channel</span>
<span class="hljs-keyword">val</span> squares = produceSquares()
<span class="hljs-comment">// consumeEach utility</span>
squares.consumeEach { println(it) }
</code></pre>
<h2 id="heading-fan-out">Fan-out</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730357192701/4d708798-6f69-4ac8-a1a0-ffc9022b0d9a.webp" alt /></p>
<p><strong>Multiple</strong> coroutines may <strong>receive</strong> from the same channel, distributing work between themselves. Unlike <code>consumeEach</code>, <code>for</code> loop pattern is the safe option to use when multiple coroutines are receiving because a consumer written via <code>consumeEach</code> always consumes (cancels) the underlying channel on its normal or abnormal completion leaving other coroutines aborted as well.</p>
<h1 id="heading-shared-data">Shared Data</h1>
<p>Coroutines can be executed parallelly using a multi-threaded dispatcher like the <code>Dispatchers.Default</code>. Given the scenario of parallel data access we have to prevent unpredictable behaviour of data.</p>
<h2 id="heading-volatile">Volatile</h2>
<p>There is a common misconception that making a variable <code>volatile</code> solves concurrency problem, because volatile variables just guarantee <strong>atomic reads</strong> and <strong>writes</strong> to the corresponding variable, but do not provide atomicity of a <strong>larger action</strong> (like addition, subtraction, etc.)</p>
<pre><code class="lang-kotlin"><span class="hljs-meta">@Volatile</span> <span class="hljs-comment">// in Kotlin `volatile` is an annotation</span>
<span class="hljs-keyword">var</span> counter = <span class="hljs-number">0</span>
</code></pre>
<h2 id="heading-thread-safe-data-structure">Thread Safe Data Structure</h2>
<p>A thread-safe (aka synchronized, linearizable, or atomic) data structure provides all the necessary <strong>synchronization</strong> for the operations that needs to be performed on a shared state.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> counter = AtomicInteger()
</code></pre>
<p>This is the <strong>fastest</strong> and most <strong>versatile</strong> solution for this particular problem. It works for plain counters, collections, queues and other standard data structures and basic operations on them. However, it does <strong>not</strong> easily scale to <strong>complex state</strong> or to complex operations that do not have ready-to-use thread-safe implementations.</p>
<h2 id="heading-thread-confinement">Thread Confinement</h2>
<p>Thread confinement is an approach to the problem of shared mutable state where all <strong>access</strong> to the particular shared state is <strong>confined</strong> to a <strong>single thread</strong>.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// confine each increment to a single-threaded context</span>
withContext(counterContext) {
    counter++
}
</code></pre>
<p>This code works very <strong>slowly</strong>, because it does fine-grained thread-confinement. In practice, thread confinement is performed in <strong>large chunk</strong>s, e.g. big pieces of state-updating business logic are confined to the single thread.</p>
<h2 id="heading-mutex">Mutex</h2>
<p>Coroutines have <code>Mutex</code>. It has <code>lock</code> and <code>unlock</code> functions to delimit a critical section. <code>Mutex.lock()</code> is a <strong>suspending</strong> function which does not block a thread. There is also <code>withLock</code> extension function that conveniently represents:</p>
<pre><code class="lang-kotlin">mutex.lock()
<span class="hljs-keyword">try</span> { ... }
<span class="hljs-keyword">finally</span> { mutex.unlock() }

<span class="hljs-comment">// using withLock</span>
withLock(mutex) {
    <span class="hljs-keyword">try</span> { ... }
}
</code></pre>
<h1 id="heading-cancellation">Cancellation</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347596003/ef9b56dc-c617-4ca3-b28b-24e94d4629c1.gif" alt="popatlal cancel cancel" /></p>
<p>Just launching the coroutine isn’t sufficient, at times even the good humans of this world have to become a part of <strong>cancel culture</strong> set by <em>Mr. Popatlal</em> to cancel some long running background coroutine.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">var</span> job = launch {
    delay(<span class="hljs-number">500L</span>) <span class="hljs-comment">// i will sleep</span>
}
delay(<span class="hljs-number">200L</span>)
println(<span class="hljs-string">"cancel culture ftw"</span>)
job.cancel() <span class="hljs-comment">// ask it to cancel</span>
job.join() <span class="hljs-comment">// wait for it to complete</span>
</code></pre>
<blockquote>
<p>There is also a <code>cancelAndJoin</code> utility method.</p>
</blockquote>
<h2 id="heading-cooperative">Cooperative</h2>
<p>Coroutine Cancellation is of <strong>cooperative nature</strong>, the cancelled coroutine has to agree with cancellation and stop the computation. If a coroutine isn’t actively checking for cancellation signal then it can’t be cancelled.</p>
<p>All the suspending functions in <code>kotlinx.coroutines</code> are cancellable, they actively check for cancellation signal and then throw a <code>CancellationException</code> when cancelled. So we shouldn’t catch <code>CancellationException</code> without intent of stopping the computation.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">try</span> {
    delay(<span class="hljs-number">500</span>)
} <span class="hljs-keyword">catch</span> (e: Exception) {
    <span class="hljs-comment">// log the exception, might have been a `CancellationException`</span>
    println(e)
}
</code></pre>
<h2 id="heading-cancellable-computation">Cancellable Computation</h2>
<p>To ensure that the library or program that we write aligns with the cancellation requirements we can pursue below two options:</p>
<ul>
<li>Calling the <code>yield</code> suspending function which checks for cancellation at regular intervals inside the coroutine.</li>
</ul>
<pre><code class="lang-kotlin">launch {
    <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-comment">// large computation</span>
        yield()
    }
}
</code></pre>
<ul>
<li>Checking the <code>isActive</code> extension property available inside the coroutine via <code>CoroutineScope</code> object</li>
</ul>
<pre><code class="lang-kotlin">launch {
    <span class="hljs-keyword">while</span> (isActive) {
        <span class="hljs-comment">// large computation</span>
    }
}
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Kotlin is an amazing language I genuinely had fun writing code in it during 2023’s <a target="_blank" href="http://github.com/king-11/AdventOfCode">Advent of Code</a> which I didn’t complete :’(. I have felt this feeling last with <code>C#</code> and <code>Golang</code> not rust. Let’s cover this thought about joy of programming in a well articulated blog later so stay tuned.</p>
<p>Thanks for reading, you guys keep me going I am planning to start publishing my blogs on <code>Medium</code> as well for better reach to increase my <a target="_blank" href="https://github.com/readme/guides/publishing-your-work">Luck Surface Area</a> till then adios, <strong>Happy Makar Sankranti</strong> may the wind gods be with you :) and yeah you know where to find me <a target="_blank" href="http://twitter.com/1108King">@1108King</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347597668/f809331c-dc8f-4fa7-a245-c98dc57cd152.gif" alt="adios fellas" /></p>
]]></content:encoded></item><item><title><![CDATA[Bitcoin, the Financial System]]></title><description><![CDATA[Financial System
Bitcoin is a financial system created to serve a highly political intent, a free and uncensored network where all can participate with equal access. It is a mechanism of organizing people and computers to make one immutable, digital ...]]></description><link>https://hashnode.king-11.dev/bitcoin-the-financial-system</link><guid isPermaLink="true">https://hashnode.king-11.dev/bitcoin-the-financial-system</guid><category><![CDATA[Bitcoin]]></category><category><![CDATA[finance]]></category><category><![CDATA[Cryptocurrency]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Thu, 28 Dec 2023 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356624946/4b5ad038-606f-4912-b8e8-a4f5f432f9ac.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-financial-system">Financial System</h1>
<p>Bitcoin is a <strong>financial system</strong> created to serve a highly political intent, a <strong>free</strong> and <strong>uncensored</strong> network where all can participate with equal access. It is a mechanism of <strong>organizing</strong> people and computers to make one immutable, digital document.</p>
<h2 id="heading-bitcoin-offerings">Bitcoin Offerings</h2>
<ul>
<li><p>Bitcoin doesn’t keep track of the identities of the people (or machines) that use it making it <strong>permissionless</strong>.</p>
</li>
<li><p>It doesn’t increase the supply of bitcoins to meet demand making it <strong>deflationary</strong> and <strong>inviolate</strong>.</p>
</li>
<li><p>It doesn’t force itself on anyone making it <strong>consensual</strong>.</p>
</li>
<li><p>It doesn’t exclude anyone from using it making it <strong>inclusive</strong>.</p>
</li>
</ul>
<blockquote>
<p>It is well enough that people of the nation do not understand our banking and monetary system, for if they did, I believe there would be a revolution before tomorrow morning - <strong>Henry Ford</strong></p>
</blockquote>
<h1 id="heading-alt-shit-coins">Alt Shit Coins</h1>
<p>Bitcoin is the OG crypto it’s not like other <strong>shitcoins</strong>, that keep popping up everyday. Every f-king day these <em>wannabe</em> crypto enthusiasts create an alt coin (short for alternate coin) thinking it will boon someday…it won’t.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347603042/73eb6174-a410-4522-9ccb-27114dd3abc2.gif" alt="shit coins trying to catch upto bitcoin" /></p>
<p>While <strong>blue-chip cryptocurrencies</strong>, such as <code>Bitcoin</code> and <code>Ethereum</code>, have robust infrastructure and fundamentals to back them up, <code>shitcoins</code> rely on short-lived hype and FOMO (Fear Of Missing Out) to build up value. In March 2023, Ethereum co-founder <strong>Vitalik Buterin</strong> sold $700,000 worth of <code>shitcoins</code> that were airdropped to him, <strong>crashing</strong> the <code>shitcoins</code> price down as they are mostly operating on large investor money.</p>
<h1 id="heading-breaking-barriers">Breaking Barriers</h1>
<p>Bitcoin has no boundaries a person sitting in USA can easily and safely do transaction with person sitting in India without worrying about paying currency exchange fees, <a target="_blank" href="https://cleartax.in/s/tax-on-foreign-remittance">foreign remittance</a>, etc and going through hassle of multiple financial channels. It is one true global currency that doesn’t divide people based on country but instead provides a simple, safe and secure mechanism to cater to all your transaction requirements.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356694568/0b70ffc2-a0c3-4c5a-945d-634b3bd868c9.webp" alt /></p>
<h1 id="heading-primitive-institutions">Primitive Institutions</h1>
<p>I was just starting to write this article and my father told me about the <a target="_blank" href="https://www.patrika.com/jodhpur-news/scam-worth-crores-of-rs-from-banks-started-from-jodhpur-1-in-custody-8600489/">latest news</a> where people defrauded banks in Jodhpur and <code>double spent</code> their actual funds due to a fault in their servers resulting in creation of money valuing around <strong>850 crores</strong> out of thin air.</p>
<p><strong>Double Spend</strong> aka <a target="_blank" href="https://www.bitpanda.com/academy/en/lessons/what-is-double-spending-and-why-is-it-such-a-problem/">Byzantine General’s problem</a> was the first problem Bitcoin had to solve as a distributed finance system. In <code>2008</code>, it was done by <a target="_blank" href="https://en.wikipedia.org/wiki/Satoshi_Nakamoto">Satoshi Nakamoto</a> using blockchain, still the supposedly <em>safe</em> and <em>secure</em> financial institution can’t protect our money and suffer from problem which was solved a decade ago.</p>
<p>Current financial institution are here to <strong>earn</strong> from you and not cater to your needs. They won’t stop badgering you until you <strong>lock</strong> in your money with them using multiple <em>Ponzi</em> schemes.</p>
<blockquote>
<p>Whatever money you don’t hold isn’t your money. - <strong>My Dad</strong></p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356702266/1069c7ac-e6ee-444c-a1b8-5e73cd54f97e.webp" alt /></p>
<p>When the day comes they start crashing like in <strong>2009</strong>, there is nothing that would be able to protect your money instead they take the route of <strong>locking</strong> your money from any kind of <strong>withdrawal</strong> to save their arses first. I highly recommend anyone to watch <a target="_blank" href="https://www.youtube.com/watch?v=vgqG3ITMv1Q">The Big Short</a> to better understand how it all went down in 2009 due to <strong>fraudulent</strong> and <strong>delusional</strong> financial institution.</p>
<blockquote>
<p>Blackrock named <strong>Jamie Dimon’s JPMorgan</strong> as their Authorized Participant for their potential <strong>Bitcoin ETF</strong>. Jamie Dimon LITERALLY said earlier this month that the <em>“if I were the government I would</em> <a target="_blank" href="https://www.youtube.com/watch?v=ujWR6t69UP8"><em>BAN Bitcoin</em></a><em>”</em> because only criminals use it and JPMorgan says ETF optimism is overhyped. You see how two faced these bankers are?</p>
</blockquote>
<h1 id="heading-negative-inflation">Negative Inflation</h1>
<p>A salaried individual in today’s world has to worry about thing like stocks, mutual funds, PPF, bonds, options, etc because we have to beat inflation and inflation is normal right your money loses power and value it holds over time, it’s meant to happen</p>
<p>But let me ask, why is it normal though why shouldn’t a 100 rupees note today hold the same value 10 years later?</p>
<blockquote>
<p>Economists have identified several possible causes for inflation from rising wages to increased aggregate demand to an <strong>increase in the supply of money</strong>.</p>
</blockquote>
<p>The fools minting out the cash don’t understand shit about the financial systems how would they most of them don’t posses any form of official college education/degree. They keep increasing the supply of money as and when they deem fit which results in overall paper bill losing its power.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356710721/7d855d60-3352-45d8-9d63-b72611ce0b76.webp" alt /></p>
<p>Bitcoin saves its owners from all these worries, given the limited supply which keeps decreasing every 4 years to half (Bitcoin Halving) making it a scarce resource. It will keep deflating (currently at <strong>164% per annum</strong>) at an exponential rate compared to any other asset like land, stocks, options, etc.</p>
<h1 id="heading-government-of-goons">Government of Goons</h1>
<blockquote>
<p>Spend some time with Bitcoin. Learn it, challenge it, and use it. You can assume no government wants you adopting this system in any capacity, and for that reason alone it’s worth consideration by honest, moral, and industrious people - <strong>Erik Voorhees</strong></p>
</blockquote>
<p>Every form of government be it monarchical or democratic or communist want just one thing <strong>control</strong> because without control they aren’t anything. Bitcoin is beyond their control:</p>
<ul>
<li><p>They can’t control the transactions or even identify individuals involved in a transaction</p>
</li>
<li><p>They can’t measure the capital value you are holding in your bitcoin wallets</p>
</li>
<li><p>They can’t inflate bitcoin by minting more of it as they do with paper money</p>
</li>
<li><p>They can’t impose state embargos on bitcoin moving across the countries</p>
</li>
</ul>
<p>All the above cited reasons are what makes bitcoin an ideal currency for medium of exchange from a user’s perspective not governments.</p>
<blockquote>
<p>I had almost finished writing my article when I learned that <strong>India’s Financial Intelligence Unit (FIU)</strong>, a branch of the Finance Ministry, had issued a <a target="_blank" href="https://pib.gov.in/PressReleaseIframePage.aspx?PRID=1991372">notice</a> and blocked the domain of several bitcoin exchanges, making another attempt to undermine <strong>bitcoin’s supremacy</strong>.</p>
</blockquote>
<h2 id="heading-data-speaks">Data Speaks</h2>
<p>Let’s consider two measuring tools which give us idea of how <strong>poorly</strong> our governments manage country finances, after all financial education needs education and most of our illiterate parliamentarians don’t have any formal education.</p>
<p><strong>Fiscal Deficit:</strong> A fiscal deficit is a shortfall in a government’s income compared with its spending. A government that has a fiscal deficit is spending beyond its means. The government has to borrow money to meet its expenses. The government’s debt increases over time as it continues to borrow.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356718906/41b25dfc-2c8d-4011-a71e-be1c7bbadf08.webp" alt /></p>
<p><strong>Fiscal Debt</strong>: It is the total debt accumulated over years of deficit spending. It is the sum of all the fiscal deficits over the years. It is the total amount of money the government owes to its creditors.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356782217/d12e570f-9a8b-4964-9cac-7ef0ef8275aa.webp" alt /></p>
<p>Every Indian today is born with a debt of <strong>Rs. 1,57,594.93</strong> (debt per capita) all thanks to the wonderful schemes put in place by our governments to provide <strong>freebies</strong> instead of generating valuable assets in terms of people and infrastructure.</p>
<h1 id="heading-instant-and-secure">Instant and Secure</h1>
<p>I understand that you are not willing to wait a minimum of 10 minutes on chai point until your bitcoin transaction confirms. Neither would you be willing to send a large sum of money in some investment or purchase over the bitcoin network since it is public ledger visible to everyone.</p>
<p>Satoshi always knew this and in <strong>2009</strong> itself he proposed for creation of layer-2 networks over the main bitcoin network.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356788255/7494fe25-09ba-4f02-929b-1bbd4ceb2c22.webp" alt /></p>
<h2 id="heading-lightning-network">Lightning Network</h2>
<p>If Bitcoin is to be used for <strong>everyday</strong> payments the transaction speed must increase and transaction costs must decrease drastically. The <strong>Lightning Network</strong> (also referred to as Lightning, or LN) is a scalability solution built on top of Bitcoin that allows users to quickly send and receive BTC with virtually no fees.</p>
<p>Lightning makes Bitcoin a viable option it can be thought of as <strong>Indian UPI</strong> system for Bitcoin just <strong>decentralized</strong>. The Lightning network uses smart contracts (HTLCs) and payment channels between two parties.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Network</td><td>Transactions (per second)</td></tr>
</thead>
<tbody>
<tr>
<td>Bitcoin</td><td>10</td></tr>
<tr>
<td>VISA</td><td>6000</td></tr>
<tr>
<td>Lightning Network</td><td>250n (n is number of channels, unlimited)</td></tr>
</tbody>
</table>
</div><p><strong>Note</strong>: Lightning network can have as many channels as it wants so TPS has no limit or we can say <em>sky is the limit.</em></p>
<h2 id="heading-liquid-network">Liquid Network</h2>
<p>The Liquid Network is a Bitcoin layer-2 solution enabling the fast, <strong>confidential</strong> settlement and issuance of digital assets, such as stablecoins, security tokens, and other financial instruments, on top of the Bitcoin timechain.</p>
<p>While it’s not fully permissionless like Bitcoin, Liquid is fault-tolerant, censorship-resistant, and has <a target="_blank" href="https://blog.liquid.net/six-differences-between-liquid-and-lightning/">different trade-offs</a> than other second layers like Lightning. Liquid’s high degree of privacy represents an important benefit for traders.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Further read to get a in depth understanding of bitcoin:</p>
<ul>
<li><p><a target="_blank" href="https://vijayboyapati.medium.com/the-bullish-case-for-bitcoin-6ecc8bdecc1">The Bullish Case for Bitcoin | by Vijay Boyapati</a></p>
</li>
<li><p><a target="_blank" href="https://whybitcoinbook.com/">Why Bitcoin</a></p>
</li>
<li><p><a target="_blank" href="https://bitcoin.org/en/bitcoin-paper">Bitcoin: A Peer-to-Peer Electronic Cash System</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=IkK0mLaEmU4">Money Creation and Society</a></p>
</li>
</ul>
<p>Give bitcoin a try, if you have any queries am more than happy to help you out with them at <a target="_blank" href="https://twitter.com/1108King">@1108King</a> but like any other investment it’s a risk <em>“should you choose to accept it your mission is to explore bitcoin”</em>. Thanks for reading and have a great year ahead.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347607625/9d74a33e-179e-4b4e-8087-9d76dc3fb18a.gif" alt="bitcoin blasting off" /></p>
]]></content:encoded></item><item><title><![CDATA[Goroutines]]></title><description><![CDATA[A goroutine is a lightweight thread of execution managed by the Go runtime. To start a new goroutine we use the go keyword
go f(x, y, z)

The evaluation of f, x, y, and z happens in the current goroutine and the execution of f happens in the new goro...]]></description><link>https://hashnode.king-11.dev/goroutines</link><guid isPermaLink="true">https://hashnode.king-11.dev/goroutines</guid><category><![CDATA[Go Language]]></category><category><![CDATA[goroutines]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Fri, 22 Dec 2023 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356408435/0c2808c1-ef44-487f-9fa6-819a6ca878dc.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A <strong>goroutine</strong> is a lightweight thread of execution managed by the <em>Go runtime</em>. To start a new goroutine we use the <code>go</code> keyword</p>
<pre><code class="lang-go"><span class="hljs-keyword">go</span> f(x, y, z)
</code></pre>
<p>The <em>evaluation</em> of <code>f</code>, <code>x</code>, <code>y</code>, and <code>z</code> happens in the current <code>goroutine</code> and the <em>execution</em> of <code>f</code> happens in the new goroutine.</p>
<p>Goroutines run in the same address space, so access to shared memory must be synchronized. The <code>sync</code> package provides useful primitives, although you won’t need them much in Go as there are other primitives like <code>channels</code>.</p>
<h1 id="heading-when-to-use">When to use?</h1>
<p>With <code>goroutine</code>, we can make asynchronous network IO and continue the program without the need to wait for the response to come back. Obviously, network IO is just one of the many examples. We can do parallel processing like a mini map reduce and fully utilize each CPU core we have on our modern days machine.</p>
<h1 id="heading-architecture">Architecture</h1>
<p><code>goroutine</code> is not a <code>os/kernel</code> thread. It is an abstraction of a thread, more commonly known as application thread. It is Go runtime’s job to manage how many OS threads to create and how goroutines are mapped to and executed on OS threads.</p>
<h2 id="heading-go-runtime-components">Go Runtime Components</h2>
<p>There are three main components involved in the execution of a goroutine i.e. the goroutine, an abstract logical processor and the machine.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356446592/eacb3b44-f2f3-43a1-b053-eee902c06871.webp" alt class="image--center mx-auto" /></p>
<ul>
<li><p><strong>Goroutine</strong>: Each goroutine is described by a <a target="_blank" href="https://github.com/golang/go/blob/master/src/runtime/runtime2.go#L339">G</a> struct. The struct keeps track of various runtime information, like stack trace and status.</p>
</li>
<li><p><strong>Logical Processor</strong>: P stands for Logical Processor. It’s an abstract resource or context. We usually call <strong>P</strong> a context that is mapped to a <strong>M</strong> to run <strong>G</strong>s.</p>
</li>
<li><p><strong>Machine</strong>: The struct <a target="_blank" href="https://github.com/golang/go/blob/master/src/runtime/runtime2.go#L404">M</a> stands for machine, which maps to an OS thread which can execute a <strong>G</strong> or goroutine.</p>
</li>
</ul>
<h2 id="heading-entity-interaction">Entity Interaction</h2>
<p>When a Go program starts, it is given a logical processor <strong>P</strong> for every virtual core. Every <strong>P</strong> is assigned an OS thread <strong>M</strong>. Every Go program is also given an initial <strong>G</strong> which is the path of execution for a Go program. OS threads are context-switched on and off a core, goroutines are context-switched on and off a <strong>M</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356471843/6c23440e-975b-4c6e-a8d3-988ee2a0fc8a.webp" alt /></p>
<p><strong>P</strong> is responsible for scheduling all <em>runnable</em> <strong>G</strong>s on <strong>M</strong>. If and when an executing <strong>G</strong> makes a blocking call, <strong>P</strong> moves onto a different <strong>M</strong> while <strong>G</strong> blocks the current <strong>M</strong>.</p>
<h3 id="heading-controlling-parallelism">Controlling Parallelism</h3>
<p>We can set the maximum number of goroutines executing in parallel by limiting the number of P.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> ( 
    <span class="hljs-string">"fmt"</span> 
    <span class="hljs-string">"runtime"</span> 
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> { 
    fmt.Println(runtime.GOMAXPROCS(<span class="hljs-number">1</span>)) 
}
</code></pre>
<p>This limits the maximum number of <strong>P</strong> to 1 but that won’t limit the program to not spawn more than 1 <strong>M</strong> (OS Threads) in case of blocking call as stated above.</p>
<h1 id="heading-thread-synchronization">Thread Synchronization</h1>
<blockquote>
<p>Don’t communicate by sharing memory; share memory by communicating</p>
</blockquote>
<p>This is the moto which go lang has popularized, in which we don’t give threads access to shared memory but instead share messages/data by communicating with each other.</p>
<h2 id="heading-channels">Channels</h2>
<p>Channels are a typed thread safe conduit through which you can send and receive values with the channel operator, <code>&lt;-</code>.</p>
<pre><code class="lang-go">ch &lt;- v <span class="hljs-comment">// Send v to channel ch.</span>
v := &lt;-ch <span class="hljs-comment">// Receive from ch, and</span>
         <span class="hljs-comment">// assign value to v.</span>
</code></pre>
<p>(The data flows in the direction of the arrow.)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730356502483/49ebeda3-999f-467a-8c05-06d8d5fe4bd8.webp" alt /></p>
<p>Like maps and slices, channels must be created before use:</p>
<pre><code class="lang-go">ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">int</span>)
</code></pre>
<p>By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.</p>
<p>We can also use <a target="_blank" href="https://go.dev/tour/concurrency/3">buffered channels</a> which won’t block on every operation but instead only on the absence of data.</p>
<blockquote>
<p>Note: Channels aren’t like files; you don’t usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loop.</p>
</blockquote>
<h3 id="heading-select-statement">Select Statement</h3>
<p>The <code>select</code> statement lets a <code>goroutine</code> wait on multiple communication operations.</p>
<p>A <code>select</code> blocks until one of its cases can run, then it executes that case</p>
<pre><code class="lang-go"><span class="hljs-keyword">select</span> {
    <span class="hljs-keyword">case</span> c &lt;- x:
        x, y = y, x+y
    <span class="hljs-keyword">case</span> &lt;-quit:
        fmt.Println(<span class="hljs-string">"quit"</span>)
        <span class="hljs-keyword">return</span>
}
</code></pre>
<h2 id="heading-shared-data">Shared Data</h2>
<p>Go’s standard library provides mutual exclusion with <a target="_blank" href="https://go.dev/pkg/sync/#Mutex"><code>sync.Mutex</code></a> and its two methods:</p>
<ul>
<li><p><code>Lock</code></p>
</li>
<li><p><code>Unlock</code></p>
</li>
</ul>
<p>We can define a block of code to be executed in mutual exclusion by surrounding it with a call to <code>Lock</code> and <code>Unlock</code>.</p>
<pre><code class="lang-go">c.mu.Lock()
<span class="hljs-comment">// Lock so only one goroutine at a time can access the map c.v.</span>
<span class="hljs-keyword">defer</span> c.mu.Unlock()
<span class="hljs-keyword">return</span> c.v[key]
</code></pre>
<h2 id="heading-data-race">Data Race</h2>
<p>It’s important to use patterns like <code>channels</code> and <code>mutex</code> locks to prevent data races otherwise <code>go</code> has a data race detector which will panic at runtime.</p>
<p>When the race detector finds a data race in the program, it prints a report. The report contains <code>stack</code> traces for conflicting accesses, as well as stacks where the involved goroutines were created.</p>
<pre><code class="lang-bash">WARNING: DATA RACE
Read by goroutine 185:[[]]
  net.(*conn).Write()
      src/net/net.go:129 +0x101

Previous write by goroutine 184:
  net.setWriteDeadline()

Goroutine 185 (running) created at:
  net.func·061()
      src/net/timeout_test.go:609 +0x288

Goroutine 184 (running) created at:
  net.TestProlongTimeout()
      src/net/timeout_test.go:618 +0x298
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347615702/155dd681-aa55-46d7-8876-95f2794d076d.gif" alt="thanks for reading" /></p>
<p>Thanks for reading please share your reviews on twitter with me <a target="_blank" href="https://twitter.com/1108King">@1108King</a> and if you found the article useful do share if for visibility.</p>
]]></content:encoded></item><item><title><![CDATA[The Hacker Way of Living]]></title><description><![CDATA[TL;DR and not for the weak hearted, please don’t start reading this until you are willing to put efforts into changing the way you deal with online subscriptions.
Childhood Fun
Since my childhood I was taught by my cousin brother (Karan) on how to ut...]]></description><link>https://hashnode.king-11.dev/the-hacker-way-of-living</link><guid isPermaLink="true">https://hashnode.king-11.dev/the-hacker-way-of-living</guid><category><![CDATA[hacker]]></category><category><![CDATA[self-hosted]]></category><category><![CDATA[umbrel]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Sun, 19 Nov 2023 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355565770/0a74ac5d-ecf8-4e23-9238-4aca75aa208a.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>TL;DR and not for the weak hearted, please don’t start reading this until you are willing to put efforts into changing the way you deal with online subscriptions.</p>
<h1 id="heading-childhood-fun">Childhood Fun</h1>
<p>Since my childhood I was taught by my cousin brother <strong>(Karan)</strong> on how to utilize the amazing peer to peer network named torrent we used to keep our systems running late at night to just download a video game, dark ages I know.</p>
<p>Back in time when I was worthy I even hard booted my first phone (YU Yureka 2014) with alternative android based operating system Cyanogen (renamed to <a target="_blank" href="https://lineageos.org/">LineageOS</a>).</p>
<p>My father got me a second hand computer first to experiment on, I do remember installing my first <a target="_blank" href="https://ubuntu.com/">Ubuntu</a>/<a target="_blank" href="https://www.linuxmint.com/">Linux Mint</a> but didn’t quite understand it that time neither there were good online resources to help me so moved back to Windows. I used to break it down every other day and papa had to call Saini/Mahesh Uncle to fix and reinstall Windows.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347620606/c93533fd-e7b5-474d-8b45-c4385de98150.gif" alt="it makes sense now" /></p>
<p>Damn, those were good days (emotional moment), it was the time of flash sales we used to look up internet find scripts to run that would get us the product that we wanted quickly. Now after doing web development I can make those scripts myself I even help my father in auctions to get the contract in milli seconds using scripts.</p>
<h1 id="heading-moving-away-from-subscription-hell">Moving away from Subscription Hell</h1>
<p>I will try to break down things and go service by on what are the <em>possible</em> alternatives. Possible being the keyword these aren’t the exact service of what the evil corporate gives you but it’s very much doable to live with the alternatives. Because of course nothing not everything comes for free.</p>
<h2 id="heading-youtube-premium">YouTube Premium</h2>
<p>Depending on platform that you are using Desktop or Android (yeah shu go away iPhone users) there are two solutions.</p>
<h3 id="heading-brave-browser">Brave Browser</h3>
<p>If you want to listen to the beats while working on laptop like I usually do just start using <a target="_blank" href="https://brave.com/">Secure, Fast, &amp; Private Web Browser with Adblocker | Brave</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355587073/9a176e1b-ff95-452c-b73d-7971db4e93ff.webp" alt class="image--center mx-auto" /></p>
<p>Brave is the best browser probably if you are a <strong>privacy enthusiast</strong> and want to protect your data and habits aka yourself from the clutches of corporate data centres then use it.</p>
<ul>
<li><p>It is as fast as Chrome because under the hood they use Chromium only the engine that powers Chrome, Edge, etc.</p>
</li>
<li><p>It blocks scripts, trackers, cookie banners, fingerprinting, <a target="_blank" href="https://brave.com/glossary/third-party-ad/">third party ads</a>, etc. and that’s why the sites don’t get stuck and frozen while browsing.</p>
</li>
<li><p>It has its own privacy focused <a target="_blank" href="https://brave.com/en-in/brave-search/">search engine</a> with AI features as well. It isn’t as good as bing or google but well it boils down to making compromise because sometime you want privacy and sometimes you just want results.</p>
</li>
<li><p>It enables https by default which keeps your <a target="_blank" href="https://www.cloudflare.com/en-gb/learning/ssl/what-is-https/">data secure</a> over the wire from other people who can listen to all the online chatter. So just install brave and head over to <a target="_blank" href="https://music.youtube.com">Youtube Music</a> or <a target="_blank" href="https://youtube.com">Youtube</a> to listen to your favourite songs without ad interruption</p>
</li>
</ul>
<h3 id="heading-revanced">ReVanced</h3>
<p>It’s <strong>ReVanced</strong> not <strong>Vanced</strong> before you start saying that Vanced was <a target="_blank" href="https://telegra.ph/Vanced-Discontinuation-03-19">discontinued</a> not because it was an ad blocker but it was due to logo infringement.</p>
<p>Here is the <a target="_blank" href="https://www.reddit.com/r/revancedapp/s/212RnQA3th">guide</a> that I used to install revanced on my Android phone and it just works. If it doesn’t for you there are two options:</p>
<ul>
<li><p>Revanced is open source unlike Vanced so just go out there and contribute to the project by either providing a reproducible or if you can code just fix it.</p>
</li>
<li><p>Pay up 👁️👁️</p>
</li>
</ul>
<h2 id="heading-spotify-premium">Spotify Premium</h2>
<p>There are multiple <strong>modded</strong> versions of Spotify available which just work fine still even with all the restrictions. I got one from <a target="_blank" href="https//wa.me/917979939400">Ankit</a> you can ask him to :P or just a quick <a target="_blank" href="https://search.brave.com/search?q=spotify+mod+8.7&amp;source=desktop">search</a> gives you a lot of modded Android version iPhone users shu shu definitely available.</p>
<p>Well there is definitely <strong>attached risk</strong> for installing mod maybe it is some harmful app instead but well isn’t that life :P. Everything is risk from stock markets to driving vehicle to <strong>travelling to Himachal</strong> but even the most chaotic of experiences won’t stop me at least from getting that <strong>adrenaline shot</strong> of investing in a new found fund, going at <strong>170km/hr</strong> on Delhi - Mumbai Expressway, Returning to my beloved mountains on a trip to Nanital, etc.</p>
<h2 id="heading-cloud-notes">Cloud Notes</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355603739/441615f1-fe23-40f8-a937-63616aa19c97.webp" alt class="image--center mx-auto" /></p>
<p>I keep <strong>track</strong> of every single thought of mine <em>blogs, shopping list, contacting people, good reads, healthy lifestyle, investments</em>, etc literally everything. Partially I write down some of the urgent notes from meetings into <strong>diary</strong> as well.</p>
<p>I use <a target="_blank" href="https://obsidian.md">Obsidian</a> for writing down notes and thoughts it’s just amazing and you will only know it’s awesomeness after trying am even writing my blog in this. Now to sync it, I use <a target="_blank" href="https://syncthing.net/">Syncthing</a>, it’s a cross platform app to keep files and folders between multiple devices in sync. I use it to keep my desktop and android obsidian in sync. Weekly I upload it to my self hosted <a target="_blank" href="https://nextcloud.com/">Next Cloud</a> so that it stays good.</p>
<p>Obsidian comes with <a target="_blank" href="https://obsidian.md/sync">Obsidian sync</a> as well which is $10/month it’s costly so I definitely would not recommend it until you are not willing to make above efforts. You also don’t have to use nextcloud you can just use <strong>OneDrive</strong> or similar alternatives as well.</p>
<h1 id="heading-self-hosting">Self Hosting</h1>
<p>Now this is the part am most excited about. I recently got a <a target="_blank" href="https://www.raspberrypi.com/products/raspberry-pi-4-model-b/">Raspberry Pi 4</a> and installed <a target="_blank" href="https://umbrel.com/">Umbrel OS</a>, what umbrel offers is a plethora of self hosted alternatives to your regular cloud hosted things like which are just a single click away on their <a target="_blank" href="https://apps.umbrel.com/">app store</a></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355627946/7997cdb5-adf9-41b8-ab12-3a0092addeed.webp" alt class="image--center mx-auto" /></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Cloud Solution</strong></td><td><strong>Self Hosted Solution</strong></td></tr>
</thead>
<tbody>
<tr>
<td>One Drive</td><td>Next Cloud</td></tr>
<tr>
<td>Netflix</td><td>Jellyfin</td></tr>
<tr>
<td>Google Photos</td><td>PhotoPrism</td></tr>
<tr>
<td>Podcasting</td><td>IPFS Podcasting</td></tr>
<tr>
<td>VPN</td><td>Tor Snowflake</td></tr>
<tr>
<td>UPI Payments</td><td>Lightning Node</td></tr>
<tr>
<td>Bank Transfers</td><td>Bitcoin Node</td></tr>
<tr>
<td>ChatGPT</td><td>LlamaGPT</td></tr>
</tbody>
</table>
</div><p>I personally use all of them except <strong>PhotoPrism</strong> (Dad paid for Google One his mailing quota was going above 20GB limit) and <strong>LlamaGPT</strong> (I have access to Bing Chat Enterprise running on GPT 4 thanks to Microsoft 😼).</p>
<p>I can access my umbrel on my Local Area Network (LAN) which is provided by my Home WiFi Router through any web browser by going to <a target="_blank" href="https://umbrel.local">https://umbrel.local</a> . It’s possible to access it remotely using <strong>Tor Address</strong> but that is a little slow but comes useful in case I have to show document which isn’t available on my mobile.</p>
<h2 id="heading-vendor-lock-in">Vendor Lock In</h2>
<p>When you use cloud hosted services you become at most of the times a victim of vendor lock in. As I wrote in my previous blog about <a target="_blank" href="https://king-11.github.io/blog/posts/customer-empathy/">Loss of Customer Empathy | Backpacking Dream</a> the corporate world is more focused on <strong>locking</strong> you into their product rather than allowing you to easily <strong>move away</strong> from their service/product.</p>
<p>I discussed it in <strong>Microsoft</strong> with one of our <strong>CVP PM</strong> about vendor lock, he also agreed to the fact that it is <strong>everywhere</strong> but there is <strong>additional value</strong> attached with it for users using it for long periods of <strong>time</strong> so sometimes it’s not bad. I concur, sometimes its good but it becomes bad when Google Photos won’t even provide you with a delete all button 😿</p>
<p>Self hosted alternatives generally use an open source protocol/standard which allows you to easily move away from it if you aren’t able to gather value out of it.</p>
<h1 id="heading-cant-we-just-pay">Can’t we just pay?</h1>
<p>Let’s calculate the bare minimum cost of self hosting:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Product</strong></td><td><strong>Cost</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Raspberry Pi 5</td><td>11460</td></tr>
<tr>
<td>External HDD (1 TB)</td><td>5000</td></tr>
<tr>
<td>SD Card (128 GB)</td><td>879</td></tr>
<tr>
<td>LAN Cable</td><td>200</td></tr>
<tr>
<td>Raspberry Pi Charger</td><td>897</td></tr>
<tr>
<td>Raspberry Pi Case</td><td>250</td></tr>
<tr>
<td>Total</td><td>18686</td></tr>
</tbody>
</table>
</div><p>Obviously this is the basic I personally use HDD -&gt; SSD (2 TB) and Basic Case -&gt; Metallic Heat Sink Case but that is just me you don’t have to it varies on your use case. Now that is all until my <strong>hardware fails</strong> (generally SD Card) I have to get a new one but that would be all.</p>
<p>Let’s compare to available cloud solutions calculated at an <strong>yearly</strong> cost.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Cloud Solution</strong></td><td><strong>Cost</strong></td></tr>
</thead>
<tbody>
<tr>
<td>One Drive (1 TB)</td><td>5840</td></tr>
<tr>
<td>Netflix (Premium)</td><td>4800</td></tr>
<tr>
<td>Total</td><td>10640</td></tr>
</tbody>
</table>
</div><p>So a self hosted solution within two years will be more cost efficient than a cloud solution, with additional perk of no vendor lock in.</p>
<h2 id="heading-azure-student-offer">Azure Student Offer</h2>
<p>If you are a student currently and looking for cheaper alternatives because “<em>Lakshya we don’t earn yet brother</em>”. Don’t worry kids <a target="_blank" href="https://azure.microsoft.com/en-us/free/students/">Azure</a> has you covered, you can try multiple of the services like VMs, SQL Server, Apps, Functions, etc. with a monthly <strong>100$ credit</strong>. For our use case just spin up a VM and install all these services individually on it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355743658/fc6cd313-e6f2-43fc-9605-20acf07b7fe9.webp" alt class="image--center mx-auto" /></p>
<p>If you want to take it a little easy and just run <strong>Umbrel</strong> instead you can do so by installing <strong>docker</strong> on your Azure Linux/Windows VM and then run the <a target="_blank" href="https://github.com/getumbrel/umbrel/blob/master/docker-compose.yml">docker compose</a> service with just a single command.</p>
<p>git clone https://github.com/getumbrel/umbrel docker compose up -d</p>
<h1 id="heading-mein-nah-sehta"><em>Mein nah sehta</em></h1>
<p>Enough said already but why am I going through so many steps and things when am well off enough to pay out for all these cloud services. Well the simple answer is</p>
<blockquote>
<p>mein na sehta bhai (I can’t bear it brother)</p>
</blockquote>
<p>As I already made well known in my <a target="_blank" href="https://king-11.github.io/blog/posts/customer-empathy/">previous blog</a> that I hate corporates trying to make me feel like a fool even when am using their services so yes I won’t bow down to them and provide them more of my data to keep in their silos and god knows what they do with it if I ever forfeit to pay for their services <strong>I am taking control of my life my data.</strong></p>
<p>Second things come with my <a target="_blank" href="/posts/living-hacker/#childhood-fun">upbringing</a>. My cousin <strong>Karan</strong> taught me to be <strong>opportunistic</strong> and get the job done without paying a single dime of money. I realize that I am already paying enough of these taxes which don’t provide me back with even basic service, I belong to the most <strong>repressed</strong> class of humans in Indian Society - <strong>A general category, non EWS, salaried, male.</strong> So yeah am willing to put in efforts to save a little money here and there.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730347624947/e286872b-f0be-495c-a761-06aafb5b805e.gif" alt="dua lipa thanks" /></p>
<p>Thanks for reading this through appreciate it. Looking forward to writing a little more consistently about life, finance, bitcoin and technology of course. You can reach out to me on <strong>twitter</strong> <a target="_blank" href="https://twitter.com/1108King">@1108King</a></p>
]]></content:encoded></item><item><title><![CDATA[Loss of Customer Empathy]]></title><description><![CDATA[Gold Plated Products
Gold Plated Products is what am calling products/services that get offered as free or for unlimited usage to get numerous people onboarded on it. After a while either they will add a paywall for complete service or some premium f...]]></description><link>https://hashnode.king-11.dev/loss-of-customer-empathy</link><guid isPermaLink="true">https://hashnode.king-11.dev/loss-of-customer-empathy</guid><category><![CDATA[Google]]></category><category><![CDATA[product]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Fri, 17 Nov 2023 18:30:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355025431/fd21a2d7-a736-4573-8eae-03fa6d28a4c2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-gold-plated-products">Gold Plated Products</h1>
<p>Gold Plated Products is what am calling products/services that get offered as free or for unlimited usage to get numerous people onboarded on it. After a while either they will add a paywall for complete service or some premium features which were previously free are now only available if you pay.</p>
<p>The issue begins when there is a lack of information provided to users of when the paywall or premium offering will become active. The Product Managers just wake one day and decide to choose violence, boom the paywall goes live.</p>
<p>Now user has two options both are miserable:</p>
<ul>
<li><p>Going through the painful process of deboarding from the service through procedures which are never well documented.</p>
</li>
<li><p>Start paying for the service if it suits your needs.</p>
</li>
</ul>
<h2 id="heading-google-mail">Google Mail</h2>
<p>The original pitch for Gmail was that you wouldn’t have to worry about deleting messages. Instead, you could just archive old emails and find them later by searching.</p>
<p>But in 2013, <a target="_blank" href="https://drive.googleblog.com/2013/05/bringing-it-all-together-15-gb-now.html">Google altered the deal</a>, creating a single 15 GB storage pool that covered all of its services, including Gmail and Google Drive. Its free storage limit hasn’t changed since then, and in recent years Gmail users have been <a target="_blank" href="https://www.bloomberg.com/news/articles/2019-10-22/gmail-hooked-us-on-free-storage-now-google-is-making-us-pay">feeling the squeeze to become paid users</a>.</p>
<h2 id="heading-google-photos">Google Photos</h2>
<p>When Google Photos launched in 2015 with the promise of free, unlimited photo storage, the pitch was that you’d never have again to worry about photo management. Because of that promise, Google Photos quickly became one of the company’s most popular services, <a target="_blank" href="https://www.fastcompany.com/90380618/how-google-photos-joined-the-billion-user-club">hitting one billion users last year</a>.</p>
<p>But soon enough, Google had a different message for those users who flocked to the service: <em>“Time to pay the piper.”</em></p>
<p>After using up Google’s 15 GB of free storage, you have to pay for a Google One storage plan starting at Rs. 1,300/year for 100GB.</p>
<blockquote>
<p>The product is ad-free, and Google has pledged not to mine users’ photo data for targeted advertising purposes.</p>
</blockquote>
<p>Let’s see how long this lasts</p>
<h2 id="heading-google-drive">Google Drive</h2>
<p>Google offered educational institution unlimited google drive space every student in institution fully made use of this as the best years of teenage life does require some space iykyk.</p>
<p>In 2022 they went back on the unlimited storage promise and limited it to 100TB for all the educational institutions. The response they were hoping was for institution to buy more storage but well the administration of most Indian Educational Institution haven’t embraced the need of cloud so they didn’t buy the subscription and are continuing with 100TB only.</p>
<p>Now a student with let’s say around 100GB of video games/movies/photos/videos is now limited to around 20GB (100*1024/5000) and 5GB for alums so they have to move 80GB.</p>
<p>One way is to download everything and then delete other is to copy (not move) it with ease to some another Google Drive. I have tried both and the files you get after download are utter rubbish to parse whereas the internal transfer is made very smooth.</p>
<p>But still you have to delete from original place in both scenarios but if most of your storage is due to Google Photos which was in my case you can’t bulk delete because <strong><em>Google Engineers forgot to add option to delete all photos</em></strong>.</p>
<p>It’s a typical example of <strong><em>vendor lock in</em></strong> 🔐.</p>
<p>So yeah basic quota is 15GB you need 80GB, <em>“Time to pay the piper.”</em></p>
<h3 id="heading-one-drive">One Drive</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355060101/194928fa-53c5-4a71-8d0d-cc898adccb50.png" alt class="image--center mx-auto" /></p>
<p>Microsoft also moved away from unlimited OneDrive storage given to educational institution to make them onboard onto the Sharepoint &amp; Teams platform during pandemic. The reason they cited is as below:</p>
<blockquote>
<p>Today, most schools (99.96%) are well below their storage allotment. With new tools, all schools can better manage their information and set thoughtful policies for data governance. Some of the benefits we expect to see include helping schools reduce some of the security risks associated with legacy storage and data sprawl, a top concern for most chief risk officers, while also benefiting our shared environmental footprint.</p>
</blockquote>
<p>Hoping the my institution falls under the 99.96 category because I moved multiple things from GDrive to OneDrive. But with OneDrive we at least won’t have the trouble of deleting backed up photos as its a folder in your OneDrive which you can delete. So Microsoft at least allows you to deboard unlike Google.</p>
<h2 id="heading-youtube-music">YouTube Music</h2>
<p>One of the most recent services released by Google. It’s a very nice service if you have a student ID you get 1 month free, but you have to start auto pay. I tried it, loved the recommendations and while crusing at 170km/hr on Delhi-Vadodra-Mumbai expressway it added even more fun to the journey where even my Mom and Dad started jamming.</p>
<p>It’s been two days since my subscription expired given that I loved it I was planning to get a family subscription (179/month) since it’s cheaper than individual subscription (79/month) if you have a pseudo family of friends also I wanted mom and dad to enjoy it but…..</p>
<p>For these two days they haven’t stopped with the ads before every song you need to waste time on two ads of 5 seconds. Moreover you don’t even have the option to keep music running in the background for scenarios like driving.</p>
<p>Least to say I have been miserable for the past two days and decided not to succumb to this unwanted pressure of subscription hell.</p>
<h3 id="heading-google-podcast">Google Podcast</h3>
<p>A very simple un-monetized service to listen to any podcast is being added to the long list of <a target="_blank" href="https://killedbygoogle.com/">killed by Google</a>.</p>
<p>They are moving podcasts to YouTube music where they can bully us into getting premium.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730355075300/76581f9e-1ff1-424d-a35f-909346ae3b95.jpeg" alt class="image--center mx-auto" /></p>
<p>A finding from reddit:</p>
<blockquote>
<p>Got an email today that YouTube Premium Family is going up to $32.99 a month. I was paying $17.99. This and the adblocker crackdown is bloody outrageous. Good luck with the ads kids.</p>
</blockquote>
<h2 id="heading-spotify-music">Spotify Music</h2>
<p>We all user experience and sound quality that Spotify used to give is unmatched from any other music service. When they started with year in review thing every other organization followed it even Paytm. But now instead of making others follow it they are following Google in making its free users feel miserable. Probably because Youtube Music was snatching away its revenue.</p>
<p>Really I mean the restrictions are quite innovative and absurd:</p>
<ul>
<li><p>prevent manual song selection from a playlist</p>
</li>
<li><p>disable option to rewind, scrub, or repeat songs.</p>
</li>
</ul>
<h1 id="heading-whats-wrong-here">What’s wrong here?</h1>
<p>I got to hear this word for the first time from Archit, <code>user empathy</code> that’s what these product based companies have started missing out on. Why do you follow the policy of <strong>lure and capture</strong> through vendor lock in instead of making it clear from the start the cost of your service and attached perils of not having using a paid plan.</p>
<p>By giving free users a miserable experience you either end up in two places:</p>
<ul>
<li><p>Get more paid users</p>
</li>
<li><p>Lose users due to the absolute lack of ethics.</p>
</li>
</ul>
<h1 id="heading-conclusion">Conclusion</h1>
<p>While there is no way to justify this but still let’s understand why it is happening. We already give companies enough data for it earn through it but as ad growth gets tougher, many of them are seeing subscriptions as a big part of their future.</p>
<p>Most of the tax paying + general category + male suffer enough at the hands of the system holding the rant for some other time. So, to tackle this I enjoy being hackish and opportunistic as Bhavya (my mentor) defined this behaviour of mine.</p>
<p><strong><em>“Bhai mai nah sehta”</em></strong></p>
<p>To learn more about on dodging the need for all these subscriptions stay tuned on my blog: <a target="_blank" href="https://king-11.github.io/blog/">The Backpacking Dream</a></p>
]]></content:encoded></item><item><title><![CDATA[Vitess LFX Mentorship Fall 2021]]></title><description><![CDATA[I recently graduated from LFX Mentorship Program. In this blog post, I will be sharing my experience of contributing to Vitess, a database clustering system for horizontal scaling of MySQL.
What is LFX Mentorship
In the exact words of the Linux Found...]]></description><link>https://hashnode.king-11.dev/lfx-mentorship-fall-2021</link><guid isPermaLink="true">https://hashnode.king-11.dev/lfx-mentorship-fall-2021</guid><category><![CDATA[Linux]]></category><category><![CDATA[Cloud]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[MySQL]]></category><category><![CDATA[mentorship]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Tue, 21 Dec 2021 15:51:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1640100879132/rvZa-xggm.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I recently graduated from LFX Mentorship Program. In this blog post, I will be sharing my experience of contributing to <a target="_blank" href="https://vitess.io/">Vitess</a>, a database clustering system for horizontal scaling of MySQL.</p>
<h2 id="heading-what-is-lfx-mentorship">What is LFX Mentorship</h2>
<p>In the exact words of the Linux Foundation, </p>
<blockquote>
<p>The Linux Foundation Mentorship Program is designed to help developers — many of whom are first-time open source contributors — with the necessary skills and resources to learn, experiment, and contribute effectively to open source communities. By participating in a mentorship program, mentees have the opportunity to learn from experienced open source contributors as a segue to get internship and job opportunities upon graduation."</p>
</blockquote>
<p>This sounded quite fascinating to me and aligned with my goals. That's how I get all excited for this program.</p>
<h2 id="heading-why-vitess">Why Vitess?</h2>
<p>During this term, I had to study Database Management Systems as a part of my college curriculum, and I had previous experience with MySQL, so I applied to the project <a target="_blank" href="https://mentorship.lfx.linuxfoundation.org/project/058a41fd-79e8-43f7-a5f7-1840c1f759be">CNCF - Vitess: Add support for comparing strings using collations and character-sets</a></p>
<p>Also, I was particularly fascinated by the extent of usage of Vitess. It was built by intelligent people at Youtube to manage their database load and used by Github, Slack, Pinterest, etc.</p>
<h2 id="heading-problem-statement-of-project">Problem Statement of Project</h2>
<p>Vitess does not yet have support for collations and character sets. So, to compare varchar strings, Vitess needs to rely on <a target="_blank" href="https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_weight-string">WEIGHT_STRING</a> function for now. MySQL documentation says WEIGHT_STRING is a debugging function meant only for internal use. </p>
<p><img src="https://media.giphy.com/media/l0Iy1U0KU3rBaewjm/giphy-downsized.gif" alt="my reaction" /></p>
<h3 id="heading-use-cases">Use Cases</h3>
<ul>
<li>Having the ability to compare strings using collation and character-set support, it would be possible to better implement ORDER BY, GROUP BY, JOIN.</li>
<li>It would be possible to leverage more advanced join techniques than currently implemented.</li>
</ul>
<h2 id="heading-plan-out">Plan Out</h2>
<p>The initial plan that can be found in the project issue was to use <code>text/collate</code> package. We decided to make its fork and make it suitable for our use case.</p>
<p>We tried our hands to replicate MySQL's <code>WEIGHT_STRING</code> using the package but had no success because:</p>
<blockquote>
<p>It only supports UCA compatible collations while MySQL supports several non-UCA collations as well. So in turn Vitess needs to support them too.</p>
</blockquote>
<p>So we headed onto the MySQL <a target="_blank" href="https://github.com/king-11/mysql-server/tree/vitess">codebase</a></p>
<p><img src="https://media.giphy.com/media/PkS3n3TERbjIntnx9E/giphy.gif" alt="onto MySQL" /></p>
<h2 id="heading-dive-into-mysql">Dive into MySQL</h2>
<h3 id="heading-unit-testing-before-anything">Unit Testing Before Anything</h3>
<p>The collations implementation in MySQL is part of the MySQL codebase. The first task that my mentor assigned to me was transpiling tests from MySQL to Vitess. It felt weird to me because who writes code first, right?... Guess what I later realized it is a well-known approach called <strong>Test-Driven Development</strong>.</p>
<p><img src="https://media.giphy.com/media/MgBJ3UifivIY/giphy.gif" alt="unit testing" /></p>
<p>MySQL had two types of tests, ones that are normal Unit Tests others that are Benchmarking tests. I transpiled both as Unit Tests into Vitess for starters.</p>
<h3 id="heading-collation-transpilation">Collation Transpilation</h3>
<p>MySQL has a lot of different charsets; only a few of them are based on the Unicode Collation Algorithm (UCA). UCA collations are implemented in <a target="_blank" href="https://pkg.go.dev/golang.org/x/text">golang/text</a>. Other collations are custom and need to be ported directly from MySQL.</p>
<h3 id="heading-extra-collations">Extra Collations</h3>
<p><a target="_blank" href="https://github.com/mysql/mysql-server/blob/8.0/strings/conf_to_src.cc">conf_to_src</a> is responsible for generating charset data for <code>extra</code> charsets in MySQL. So I was supposed to port this to Vitess.</p>
<p>For parsing the XML Data maps, I learned to use <a target="_blank" href="https://pkg.go.dev/encoding/xml">encoding/xml</a> as I was pretty new to golang and its patterns. <a target="_blank" href="https://twitter.com/vmg">Vicent Marti</a>, my mentor, helped me a lot by providing me reviews and making me understand go patterns and how to write better, more robust code.</p>
<p>Parsing the XML Charsets was a recursive process where you needed to drop down to levels and merge with previously found charsets their collations.</p>
<h3 id="heading-uca-tailorings">UCA Tailorings</h3>
<p>UCA collations are built on the <code>utf8_0900</code> collation, where they modify the standard weight as per language needs. Those modifications are called <a target="_blank" href="https://unicode.org/reports/tr10/#Tailoring">tailorings</a>. Each UCA collation specifies tailorings which then are responsible for modifying weights.</p>
<p>Example: <code>a &lt;&lt;&lt; A &lt;&lt; à &lt;&lt;&lt; À &lt; b &lt;&lt;&lt; B</code></p>
<p>I was to understand the UCA tailoring syntax, copy over the tailorings from MySQL and make a parser to make modifications.</p>
<p>Vicent had a new idea that instead of parsing those strings, we can use the parsing done by MySQL by utilizing the in-memory weights. For that, we decided to dump the UCA weights in JSON using a custom test for each collation.</p>
<p>After that, we diff the ones different from the original UCA weights into separate Go source code that makes our tailorings.</p>
<h3 id="heading-license-issues">License Issues</h3>
<p>Due to Vitess and Oracle license issues, we can't parse the XML as we were doing using <code>conf_to_src</code>. The license only allows us to use in-memory things. So we dump those collations as JSON by attaching to MySQL Unit Testing with a custom unit test and then convert them into <code>go</code> code. </p>
<p><img src="https://media.giphy.com/media/3o6Mb5N2oCnG4dMvIc/giphy.gif" alt="license issue" /></p>
<p>So instead of using <code>encoding/xml</code>, I switched to <code>encoding/json</code>, and we were good to go with a few structural changes. At certain places, I was using <code>regex</code>, which vicent amended to use <code>bufio</code> robust architecture instead.</p>
<p><strong>Result:</strong></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/vitessio/vitess/pull/8991">https://github.com/vitessio/vitess/pull/8991</a></div>
<h2 id="heading-collation-module-integration">Collation Module Integration</h2>
<p>After the <code>mysql/collations</code> module was in Vitess we had a meeting with Andres, Harshit, Florent, Vicent and me. In that meeting, we decided on the next step which was integrating the module into Vitess's Evaluation Engine.</p>
<p>Function <code>NullSafeCompare</code> is the one that is used for any form of comparison in Vitess. For <code>Text</code> comparisons is used to return an unsupported type error.</p>
<p>To make it collation aware I added another parameter into its definition that is the <code>collationID</code>. If the <code>ID</code> isn't <code>0</code> and we get a collation from <code>collations</code> module lookup function then we use it to collate the values.</p>
<p>Similar to <code>NullSafeCompare</code> we had <code>Min</code>, <code>Max</code> and <code>minmax</code> which were made collation aware so that they can use <code>NullSafeCompare</code> as it needs to be. Unit tests were added similar to ones in MySQL to test the new capabilities of these functions.</p>
<p>So, all the places that were using <code>NullSafeCompare</code> now were supposed to pass down collation information but for starters I just made them pass a <code>0</code> and added in TODO.</p>
<pre><code class="lang-go">v1, v2 := <span class="hljs-string">"c"</span>, <span class="hljs-string">"cs"</span>
<span class="hljs-comment">// hungarian accent insensitive case insensitive collation</span>
max, _ := Max(v1, v2, <span class="hljs-string">"utf8mb4_hu_0900_ai_ci"</span>)
<span class="hljs-comment">// max == "cs"</span>
</code></pre>
<h2 id="heading-aggregates-and-groupby">Aggregates and GroupBy</h2>
<p>The <code>OrderedAggregate</code> struct was missing collation information it only contained the default charset information in it. To add collation information into semantic analysis Andres and Florent started working on <a target="_blank" href="https://github.com/vitessio/vitess/pull/9038">gen4: add collation name to the type definition</a>.</p>
<p>Through PR #4038 Collations were made available throughout the planning phase using semTable's <code>CollationFor(expr sqlparser.Expr)</code> method. Using this method, <code>OrderedAggregate</code> was now aware of its grouping keys' collations.</p>
<p>OA has two methods which call in <code>NullSafeCompare</code> those are:</p>
<ul>
<li>keysEqual</li>
<li>merge</li>
</ul>
<p>Collations are fetched from OA as a <code>map[int]collations.ID</code> because not all columns have collation info so helps to reduce space requirements.</p>
<p>The map is then passed down to the above functions. If rows with respect to GroupByKeys are equal then they are merged. Aggregation is done based on the opCode for that particular aggregation which in turn might call the new <code>Min</code> and <code>Max</code>.</p>
<p>Finally, unit testing was done for grouping using various collations like case insensitive, accent sensitive and kana sensitive ones.</p>
<p>The following example when grouped using a case and accent insensitive collation:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>col</td><td>count</td></tr>
</thead>
<tbody>
<tr>
<td>a</td><td>1</td></tr>
<tr>
<td>A</td><td>1</td></tr>
<tr>
<td>Ǎ</td><td>1</td></tr>
<tr>
<td>ß</td><td>11</td></tr>
<tr>
<td>ss</td><td>2</td></tr>
</tbody>
</table>
</div><p>results in:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>col</td><td>count</td></tr>
</thead>
<tbody>
<tr>
<td>a</td><td>3</td></tr>
<tr>
<td>ß</td><td>13</td></tr>
</tbody>
</table>
</div><p><strong>Result:</strong></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/vitessio/vitess/pull/9018">https://github.com/vitessio/vitess/pull/9018</a></div>
<h2 id="heading-memory-route-and-merge-sort">Memory, Route and Merge Sort</h2>
<h3 id="heading-comparer">Comparer</h3>
<p>All these methods are connected by a single struct i.e. <code>engine.comparer</code>. The struct contains details about which column to use for ordering and whether it needs to be descending or not.</p>
<p>It made sense to include collation information too in the struct for ease of access wherever required. Now when calling <code>comparer.compare</code> we can access collation ID and pass it down to the <code>NullSafeCompare</code> call inside the function body.</p>
<p>A new <code>comparer</code> is made from the <code>OrderByParams</code> so they need to carry the collation information as well in form of a new field.</p>
<h3 id="heading-order-by-params">Order By Params</h3>
<p><code>OrderByParams</code> are created using the <code>planbuilder</code> module. To get collation ID we use the <code>semTable.CollationFor(expr sqlparser.Expr)</code>.</p>
<ul>
<li>For planning Route Sort it already contains details about order <code>abstract.OrderBy</code>. Order contains the expression for the statement on which we can call <code>CollationFor</code> providing us with Collation ID.</li>
<li>Creating a memory sort plan on aggregation we first need to find the expression that matches our order expression. If we get a match with one of our GroupByKeys then we can access its collation ID for use.</li>
<li>For memory sort planning with <code>planningContext</code> is similar to route sort we just have to access the semantic table using the context.</li>
</ul>
<h3 id="heading-unit-testing">Unit Testing</h3>
<p>Based on the already present tests for weight string sort with Memory and Route sort testing was done for:</p>
<ul>
<li>Ordering by Hungarian Collation</li>
<li>Descending Order Sorting</li>
<li>Upper Limit for returned entries</li>
<li>Error with Unknown Collation</li>
<li>Error with Unsupported Collation</li>
</ul>
<h3 id="heading-e2e-testing">E2E Testing</h3>
<p>Unit testing only tested memory, merge and route sort separately. To test Memory Sort on aggregation we needed to look at E2E tests.</p>
<p>To add collation details to the Order By statement we updated the <code>String()</code> method to add in the <code>COLLATE</code> statement as well with it.</p>
<p>We then updated the aggregation cases to carry collate information in the OrderBy field to be properly able to test the feature. For this, I had to pair code with Andres and Florent because I wasn't much familiar with eval engine testing.</p>
<p><strong>Result:</strong></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/vitessio/vitess/pull/9155">https://github.com/vitessio/vitess/pull/9155</a></div>
<h2 id="heading-learnings">Learnings</h2>
<p>A three-month-long journey and I got to learn so many things:</p>
<p><img src="https://media.giphy.com/media/5RpWGcd0D8siGo5oCB/giphy.gif" alt="skilling up" /></p>
<ul>
<li>Got familiar with golang that too in a project which was one of the early adopters of go.</li>
<li>I better understand why the design patterns are used in language and can also better implement them.</li>
<li>Went into a deep dive about string representation in charsets and Unicode which was a prerequisite of the project. <a target="_blank" href="https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/">Interesting Read</a></li>
<li>Got to take a look at the inner workings of MySQL and its humongous codebase and test suite.</li>
<li>I became collation aware just like Vitess :)</li>
</ul>
<h2 id="heading-end-on-high-note">End on High Note</h2>
<p>I am very thankful to <a target="_blank" href="https://twitter.com/vmg">Vicent</a> for walking me through the mentorship. The reviews I received from him and pair coding under his supervision really helped me grow as a programmer.</p>
<p>Also wanna thank <a target="_blank" href="https://www.linkedin.com/in/florent-poinsard">Florent</a> and <a target="_blank" href="https://www.linkedin.com/in/andrestaylor">Andres</a> who were working alongside me on this project and really helped me wherever was needed.</p>
<p>Lastly, I did like to thank my mentor <a target="_blank" href="https://www.linkedin.com/in/shivanshs9/">Shivansh Saini</a> for always being a motivation, always will be and one of the reasons I applied for LFX.</p>
<p><img src="https://media.giphy.com/media/lD76yTC5zxZPG/giphy.gif" alt="thanks" /></p>
]]></content:encoded></item><item><title><![CDATA[Google Summer of Code 2021  : Final Report]]></title><description><![CDATA[Abstract
Chapel is a programming language designed for productive parallel computing at scale.  It simplifies parallel programming through elegant parallel programming constructs. As Chapel can utilize a system to its fullest potential, it seems like...]]></description><link>https://hashnode.king-11.dev/gsoc-2021-final-report</link><guid isPermaLink="true">https://hashnode.king-11.dev/gsoc-2021-final-report</guid><category><![CDATA[Open Source]]></category><category><![CDATA[gsoc]]></category><category><![CDATA[socket]]></category><category><![CDATA[Google]]></category><category><![CDATA[technology]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Thu, 26 Aug 2021 06:37:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1629516544215/xMJbznBI-5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-abstract">Abstract</h2>
<p><a target="_blank" href="https://chapel-lang.org/">Chapel</a> is a programming language designed for productive parallel computing at scale.  It simplifies parallel programming through elegant parallel programming constructs. As Chapel can utilize a system to its fullest potential, it seems like one of the ideal solutions to handle millions of network requests.</p>
<p>Currently, we can do network programming by using <a target="_blank" href="https://chapel-lang.org/docs/language/spec/interoperability.html">C Interoperability</a>, but those constructs are not intuitive and good enough for users to easily do their tasks.</p>
<p><img src="https://media.giphy.com/media/SSQsUSbsju3CXoX4DY/giphy.gif?cid=ecf05e474k84ujkw7cv89s2gjlvnj2c9el491atn348sv1zx&amp;rid=giphy.gif&amp;ct=g" alt="let's begin" /></p>
<h2 id="heading-my-project">My Project</h2>
<p>My Google Summer of Code project with Chapel was focused on creating a standard "Socket Library". This project aimed to ensure concurrent, parallel safe, and easy to use constructs for networking.</p>
<p>The project was built on top of C System Calls, saving users from their complexity to perform even the most trivial tasks.</p>
<p>This blog post is for my final submission of the GSoC Project.</p>
<ul>
<li>Project: <a target="_blank" href="https://summerofcode.withgoogle.com/projects/#5343790958641152">Socket Library</a></li>
<li>Mentor: <a target="_blank" href="https://github.com/mppf">Michael Ferguson</a>, <a target="_blank" href="https://github.com/krishnadey30">Krishna Dey</a> and <a target="_blank" href="https://github.com/ankingcodes">Ankush Bhardwaj</a>.</li>
<li>Organisation: <a target="_blank" href="https://github.com/chapel-lang">Chapel</a></li>
</ul>
<p>Under this project, the following four major parts needed to be managed:</p>
<ol>
<li>Getting review over design for the socket library from other developers.</li>
<li>Adding and updating runtime functions that can then be used in Socket Module.</li>
<li>Nonblocking but synchronous procedures that allow other tasks to run freely.</li>
<li>Creating network constructs for UDP and TCP that align themselves except for the I/O differences.</li>
</ol>
<p>Pull requests created in the period of GSoC:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>PR Title</td><td>Review Status</td><td>Merge Status</td></tr>
</thead>
<tbody>
<tr>
<td><a target="_blank" href="https://github.com/chapel-lang/chapel/pull/17899">Design: Socket Library</a></td><td>Approved</td><td>Draft</td></tr>
<tr>
<td><a target="_blank" href="https://github.com/chapel-lang/chapel/pull/17932">Socket Construct Additions Sys Module</a></td><td>Approved</td><td>Merged</td></tr>
<tr>
<td><a target="_blank" href="https://github.com/chapel-lang/chapel/pull/17988">File Descriptor Getter for <code>file</code></a></td><td>Approved</td><td>Merged</td></tr>
<tr>
<td><a target="_blank" href="https://github.com/chapel-lang/chapel/pull/18019">Qthread Select</a></td><td>Approved</td><td>Merged</td></tr>
<tr>
<td><a target="_blank" href="https://github.com/chapel-lang/chapel/pull/18072">Update Addrinfo Constructs</a></td><td>Approved</td><td>Merged</td></tr>
<tr>
<td><a target="_blank" href="https://github.com/chapel-lang/chapel/pull/17960">Socket Library</a></td><td>Approved</td><td>Open</td></tr>
</tbody>
</table>
</div><h2 id="heading-work-done">Work Done</h2>
<p><img src="https://media.giphy.com/media/25KEhzwCBBFPb79puo/giphy.gif?cid=ecf05e47ku335ppulnhax2vvpe1f5ezlhi60b40zj1zu8kem&amp;rid=giphy.gif&amp;ct=g" alt="story time" /></p>
<h3 id="heading-design">Design</h3>
<p>Even though my GSoC <a target="_blank" href="https://docs.google.com/document/d/1e95RBpy5eSPHiJUQAJmlPDWjjAaXG0LOm8GnH9J6Lfc/edit?usp=sharing">Proposal</a> talked about how the Socket Module should look like its design was entirely based on Python and C System Calls which aren't the best ones and don't align well with how we wanted it to look for Chapel.</p>
<p>My initial task was to look over how other modern-day programming languages implement their Socket Modules. I was recommended to look over at Julia, Go, Python, D, etc. I made did my analysis and brought together a simple <a target="_blank" href="https://gist.github.com/king-11/dc50ba6e3f97b8949a4ec78bbe5cb098">gist</a> as suggested to me by my mentors.</p>
<p>Finally, after analyzing implementations of other languages and multiple design discussion sessions with Chapel developers, I made a design pull-request describing the API.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/chapel-lang/chapel/pull/17899">https://github.com/chapel-lang/chapel/pull/17899</a></div>
<h3 id="heading-changes-to-runtime">Changes to Runtime</h3>
<p>The module that is storing most of the extern procs, records, and constants is the <a target="_blank" href="https://chapel-lang.org/docs/modules/standard/Sys.html">Sys</a> standard module. There were several changes made to the module which were as follows:</p>
<ul>
<li>Add in new constants to be used as flags in C System Calls e.g. <code>F_GETFL</code>, <code>SOL_SOCKET</code> to be used in <a target="_blank" href="https://linux.die.net/man/2/fcntl">fcntl</a> and <a target="_blank" href="https://www.ibm.com/docs/en/zos/2.3.0?topic=functions-setsockopt-set-options-associated-socket">setsockopt</a> or <a target="_blank" href="https://man7.org/linux/man-pages/man2/getsockopt.2.html">getsockopt</a>.</li>
<li>New opaque types <code>sys_in_addr_t</code> and <code>sys_in6_addr_t</code> which are for standard network addresses like loopback, any, and broadcast.</li>
<li>Standard Sizes for address and service buffer length to be used in <a target="_blank" href="https://man7.org/linux/man-pages/man3/getnameinfo.3.html">getnameinfo</a>.</li>
<li>Add in generic getters and setters for <code>sockaddr_storage</code> record.</li>
</ul>
<p>All this was done as a part of the below PR and soon will be moved to Socket Module when it gets added in.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/chapel-lang/chapel/pull/17932">https://github.com/chapel-lang/chapel/pull/17932</a></div>
<p>To treat socket connections like chapel <code>file</code> we needed access to their file descriptor for all the operations for this a minor addition was made in runtime to fetch the file descriptor. This allowed us to use Chapel I/O in the Socket Module which handles buffered I/O and keeps the I/O methods consistent across chapel modules.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/chapel-lang/chapel/pull/17988">https://github.com/chapel-lang/chapel/pull/17988</a></div>
<p>Finally, to resolve Domain Name Service from user inputs like <em>"https://summerofcode.withgoogle.com/"</em> I made some fixes to <code>getaddrinfo</code> and constructs related to it whose old implementation had a few issues:</p>
<ul>
<li>Some of the function definitions were not correct which were resulting in segmentation fault and memory leak.</li>
<li><code>addrinfo</code> wasn't using the new capabilities of chapel runtime and was not interacting with C code it was defined separately.</li>
<li>As <code>sys_addrinfo_ptr</code> was an opaque type we can't compare it with <code>nil</code> which was necessary for checking the end of the linked list returned by <code>getaddrinfo</code>.</li>
</ul>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/chapel-lang/chapel/pull/18072">https://github.com/chapel-lang/chapel/pull/18072</a></div>
<h3 id="heading-nonblocking-procedures">NonBlocking Procedures</h3>
<p>The architecture for the socket library was decided to be synchronous but nonblocking as that's how most chapel procedures work ( async is a possibility for the future ). If they need to block they will yield the main thread so that other tasks of the process can run without being blocked.</p>
<p>For this, I decided to use I/O multiplexing using <code>select</code> system calls where the procedure waits until it becomes ready which can mean it becomes readable, writable or a timeout occurred.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629635056200/job0Y6Y0A.png" alt="blocking.png" /></p>
<p>The issue was that calling in normal select will cause the <code>pthread</code> on which chapel <code>qthreads</code> are scheduled to block. Hence, to counter this <a target="_blank" href="https://cs.sandia.gov/qthreads/">qthreads library</a> provides its own set of system calls that will block but not on the current <code>pthread</code> instead are transferred to another helper <code>pthread</code> where they do blocking.</p>
<p>The outcome was making use of <code>qt_select</code> inside of our <code>sys_select</code> call.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629635302535/WtDqzyZOn.png" alt="Qt_select.png" /></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/chapel-lang/chapel/pull/18019">https://github.com/chapel-lang/chapel/pull/18019</a></div>
<p>There were certain hurdles and PR remained stale for some time because we faced hurdles due to bugs in error informing inside of <code>qthread's</code> library procedures, which were resolved by collaborating with <code>qthread's</code> core team. The following is the issue that describes the bugs in detail.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/Qthreads/qthreads/issues/88">https://github.com/Qthreads/qthreads/issues/88</a></div>
<h3 id="heading-socket-module">Socket Module</h3>
<p>The socket module was designed as stated in the design PR and had a lot of modifications being made to the exposed API as reviews were coming in.</p>
<blockquote>
<p>The main intent was to hide the complexity associated with the C System Calls under custom procedures and records.</p>
</blockquote>
<p>The major records in Socket Module that do all the heavy lifting include</p>
<ul>
<li>ipAddr</li>
<li>tcpConnection</li>
<li>tcpListener</li>
<li>udpSocket</li>
</ul>
<p>Along the lines of <a target="_blank" href="https://docs.julialang.org/en/v1/stdlib/Sockets/#Sockets.IPAddr">Julia</a> utility procedures were provided in the module to user which included <code>bind</code>, <code>naggle</code>, <code>delayAck</code>, <code>getsockname</code>, <code>getpeername</code>, <code>setSockopt</code> and <code>getSockOpt</code>.</p>
<blockquote>
<p>The PR has been rebased and changes are being made to it since the finalization of the design for the Module. It consists of all the tests, documentation, and the module itself as well.</p>
</blockquote>
<p>Currently, all the tests are passing and PR is under review while performance testing is being done.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/chapel-lang/chapel/pull/17960">https://github.com/chapel-lang/chapel/pull/17960</a></div>
<h3 id="heading-libevent-integration">Libevent Integration</h3>
<p><a target="_blank" href="https://libevent.org/">Libevent</a> exposes APIs that are more performant and handle more open file descriptors or connections than <code>select</code> call ever could. The reason being that libevent uses kernel methods that have a time complexity of <code>O(1)</code> unlike select which is <code>O(N)</code>.</p>
<p>Libevent works using callbacks but we have to ensure to make it work in a non-blocking and synchronous manner. Integrating libevent was something that was never done in the chapel so it was a completely new experience for me.</p>
<p>The architecture can be best explained with diagrams, so here goes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629958604326/FO1iqdfaY.png" alt="connect with event loop.png" /></p>
<p>The events are handled by the event loop which runs a callback whenever an event ( read/ write/ timeout ) occurs on the file. It writes back the event's value to a sync variable (passed as an argument to the callback function) transitioning to full state and the procedure waiting on the sync variable is finally woken up.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1629958778758/UQNWTEC69.png" alt="event loop.png" /></p>
<h2 id="heading-usage-of-socket-module">Usage of Socket Module</h2>
<p>A TCP Client in Chapel is as follows:</p>
<pre><code class="lang-python">use Socket;
use Time;

proc main() {
  config const host:string = <span class="hljs-string">"chapel-lang.org"</span>, port:uint(<span class="hljs-number">16</span>) = <span class="hljs-number">80</span>;  
  const x = connect(host, port);
  const writer = x.writer();
  writer.writeln(<span class="hljs-string">"hello world!"</span>);
  writer.close();
  x.close();
}
</code></pre>
<p>To serve a basic TCP Server using Socket Module will look as follows:</p>
<pre><code class="lang-python">use Socket;

proc main() {
  var address = ipAddr.create(<span class="hljs-string">"127.0.0.1"</span>, <span class="hljs-number">8000</span>, IPFamily.IPv4);
  var server = listen(address, backlog = <span class="hljs-number">6000</span>);
  writeln(<span class="hljs-string">"Listening for connections on "</span>, server.addr.host, <span class="hljs-string">":"</span>, server.addr.port);
  defer server.close();

  <span class="hljs-keyword">while</span> (true) {
    var conn = server.accept();
    const address = getpeername(conn);
    const writer = conn.writer();
    writer.writeln(address, <span class="hljs-string">" connected "</span>);
    writer.close();
    conn.close();
  }
}
`
</code></pre>
<p>We can utilize chapel <code>begin</code> to demonstrate UDP connections in a single program. </p>
<p><code>begin</code> creates a new task or user-level thread which has a separate execution context from the main task/thread providing us capabilities for task parallelization.</p>
<pre><code class="lang-python">use Socket;

proc main() throws {
  var address = ipAddr.ipv4(IPv4Localhost, <span class="hljs-number">8111</span>);
  var receiver = new udpSocket();
  bind(receiver, address);

  var sender = new udpSocket();

  var sent = <span class="hljs-string">b"hello world!"</span>;
  begin {
    var sentBytes = sender.send(sent, address);
  }
  var received:bytes;
  received = receiver.recv(sent.size);
  writeln(received);
}
</code></pre>
<h2 id="heading-weekly-updates">Weekly Updates</h2>
<blockquote>
<p>Updates for all the weekly meetings that took place can be found on this <a target="_blank" href="https://curse-okapi-b2c.notion.site/ef73f6e5c0b840b1a2e0b1ec977e0c24?v=e62ff72d91f84d728d9594714e228efd">notion site</a>.</p>
</blockquote>
<h2 id="heading-future-work">Future Work</h2>
<p><img src="https://media.giphy.com/media/ZZkCo8zKWtt2ZgozfX/giphy.gif?cid=ecf05e47dlzpd6z4xb6eam0prpm729lgz33cxjudxlx2sgkj&amp;rid=giphy.gif&amp;ct=g" alt="future possibilities" /></p>
<ul>
<li>Integrating <code>libevent</code> with the chapel channels through an I/O plugin.</li>
<li>Running performance tests to analyze the network calls and I/O latency.</li>
<li>Supporting opaque types with, the <a target="_blank" href="https://llvm.org/">LLVM</a> backend.</li>
<li>Providing users with libevent as a dependency if they don't have it on their system.</li>
</ul>
<h2 id="heading-learning">Learning</h2>
<p><img src="https://media.giphy.com/media/6NVOQr1I5H1MA/giphy.gif?cid=ecf05e47ejaapa9tkvvis7p2hqauem2mls3ueht6vlehn1ed&amp;rid=giphy.gif&amp;ct=g" alt="learning" /></p>
<ul>
<li>The major learning outcome from this project was good coding practice. I learned how to write DRY, reusable code following SOLID principles. I also learned how to write good tests/specs covering all possible scenarios.</li>
<li>When writing the Design for the project, I had long discussions with my mentors trying to decide on exposed APIs. Coming up with good names for methods, variables, and hiding the complexity from end-users.</li>
<li>Through this journey, I learned a lot about how open source projects work, getting involved with the community, and contributing to the projects.</li>
<li>The major tech takeaway for me was how familiar I got in working with C System Calls, Pointer Exceptions, and Chapel itself.</li>
<li>I am still exploring Asynchronous I/O through <a target="_blank" href="https://libevent.org/doc/event_8h.html">libevent</a> for the project which is something that powers fast servers like NodeJS, Julia, and Go.</li>
</ul>
<h2 id="heading-special-thanks">Special Thanks</h2>
<p><img src="https://media.giphy.com/media/3oz8xIsloV7zOmt81G/giphy.gif?cid=ecf05e47wfztqcfc1kar8rdur4bis3k3okqbyalqd8etblmx&amp;rid=giphy.gif&amp;ct=g" alt="thank you" /></p>
<p>It was wonderful working with the Chapel community throughout the GSoC project. I would like to thank Michael, Krishna, and Ankush for solving my queries, debugging issues with me, giving constructive suggestions and guiding me through the program. Thanks to Brad, Lydia, Engin, Greg, Paul, and the members of the Chapel Community for helping with their suggestions.</p>
<p>I would like to thank <a target="_blank" href="https://github.com/shivanshs9">Shivansh Saini</a>, <a class="user-mention" href="https://hashnode.com/@nishantwrp">Nishant Mittal</a>, and <a class="user-mention" href="https://hashnode.com/@krashish8">Ashish Kumar</a> for motivating and guiding me in applying and getting through the whole program.</p>
<p>Final thanks to Google for organizing this amazing program. I feel GSoC made it easier for me to get started with open source contributions. It was a great lesson on how projects are built and maintained with great quality. I am excited to continue contributing to the open-source community</p>
<p><img src="https://media.giphy.com/media/l4pTjOu0NsrLApt0Q/giphy.gif?cid=ecf05e47pk00jzahpd3ucyy3rjpo49w3kfn4fpg3rhiooqxz&amp;rid=giphy.gif&amp;ct=g" alt="the end" /></p>
<p>Thanks for reading :) and please share your thoughts. I always like to meet more enthusiastic people, so do reach out to me on <a target="_blank" href="https://twitter.com/1108King">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/lakshyasingh11/">Linkedin</a> to share your feedback or for any queries. I'd be more than happy to help and connect.</p>
]]></content:encoded></item><item><title><![CDATA[OnCampus Interviewing Experience: Microsoft SWE]]></title><description><![CDATA[Microsoft is like a dream company for many people me included :P. 
Why won't it be its the company which develops typescript making web app development so much easier, VSCode favourite IDE of all developers 😌, Azure Cloud Services, Windows the first...]]></description><link>https://hashnode.king-11.dev/interviewing-experience-microsoft</link><guid isPermaLink="true">https://hashnode.king-11.dev/interviewing-experience-microsoft</guid><category><![CDATA[Microsoft]]></category><category><![CDATA[interview]]></category><category><![CDATA[internships]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Tue, 10 Aug 2021 08:08:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1628580576027/HFTxAaIwC.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Microsoft is like a dream company for many people me included :P. </p>
<p>Why won't it be its the company which develops typescript making web app development so much easier, VSCode favourite IDE of all developers 😌, Azure Cloud Services, Windows the first Operating System that most people use.</p>
<p><img src="https://media.giphy.com/media/thA1QtTj8ZYHK/giphy.gif" alt="Microsoft Windows" /></p>
<p>The Process Included two parts the Coding Round and then Interviews, based on which students were selected. While Coding Round was eliminating Interviews were not, so everyone was able to give 2+ interviews.</p>
<h2 id="heading-coding-round">Coding Round</h2>
<p>Microsoft provided us with two questions on Codility. The first one was an easy greedy + sorting question where you have to check by using available cranes can an object be moved from <code>B</code> to <code>E</code>. Sort the <code>(crane position - length , crane position + length)</code> then keep on moving B till it reaches a crane that has B and E in the same range. Made sure to swap B if it's greater than E. That was that. </p>
<p><img src="https://media.giphy.com/media/26tn33aiTi1jkl6H6/giphy.gif" alt="coding round" /></p>
<p>Another one was also an easy greedy problem. We were given that a player made <code>T</code> dice moves off which he only remembers <code>N</code> moves exactly and mean of all the dice moves. So we just have to find the remaining possible value of move which can be done very easily by dividing the remaining sum ( found using mean*T - the sum of N) among all values equally and if some still remain divide it one to each.</p>
<blockquote>
<p>The thing about Codility is they won't run any test cases in front of you they are all hidden which I only realized after submitting 1st question.</p>
</blockquote>
<h2 id="heading-interviews">Interviews</h2>
<p>2 Rounds were conducted for me there was no clear separation as to whether they were HR or Technical. I was asked HR-related and technical questions in both rounds.</p>
<h3 id="heading-round-1">Round 1</h3>
<h4 id="heading-introduction">Introduction</h4>
<p>The interviewer asked me about myself. I had been finding the right answer for this for quite some time now. I started with personal info, then what I do? which is <a target="_blank" href="https://github.com/king-11">open source</a> contributions, <a target="_blank" href="http://blog.manlakshya.tech/">technical blogging</a> and attending conferences. He seemed impressed as he told me that wasn't the usual answer he gets.</p>
<p>I also told him about how I started my technical journey as a child curious to get acquainted with Windows XP and MS Office. Also, my current stack is Visual Studio Code and Typescript, both developed by MS again 😄.</p>
<p><img src="https://media.giphy.com/media/4mXjpVNJAFlvi/giphy.gif" alt="windows XP" /></p>
<h4 id="heading-knight-and-destination">Knight and Destination</h4>
<p>The was that question given a <code>n*m</code> chessboard, and you have a Knight piece that needs to go from <code>S</code> to <code>D</code>, find the minimum number of moves required to reach destination <code>D</code>. I started with a crude simple BFS solution, and before coding, I explained my approach to him. After a go-ahead, I coded the initial solution, which was un-optimized. He asked me to do a quick dry run to show that it works.</p>
<p><img src="https://media.giphy.com/media/32dfpYx8kBX1bXSEu8/giphy.gif" alt="chessboard knight moves" /></p>
<p>Next, he asked me how would I do memoization so that the complexity is not exponential. So I implemented memorization using a <code>n*m</code> array which stores the minimum move from that location <code>(x,y)</code>. Next, he asked me how can I do pruning for the solution so that we don't go to longer paths if we already have a minimum implemented that was just an if-else check on the current minimum to stop when needed.</p>
<p>Finally, he asked me, since it was uninformed BFS, what better could be done. I told him that Dijkstra's Algorithm would do the job nicely, but since it's a matrix, we can use <a target="_blank" href="https://www.redblobgames.com/pathfinding/a-star/introduction.html">A* Heuristic Search Algorithm</a> to do even better. I showed him why this would happen by defining the heuristic function as manhattan distance. I wasn't asked to code them, just what and how better?</p>
<h4 id="heading-why-microsoft">Why Microsoft?</h4>
<p>Finally, he seemed satisfied and asked me why Microsoft I also had it covered. My answer was that I wanted to empower new developers to build even better software using services like Azure, Typescript and VSCode which will give me a sense of pride that the software I built is being used by developers to create even better services for users.</p>
<h4 id="heading-anything-else">Anything Else?</h4>
<p>He then asked me if I wanted to ask anything. I asked him what he does, and day to day workings of his at Microsoft. He gladly told me about the project he was working on which included created higher-level APIs for Database manipulation in Azure.</p>
<p><img src="https://media.giphy.com/media/kPrlykW2TpVU4HWx2O/giphy.gif" alt="Database" /></p>
<h3 id="heading-round-2">Round 2</h3>
<h4 id="heading-level-order-traversal-binary-tree">Level Order Traversal Binary Tree</h4>
<p>This started without my introduction. This time he gave me a problem after introducing himself. The problem was printing level order traversal of a binary time. This time I was asked to code first then explain, so I quickly went ahead and gave a solution using queue and yeah, it seemed good to him.</p>
<p>Although he stopped me midway when I used <code>auto</code> in C++ because that surely makes it difficult for humans at the end, humans should understand code, not just machines. Finally, I did a Dry Run of the implementation and was done with the question.</p>
<h4 id="heading-explain-any-project">Explain Any Project</h4>
<p>Next, he asked me what was the most difficult part of any project I had mentioned in my resume. I asked him do open-source contributions count? and he was impressed and went on to tell me that at Microsoft, they value Open Source so yes they count. So I told him, in brief, all the issues I had when I started with <a target="_blank" href="https://github.com/DXHeroes/dx-scanner/pulls?q=is%3Apr+author%3A%40me+">DXHeroes</a> and <a target="_blank" href="https://github.com/pgRouting/pgrouting">PGRouting</a> also talked a bit about my <a target="_blank" href="https://summerofcode.withgoogle.com/projects/#5343790958641152">GSOC project</a>, which I didn't particularly tell as GSOC project but just any open source contribution.</p>
<p><img src="https://media.giphy.com/media/xTiTnoUnHxVaaVNWhO/giphy.gif" alt="google summer of code project" /></p>
<h4 id="heading-talk-about-gsoc-project-and-async-io">Talk about GSOC Project and Async I/O</h4>
<p>As open source is huge, he wanted to know just something specific he asked me about my GSOC Project at Chapel, which I cited as a productive parallel programming language. I told him that this was my first time working with C System Call, joked about getting my hands dirty with pointers, allocation, etc. ( he laughed too xD ).</p>
<p>I finally told him about issues with I/O multiplexing, which I was resolving using Asynchronous I/O. Async IO hit him as something that college don't have experience with, and he himself worked on it, so he told me, like, yeah, that is a totally different game.</p>
<h4 id="heading-anything-else-1">Anything else?</h4>
<p>Finally, my chance to ask, I asked him what interns do whether their code makes into actual user apps or not.</p>
<h2 id="heading-end">End</h2>
<p>Some people had round 3 as HR, or Technical mine wasn't, so after the interview, I was sad, but Training Placement Cell Representative told me that it wasn't the case that I was eliminated, so was happy again.</p>
<p><img src="https://media.giphy.com/media/kg129XRsLTbezr509v/giphy.gif" alt="work for me" /></p>
<p>And Yeah <a target="_blank" href="https://www.linkedin.com/feed/update/urn:li:activity:6830505027312918529/">Selected</a> 😊</p>
<p>Thanks for reading :) and please share your thoughts. I always like to meet more enthusiastic people, so do reach out to me on <a target="_blank" href="https://twitter.com/1108King">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/lakshyasingh11/">Linkedin</a> to share your feedback or for any queries. I'd be more than happy to help and connect.</p>
]]></content:encoded></item><item><title><![CDATA[My Journey: Getting Selected in Google Summer of Code]]></title><description><![CDATA[What is GSoC?

Google Summer of Code is a global program focused on bringing more student developers into open source software development. Students work with an open-source organization on a 10-week programming project during their break from school...]]></description><link>https://hashnode.king-11.dev/guide-google-summer-of-code</link><guid isPermaLink="true">https://hashnode.king-11.dev/guide-google-summer-of-code</guid><category><![CDATA[gsoc]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[C++]]></category><category><![CDATA[algorithms]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Mon, 05 Jul 2021 02:46:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1625127392378/7hAddDbRV.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-gsoc">What is GSoC?</h1>
<blockquote>
<p>Google Summer of Code is a global program focused on bringing more student developers into open source software development. Students work with an open-source organization on a 10-week programming project during their break from school. </p>
</blockquote>
<p>This post highlights <strong>my journey</strong> of getting selected into the program from the very beginning. I believe that there is no defined path for getting selected in such open-source fellowships. Everyone has a unique journey, and you can take a few things from other journeys to write yours :) because the essence of each one is similar.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1625409867224/y_wlVPKZ2.gif" alt="Let's get started" /></p>
<p>Now that I have your attention, let's get started. I will talk about my journey in two parts: </p>
<ul>
<li>the initial <strong>Pre-GSoC</strong> part will cover how I came about making my first contribution in Open Source and developed my skills</li>
<li>the later part <strong>GSoC InFocus</strong> focuses on GSoC specific things like selecting an organization, contributing, writing a proposal, etc.</li>
</ul>
<h1 id="heading-pre-gsoc">Pre-GSoC</h1>
<p>This was a phase where I wasn't much worried about GSoC and focused on developing my skills, adding new tech stacks into my belt, developing more projects, and contributing to open source.</p>
<blockquote>
<p>This phase is crucial because your zeal and fire to contribute and make a mark in the open-source community starts to rage, and doing some fuels that fire further.</p>
</blockquote>
<h2 id="heading-how-i-came-to-know-about-gsoc">How I came to know about GSoC?</h2>
<p>The first time I heard about GSoC was in an event conducted by <a target="_blank" href="http://copsiitbhu.co.in/">Club of Programmers IITBHU</a> where I was introduced to open-source programs like GSoC, Outreachy, etc. and people who were previously selected shared their experience with us. </p>
<p><img src="https://media.giphy.com/media/JUXtbHuixcZKeGJEro/giphy.gif" alt="conference" /></p>
<p>I wasn't sure whether I would someday dwell into the realm of Open Source as, at that time, I was more focused on Competitive Programming like most of my peers. But things changed after the programming Camp in the Winter of 2019, where I started with Web Dev, and now I was sure I want to be amongst the group of people who clear GSoC.</p>
<p>Then came the GSoC'20. Many of my seniors who applied got selected, and I thought that a first-year student could never clear GSoC ( that perception changed this year :) ), so I focused on improving my skills in Web Development and didn't bother applying in 2020.</p>
<h2 id="heading-learning-phase">Learning Phase</h2>
<p>I was <em>burning the midnight oil</em> to make web development my forte be it backend or frontend, vue or react, Django or NodeJS... I wanted to know it all as there existed so many fascinating things for me to learn.</p>
<p><img src="https://media.giphy.com/media/3ohuAxV0DfcLTxVh6w/giphy.gif" alt="learning new things" /></p>
<p>So here are some of the things I did to strengthen my skills in web development :</p>
<ul>
<li>I utilized <a target="_blank" href="http://frontendmasters.com/">Frontend Masters</a> to cover most front-end things like frameworks and Design. Also took a git course by <a target="_blank" href="https://twitter.com/nnja">@nnja</a></li>
<li>For Django, I started dwelling into the docs of <a target="_blank" href="https://docs.djangoproject.com/en/3.2/">Django</a> and <a target="_blank" href="https://www.django-rest-framework.org/">DRF</a> to learn more advanced features after completing basic stuff from <a target="_blank" href="https://djangogirls.org/">DjangoGirls</a></li>
<li>Then, I did some projects using what I have learned to combine both backend and frontend. I did invest quite some time in them, and it was fun.</li>
<li>Later on, when I came to know about things like NodeJS being faster and a more scalable DB such as MongoDB, I did a project using them in a <a target="_blank" href="https://devfolio.co/submissions/peer-io-7356">Hackathon</a> with my friends <a target="_blank" href="https://github.com/m-e-l-u-h-a-n">@Purushottam</a> and <a target="_blank" href="https://github.com/dasari810">@Madhava</a>, which we won too 🥳</li>
</ul>
<blockquote>
<p>Apart from my own projects, I participated in projects of our Programming Club and also did an intern in a freelance project. These things prepared me to swiftly walk through a large codebase, collaborate on Github, use version control, apply my knowledge, etc.</p>
</blockquote>
<h2 id="heading-open-source-hacktoberfest">Open Source Hacktoberfest</h2>
<blockquote>
<p>There couldn't be a better start for your open-source journey than <a target="_blank" href="https://hacktoberfest.digitalocean.com/">HacktoberFest</a>. It's an annual open-source event where project maintainers await your contributions, and they prepare their projects to accept new contributors.</p>
</blockquote>
<p>Apart from contributing, you also get rewarded swags, tees, etc., by DigitalOcean and some of the projects. You can check out <a target="_blank" href="https://hacktoberfestswaglist.com/">hacktoberfestswaglist</a> during hacktoberfest to know about projects offering additional swags.</p>
<p>I outlined my hacktoberfest with my friend <a target="_blank" href="https://github.com/K-Kumar-01">Kushal</a> ahead of October. We decided to go good-first hunting, work on several issues and earn some swags. Who doesn't like swags, right? So I intended on completing the tasks to get those swags.</p>
<p>All of the projects were very welcoming. Even though I had <strong>no idea</strong> about the tech stack they were using, I contributed to them, but I focused on solving issues and asked many questions. </p>
<p><img src="https://media.giphy.com/media/5wFjITVDtKD0wwJe7V/giphy.gif" alt="helping out" /></p>
<p>Some of my contributions which you can check out :</p>
<ul>
<li><a target="_blank" href="https://github.com/DXHeroes/dx-scanner/issues?q=is%3Aclosed+author%3Aking-11">DX Heroes</a></li>
<li><a target="_blank" href="https://github.com/OperationCode/resources_api/pulls?q=is%3Apr+author%3Aking-11+is%3Aclosed">Operation Code</a></li>
<li><a target="_blank" href="https://github.com/datenanfragen/website/issues?q=author%3Aking-11+is%3Aclosed">Datenanfragen</a></li>
<li><a target="_blank" href="https://github.com/jayehernandez/letra-extension/issues?q=author%3Aking-11+is%3Aclosed">Letra</a></li>
</ul>
<blockquote>
<p>By the end of October, I was familiar with contributing to open source projects, interacting with communities, finding issues, making PRs, and working my way around good first issues.</p>
</blockquote>
<h1 id="heading-gsoc-infocus">GSoC InFocus</h1>
<p>For most people, this phase is after and around December and January, where you start looking at organizations finding relevant and interesting projects to contribute to.</p>
<h2 id="heading-selecting-organizations">Selecting Organizations</h2>
<p>I started looking at GSoC archives in January and probably would have gone through the whole A-Z list about 10-20 times. Earlier, they didn't have filters for the tech stack, but they have it now, and it really helps to select the organization.</p>
<p>First, I jotted down the list of organizations I want to contribute to based primarily on my interest in their past and current projects and those that didn't require me to learn something completely new ( biggest mistake '-' ).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1625384922319/dGkrSGMjD.jpeg" alt="filtered org list.jpg" /></p>
<p>One of the most useful tools I found when selecting my GSoC organization was developed by one of my seniors <a class="user-mention" href="https://hashnode.com/@nishantwrp">Nishant Mittal</a>. With all the statistics at hand, I can filter out organizations.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.gsocorganizations.dev/">https://www.gsocorganizations.dev/</a></div>
<p>The list, as you can see, consisted of around 30-40 organizations. So I started filtering them out based on:</p>
<ul>
<li>Number of times org was selected for GSoC in past</li>
<li>The tech stack they were working on should align with what I know, things like Javascript, Python, NodeJS, Rest APIs, etc.</li>
<li>Number of students they select, which I filtered to be at least greater than or equal to 4.</li>
<li>Amount of people already contributing to them because eventually only a few students will be selected for summer.</li>
<li>Organizations using IRC as a means of communication were a <em>big NO!</em> for me.</li>
</ul>
<p>In the end, I decided to go with <a target="_blank" href="https://github.com/HTTP-APIs">HTTP-APIs</a>. I started checking out their Contributing Guidelines, Resources to get started, and their repositories. I selected HTTP-APIs because REST APIs are my forte, and they were doing something pretty interesting.</p>
<p>I made a few contributions to their repos, upgraded their dependencies to support python v3.8 and updated Dockerfile. </p>
<p>Still, a few things that took me away from them were that the mentors weren't that responsive, and even though I went through all of their resources, I couldn't find something significant to contribute.</p>
<p>So I drifted away from HTTP-APIs, but at the back of my mind, it was still that I have to make it work there somehow.</p>
<h2 id="heading-change-of-plans">Change of Plans</h2>
<p>If you know me prior, you already know that I never went through with HTTP-APIs instead, it was <a target="_blank" href="https://chapel-lang.org/">Chapel</a>. Chapel is a programming language designed for productive parallel computing at scale.</p>
<p>The story behind the finding of Chapel is something that you don't hear often. I was in a meeting with my peers, and we started talking about things we are doing, and GSoC became a part of the discussion. </p>
<p>My friend <a target="_blank" href="https://codeforces.com/profile/rivalq">@Jatin</a> stated to me that, and I quote, "there is this language where you can run statements simultaneously using a <code>forall</code> loop". He seemed pretty interested, and so sparked the idea of taking a look at Chapel.</p>
<p>It was also at the same time, i.e. February, I was talking with one of my seniors <a target="_blank" href="https://www.linkedin.com/in/ashishkr23438/">@Ashish</a>, who previously got selected in GSoC under <a target="_blank" href="https://github.com/pgRouting">OSGeo</a>. My primary concern was that HTTP-APIs didn't work, and if I go in places related to Web Development there, the amount of already active students is way more than I wish to compete with.</p>
<p><img src="https://media.giphy.com/media/9Dtye59YLYQpIwQWpv/giphy.gif" alt="change of plans" /></p>
<p>So the plan I made after discussing with Ashish was to contribute to something, not JS, not Python, but things constituting C++, C, or some new language. And since Chapel caught my interest, I started there.</p>
<p>It is hard to find a project where you have experience with all the technical tools, so in hindsight, it’s okay for you to select an organization where you have only 40% of the tech stack down. You might even end up working with the part of the software that uses a language you have zero familiarity with, like me.</p>
<h2 id="heading-contributing-to-the-project">Contributing to the project</h2>
<p>The thing with all GSoC organizations is that they have excellent resources for you to get started with. This includes documentation, contributing guidelines, getting started with contributions, etc.</p>
<p>Just as HTTP-APIs, Chapel also had excellent resources for me to learn it, and I went straight for them started writing small scripts, learning the syntax incrementally.</p>
<p>The question you might have for me is why I decided to stick around with Chapel? The difference was chapel has so many issues <em>( over 2k )</em>, and these are the ones made by the core team itself. That made it pretty clear that I can contribute a lot and the team is highly active in developing the project.</p>
<p>I was observant even when reading the documentation and talked in the <a target="_blank" href="https://gitter.im/chapel-lang/chapel">gitter</a> channel about how the documentation can be improved. I was also helping out by answering some of the questions in the channel.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1625410769039/Am_Fu6jT4.gif" alt="coding is fun" /></p>
<p>Something that usually people forget about is interacting and being a part of the community. It's not just about coding your way around, and I made sure that I opened gitter every day to take a look at the ongoing discussion here as well as on Github Issues.</p>
<p>As chapel is a comparatively new language, I knew there could be scope for improvement on the implementation done in Modules. Also, at the time when I started contributing, I was pursuing courses on Algorithms and Operating System as part of my college curriculum.</p>
<p>So I went on to find the implementation of Quick Sort and Heap in the codebase, discussed few updates on them, and made a Pull Request.</p>
<p>After that, I started looking at existing issues, discussing how I should work them out, the idea of the core team about the issue, and eventually made the Pull Request for it to be reviewed.</p>
<p>The thing that kept me engaged in chapel was the quick response from mentors within a day or two. That made me feel that my contributions are very much appreciated.</p>
<h2 id="heading-writing-proposal">Writing Proposal</h2>
<p>It is expected for a proposal to contain a detailed explanation of your implementation and timeline. What gives you an edge is your contributions to the project until then. This helps solidify the trust in your abilities to finish the project.</p>
<p>Even though I had drifted away from Web Dev, it all came back when projects that were announced by Chapel had a project on <strong>Socket Library</strong>. This was something that I was targeting since it was announced even before organizations were announced.</p>
<blockquote>
<p>Even though Chapel gave me a place to contribute to it was the project that kept me going because it's my niche and was something where I can apply all the knowledge I gathered over time.</p>
</blockquote>
<p>I started working on my proposal after getting clarity on few things from my mentor on what were they expecting from the project. I also used to look out for questions that other people were asking related to my project.</p>
<p><img src="https://media.giphy.com/media/XIqCQx02E1U9W/giphy.gif" alt="writing" /></p>
<p>I got up to speed on working with sockets in <code>C</code>, went through the design of the socket library in <code>Python</code>, gathered more information about non-blocking sockets, and finally designed my proposal.</p>
<p>I made sure to add in code snippets and mock implementation of how the code will be implemented in <code>C</code> and <code>Chapel</code>. It is also a good idea to add in diagrams which I did, because images speak more than text.</p>
<p>My organization mentors seemed happy with the design because they didn't seem to have much issue with what I had shown them in the draft. </p>
<p>But <a target="_blank" href="https://shivanshs9.me/">@Shivansh</a>, one of my seniors I requested to review my proposal, told me that it was less technical and needed more of it. This pushed me to improve my proposal further, add more details about the implementation, add in diagrams and code snippets.</p>
<p>You can find mine and several other accepted proposals in this repository. Courtesy of <a target="_blank" href="http://copsiitbhu.co.in/">Club of Programmers IIT BHU</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/COPS-IITBHU/GSoC-Accepted-Proposals">https://github.com/COPS-IITBHU/GSoC-Accepted-Proposals</a></div>
<h2 id="heading-post-proposal-submission">Post Proposal Submission</h2>
<p>Going inactive after proposal submission shows that you aren't interested in the community, and you were doing it just for namesake.</p>
<p>I ensured that after proposal submission, I kept contributing and was active not that much but still had my presence in the channel. I wrote in my proposal that I would get all my pending PRs merged, and that's what I did.</p>
<p>Fast forward to 17th May, I was in a voice call when the result came out, and I literally shouted woohoo!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1625417870501/Q4LP1LZBa.png" alt="gsoc result mail" /></p>
<h1 id="heading-final-thoughts">Final thoughts</h1>
<p>GSoC is a non-competitive (after getting selected, of course 😏) program so try to cherish the community alongside it. Find your motivation; why do you even want to do it first, and the rest will follow.</p>
<p>GSoC is not an internship and should not be looked at as a way to earn money. It is definitely not something you should pursue half-heartedly or just for the sake of it, neither it would help you nor the community, and there can be better ways for you than open-source.</p>
<p>I am learning a lot from my mentors and fellow GSoC mentees. The community is something I will definitely enjoy and use my summer to learn from them and, as I say, make <strong>Chapel go to Web</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1625418481704/4n4ZdmURx.gif" alt="that's all folks" /></p>
<p>Thanks for reading :) and please share your thoughts. I always like to meet more enthusiastic people, so do reach out to me on <a target="_blank" href="https://twitter.com/1108King">Twitter</a> or <a target="_blank" href="https://www.linkedin.com/in/lakshyasingh11/">Linkedin</a> to share your feedback or for any queries. I'd be more than happy to help and connect.</p>
]]></content:encoded></item><item><title><![CDATA[Dynamic Classes and Styles]]></title><description><![CDATA[In this article, I aim to provide a not so new but also not so known way of adding dynamic features into your application, ensuring that you can achieve what you wish to simply without writing boilerplate code and meddling with string concatenation.
...]]></description><link>https://hashnode.king-11.dev/dynamic-classes-and-styles</link><guid isPermaLink="true">https://hashnode.king-11.dev/dynamic-classes-and-styles</guid><category><![CDATA[Vue.js]]></category><category><![CDATA[CSS]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Design]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Wed, 23 Jun 2021 07:05:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1624382602738/Ar0FuDoiN.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, I aim to provide a not so new but also not so known way of adding <strong>dynamic features</strong> into your application, ensuring that you can achieve what you wish to simply <strong>without</strong> writing <em>boilerplate code</em> and meddling with <em>string concatenation</em>.</p>
<p>When writing Dynamic UI Components that respond to user actions and events, we require methods to respond to these events by translating them into our DOM. Change in DOM is usually achieved by changing <em>styles</em> and <em>classes</em> based on certain <strong>reactive data</strong> that we have in our javascript. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624430311612/E4UZ-uktt.png" alt="old methods work but we can do better" /></p>
<blockquote>
<p>While we can certainly do string concatenation, calculate a string and then bind a string to class or style... this method is error-prone and cumbersome at times to deal with. That's where Vue.js's clean suite of enhancements come into vue <em>( french for 'view' )</em></p>
</blockquote>
<h2 id="heading-quick-recap-data-binding">Quick Recap Data Binding</h2>
<p>If you aren't familiar with what data binding is....it's essentially binding any attribute of an element in your <code>template</code> to the data available in your <code>script</code> tag, which can be props,  data or computed properties.</p>
<p>Data binding is one of the most elegant features of Vue.js because it provides reactive data binding with a straightforward syntax using <code>v-bind</code>.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> 
  <span class="hljs-attr">v-bind:class</span>=<span class="hljs-string">"dynamicClass"</span>
&gt;</span>Hello World!
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>A shorthand for data binding is but just using <code>:</code> and then the attribute name, which I guess anyone would prefer using more.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> 
  <span class="hljs-attr">:class</span>=<span class="hljs-string">"dynamicClass"</span>
&gt;</span>Hello World!
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Let's suppose that the above class is not <em>a once initialized and stays the same</em> kind of class it changes based on user input, so we have to use a <code>computed</code> property or <code>watch</code> to make changes to our <code>dynamicClass</code> variable. So things will start to look like this.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  data( ) {
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">changingBoolean</span>: <span class="hljs-literal">false</span>
    }
  },
  <span class="hljs-attr">computed</span>: {
    <span class="hljs-attr">dynamicClass</span>: <span class="hljs-function">( ) =&gt;</span> changingBoolean : <span class="hljs-string">'text-center text-lg'</span> ? <span class="hljs-string">'text-justify text-xl'</span>
  }
}
</code></pre>
<blockquote>
<p>Looking at the code above we can see that for a simple switch in classes based on a variable we had to write so much code. So simply creating a dynamic class won't work.</p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624385259678/5by80HsTa.gif" alt="we don't do simple data binding" /></p>
<h2 id="heading-array-syntax-for-classes">Array Syntax for Classes</h2>
<p>Enter array syntax which makes the previous task less cumbersome and also keeps it DRY at times when needed.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span> 
  <span class="hljs-attr">:class</span>=<span class="hljs-string">"[changingBoolean : ? 'text-center' : 'text-justify']"</span>
&gt;</span>
    Hello World!
<span class="hljs-tag">&lt;/<span class="hljs-name">aside</span>&gt;</span>
</code></pre>
<p>This looks so much cleaner than the previous method right ≧◠‿◠≦✌. But it's an array so we can add multiple values into it too :). Now we can toggle the text alignment class while flex and width will always be present.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span> 
  <span class="hljs-attr">:class</span>=<span class="hljs-string">"[changingBoolean : ? 'text-center' : 'text-justify', 'flex w-2']"</span>
&gt;</span>
    Hello World!
<span class="hljs-tag">&lt;/<span class="hljs-name">aside</span>&gt;</span>
</code></pre>
<h2 id="heading-object-syntax-for-classes">Object Syntax for Classes</h2>
<p>Sometimes we just want to add toggle a single class on/off when a boolean is <code>true</code> and nothing when it's <code>false</code>. Using ternary operator it will look as below</p>
<pre><code class="lang-js">:<span class="hljs-class"><span class="hljs-keyword">class</span> </span>= [changingBoolean : ? <span class="hljs-string">'text-center'</span> : <span class="hljs-string">' '</span>, <span class="hljs-string">'flex w-2'</span>]
</code></pre>
<p>We can do better, enter <strong>object syntax</strong> because eventually, everything is an object in javascript so why not.</p>
<p><img src="https://media.giphy.com/media/gkEwPJyg6CxtVQ5rzK/giphy-downsized.gif" alt="I object as in javascript everything is an object" /></p>
<pre><code class="lang-js">:<span class="hljs-class"><span class="hljs-keyword">class</span> </span>= [ { <span class="hljs-string">'text-center'</span> : changingBoolean }, <span class="hljs-string">'flex w-2'</span>]
</code></pre>
<p>You can also bind an object directly to <em>class</em> instead of keeping it inside an array and it also supports multiple togglable classes just like an array.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>
  <span class="hljs-attr">class</span>=<span class="hljs-string">"absolute"</span>
  <span class="hljs-attr">:class</span>=<span class="hljs-string">"{ active: isActive, 'text-xl': largeText }"</span>
&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
</code></pre>
<blockquote>
<p><code>active</code> is a simple string variable for class whereas <code>isActive</code> and <code>largeText</code> are boolean variables. Also if you noticed <em>class</em> and <em><code>:class</code></em> can simultaneously exist on a single element ツ</p>
</blockquote>
<h3 id="heading-passing-in-objects">Passing in Objects</h3>
<p>We can also pass in reactive <code>array/object</code> stored in our <code>data</code> or <code>computed</code> to classes. This can be a more powerful pattern at times when you have to do multiple checks and toggling which when accommodated into HTML won't look good and readable.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span> <span class="hljs-attr">:class</span>=<span class="hljs-string">"classObject"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
</code></pre>
<h2 id="heading-modifying-child-classes">Modifying Child Classes</h2>
<p>Suppose we have a nice and shiny icon element we have specified several classes to it which works for most cases so we didn't bother making it a prop. But a time came when we had to change its colour in that case we want to pass down a new class to our child.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">my-icon</span>
  <span class="hljs-attr">:class</span>=<span class="hljs-string">"text-blue-600"</span>
/&gt;</span>
</code></pre>
<p>Now the <code>:class</code> will be appended at the end of the class inside of our component's parent. We can obviously also send in a simple <code>_class_</code> too.</p>
<h2 id="heading-array-and-object-syntax-for-styles">Array and Object Syntax for Styles</h2>
<p>The array and object syntax for classes and style looks exactly identical except for a very minor change. It's not about the truthiness of variables anymore it's about assigning them to the right CSS property.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span> 
<span class="hljs-attr">:style</span>=<span class="hljs-string">"{ marginTop: marginTop + 'px', backgroundColor: infoColor }"</span>
&gt;</span>Doge Coin
<span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
</code></pre>
<p>In the above example, we are assigning the <code>color</code> property a dynamic value and a similar operation for <code>fontSize</code>.</p>
<ul>
<li>We can write properties as kebab case too just ensure to wrap them in quotes</li>
<li>It can be more powerful to directly pass in an object to <code>style</code> which is a more readable and cleaner method.</li>
</ul>
<p>The purpose for array syntax in style reduces to allowing us to pass in multiple objects <em>( Duhhh that's what arrays do right :P )</em> for style as passing a string to style works won't make much sense in the special syntax.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span> 
<span class="hljs-attr">:style</span>=<span class="hljs-string">"[marginObject, backgroundObject]"</span>
&gt;</span>Doge Coin
<span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
</code></pre>
<h2 id="heading-bonus-treats">Bonus Treats</h2>
<p><img src="https://media.giphy.com/media/ZAXpoT2WEYO3u/giphy.gif" alt="Bonus treats extra vue knowledge" /></p>
<p>Some CSS properties require us to use vendor prefixes. Vue will apply them for us implicitly but if you want to be explicit you can pass in multiple values for a single property through object syntax and providing an array of values. Vue will only render the last value in the array which the browser supports.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">:style</span>=<span class="hljs-string">"{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
<p>Thanks for reading! :). Please share your thoughts about the array and object syntax would you prefer them over strings?</p>
<p>Reach out to me on <a target="_blank" href="https://twitter.com/1108King">Twitter</a> to share your feedback or for any queries. I'd be more than happy to help!</p>
]]></content:encoded></item><item><title><![CDATA[Comprehensive Guide for not so Regular Expressions]]></title><description><![CDATA[What is Regex?
Regular expressions ( or regexes, or regex patterns) are essentially a kind of formal grammar/syntax used to find the set of possible strings that you want to match.
At first, REs can look pretty scary and daunting, but we can write hi...]]></description><link>https://hashnode.king-11.dev/understanding-not-so-regular-expressions</link><guid isPermaLink="true">https://hashnode.king-11.dev/understanding-not-so-regular-expressions</guid><category><![CDATA[Regex]]></category><category><![CDATA[string]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Visual Studio Code]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Sun, 16 May 2021 14:33:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621173739440/tqR6ykb0V.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-what-is-regex">What is Regex?</h2>
<p>Regular expressions ( or regexes, or regex patterns) are essentially a kind of formal grammar/syntax used to find the set of possible strings that you want to match.</p>
<p>At first, REs can look pretty scary and daunting, but we can write highly efficient matching patterns in terms of length and speed after understanding even a few special characters.</p>
<p>We can use REs to save the day in a variety of use cases :</p>
<ul>
<li>Checking a pattern in string</li>
<li>Splitting into strings</li>
<li>Replacing part of strings</li>
<li>Matching a complete string</li>
<li>Cleaning raw data in Natural Language Processing</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621171450122/Kr_hwYfrz.png" alt="Hardcoding string expressions not the right way" /></p>
<p>All major programming languages and even IDEs have their own standard module for regex where the syntax might change, but the underlying concept remains the same.</p>
<pre><code class="lang-python"><span class="hljs-comment"># python3</span>
<span class="hljs-keyword">import</span> re

pattern = re.compile(<span class="hljs-string">"doge\\shen+lo+"</span>,re.I)
<span class="hljs-keyword">if</span> pattern.match(<span class="hljs-string">"Doge hennnloo"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
  print(<span class="hljs-string">"Henlo Doge"</span>)
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// javascript</span>
<span class="hljs-keyword">const</span> pattern = <span class="hljs-regexp">/doge\shen+lo+/i</span>
<span class="hljs-keyword">if</span> (pattern.test(<span class="hljs-string">"Doge hennnloo"</span>)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Henlo Doge"</span>)
}
</code></pre>
<h2 id="heading-lets-get-started">Let's get started 🚀</h2>
<h3 id="heading-normal-characters">Normal Characters 🇦</h3>
<p>You can use regex as you use normal strings/characters for matching too :</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.debug(<span class="hljs-regexp">/king-11/</span>.test(<span class="hljs-string">'king-11'</span>)) <span class="hljs-comment">// returns true</span>
</code></pre>
<p>But certain special characters have to be escaped because they carry special meaning in regex.</p>
<p><code>\ / [ ] { } . ? + * ^ $ | ( )</code></p>
<pre><code class="lang-js"><span class="hljs-comment">// we have to escape back slash in string to be tested as well</span>
<span class="hljs-built_in">console</span>.debug(<span class="hljs-regexp">/\\\/\[\]\{\}\.\?\+\*\^\$\|\(\)/</span>.test(<span class="hljs-string">'\\/[]{}.?+*^$|()'</span>))
<span class="hljs-comment">// returns true</span>
</code></pre>
<h3 id="heading-character-class-and-regex-characters">Character Class and Regex Characters 🧑🏼‍🤝‍🧑🏼</h3>
<p>A character class allows you to define a set of characters from which a match is considered if any of the characters match.</p>
<pre><code class="lang-js">/[aeiou]/.test(<span class="hljs-string">'e'</span>) <span class="hljs-comment">// returns true</span>
/[aeiou]/.test(<span class="hljs-string">'c'</span>) <span class="hljs-comment">// returns false</span>
</code></pre>
<p>You can also provide range values to regex for defining character classes using <code>-</code>.</p>
<pre><code class="lang-js">/[a-z]/.test(<span class="hljs-string">'l'</span>) <span class="hljs-comment">// returns true matches all lowercase alphabets</span>
/[A-Z]/.test(<span class="hljs-string">'L'</span>) <span class="hljs-comment">// returns true matches all uppercase alphabets</span>
/[<span class="hljs-number">0</span><span class="hljs-number">-9</span>]/.test(<span class="hljs-string">'8'</span>) <span class="hljs-comment">// returns true matches all digits from 0 to 9</span>
/[<span class="hljs-number">0</span><span class="hljs-number">-5</span>]/.test(<span class="hljs-string">'8'</span>) <span class="hljs-comment">// returns false matches all digits from 0 to 5</span>
</code></pre>
<p>But if you want to match <code>-</code>, you have to escape it or keep it at the start or end of character class, i.e. <code>[]</code>.</p>
<pre><code class="lang-js">/[<span class="hljs-number">0</span>\<span class="hljs-number">-5</span>]/.test(<span class="hljs-string">'-'</span>) 
<span class="hljs-comment">// returns true matches 0, 5, -</span>
/[<span class="hljs-number">-0</span><span class="hljs-number">-5</span>]/.test(<span class="hljs-string">'-'</span>) 
<span class="hljs-comment">// returns true matches digits from 0 to 5 and -</span>
</code></pre>
<p>We can define complement character class, i.e. characters we don't want to match, by adding <code>^</code> at the start of our class.</p>
<pre><code class="lang-js">/[^a-z]/.test(<span class="hljs-string">'A'</span>) 
<span class="hljs-comment">// returns true doesn't match any lowercase alphabet</span>
</code></pre>
<p>Inside a character class, only two characters carry special meaning <code>-</code> in-between characters and <code>^</code> at the start of the class rest all other characters don't carry their special meaning; hence we don't need to escape them.</p>
<pre><code class="lang-js">/[$+]/.test(<span class="hljs-string">'$'</span>) <span class="hljs-comment">// returns true matches $ and +</span>
</code></pre>
<p>You can define character classes for things like alphabets and digits but regex makes it easier for you by defining several special regex characters:</p>
<ul>
<li><code>\w</code> [a-zA-Z0-9_] Alphabets and Digits Class</li>
<li><code>\W</code> [^a-zA-Z0-9_] Negated Class of <code>\w</code></li>
<li><code>\d</code> [0-9] Digits Class</li>
<li><code>\D</code> [^0-9] Negated Class of <code>\d</code></li>
<li><code>\t</code> Tab Character</li>
<li><code>\n</code> Newline Character</li>
<li><code>\s</code> [ \t\r\f\v\n] Matches all white space characters like space, tab, newline, carriage return, vertical tab, form feed, etc.</li>
<li><code>\S</code> [^\s]</li>
<li><code>\b</code> Matches Word Boundary where there is a <code>\w</code> on one side and <code>\W</code> on other side of position
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621156523189/iD9HihDYQ6.jpeg" alt="boundary.jpg" /></li>
<li><code>\B</code> [^\b] Matches all non Word Boundaries</li>
</ul>
<h3 id="heading-wild-cards">Wild 🐯 Cards</h3>
<ul>
<li><code>^</code> symbol allows us to match the starting of the string </li>
<li><code>$</code> allows you to match the end of the string</li>
<li><code>.</code> allows us to match any character</li>
</ul>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tall"</span>.match(<span class="hljs-regexp">/l$/ig</span>))
<span class="hljs-comment">// [ 'l' ]</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tight"</span>.match(<span class="hljs-regexp">/^t/ig</span>))
<span class="hljs-comment">// [ 'T' ]</span>
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621157593734/CW3JoG7Z2.png" alt="example regex for end of line" /></td><td><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621157545875/_pjsWxTbs.png" alt="example regex for start of line" /></td><td><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621157607532/YWaWbkMSn.png" alt="example regex comparison" /></td></tr>
</thead>
<tbody>
<tr>
<td></td><td></td><td></td></tr>
</tbody>
</table>
</div><p>In the above example, while <code>l</code> was matched only with the last one, whereas <code>T</code> was matched with the first one due to <code>$</code> and <code>^</code>, respectively. Without <code>$</code> as you can see, all the <code>l</code>s were matched.</p>
<pre><code class="lang-python">regex = re.compile(<span class="hljs-string">"ho.dog"</span>)

print(regex.search(<span class="hljs-string">"hotdog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
print(regex.search(<span class="hljs-string">"hoddog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
</code></pre>
<p><code>.</code> allowed us to match both <code>d</code> and <code>t</code> in the above example. All the three wildcards are special characters to match them specifically, i.e. <code>^</code>, <code>$</code> and <code>.</code> you have to escape them using <code>\</code>.</p>
<h3 id="heading-flags">Flags 🎌</h3>
<p>You might have observed usage of <code>g</code> or <code>i</code> after the regex expression so what are these things?
These are regex flags that affect the number and type of match we want to make :</p>
<ul>
<li><strong>i</strong> -  Case insensitive match which doesn't differentiate <code>t</code> and <code>T</code></li>
<li><strong>g</strong> - Global Flag allows us to match more than one instance of our expression and not just the first instance</li>
<li><strong>m</strong> - Multiline Flag affects the behaviour of <code>^</code> and <code>$</code> where a <code>\n</code> newline character would mean the start of a new string<pre><code class="lang-python"><span class="hljs-keyword">import</span> re
print(re.search(<span class="hljs-string">"^football"</span>,<span class="hljs-string">"rugby\nfootball"</span>,re.I|re.M))
<span class="hljs-comment"># &lt;re.Match object; span=(6, 14), match='football'&gt;</span>
print(re.search(<span class="hljs-string">"^football"</span>,<span class="hljs-string">"rugby\nfootball"</span>,re.I))
<span class="hljs-comment"># None</span>
</code></pre>
</li>
<li><strong>s</strong> - DotAll Mode, allows wildcard <code>.</code> to match newline character as well.</li>
<li><strong>u</strong> - Unicode support enabled</li>
</ul>
<blockquote>
<p>Half Way through, but I believe the next half will be easier</p>
</blockquote>
<p><img src="https://media.giphy.com/media/y2i2oqWgzh5ioRp4Qa/giphy-downsized.gif" alt="Half Way Checkpoint" /></p>
<h3 id="heading-quantifiers-3">Quantifiers 3️⃣</h3>
<p>Sometimes we require to match a character class, character, group ( coming up ) zero, one, more than one or even, let's say <code>11-22</code> times ( random numbers ); in such cases, quantifiers come to the rescue:</p>
<ul>
<li><p><code>?</code> Matches its preceding character, class or group zero or one time.</p>
<pre><code class="lang-python">regex = re.compile(<span class="hljs-string">"hot?dog"</span>)

print(regex.search(<span class="hljs-string">"hotdog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
print(regex.search(<span class="hljs-string">"hodog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
</code></pre>
</li>
<li><p><code>*</code> Matches its preceding character, class or group zero or more times ( ∞ ).</p>
<pre><code class="lang-python">regex = re.compile(<span class="hljs-string">"hot*dog"</span>)

print(regex.search(<span class="hljs-string">"hotttttdog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
print(regex.search(<span class="hljs-string">"hodog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
print(regex.search(<span class="hljs-string">"hotog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
</code></pre>
</li>
<li><p><code>+</code> Matches its preceding character, class or group one or more times ( ∞ ).</p>
<pre><code class="lang-python">regex = re.compile(<span class="hljs-string">"hot+dog"</span>)

print(regex.search(<span class="hljs-string">"hotttttdog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
print(regex.search(<span class="hljs-string">"hodog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># False</span>
print(regex.search(<span class="hljs-string">"hotog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
</code></pre>
</li>
<li><p><code>{n,m}</code> Matches its preceding character at least <code>n</code> times and at most <code>m</code> times. The default value for <code>n</code> is <code>0</code> and the default for <code>m</code> is <code>&amp;#8734;</code></p>
<pre><code class="lang-python">regex = re.compile(<span class="hljs-string">"hot{1,3}dog"</span>)

print(regex.search(<span class="hljs-string">"hotdog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
print(regex.search(<span class="hljs-string">"hottttdog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># False</span>
print(regex.search(<span class="hljs-string">"hotttog"</span>) <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>)
<span class="hljs-comment"># True</span>
</code></pre>
</li>
</ul>
<h3 id="heading-groups">Groups ✨</h3>
<p>Groups allow us to create grouped expressions that can help us in substitution, referencing them in later parts of a regular expression.</p>
<p>Let's say we want to replace all the <code>function</code> with <code>arrow functions</code>. Obviously, we would like to retain the name of the function and its arguments, but we need to reference them in replacement. With VSCode, our favourite editor and regex, we can do something like :</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NotAnArrow</span>(<span class="hljs-params">argument</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I do something"</span>)
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621165168400/8CTy9luAC.png" alt="Vscode regular expression" /></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> NotAnArrow = <span class="hljs-function">(<span class="hljs-params">argument</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I do something"</span>)
}
</code></pre>
<p>What we used were <code>capturing groups</code>, which we created using <code>(.+)</code> and <code>(.*)</code> ( <code>arguments</code> might not be there ). Anything inside those brackets forms our group, and the expression inside them is the one that will be matched.</p>
<p>There are other types of groups as well:</p>
<ul>
<li>Named Groups <code>(?&lt;Name&gt;...)</code> is a group that provides us reference to that group using its name instead of numbers</li>
<li>Non Capturing Groups <code>(?:...)</code> is a group that will match, but we can't reference them in the result of the regex expression.</li>
</ul>
<h4 id="heading-alternation">Alternation <code>|</code></h4>
<p>Alternation is a simple <code>OR</code> that we can use between different parts of our regex pattern to match this or that or even that by providing different options, just like radio buttons.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(java|type)(?:script)?|html5?|css3?|php|c(\+\+)?\s/gi</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> x <span class="hljs-keyword">of</span> <span class="hljs-string">`JavaScript is here but PhP came
before them and now its TypeScript`</span>.matchAll(regex)) {
  <span class="hljs-built_in">console</span>.log(x)
}
<span class="hljs-comment">// [ 'TypeScript', 'Type', index: 56, input: 'JavaScript is ..... ]</span>
<span class="hljs-comment">// .</span>
<span class="hljs-comment">// .</span>
</code></pre>
<p>So here is what we did with that complex-looking but now easy for you to understand Regular Expression.</p>
<ul>
<li>Created Group to match both <code>Java</code>, <code>Javascript</code> and <code>Typescript</code> using <code>|</code> and <code>?</code></li>
<li>Used <code>|</code> to match other languages as well</li>
<li>Escaped <code>+</code> to match for <code>C++</code> and <code>C</code> as well using <code>?</code></li>
<li>Finally, a character class <code>\s</code> to signify the end of the language name</li>
<li>Flags like <code>gi</code> to match all languages and irrespective of case</li>
</ul>
<blockquote>
<p>Usually, you will find yourself using <code>|</code> inside of groups as you wouldn't want to pollute your global regex just like you always use virtual environment. Make sure to make them <code>non capturing</code> if you don't want to reference or find them in your results.</p>
</blockquote>
<h2 id="heading-trick-treat">Trick 🎃 Treat</h2>
<blockquote>
<p><code>+</code> and <code>*</code> are of nature greedy. They will keep adding characters to the match until they find the last instance of any succeeding expression or the sentence ends.</p>
</blockquote>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> re
regex = re.compile(<span class="hljs-string">"(a|m).+e"</span>)
print(regex.match(<span class="hljs-string">"apple maple"</span>))
<span class="hljs-comment"># expected ['apple','maple'] found 'apple maple'</span>
</code></pre>
<p>Here <code>.+</code> ignored the <code>e</code> of <code>apple</code> and went all the way to finish at <code>e</code> of <code>maple</code> as it was the last instance of <code>e</code> that it was able to find.</p>
<p>Lazy Mode for <code>*</code> and <code>+</code> can be activated by appending <code>?</code> after the quantifier matches only the minimum required characters for the regex expression.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> regex = <span class="hljs-regexp">/(?:a|m).+?e/gi</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> x <span class="hljs-keyword">of</span> <span class="hljs-string">"apple mapple"</span>.matchAll(regex)) {
  <span class="hljs-built_in">console</span>.log(x);
}
<span class="hljs-comment">// expected ['apple','maple'] found ['apple' 'maple']</span>
</code></pre>
<p>I highly recommend you to check language-specific docs for syntax and available features. One of the best docs for regex is for <a target="_blank" href="https://docs.python.org/3/howto/regex.html">python</a>. </p>
<p>I didn't cover one feature that I might make a new article on it is <a target="_blank" href="https://javascript.info/regexp-lookahead-lookbehind">Lookahead and Lookbehind</a>. You can wait :) or check out the link.</p>
<p><img src="https://media.giphy.com/media/MCZ39lz83o5lC/giphy-downsized.gif" alt="Use regex carefully due to backtracking and recursive nature" /></p>
<p>Why did I say that? Because sometimes regex can take exponential time to search a be really <a target="_blank" href="https://javascript.info/regexp-catastrophic-backtracking">catastrophic</a>. So .....</p>
<blockquote>
<p>May the code be with you 🖖</p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[Good Commits]]></title><description><![CDATA[Git commits are everywhere, and you might be generating more than 1k commits over a year. So it becomes crucial to understand that commit should be structured and created in a scalable manner.

Why bother?

Writing better commits can make the differe...]]></description><link>https://hashnode.king-11.dev/good-commits</link><guid isPermaLink="true">https://hashnode.king-11.dev/good-commits</guid><category><![CDATA[Git]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Devops]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Lakshya Singh]]></dc:creator><pubDate>Fri, 07 May 2021 07:33:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1620372649677/9k-UurVak.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Git commits are everywhere, and you might be generating more than 1k commits over a year. So it becomes crucial to understand that commit should be structured and created in a scalable manner.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620370751015/SCRWL-P3a.png" alt="commit.png" /></p>
<h2 id="heading-why-bother">Why bother?</h2>
<ul>
<li><p>Writing better commits can make the difference between your debugging session lasting <strong>1 hour to a few minutes</strong>.</p>
</li>
<li><p>With good commits, it's easier for anyone to understand the progress of a project and get up to speed. </p>
</li>
<li><p>It also allows reviewers to understand your progress during the resolution of an issue clearly.</p>
</li>
<li><p>Generating good commits will allow you to track back changes/issues to a specific module/file and associate it to the code easily.</p>
</li>
<li><p>They enable you to understand how the issue crept in the codebase and how you can easily resolve it.</p>
</li>
<li><p>Good commit messages can save you the hassle while creating release notes</p>
</li>
</ul>
<h2 id="heading-what-are-good-commits">What are good commits?</h2>
<h3 id="heading-modular">Modular</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1620372512823/nU2KOcvIB.jpeg" alt="Modular Commits" /></p>
<p>A commit should be <strong>modular</strong> in nature, just like our codebase. Each commit should <strong>encapsulate</strong> a single logical idea only that might span over several changes but as a whole is a single related group of changes.</p>
<p>E.g., add CSS to a component, change the margin of all pages, strong typing your functions, etc.</p>
<h3 id="heading-type-of-commit">Type of Commit</h3>
<p><strong>Categorising</strong> your commits into types also clarifies what type of change it made and can be identified instantly. I usually keep a template file that contains those types so I don't have to remember them :P</p>
<p>Some of the subtypes can be a chore, feat, fix, refactor, style, etc. What meaning does each carry can vary based on your team or you as an individual as well. Below are the types that I use in my commits :</p>
<ul>
<li>feat: new feature</li>
<li>fix: bug fix</li>
<li>refactor: refactoring production code</li>
<li>style: formatting, missing semicolons, etc.; no code change</li>
<li>docs: changes to documentation</li>
<li>test: adding or refactoring tests no production code change</li>
<li>chore: updating dependencies etc. no production code change</li>
</ul>
<h3 id="heading-description">Description</h3>
<p><img src="https://media.giphy.com/media/kEFa2FuLcG0mn3t0ef/giphy.gif" alt="Perfect Description" /></p>
<p>A commit message except for the subject line limited to <code>50</code> chars should include a description broken into <code>72</code> char lines/line. The description is separated from the subject by a blank line. The description should try to cover things like :</p>
<ul>
<li>the current behaviour,</li>
<li>what change are you making?</li>
<li>why this fix is needed?</li>
<li>why take the current approach for this change?</li>
</ul>
<p>Commit message should be in the future tense, i.e. 'Fix' vs 'Fixed.' </p>
<h2 id="heading-bonus-treats">Bonus Treats</h2>
<p><img src="https://media.giphy.com/media/Y0UmGpoLtAlrvdrK9Q/giphy.gif" alt="Treat" /></p>
<p>You can specify a template for your git commits by adding the following config to your <code>$HOME/.gitconfig</code></p>
<pre><code class="lang-bash">[commit]
    template = ~/path/to/template
</code></pre>
<p>My template looks like this, which allows constraining the number of characters in the subject and description line. I also add the types and just in case I don't remember :'(</p>
<pre><code class="lang-bash"><span class="hljs-comment"># &lt;type&gt;: &lt;subject&gt;</span>
<span class="hljs-comment">##### Subject 50 characters ################# -&gt; |</span>


<span class="hljs-comment"># Body Message</span>
<span class="hljs-comment">######## Body 72 characters ####################################### -&gt; |</span>

<span class="hljs-comment"># --- COMMIT END ---</span>
<span class="hljs-comment"># Type can be</span>
<span class="hljs-comment">#   feat    : new feature</span>
<span class="hljs-comment">#   fix     : bug fix</span>
<span class="hljs-comment">#   refactor: refactoring production code</span>
<span class="hljs-comment">#   style   : formatting, missing semi colons, etc; no code change</span>
<span class="hljs-comment">#   docs    : changes to documentation</span>
<span class="hljs-comment">#   test    : adding or refactoring tests</span>
<span class="hljs-comment">#             no production code change</span>
<span class="hljs-comment">#   chore   : updating grunt tasks etc</span>
<span class="hljs-comment">#             no production code change</span>
</code></pre>
<p><em><strong>Note</strong></em> : For your template to be prompted, you have to use <code>git commit</code>.</p>
]]></content:encoded></item></channel></rss>