<?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[chandraji.dev | Blog]]></title><description><![CDATA[Siddharth's Blog on Software Development, Programming Languages and Algorithms. Software Engineering | Python | Java | Scala | SQL | Game Development | Computer Vision.]]></description><link>https://chandraji.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1631533420614/mPhSTF4QY.png</url><title>chandraji.dev | Blog</title><link>https://chandraji.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 21 Apr 2026 20:07:22 GMT</lastBuildDate><atom:link href="https://chandraji.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Diving into Docker: A Comprehensive Guide for Beginners]]></title><description><![CDATA[Docker has revolutionized the way we build, ship, and run applications. It's a containerization platform that enables developers to package applications and their dependencies into isolated containers. These containers can run consistently across dif...]]></description><link>https://chandraji.dev/diving-into-docker-a-comprehensive-guide-for-beginners</link><guid isPermaLink="true">https://chandraji.dev/diving-into-docker-a-comprehensive-guide-for-beginners</guid><category><![CDATA[Docker]]></category><category><![CDATA[containers]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[Java]]></category><category><![CDATA[Springboot]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Tue, 05 Sep 2023 14:42:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1693924772547/88f89474-06b5-4933-bbfe-c930e11b1387.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Docker has revolutionized the way we build, ship, and run applications. It's a containerization platform that enables developers to package applications and their dependencies into isolated containers. These containers can run consistently across different environments, from development to production, making it easier to manage and scale applications.</p>
<p>In this article, we will try to understand its basics while diving deep enough so that you will be able to start working with Docker as a software engineering professional.</p>
<hr />
<h2 id="heading-installing-docker">Installing Docker</h2>
<p>Before we dive into Docker, we need to install it on our system. Docker provides installation packages for various operating systems, including Windows, macOS, and Linux. You can download the appropriate package for your OS from the official Docker <a target="_blank" href="https://docs.docker.com/engine/install/">website</a>.</p>
<p>Once Docker is installed, open a terminal or command prompt and run the following command to verify the installation:</p>
<pre><code class="lang-bash">docker --version
</code></pre>
<p>If you see the Docker version information like the below image, you're ready to move on to the next steps.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693923810337/c96baee7-9f87-4adc-ad5f-303d5bc81820.png" alt /></p>
<h2 id="heading-running-your-first-docker-container">Running Your First Docker Container</h2>
<p>Let's start by running a simple Docker container. Docker containers are instances of Docker images, which are pre-packaged, portable environments. We'll use the official Docker image for the "hello-world" application.</p>
<p>Open your terminal and run the following command:</p>
<pre><code class="lang-bash">docker run hello-world
</code></pre>
<p>Docker will download the "hello-world" image if it's not already available and run it. You'll see a message indicating that your installation appears to be working correctly.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693923837031/c2d7a170-f534-4b4d-b274-b824c5075867.png" alt /></p>
<p>In the above image, you'll see that since <code>hello-world</code> Docker image was not present locally, Docker downloaded it and displayed additional information on what happened behind the scenes.</p>
<blockquote>
<p>Note: See <code>Docker daemon</code>, search for this on the internet, doing so, you will get to learn about the internals of Docker as a bonus.</p>
</blockquote>
<h2 id="heading-understanding-docker-images">Understanding Docker Images</h2>
<p>Docker images are the building blocks of containers. They contain everything needed to run an application, including the code, runtime, libraries, and system tools. Images are stored in a Docker registry, which is like a repository for Docker images.</p>
<p>You can search for Docker images on the <a target="_blank" href="https://hub.docker.com/">Docker Hub</a> (Docker Registry) or create your own custom images. Let's create a simple Java application and package it into a Docker image.</p>
<blockquote>
<p>Note: For some developers, this may seem like a lot of information. Try to code along with the article at your own pace and whenever in doubt, just search it over the internet!</p>
</blockquote>
<pre><code class="lang-java"><span class="hljs-comment">// HelloWorld.java</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloWorld</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        System.out.println(<span class="hljs-string">"Hello, Docker!"</span>);
    }
}
</code></pre>
<p>To create a Docker image for this Java application, create a <code>Dockerfile</code> in the same directory with the following content:</p>
<blockquote>
<p>Note: To create a Dockerfile, if you are a terminal enthusiast then you can do something like <code>touch Dockerfile</code>. Make sure you are in the same directory as <code>HelloWorld.java</code> file.</p>
</blockquote>
<pre><code class="lang-Dockerfile"><span class="hljs-comment"># Use an official Java runtime as a parent image</span>
<span class="hljs-keyword">FROM</span> openjdk:<span class="hljs-number">8</span>-jdk

<span class="hljs-comment"># Set the working directory to /app</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-comment"># Copy the current directory contents into the container at /app</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . /app</span>

<span class="hljs-comment"># Compile the Java code</span>
<span class="hljs-keyword">RUN</span><span class="bash"> javac HelloWorld.java</span>

<span class="hljs-comment"># Run the application</span>
<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"java"</span>, <span class="hljs-string">"HelloWorld"</span>]</span>
</code></pre>
<p>Now, build the Docker image using the <code>docker build</code> command:</p>
<pre><code class="lang-bash">docker build -t hello-java .
</code></pre>
<p>The <code>-t</code> flag allows you to tag the image with a name ("hello-java" in this case). You can replace "hello-java" with any name you prefer.</p>
<blockquote>
<p>Note: I have added comments in <code>Dockerfile</code> itself, it is pretty straight forward, just give it some time and you'll understand it easily. Note the <code>COPY</code> command, you need to copy the files inside your <code>Dockerfile</code>. When you use <code>docker build .</code>, then the current directory files are available to you as context but they are not inside image.</p>
</blockquote>
<h2 id="heading-running-your-custom-docker-image">Running Your Custom Docker Image</h2>
<p>Now that we have created a custom Docker image, let's run it as a container:</p>
<pre><code class="lang-bash">docker run hello-java
</code></pre>
<p>The "Hello, Docker!" message is printed in the terminal, indicating that the Java application is running inside the Docker container.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693924104117/c52c960f-efc7-43b3-be7b-7dc4b3f666b1.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-docker-containers-are-stateless">Docker Containers Are Stateless</h2>
<p>One important concept to understand is that Docker containers are stateless by default. This means that any changes made inside a container are ephemeral and do not persist after the container exits. To demonstrate this, let's modify our Java application to accept user input and see how the container behaves.</p>
<pre><code class="lang-java"><span class="hljs-comment">// HelloWorld.java (Updated)</span>
<span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloWorld</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);
        System.out.print(<span class="hljs-string">"Enter your name: "</span>);
        String name = scanner.nextLine();
        System.out.println(<span class="hljs-string">"Hello, "</span> + name + <span class="hljs-string">"!"</span>);
    }
}
</code></pre>
<p>Now, rebuild the Docker image and run it again:</p>
<pre><code class="lang-bash">docker build -t hello-java .
docker run -it hello-java
</code></pre>
<p>You'll notice that the container stops after taking user input and displaying the message. This is because containers are designed to be disposable and do not retain state between runs.</p>
<p>You can see the result below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693924134885/66891ba7-edc9-42b3-a8dc-65dce59c4f8a.png" alt /></p>
<h2 id="heading-docker-volumes-for-data-persistence">Docker Volumes for Data Persistence</h2>
<p>To persist data between container runs, you can use Docker volumes. Volumes are a way to share data between the host system and containers or between containers. Let's modify our Java application to write user input to a file and use a Docker volume to persist the data.</p>
<pre><code class="lang-java"><span class="hljs-comment">// HelloWorld.java (Updated)</span>
<span class="hljs-keyword">import</span> java.io.FileWriter;
<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.util.Scanner;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloWorld</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Scanner scanner = <span class="hljs-keyword">new</span> Scanner(System.in);
        System.out.print(<span class="hljs-string">"Enter your name: "</span>);
        String name = scanner.nextLine();

        <span class="hljs-keyword">try</span> {
            FileWriter writer = <span class="hljs-keyword">new</span> FileWriter(<span class="hljs-string">"/app/output.txt"</span>);
            writer.write(<span class="hljs-string">"Hello, "</span> + name + <span class="hljs-string">"!"</span>);
            writer.close();
            System.out.println(<span class="hljs-string">"Data written to output.txt"</span>);
        } <span class="hljs-keyword">catch</span> (IOException e) {
            System.err.println(<span class="hljs-string">"Error writing to file: "</span> + e.getMessage());
        }
    }
}
</code></pre>
<p>Rebuild the Docker image and run it, this time with a Docker volume:</p>
<pre><code class="lang-bash">docker build -t hello-java .
docker run -it -v $(<span class="hljs-built_in">pwd</span>)/data:/app/data hello-java
</code></pre>
<p>The <code>-v</code> flag is used to mount a host directory (<code>./data</code>) as a volume inside the container. Now, the data is written to <code>output.txt</code> will be persisted on your host system in the <code>./data</code> directory.</p>
<p>That's a lot of information! Let's move on to something more fun.</p>
<h2 id="heading-dockerizing-a-java-web-application">Dockerizing a Java Web Application</h2>
<p>Docker is not limited to running simple command-line applications. It can also containerize web applications. Let's take a Java-based web application as an example. We'll use Spring Boot, a popular Java framework, to create a simple REST API.</p>
<p><strong>Example Java Web Application (HelloAPI.java):</strong></p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> org.springframework.boot.SpringApplication;
<span class="hljs-keyword">import</span> org.springframework.boot.autoconfigure.SpringBootApplication;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.GetMapping;
<span class="hljs-keyword">import</span> org.springframework.web.bind.annotation.RestController;

<span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-meta">@RestController</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HelloAPI</span> </span>{
    <span class="hljs-meta">@GetMapping("/")</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">hello</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Hello, Dockerized API!"</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        SpringApplication.run(HelloAPI.class, args);
    }
}
</code></pre>
<p>To Dockerize this application, create a Dockerfile similar to the one we used earlier but with a few modifications:</p>
<p><strong>Dockerfile for Java Web Application:</strong></p>
<pre><code class="lang-Dockerfile"><span class="hljs-comment"># Use an official OpenJDK runtime as a parent image</span>
<span class="hljs-keyword">FROM</span> openjdk:<span class="hljs-number">8</span>-jdk

<span class="hljs-comment"># Set the working directory to /app</span>
<span class="hljs-keyword">WORKDIR</span><span class="bash"> /app</span>

<span class="hljs-comment"># Copy the current directory contents into the container at /app</span>
<span class="hljs-keyword">COPY</span><span class="bash"> . /app</span>

<span class="hljs-comment"># Build the Java application</span>
<span class="hljs-keyword">RUN</span><span class="bash"> ./mvnw package -DskipTests</span>

<span class="hljs-comment"># Expose port 8080 for the Spring Boot application</span>
<span class="hljs-keyword">EXPOSE</span> <span class="hljs-number">8080</span>

<span class="hljs-comment"># Run the Spring Boot application</span>
<span class="hljs-keyword">CMD</span><span class="bash"> [<span class="hljs-string">"java"</span>, <span class="hljs-string">"-jar"</span>, <span class="hljs-string">"target/demo-0.0.1-SNAPSHOT.jar"</span>]</span>
</code></pre>
<p>Now, build the Docker image for your Java web application using the same <code>docker build</code> command as before:</p>
<pre><code class="lang-bash">docker build -t hello-api .
</code></pre>
<p>Once the image is built, you can run a container from it, and your Spring Boot application will be accessible at <code>http://localhost:8080</code> in your web browser.</p>
<h2 id="heading-docker-registry-and-pushing-images">Docker Registry and Pushing Images</h2>
<p>So far, we've been working with local Docker images. You can use Docker registries to share your Docker images with others or deploy them to remote servers. Docker Hub is a popular public registry, but you can also set up your private registry.</p>
<p>To push your custom Docker image to Docker Hub, follow these steps:</p>
<ol>
<li>Log in to Docker Hub using the <code>docker login</code> command.</li>
</ol>
<pre><code class="lang-bash">docker login
</code></pre>
<ol>
<li>Tag your image with your Docker Hub username and repository name.</li>
</ol>
<pre><code class="lang-bash">docker tag hello-java &lt;your-docker-hub-username&gt;/hello-java
</code></pre>
<ol>
<li>Push the image to Docker Hub.</li>
</ol>
<pre><code class="lang-bash">docker push &lt;your-docker-hub-username&gt;/hello-java
</code></pre>
<p>Now, your custom Docker image is available on Docker Hub and can be pulled by others.</p>
<h2 id="heading-container-orchestration-with-docker-swarm-and-kubernetes">Container Orchestration with Docker Swarm and Kubernetes</h2>
<p>Docker can be used for container orchestration, which manages multiple containers across a cluster of machines. Two popular tools for container orchestration are Docker Swarm and Kubernetes.</p>
<ul>
<li><p><strong>Docker Swarm</strong>: Docker Swarm is a built-in orchestration solution for Docker. It allows you to create and manage a swarm of Docker nodes (machines) and deploy services to them. Docker Swarm is easy to set up and is suitable for smaller deployments.</p>
</li>
<li><p><strong>Kubernetes</strong>: Kubernetes is a powerful and widely adopted container orchestration platform. It provides advanced features for managing containerized applications at scale. Kubernetes has a steeper learning curve than Docker Swarm but offers more flexibility and scalability.</p>
</li>
</ul>
<p>To get started with Docker Swarm or Kubernetes, you can refer to their official documentation and tutorials.</p>
<h2 id="heading-takeaways">Takeaways</h2>
<p>Docker is a powerful tool that simplifies application development, deployment, and scaling by using containers. In this article, we've covered the essential steps to get started with Docker, with these fundamental concepts and practical examples, you can begin harnessing the full potential of Docker for your Java development projects. Docker's ability to create consistent and isolated environments will streamline your development process and make your applications more portable and maintainable. Happy Dockerizing!</p>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/data-structure-algorithms">Data Structures &amp; Algorithms</a> to more fun topics like <a target="_blank" href="series/computer-vision">Computer Vision</a>.</p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
<li><p>Starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Stable and Unstable Sorting: Why Stability Matters?]]></title><description><![CDATA[Sorting is a fundamental operation in computer science and one that is used in solving some of the most common real-world problems. It involves arranging a collection of elements in a specific order, often in ascending or descending order. However, n...]]></description><link>https://chandraji.dev/stable-and-unstable-sorting-why-stability-matters</link><guid isPermaLink="true">https://chandraji.dev/stable-and-unstable-sorting-why-stability-matters</guid><category><![CDATA[algorithms]]></category><category><![CDATA[Java]]></category><category><![CDATA[Python]]></category><category><![CDATA[Design]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Sun, 27 Aug 2023 13:34:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1693142972829/300977bf-054f-4552-9ddd-b5b2158ac959.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sorting is a fundamental operation in computer science and one that is used in solving some of the most common real-world problems. It involves arranging a collection of elements in a specific order, often in ascending or descending order. However, not all sorting algorithms are created equal!</p>
<p>Some sorting algorithms ensure that the relative order of <strong>equal elements</strong> remains unchanged after sorting, while others make no such guarantee. This distinction gives rise to the concepts of <em>stable</em> and <em>unstable</em> sorting algorithms. These categories may seem subtle, but they can have significant implications for various applications.</p>
<blockquote>
<p>Note: Equality of elements will depend on their data types, for primary types - their face values - and for secondary types i.e. objects - their custom-defined comparable methods - will act as the equality differentiator.</p>
</blockquote>
<p>In this article, we will delve into the significance of stable and unstable sorting, exploring their differences and discussing scenarios where their distinctions matter.</p>
<h2 id="heading-understanding-stable-and-unstable-sorting">Understanding Stable and Unstable Sorting</h2>
<p>Stability in sorting algorithms refers to the preservation of the relative order of elements with equal keys. In other words, if two elements have equal keys, and one appears before the other in the original sequence, a stable sorting algorithm will maintain that order in the sorted output. On the other hand, an unstable sorting algorithm makes no such promise. When two elements have equal keys, their relative positions in the sorted output may not match their original relative positions.</p>
<p>To illustrate this concept, consider a scenario where you have a list of student records, each containing a name and a score. You want to sort the records first by score in ascending order and then by name. A stable sorting algorithm will ensure that if two students have the same score, their names will remain in the same order as in the initial list. An unstable sorting algorithm, however, might rearrange the names of these students, leading to a different order.</p>
<p>Let's delve into some code examples to showcase stable and unstable sorting algorithms!</p>
<h2 id="heading-code-example-in-python">Code Example In Python</h2>
<p>Consider the following example in Python using the <code>sorted()</code> function, which employs a stable sorting algorithm:</p>
<pre><code class="lang-python">data = [(<span class="hljs-number">3</span>, <span class="hljs-string">"apple"</span>), (<span class="hljs-number">1</span>, <span class="hljs-string">"banana"</span>), (<span class="hljs-number">3</span>, <span class="hljs-string">"orange"</span>), (<span class="hljs-number">2</span>, <span class="hljs-string">"grape"</span>)]

sorted_data = sorted(data)

print(sorted_data)
</code></pre>
<p>The output will be:</p>
<pre><code class="lang-plaintext">[(1, 'banana'), (2, 'grape'), (3, 'apple'), (3, 'orange')]
</code></pre>
<p>Notice that the two elements with the key <code>3</code> appear in the same order as they did in the original list.</p>
<blockquote>
<p>Note: <code>sorted</code> function when not given any <code>key</code> will take the first element of the inner tuples to perform the sorting in ascending order by default.</p>
<p>Note: Python internally uses different sorting algorithms to perform sorting. In certain scenarios, its interpreter could use the quick sort algorithm which would result in an unstable sort. Read more about why the quick sort is unstable <a target="_blank" href="https://saturncloud.io/blog/understanding-quicksort-algorithm-stability/">here</a>.</p>
</blockquote>
<h2 id="heading-code-examples-in-java">Code Examples In Java</h2>
<h3 id="heading-stable-sorting">Stable Sorting</h3>
<p>Java provides a built-in sorting method using the <code>Arrays</code> class, which uses a stable sorting algorithm. Here's how you can use it:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.Arrays;
<span class="hljs-keyword">import</span> java.util.Comparator;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> </span>{
    String name;
    <span class="hljs-keyword">int</span> score;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Student</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> score)</span> </span>{
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.score = score;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">StableSortingExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Student[] students = {
            <span class="hljs-keyword">new</span> Student(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">85</span>),
            <span class="hljs-keyword">new</span> Student(<span class="hljs-string">"Bob"</span>, <span class="hljs-number">90</span>),
            <span class="hljs-keyword">new</span> Student(<span class="hljs-string">"Carol"</span>, <span class="hljs-number">85</span>),
            <span class="hljs-keyword">new</span> Student(<span class="hljs-string">"David"</span>, <span class="hljs-number">78</span>)
        };

        <span class="hljs-comment">// First, sort by score, then by name</span>
        Arrays.sort(students, Comparator.comparingInt((Student s) -&gt; s.score)
                                       .thenComparing(s -&gt; s.name));

        <span class="hljs-keyword">for</span> (Student student : students) {
            System.out.println(student.name + <span class="hljs-string">": "</span> + student.score);
        }
    }
}
</code></pre>
<p>The output will be:</p>
<pre><code class="lang-plaintext">David: 78
Alice: 85
Carol: 85
Bob: 90
</code></pre>
<p>In this example, the <code>Arrays.sort</code> method first sorts the students by their scores. Since both Alice and Carol have the same score, their original order is preserved due to the stability of the sorting algorithm.</p>
<h3 id="heading-unstable-sorting">Unstable Sorting</h3>
<p>To demonstrate an unstable sorting algorithm, we can use the <code>Collections</code> class, which provides a method to sort lists:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.Collections;
<span class="hljs-keyword">import</span> java.util.Comparator;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UnstableSortingExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        List&lt;Student&gt; students = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
        students.add(<span class="hljs-keyword">new</span> Student(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">85</span>));
        students.add(<span class="hljs-keyword">new</span> Student(<span class="hljs-string">"Bob"</span>, <span class="hljs-number">90</span>));
        students.add(<span class="hljs-keyword">new</span> Student(<span class="hljs-string">"Carol"</span>, <span class="hljs-number">85</span>));
        students.add(<span class="hljs-keyword">new</span> Student(<span class="hljs-string">"David"</span>, <span class="hljs-number">78</span>));

        <span class="hljs-comment">// Sort by score using an unstable sorting algorithm</span>
        Collections.sort(students, Comparator.comparingInt((Student s) -&gt; s.score));

        <span class="hljs-keyword">for</span> (Student student : students) {
            System.out.println(student.name + <span class="hljs-string">": "</span> + student.score);
        }
    }
}
</code></pre>
<p>The output could be:</p>
<pre><code class="lang-plaintext">David: 78
Carol: 85
Alice: 85
Bob: 90
</code></pre>
<p>In this example, the <code>Collections.sort</code> method sorts the students by their scores. However, unlike the stable sorting example, the original order of students with the same score (e.g., Alice and Carol) <strong>might not be preserved</strong> in the sorted output.</p>
<h2 id="heading-why-stability-matters">Why Stability Matters</h2>
<p>The stability of sorting algorithms might seem like a subtle distinction, but it can have significant implications in various applications.</p>
<p>Consider a situation where you have a dataset of individuals of the same age, and you want to sort them by their names. A stable sorting algorithm would ensure that if two people share the same age, their names remain in the same order as they were initially. This could be essential, especially when dealing with historical data or maintaining user preferences.</p>
<p>Here are a few scenarios where stability matters:</p>
<ol>
<li><p><strong>Multi-level Sorting:</strong> In cases where you need to sort data by multiple criteria, using a stable sorting algorithm ensures that the order of previous sorts is maintained. This is particularly useful in scenarios like the student records example shown earlier in the article.</p>
</li>
<li><p><strong>Preserving Initial Order:</strong> Stable sorting is crucial when dealing with data that already has a meaningful order. For instance, when sorting log entries by timestamp, you'd want to maintain the original order of entries that occurred at the same time.</p>
</li>
<li><p><strong>Algorithm Composition:</strong> Stable sorting is often used as a building block in more complex algorithms. If intermediate steps require sorted data, the stability of the sorting algorithm can impact the correctness of the overall process.</p>
</li>
</ol>
<blockquote>
<p>Note: An unstable sorting algorithm might be more efficient in terms of time or memory usage. Algorithms like Quicksort and Heapsort are often unstable, but they can offer better performance in certain scenarios. For instance, if stability is not a concern and you're dealing with large datasets, an unstable sorting algorithm might be preferred due to its speed and memory efficiency.</p>
</blockquote>
<h2 id="heading-takeaway">Takeaway</h2>
<ol>
<li><p>Sorting is not just about arranging elements; it's about maintaining the integrity of the data and respecting the original order when necessary. Stable and unstable sorting algorithms provide different approaches to achieving this goal.</p>
</li>
<li><p>When maintaining the initial order of equal elements is vital, a stable sorting algorithm is the way to go. However, if performance is a priority and stability is not a concern, an unstable sorting algorithm might offer better efficiency.</p>
</li>
<li><p>At last, it all comes down to an individual choice and the problem a developer is trying to solve. As a developer, understanding stable and unstable sorting empowers you to choose the right sorting algorithm for the task at hand, ensuring the accuracy and reliability of your applications.</p>
</li>
</ol>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/data-structure-algorithms">Data Structures &amp; Algorithms</a> to more fun topics like <a target="_blank" href="series/computer-vision">Computer Vision</a>.</p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
<li><p>Starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Python Programmer to a Java Developer: Things I Learned]]></title><description><![CDATA[So, a couple of months back I started learning Java Programming Language for a project at my organisation. Initially, like most of us, I felt intimidated by Java. For almost every time, as far as I can remember, I never looked at Java as my choice of...]]></description><link>https://chandraji.dev/python-programmer-to-a-java-developer-things-i-learned</link><guid isPermaLink="true">https://chandraji.dev/python-programmer-to-a-java-developer-things-i-learned</guid><category><![CDATA[Python]]></category><category><![CDATA[Java]]></category><category><![CDATA[learning]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Sat, 02 Apr 2022 17:02:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1648917098765/C2nQaUXSN.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So, a couple of months back I started learning <a target="_blank" href="https://en.wikipedia.org/wiki/Java_(programming_language">Java Programming Language</a> for a project at my organisation. Initially, like most of us, I felt intimidated by Java. For almost every time, as far as I can remember, I never looked at Java as my choice of language to complete any task at hand. It felt distant and very difficult to understand just because of one <code>System.out.println</code>.</p>
<p>But, any way I took, which looked daunting at first, the task of learning Java! And I am not going to lie, Java is the most user-friendly programming language for anyone who works with <a target="_blank" href="https://en.wikipedia.org/wiki/Object-oriented_programming">Object Oriented Programming</a> almost every day. Heck, if you love <a target="_blank" href="https://en.wikipedia.org/wiki/Functional_programming">Functional Programming</a>, Java got you covered (but I am a little biased towards <a target="_blank" href="https://en.wikipedia.org/wiki/Scala_(programming_language">Scala Programming Language</a>).</p>
<p>Being a Python Developer since college and now learning Java, I wanted to highlight some of the many things that I learned during this transition, which might help you decide whether you should go ahead and over that intimidation to learn Java or not.</p>
<hr />
<h3 id="heading-dont-be-afraid-of-java-hello-world-program">Don't Be Afraid Of Java Hello World Program</h3>
<p>I have seen people disliking Java immediately after seeing the code of <a target="_blank" href="https://www.javatpoint.com/simple-program-of-java">Hello World</a> written in Java (I was one of them). They start comparing it with Python's syntax of <a target="_blank" href="https://www.python-ds.com/python-hello-world">Hello World</a> program and get intimidated and leave before even trying to understand why its syntax is like that.</p>
<p>So, Java is almost a complete Object-Oriented Programming (OOP) language and as we all know, in OOP we deal with classes/objects and when we talk about classes or objects, we need to understand that the code written might be big but it is guaranteed to be human-readable and understandable and highly manageable.</p>
<p>If you don't know, almost everything that Python offers is actually an object of some type behind the scenes. It is abstracting it all out so that we write less code and can focus on delivering fast. But, it comes at a cost of speed (which now with many enhancements is improving).</p>
<blockquote>
<p>Note: You can start learning Scala to write less code and be as fast as Java <a target="_blank" href="series/scala">here</a>.</p>
</blockquote>
<p>So, before starting to learn Java, you should know that classes will be defined, objects will be created, methods will be called and all will be in accordance with OOP, and you will learn OOP either as a beginner or as a professional from the get-go through Java.</p>
<p>Don't be afraid of that Hello World program anymore.</p>
<h3 id="heading-java-works-with-primitive-data-types">Java Works With Primitive Data Types</h3>
<p>Java is not 100% OOP language in nature, it also works with <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html">primitive data types</a>.</p>
<p>Well, after learning that the Java Hello World program deals with OOP concepts and now getting to know that Java is not 100% OOP language, I felt relieved, because you know, C++ works with primitive data types and even though Python is dynamically typed, behind the scenes it works with primitive data types, then it means that learning curve would be same for anyone learning a new programming language.</p>
<p>But, Java aims to be 100% OOP language and to cover primitive data types, it offers wrappers around primitive types. So, for each primitive type, there is a corresponding class we can rather use.</p>
<pre><code class="lang-java"><span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>;
<span class="hljs-comment">// is same as</span>
Integer i = <span class="hljs-number">0</span>;
</code></pre>
<p>Taking the above example, <code>int</code> is a primitive data type and <code>Integer</code> is a wrapper class around it.</p>
<p>Then, how can it directly assign an <code>Integer</code> type variable to a primitive value when we know that it is a wrapper class? It is accomplished using autoboxing. Similarly, we can directly use the <code>Integer</code> type value or any other wrapper class value using unboxing whenever needed within the program.</p>
<p>Both autoboxing and unboxing are done by JVM behind the scenes and can also be done explicitly, so you do not need to worry about it much. Also, this article is not intended to help you learn <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html">auto/unboxing</a>, but it's better to know the inner workings and I would recommend you to check the link provided.</p>
<h3 id="heading-a-lot-of-similarities">A Lot Of Similarities</h3>
<p>After spending a lot of time learning Java, I figured that it is not much different from Python when it comes to programming language concepts. As they say, learning another programming language is easy when you know one already.</p>
<ul>
<li>Python provides conditional statements so does Java.</li>
<li>Python has looping constructs like <code>for</code> and <code>while</code>, and so does Java. Only they differ in syntax.</li>
<li>Python provides exception handling using <code>try-catch</code> and so does Java.</li>
<li>Python can be used for OOP, guess what, Java is OOP.</li>
<li>Python can be used for functional programming, and so does Java.</li>
<li>Python provides <code>list</code>, <code>set</code> and <code>dict</code> and Java have <code>ArrayList</code>, <code>HashSet</code> and <code>HashMap</code>.</li>
<li>Python is used for competitive programming (CP), and Java is 2nd most used programming language for CP after C++.</li>
<li>A big community of developers to help each other out.</li>
</ul>
<p>So, with all these similarities we can be less worried about learning Java.</p>
<h3 id="heading-not-everything-is-similar">Not Everything Is Similar</h3>
<p>Even though Java and Python are a lot similar in many concepts, there are some things that Java differs on and these are some of them:</p>
<ul>
<li>Java have <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html">access modifiers</a>. <code>public</code>, <code>private</code>, <code>protected</code> and <code>package-private</code>.</li>
<li>Java works with <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html">interfaces</a>. Java defines interfaces to provide the ability of a <code>can</code> relationship between classes, similar to what an <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html">abstract class</a> defines, <code>is a</code> relationship.</li>
<li>Inner classes in Java are handled very differently than in Python.</li>
<li><code>static</code> members in a class can be defined. Although, Python have <code>@classmethod</code> and <code>@staticmethod</code>, but as Zen of Python says, we are all adults here!</li>
<li>Generic classes. One step closer to being dynamically typed classes!</li>
<li>2 IO packages, <a target="_blank" href="https://docs.oracle.com/javase/tutorial/essential/io/streams.html">java.io</a> and <a target="_blank" href="https://docs.oracle.com/javase/tutorial/essential/io/fileio.html">java.nio</a>. <code>java.io</code> has similarities to traditional input/output programmes that we are used to. But, <code>java.nio</code> is something else completely. It uses channels/buffers and sometimes selectors to perform the reading/writing of data.</li>
<li><code>Serializable</code> interface, helps when we need to output classes to streams.</li>
<li>It provides the <code>java.sql</code> package as an out of the box library to directly connect with databases in a very OOP way using <a target="_blank" href="https://docs.oracle.com/javase/tutorial/jdbc/basics/index.html">JDBC</a> drivers.</li>
</ul>
<p>There are many more dissimilarities, but now we get a general idea that both Python and Java are similar and dissimilar on many points giving different advantages.</p>
<h3 id="heading-an-ocean-of-opportunities">An Ocean Of Opportunities</h3>
<p>When Java gets used with frameworks like <a target="_blank" href="https://spring.io/">spring</a>, it becomes a beast of a language, providing almost all the capabilities that we need in general to develop fully functional end-to-end applications.</p>
<p>I am still learning a lot in the Java tech space and will continue to do so, you can also start learning it or any other technology that you feel intimated by and you will soon realize that it's not that difficult and easy to apply in your daily dev tasks.</p>
<p>At the end of this article I just want to say that - when you stop learning and experimenting, you start ignoring those opportunities that lie in front of you.</p>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a> to <a target="_blank" href="series/java">Java</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Books I Read in 2021]]></title><description><![CDATA[Overview
With the year coming to an end, when I look back at how it started and how it is going to end, I think I can proudly say that this year was much more exciting, inspiring and full of learnings.
I ended the year 2020 with no books to show, but...]]></description><link>https://chandraji.dev/books-i-read-in-2021</link><guid isPermaLink="true">https://chandraji.dev/books-i-read-in-2021</guid><category><![CDATA[books]]></category><category><![CDATA[Business and Finance ]]></category><category><![CDATA[personal]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Sun, 26 Dec 2021 12:07:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1640519998598/Y8miqWpWJ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-overview">Overview</h2>
<p>With the year coming to an end, when I look back at how it started and how it is going to end, I think I can proudly say that this year was much more exciting, inspiring and full of learnings.</p>
<p>I ended the year 2020 with no books to show, but with the start of the year 2021, I made sure to read at least a book per month. And, here I am bringing you the list of 13 books that I read this year and which you can include in your reading list for the next year.</p>
<p>Without further ado, let's dive into the books I read!</p>
<hr />
<h2 id="heading-the-alchemisthttpsamznto32aj160"><a target="_blank" href="https://amzn.to/32Aj160">The Alchemist</a></h2>
<p>The Alchemist is a novel by Paulo Coelho, a Brazilian author who first published it in 1988. It was originally written in Portuguese and became an international bestseller after being widely translated.</p>
<p>I started the year with none other than "The Alchemist". This was a re-read for me, also my first book I read as non-fiction.</p>
<p>The Alchemist stands out as a love story that rejects the notion that romantic love must be at the centre of people's lives. Each person has a unique destiny that is unaffected by the actions of others. It's the thing you'd do or be if you had all the love and money in the world.</p>
<p>It doesn't matter if you enjoy reading novels or not; there are those that everyone should read, and "The Alchemist" is one of them. It instils faith in love, dreams, and oneself. The finest thing you can do is follow your dreams.</p>
<p>If you have not read it already, then start next year this motivational impetus.</p>
<h2 id="heading-dharmayoddha-kalki-avatar-of-vishnuhttpsamznto30zvg21"><a target="_blank" href="https://amzn.to/30ZvG21">Dharmayoddha Kalki: Avatar of Vishnu</a></h2>
<p>A work of fiction that takes inspiration from the life of Kalki, the idea of Kaliyug and other Mahabharata and Ramayan references. Written by Kevin Missal.</p>
<p>This is part 1 of an awe-inspiring trilogy that I re-read this year and is also my first read on mythological fiction.</p>
<p>The premise is intriguing, as it includes characters from prior Vishnu Avataras such as Parshuram, Ram, and Krishna. As you progress through the book, you'll notice that all of the parts are falling into place in accordance with certain old myths while also establishing some new ones.</p>
<p>I liked how the author strives to give us a full description of weapons and manoeuvres throughout fight scenarios. I would not recommend this book to extremely young readers because there is a lot of violence in this cruel society setup.</p>
<h2 id="heading-satyayoddha-kalki-eye-of-brahmahttpsamznto3pozw4x"><a target="_blank" href="https://amzn.to/3pozW4x">Satyayoddha Kalki: Eye of Brahma</a></h2>
<p>This is part 2 in the trilogy, it continues with a cliff-hanger from part 1 (read part 1 to know the cliff-hanger 😉).</p>
<p>When compared to Dharmayoddha, the storytelling in Satyayoddha has clearly improved, owing to the fact that the premise is now more recognisable to the readers, and they have a better notion of what the characters are like. Kalki channels a few more Avatars in this book and both Narasimha and Varaha are quite impressive with their different philosophical takes on their actions.</p>
<p>There is a lot of action in this book, so the dialogues are short and interchanges are quick, funny and sarcastic at times. The characters might live in Illavarti of unknown times, but they speak like us!</p>
<h2 id="heading-mahayoddha-kalki-sword-of-shivahttpsamznto3en11te"><a target="_blank" href="https://amzn.to/3En11te">Mahayoddha Kalki: Sword of Shiva</a></h2>
<p>This is the last part of the trilogy, here, when we left the numerous characters of this world at end of Satyayoddha Kalki, the threat of war was imminent with so many factions moving against one another. While the personal battles of the main characters were also reaching turning points.</p>
<p>Mahayoddha Kalki takes us back to the multiple stories including Kalki’s journey towards Bhargav Ram‘s abode, Manasa‘s quest for revenge against Kali and the inner struggles for kingship at Illavarti.</p>
<p>Kalki, remains the adorable, good incarnate, a strong warrior who braves all odds and deals with the conspiracies that mark his way throughout the journey to finally become the Avatar of this Yuga.</p>
<p>You should definitely include this in your reading list.</p>
<h2 id="heading-the-richest-man-in-babylonhttpsamznto3z0akob"><a target="_blank" href="https://amzn.to/3z0akOB">The Richest Man in Babylon</a></h2>
<p>The Richest Man in Babylon is a 1926 book by George S. Clason that dispenses financial advice through a collection of parables set 4,000 years ago in ancient Babylon. The book remains in print almost a century after the parables were originally published, and is regarded as a classic of personal financial advice.</p>
<p>This is the book I read for the first time this year and also my first read on personal finance.</p>
<p>How often is that we seek advice on personal finance from experienced people? How often do we implement that advice? And, how exactly are they able to give such solid advice? The Richest Man in Babylon, is the book that asks these questions, considers several scenarios (that are still valid to this date given that the book was first published in 1926), gives a proper plan to personal finance that could lead a person to become rich and have enough in his pocket so that he could enjoy his retirement!</p>
<p>I have done a review on the same book, you can check that out <a target="_blank" href="richest-man-in-babylon">here</a> and please include this to your reading list, it is a must for everyone in my honest opinion.</p>
<h2 id="heading-rogue-lawyerhttpsamznto3eljtco"><a target="_blank" href="https://amzn.to/3elJTcO">Rogue Lawyer</a></h2>
<p>Rogue Lawyer is a novel by John Grisham. It is a legal thriller about unconventional street lawyer Sebastian Rudd.</p>
<p>The plot follows Rudd's (protagonist) involvement in a number of seemingly "unwinnable" cases, as well as the steps he takes to improve his client's chances. All of the narratives are intricately linked to Rudd's personal life and are loosely connected. This has an incredibly intrusive and objective look at a court and gets right into the heart of the realities of trying cases, with a remarkably refreshing perspective.</p>
<p>It was really a thrilling read of how a lawyer (kind of honest but rogue) fights against the system at every turn shown through a collection of criminal cases and how he tackles his day-to-day life, especially the encounters with his wife.</p>
<h2 id="heading-the-immortals-of-meluhahttpsamznto3yxerko"><a target="_blank" href="https://amzn.to/3yXeRkO">The Immortals of Meluha</a></h2>
<p>The Immortals of Meluha is the first book of Amish Tripathi, the first book of Amishverse, and also the first book of Shiva Trilogy. The story is set in the land of Meluha and starts with the arrival of the Shiva. The Meluhans believe that Shiva is their fabled saviour Neelkanth.</p>
<p>The story is a perfect blend of modern-day technologies and Hindu mythological legends. Every character is described well and in an informative manner. Whether it is a war sequence or a simple conversation, Amish's writing hooked the readers. The narrations are explicit, as well as the language.</p>
<p>Amish creates a world of fantasy in his book, including corruption, caste system, unnecessary laws, and enters the readers' hearts. I definitely recommend this book; if you're a mythological fan, don't miss out on this book.</p>
<h2 id="heading-the-secret-of-the-nagashttpsamznto33ngdhm"><a target="_blank" href="https://amzn.to/33NGdhM">The Secret Of The Nagas</a></h2>
<p>In the second part of the Shiva trilogy, the hunt is on. The sinister Naga warrior has killed his friend and now stalks his wife. Shiva, who is the prophesied destroyer of evil, will not rest till he finds his demonic adversary. His vengeance and the path to evil will lead him to the door of the Nagas, the serpent people. Of that he is certain. In a journey that will take him across the length and breadth of ancient India, Shiva searches for the truth in a land of deadly mysteries – only to find that nothing is what it seems.</p>
<p>This book is full of turns and will have you skipping pages like never before.</p>
<h2 id="heading-the-oath-of-the-vayuputrashttpsamznto3eutwr4"><a target="_blank" href="https://amzn.to/3EuTwR4">The Oath of the Vayuputras</a></h2>
<p>In the last part, everything is explained ideally so that readers don't have any loose ends. This book is all about the equilibrium between virtue and vice. It portrays that whenever darkness rises, it will be destroyed by the light. However, the people chosen by God will build a new path despite the loss they have to endure. The battle demanded sacrifices, and in this story, it took everything from Shiva. Even his reason to smile and live.</p>
<h2 id="heading-i-will-teach-you-to-be-rich-no-guilt-no-excuses-no-bs-just-a-6-week-program-that-workshttpsamznto3en7oln"><a target="_blank" href="https://amzn.to/3en7olN">I Will Teach You to Be Rich: No Guilt. No Excuses. No BS. Just a 6-Week Program That Works</a></h2>
<p>I Will Teach You To Be Rich is a 2009 personal finance book by Ramit Sethi who writes a blog of the same name.</p>
<p>I Will Teach You to Be Rich is aimed at 20-to-35-year-olds, and it’s essentially a guide to getting your finances on track. The book covers a six-week program that automates saving and jump-starts investing — with more than a little information on banking, budgeting and entrepreneurship along the way.</p>
<p>This was a very fun read that has a crazy perspective on how to spend money. It is not like any other personal finance book out there, it gives you the required framework so that you can enjoy your life and have enough saved to enjoy your retirement also.</p>
<h2 id="heading-think-and-grow-richhttpsamznto3psjwtv"><a target="_blank" href="https://amzn.to/3psJWtv">Think and Grow Rich</a></h2>
<p>Think and Grow Rich is a book written by Napoleon Hill in 1937 and promoted as a personal development and self-improvement book.</p>
<p>This book tries to explain why some people amass great fortunes while others fail to make ends meet. In one of the chapters on "Desire", Napoleon Hill tells us the story of his child, born deaf-mute. Seeing him, he says to himself “I want my son to hear and speak, I want him to have a normal life.”</p>
<p>The book discusses the concepts of dominant thinking, desire, faith, subconscious auto-suggestion, imagination, taking action, making decisions, having a mastermind group, power of sex transmutation and how to defeat the six ghosts of fear.</p>
<p>It is again a must-read, give a lot of time while reading this book, don't skip-read this, try to understand what each line is trying to tell and the meaning it contains.</p>
<h2 id="heading-skipping-christmas-christmas-with-the-krankshttpsamznto3eu7jag"><a target="_blank" href="https://amzn.to/3Eu7jag">Skipping Christmas: Christmas with The Kranks</a></h2>
<p>Skipping Christmas is a comedic novel by John Grisham. It was published by Doubleday on November 6, 2001, and reached #1 on The New York Times Best-Seller List on December 9 that year.</p>
<p>While it stresses giving back to the community, like most other secular offerings throughout the Christmas season, it's a reasonably clean, enjoyable read for the holidays. If you can get beyond that stumbling block, though, this could be a delightful way to spend your holiday break.</p>
<p>The festive outline of the book is not limited to Christmas, it can have parallels with other festivities, but it is a good read for the winter season without a doubt.</p>
<h2 id="heading-the-girl-on-the-trainhttpsamznto3z2bsmr"><a target="_blank" href="https://amzn.to/3z2BSmr">The Girl on the Train</a></h2>
<p>The Girl on the Train is a 2015 psychological thriller novel by British author Paula Hawkins that gives narratives from three different women about relationship troubles and, for the main protagonist, alcoholism.</p>
<p>It is a fantastic read, Hawkins does a great job with both the mystery elements, the character development and with great attention to detail, it is a tight, suspenseful chiller with a dubious narrator, who tries to solve the mystery of a woman's disappearance.</p>
<p>I recently finished this book and my god, you will definitely love every page of this book. Don't wait and grab a copy of yours today.  </p>
<hr />
<h2 id="heading-winding-up">Winding Up</h2>
<p>With the year coming to an end, I am taking a week break from reading books. I am linking all the books below for you to purchase or you can directly purchase them from your nearest retail outlet.</p>
<p>Enjoy your holidays and a happy new year 🎉🎉🎉</p>
<h2 id="heading-links">Links</h2>
<ol>
<li><a target="_blank" href="https://amzn.to/32Aj160">The Alchemist</a></li>
<li><a target="_blank" href="https://amzn.to/30ZvG21">Dharmayoddha Kalki: Avatar of Vishnu</a></li>
<li><a target="_blank" href="https://amzn.to/3pozW4x">Satyayoddha Kalki: Eye of Brahma</a></li>
<li><a target="_blank" href="https://amzn.to/3En11te">Mahayoddha Kalki: Sword of Shiva</a></li>
<li><a target="_blank" href="https://amzn.to/3z0akOB">The Richest Man in Babylon</a></li>
<li><a target="_blank" href="https://amzn.to/3elJTcO">Rogue Lawyer</a></li>
<li><a target="_blank" href="https://amzn.to/3yXeRkO">The Immortals of Meluha</a></li>
<li><a target="_blank" href="https://amzn.to/33NGdhM">The Secret Of The Nagas</a></li>
<li><a target="_blank" href="https://amzn.to/3EuTwR4">The Oath of the Vayuputras</a></li>
<li><a target="_blank" href="https://amzn.to/3en7olN">I Will Teach You to Be Rich: No Guilt. No Excuses. No BS. Just a 6-Week Program That Works</a></li>
<li><a target="_blank" href="https://amzn.to/3psJWtv">Think and Grow Rich</a></li>
<li><a target="_blank" href="https://amzn.to/3Eu7jag">Skipping Christmas: Christmas with The Kranks</a></li>
<li><a target="_blank" href="https://amzn.to/3z2BSmr">The Girl on the Train</a></li>
</ol>
<hr />
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Blockchain Fundamentals, Cryptocurrencies and Open Source]]></title><description><![CDATA[Overview
This article is divided into 4 sections, 1st section is about blockchain fundamentals, 2nd section deals with the key features of building a blockchain mobile app, 3rd section dives into cryptocurrency wallets available for us to use and 4th...]]></description><link>https://chandraji.dev/blockchain-fundamentals</link><guid isPermaLink="true">https://chandraji.dev/blockchain-fundamentals</guid><category><![CDATA[Blockchain]]></category><category><![CDATA[Web3]]></category><category><![CDATA[Cryptocurrency]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Sat, 25 Dec 2021 10:22:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1640427069260/JwmYC4-O4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-overview">Overview</h2>
<p>This article is divided into 4 sections, 1<sup>st</sup> section is about blockchain fundamentals, 2<sup>nd</sup> section deals with the key features of building a blockchain mobile app, 3<sup>rd</sup> section dives into cryptocurrency wallets available for us to use and 4<sup>th</sup> section outlines how the opensource is driving the blockchain revolution.</p>
<p>You can jump onto any section you like to read, the order of reading these sections are not related.</p>
<hr />
<h2 id="heading-blockchain-fundamentals">Blockchain Fundamentals</h2>
<p>Blockchain technology is a constantly evolving, secure and shared record-keeping system in which each user has a copy of the data, which can only be modified if all parties involved in a transaction agree. This section examines the fundamentals of blockchain technology.</p>
<h3 id="heading-a-blockchain-transaction">A Blockchain Transaction</h3>
<p>To understand the fundamentals of the blockchain, we need to understand how a transaction can be added to the existing blockchain. This can be done by going through a few important steps, as illustrated in the below figure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640427151158/95A8tJwIo.jpeg" alt="fig1.jpeg" /></p>
<ol>
<li>Assume that user 1 wants to send X amount of digital bitcoins to user 2. User 1 then initiates the transaction.</li>
<li>A transaction is initiated by user 1's node by first making it and then digitally signing it with its private key. A transaction in a blockchain can reflect a range of actions.</li>
<li>A peer-to-peer (P2P) network broadcasts the desired transaction to each individual computer (or node).</li>
<li>Individual nodes receive the request and attempt to validate the transaction using cryptographic techniques. The miner node is the final node in the validation chain. These miner nodes are compensated in Bitcoin.</li>
<li>The verified blocks are now added to the blockchain network. Hashing is used to connect these nodes.</li>
<li>The approved transactions are then recorded in a public ledger. Transactions are completed and the ledger is updated after the block is added to an existing chain.</li>
</ol>
<h3 id="heading-cryptography-techniques-used-in-blockchain">Cryptography Techniques Used in Blockchain</h3>
<p>Hashing, public-private key mechanisms, and digital signatures are the key cryptographic techniques used by the blockchain community. In this case, a hash feature is implemented to offer each user the opportunity to view the blockchain in its entirety. Blockchain characteristically uses the SHA-256 hashing algorithm. Public-private key pairs are used to gain access to the information and allow transactions. Digital signatures are also used for multi-signature contracts and digital wallets on the blockchain, as well as to ratify transactions by signing them securely (offline).</p>
<h3 id="heading-working-of-a-blockchain-network">Working of A Blockchain Network</h3>
<p>In a blockchain network, each node holds a complete copy of the distributed ledger. The four fields of a block in this network are the block number, the data field, the hash value, and the nonce. Miners adjust the value of nonce to make it a suitable number for hashing the value of a block. A nonce is a random whole number that is a 32-bit (4-byte) field that is changed by miners to make it an acceptable number for hashing the value of a block. In addition, the chain of blocks is generated by applying the hash of the previous block to the current block. The previous block's hash is stored in the field prior.</p>
<p>Four zeros are used to begin the hash value. This determines whether or not a block is valid. Each new hash value is created by combining the old hash value, the new transaction block, and a nonce. The hash cash difficulty factor is determined by the number of leading zeroes required in the hash output. The difficulty is tweaked so that block production stays consistent at about one block per ten minutes. The more difficult it is to alter the blockchain, the tougher it is to overwrite the blockchain and double-spend coins.</p>
<h3 id="heading-winding-up">Winding Up</h3>
<p>Blockchain technology is widely accepted by a variety of businesses. It has opened up a plethora of opportunities in the areas of healthcare, finance, accountancy and the online marketplace. The adoption of blockchain technology is expected to grow manifold in the coming years, offering quite a wide range of jobs for young aspirants.</p>
<hr />
<h2 id="heading-basics-of-building-a-blockchain-app">Basics of Building a Blockchain App</h2>
<p>A blockchain stores data in such a way that it is almost impossible to alter or hack it. In this section, we will go through the key features of the blockchain, look at blockchain development platforms, and view the steps in the blockchain mobile app development process.</p>
<h3 id="heading-some-blockchain-apps">Some Blockchain Apps</h3>
<p>While blockchain development began with cryptocurrencies, it is no longer limited to them. Blockchain applications have now gone beyond cryptocurrency and into a variety of other sectors. As we all know, the main benefit of blockchain technology is that it ensures maximum data transparency and security, helping businesses and organisations save a significant amount of money on standard security methods.</p>
<p>The following are some useful blockchain apps.</p>
<p><strong>1. Filament:</strong> This is an excellent example of a blockchain-based IoT app that uses blockchain data ledger systems to manage data processed by software and microchip hardware. Several linked devices can communicate information over the blockchain and keep in sync with the help of the app.</p>
<p><strong>2. KYC-chain:</strong> For many firms, completing Know Your Customer (KYC) documentation is a must. This simple and effective blockchain-based program streamlines the entire process of handling client documentation across administrative and criminal databases in many nations.</p>
<p><strong>3. BurstIQ:</strong> BurstIQ is healthcare software that uses Big Data and blockchain technology to allow patients and doctors to share and collaborate on vital medical information.</p>
<h3 id="heading-development-platforms">Development Platforms</h3>
<p>There are more than two dozen blockchain development platforms. A few of them are described below.</p>
<p><strong>1. Multichain:</strong> With this powerful platform, developers can create and deploy private blockchains that can be used by a variety of businesses.</p>
<p><strong>2. Hyperledger:</strong> This distributed ledger technology is used to govern the connected ecosystem of things and supply chains. This advanced blockchain platform has received a lot of acclaims.</p>
<p><strong>3. Ethereum:</strong> A versatile opensource blockchain technology, Ethereum is commonly used for decentralised apps, smart contracts and initial coin offerings (ICOs).</p>
<p><strong>4. EOS:</strong> The EOS platform’s goal is to create a reliable smart contract function. It’s also appropriate for modern businesses’ need for highly scalable and decentralised storage and hosting.</p>
<p>Blockchain systems are available in a wide range of sizes and shapes. Determining which platform is better and more suitable for one's application needs might be confusing. The solution is contingent on the desired capabilities and use-cases.</p>
<p><strong>Choosing the most appropriate platform:</strong> The key to your project’s success lies in determining the platform’s character. Platforms based on cryptocurrencies as well as those based on smart contracts are available.</p>
<p><strong>Decide whether you need smart contracts or not:</strong> You need to determine if your app needs smart contracts or not.</p>
<p><strong>Selecting the consensus protocol:</strong> The consensus protocol ensures that every new block added to the blockchain is the only version of the truth that all nodes in the blockchain agree on, such as proof of stake, proof of work, proof of elapsed time, and so on.</p>
<p><strong>Choosing the cryptocurrency:</strong> Another challenge is determining whether or not a cryptocurrency is required.</p>
<p><strong>Selecting between a public and private network:</strong> Based on the requirement, you need to decide whether a public or a private network is needed.</p>
<h3 id="heading-process-of-blockchain-mobile-app-development">Process of Blockchain Mobile App Development</h3>
<p>There are mainly five stages in the blockchain app development process.</p>
<p><strong>1. Identify the problem that the blockchain is required to solve:</strong> To begin, thoroughly examine the problem description and create a full report on it. Consider whether you need to create a new app from scratch or if you can just integrate the blockchain into an existing one.</p>
<p><strong>2. Select the best platform for the app:</strong> Select the most appropriate platform for your project. Determine if you need a smart contract app or a crypto-transaction app, as well as the type of network and consensus protocol you'll need.</p>
<p><strong>3. Requirement analysis:</strong> Begin by doing the requirement analysis and evaluating the app idea’s requirements. Do more brainstorming around the idea and, if possible, fine-tune it.</p>
<p><strong>4. Create a blueprint of the idea:</strong> Try to develop the proof of concept that will put the entire app concept into a visual structure.</p>
<p><strong>5. Development of the application:</strong> Develop the application employing best practices. Ensure to build a robust blockchain app.</p>
<h3 id="heading-winding-up">Winding Up</h3>
<p>We’ve covered the basics of blockchain in this essay — its main characteristics, as well as several development platforms and stages for developing blockchain applications. If you find the subject interesting, you can delve deeper into it. There are a variety of resources available on the Internet.</p>
<hr />
<h2 id="heading-cryptocurrency-wallets">Cryptocurrency Wallets</h2>
<p>Cryptocurrencies are getting entrenched in the global financial system slowly and steadily, with certain companies using these to pay their employees too. Hesitancy with respect to their use is slowly ebbing, and you may run the risk of being behind the times if you don’t stay updated on the latest trends in this domain. This section lists the exchanges and wallets you should be aware of in case you want to buy or trade-in cryptocurrencies.</p>
<h3 id="heading-trends-in-cryptocurrencies">Trends in Cryptocurrencies</h3>
<p>Due to the high potential for profit, cryptocurrency trading is considered extremely lucrative, particularly among the younger population. Traditional stock market trading has a lot of restrictions and rules. There are no such limitations in the case of cryptocurrencies, and big profits can be produced immediately. The 'crypto market,' in which 'crypto users' trade various types of cryptocurrencies, is also known as the cryptocurrency industry.</p>
<p>The price of a BitCoin (BTC) was less than one US dollar around 10 years back when it was launched. Today, its price is more than US$ 30,000. A few months ago, its price touched around US$ 60,000, proving it is a very attractive form of investment.</p>
<p>The market capitalisation of cryptocurrencies is around 338 million US dollars, with 13,951 BitCoin ATMs located in different parts of the world, as per a report from Statista.</p>
<h3 id="heading-wallets-and-exchanges">Wallets and Exchanges</h3>
<p>Currently, there are a number of exchanges in the world that offer platforms and wallets for buying and trading cryptocurrencies. These include Web-based environments as well as apps for Android, iPhone and other mobile phone platforms. Crypto users can buy and sell different currencies that are legal tender around the world with ease on these sites.</p>
<p>The major worldwide crypto exchanges in the world that provide wallets and Web platforms for cryptocurrency trading are listed in the below figure. In crypto exchanges, pairings refer to the pairs of cryptocurrencies that are used to buy and sell such coins.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640427259763/bIN_-rYI3.png" alt="fig2.png" /></p>
<p>In the crypto world, there are two types of exchanges and wallets — centralised and decentralised.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640427269884/Ao3ACLUK-.jpeg" alt="fig3.jpeg" /></p>
<h4 id="heading-centralized-exchanges">Centralized Exchanges</h4>
<p>The centralised exchanges and wallets are owned by companies or corporate giants, which record the complete Know Your Customer (KYC) details either through video KYC or paper-based KYC. Users can open accounts in these centralised exchanges and then trade in any cryptocurrency.</p>
<p>The below figure lists some centralized exchanges.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640427285675/PKkGxWZiT.png" alt="fig4.png" /></p>
<h4 id="heading-decentralized-exchanges">Decentralized Exchanges</h4>
<p>Decentralised exchanges are platforms on which the account is opened directly without any intermediate company, and trading is done directly by the crypto users.</p>
<p>The below figure lists some decentralized exchanges.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640427313694/LmhcxQcF-.png" alt="fig5.png" /></p>
<h3 id="heading-winding-up">Winding Up</h3>
<p>The jury is out on the use of cryptocurrencies because these are sometimes used to circumvent the national money transfer system. Some governments prohibit their use in order to prevent money laundering.</p>
<p>In order to incorporate the maximum benefits and features into a real-world scenario, the use of cryptocurrencies in any country demands legislation and procedures. The benefits to society and the corporate sector might be substantial if cryptocurrencies are used for real-time applications and e-governance.</p>
<hr />
<h2 id="heading-open-source-blockchain-revolution">Open Source Blockchain Revolution</h2>
<p>Blockchain is a disruptive technology that is changing the world in a variety of ways. Cryptocurrencies are the most obvious example. This section compares and contrasts this technique with opensource, another revolutionary technology that has transformed software development.</p>
<h3 id="heading-blockchain-characteristics">Blockchain Characteristics</h3>
<p><strong>Immutability:</strong> A hallmark feature of blockchain is that it is incorruptible. Data once saved in a block cannot be changed without breaking the chain.</p>
<p><strong>Decentralisation:</strong> Blockchain does not require a central authority to maintain the ledger. All nodes in the network have a copy of the ledger that gets updated with every transaction.</p>
<p><strong>Enhanced security:</strong> Decentralisation and consensus mechanisms built into blockchain make it highly secure, as every transaction has to be verified with ‘proof of work’.</p>
<p><strong>Distributed:</strong> The blockchain ledger is not a singular entity in the hands of a few; instead it is a shared entity that is accessible and maintained by everyone in the network.</p>
<p><strong>Transparency:</strong> Every addition to the blockchain requires consensus from all nodes in the peer-to-peer network. This makes every transaction transparent and public.</p>
<h3 id="heading-open-source-characteristics">Open Source Characteristics</h3>
<p><strong>Transparency:</strong> The founding principle of open source is to make the source code of the project public. This enhances the transparency of the project, as every detail that goes into its development can be freely accessed by anyone.</p>
<p><strong>Enhanced security:</strong> Finding security loopholes in the software is way easier when the code is non-proprietary and is publicly available. This naturally enhances the security of the software or, at the very least, can help raise public awareness about the potential security-related pitfalls.</p>
<p><strong>Collaboration:</strong> The primary purpose of open source software is to encourage other developers to collaborate and contribute to the development of the software. This makes open source development, by nature, a community experience.</p>
<p><strong>Modifiability:</strong> Open source software can be modified and re-distributed to solve different problems. This is the case with Linux, as its modified ‘distributions’ are used in various different gadgets and computers.</p>
<p><strong>Decentralisation:</strong> One can argue that open source software is not inherently decentralised as making changes to the main project still requires the approval of the project moderator(s) and the owner(s). But if perceived from a different angle, given that the source code can be modified and re-distributed under proper licensing, this gives the developer the autonomy to use the software as and how desired thus making the process decentralised.</p>
<h3 id="heading-convergent-evolution">Convergent Evolution</h3>
<p>Opensource software and blockchain are two independent technologies with different themes and strategies for addressing different problems. When we compare the attributes of blockchain to open source, however, we discover certain similarities.</p>
<p>In evolutionary biology, the term 'convergent evolution' refers to the occurrence in which animals from distinct time periods or epochs acquire similar characteristics. This can be seen in molecular biology, animal morphology, and even plant morphology. This holds true for technical breakthroughs as well. We produce new technologies every day to address a wide range of problems; nonetheless, there are underlying patterns in the motivations that drive the creation of these technologies.</p>
<h3 id="heading-winding-up">Winding Up</h3>
<p>Blockchain is new, but open source technology has been around for a long time. In my perspective, the rise of open source technology has had a direct impact on the birth of blockchain. Both technologies are focused on transferring power from a small number of people to a big number of people. Both strive to increase product security and transparency while also promoting fairness and collaboration. While the applications of open source and blockchain are diverse, the motives for their creation are similar. It is safe to assume that open source and blockchain share many characteristics in common and are hence the product of technological convergence.</p>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Big Data Open Source Frameworks]]></title><description><![CDATA[Big Data is a term used to define large scale data sets that are too complex to be manipulated with basic DBMS. Handling Big Data requires sophisticated hardware and software technologies.
Just as open-source has been the primary reason for the Big D...]]></description><link>https://chandraji.dev/big-data-open-source-frameworks</link><guid isPermaLink="true">https://chandraji.dev/big-data-open-source-frameworks</guid><category><![CDATA[big data]]></category><category><![CDATA[Scala]]></category><category><![CDATA[hadoop]]></category><category><![CDATA[spark]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Thu, 02 Dec 2021 12:48:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1638445825326/h1sZBUeYa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Big Data is a term used to define large scale data sets that are too complex to be manipulated with basic DBMS. Handling Big Data requires sophisticated hardware and software technologies.</p>
<p>Just as open-source has been the primary reason for the Big Data revolution, so has it been at the forefront of developing tools to counter the challenges that we face with the data. And while there are hundreds of popular open-source projects that are focused on Big Data management, in this article, we shall focus on the top three that caught my attention.</p>
<p>We shall discuss the Hadoop framework, the Spark analytics engine and the Kafka framework.</p>
<hr />
<h3 id="heading-is-big-data-hard-to-handle">Is Big Data Hard To Handle?</h3>
<ul>
<li><p>Almost 90% of the Big Data we produce today is unstructured and there are no predefined models that it adheres to. And there is no quick and easy way to access and analyse unstructured data.</p>
</li>
<li><p>Not only is Big Data unstructured, but it is also extremely complex. This means traversing through it requires advanced algorithms that are being run on top of grade-A machinery and not everyone can afford that.</p>
</li>
<li><p>We have multiple sources from which we accrue data and there are no clean ways to integrate disparate data from so many sources.</p>
</li>
<li><p>With Big Data comes big mistakes. Storing massive and complex data in a secure manner is a really daunting challenge. It is also the need of the hour. Since the beginning of the pandemic, more people are stuck at home with their computers than ever before and cybercrime and data theft have gone up by 400%.</p>
</li>
</ul>
<h3 id="heading-open-source-softwares">Open Source Softwares</h3>
<h4 id="heading-hadoop">Hadoop</h4>
<p>Developed by the Apache Foundation, Hadoop is a framework for Big Data management. It uses distributed systems architecture, which has the ability to store and easily access vast amounts of data.</p>
<p>While there are many different types of Big Data management solution software, what makes Hadoop stands out are 3 components, HDFS, MapReduce and YARN.</p>
<ul>
<li>HDFS (Hadoop Distributed File System)</li>
</ul>
<p>The Hadoop Distributed File System (HDFS) is a powerful and dynamic tool that is efficient at handling Big Data. HDFS breaks down Big Data into blocks and the default size of each block is 128MB. This makes accessing data simple, as the HDFS only has to access the specific block of data that the user is searching for. HDFS is a resilient framework, thanks to its replication methodology. To maintain the accessibility of the data even when one of the distributed system blocks is down, HDFS replicates that block data in a three-fold fashion making it robust to avoid failures or inconsistency.</p>
<ul>
<li>MapReduce</li>
</ul>
<p>Storing and accessing Big Data, with all its complications and difficulties, is still the easy part. The real fun begins when we try to process Big Data. MapReduce is exactly what it sounds like, it maps the data followed by reducing it. MapReduce takes the data as input and splits it into different parts. It then maps each individual component within each part. Then the data is shuffled and sorted into clusters of homogenous data. The data is then reduced by integrating homogenous data and assigning IDs, which give the smaller final output.</p>
<ul>
<li>YARN (Yet Another Resource Negotiator)</li>
</ul>
<p>A Hadoop environment is constrained to the number of resources it has, namely, CPUs, memory units, storage space, etc. But since Hadoop is designed to be able to run multiple processes at the same time, a mechanism for allocating resources is necessary to make sure there are no deadlocks and every task is accomplished in its desired time period. Now, YARN comes into play, when a job requires the resources to run, the application manager sends a request to the node manager to allocate the physical resources. The node manager then sends the resources to the resource manager, which assigns the physical resource to the client process.</p>
<h4 id="heading-spark">Spark</h4>
<p>While HDFS, MapReduce and YARN are the three major defining components of Hadoop, the Hadoop ecosystem has more tools to offer when it comes to Big Data processing, one such tool is Apache Spark. Spark is one of the few tools in the industry that combines Big Data analytics tools with Machine Learning and AI. Spark is 100 times faster than MapReduce in processing data. Spark computations are done in memory itself, it has the ability to perform both batch processing real-time processing of data. Spark is also comparatively lightweight as most of it is written in <a target="_blank" href="series/scala">Scala</a>.</p>
<p>Following are the Spark components:</p>
<ul>
<li>Spark Core</li>
<li>Spark SQL</li>
<li>Spark Streaming</li>
<li>Spark MLib</li>
<li>Spark GraphX</li>
</ul>
<h4 id="heading-kafka">Kafka</h4>
<p>Apache Kafka is a framework implementation of a software bus using stream processing. If you break down an information transaction on the Internet, it's essentially nothing but an exchange of information between 2 systems which we sometimes call producers and consumers. Each transaction can be thought of as integration between producer and consumer. In order to simplify complex integrations, Kafka acts as a broker between producer and consumer, which can be well integrated with Hadoop and Spark.</p>
<p>Kafka consists of Brokers and a Zookeeper.</p>
<ul>
<li>Broker</li>
</ul>
<p>A broker is a Kafka server that runs in a Kafka cluster. Each broker divides a unique transaction between the producer and consumer into a topic. Now, these topics within the broker are used to consume and broadcast the messages in an asynchronous fashion.</p>
<ul>
<li>Zookeeper</li>
</ul>
<p>In order to define topics and keep a metadata record of all the topics defined in the cluster, Kafka uses Zookeeper which is a replicated distributed log with a file system API built on top. It keeps a record of all the topics within all the nodes and also keeps track of which nodes are down and which are up and running.</p>
<h3 id="heading-where-to-go-from-here">Where To Go From Here?</h3>
<p>The tools and frameworks discussed in this article are a high-level overview of the innovation and efforts taking place in the Big Data management industry. There are many more open source tools and frameworks that can be learned and used for Big Data management.</p>
<p>Google all the available resources and check which fits your Big Data management need to the point and become a Big Data Engineer one step at a time.</p>
<p>Books to check out more on Big Data Engineering:</p>
<ul>
<li><a target="_blank" href="https://amzn.to/3DbHhYN">Big Data Simplified</a></li>
<li><a target="_blank" href="https://amzn.to/3phG2CF">Big Data Analytics, Introduction to Hadoop, Spark, and Machine-Learning</a></li>
<li><a target="_blank" href="https://amzn.to/3rvFcoE">Big Data and Analytics</a></li>
</ul>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Preptember - Prepare For HacktoberFest 2021]]></title><description><![CDATA[Hey everyone, HacktoberFest is around the corner (just 15 days away) and for all those who are searching for repositories to contribute to this October, worry not, I have gathered a list of repositories best suited for beginners in open source.

What...]]></description><link>https://chandraji.dev/preptember-prepare-for-hacktoberfest-2021</link><guid isPermaLink="true">https://chandraji.dev/preptember-prepare-for-hacktoberfest-2021</guid><category><![CDATA[Python]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Scala]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Wed, 15 Sep 2021 12:11:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1631707189635/aqY7K57u6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey everyone, HacktoberFest is around the corner (just 15 days away) and for all those who are searching for repositories to contribute to this October, worry not, I have gathered a list of repositories best suited for beginners in open source.</p>
<hr />
<h3 id="heading-what-is-hacktoberfest">What is HacktoberFest?</h3>
<p>Hacktoberfest 2021 will be a month-long virtual festival event to celebrate open source contributions. It is the easiest way to get into open source!</p>
<p>During the entire month of October 2021, all you have to do is contribute to any open-source projects and open at least 4 pull requests. Yes, any project and any kind of contribution. You don’t need to be an expert in programming or coding. It can be a bug fix, improvement, or even a documentation change (I don't recommend it, explore where you can do code changes if there are not many)! And win an awesome T-shirt and awesome stickers.</p>
<p>The Hacktoberfest’s simple plain objective is:</p>
<p><strong>Support open source and earn a limited-edition T-shirt!</strong></p>
<p>But, it’s not just about the t-shirts or stickers. It's about supporting open source. It's about celebrating open source and giving it back. If you’ve never contributed to open source before, this is the perfect time to get started because Hacktoberfest provides a large list of available contribution opportunities (and yes, there are always plenty for beginners too).</p>
<p><strong><a target="_blank" href="https://hacktoberfest.digitalocean.com/">HacktoberFest 2021</a></strong></p>
<p>Let's look at some of the most awesome beginner-friendly repositories that you can look at and start your contributions right off the bat.</p>
<hr />
<h3 id="heading-for-complete-beginners">For Complete Beginners</h3>
<p>This section contains repositories for complete beginners. You can go and learn about first contributions and how to raise PRs.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></strong></li>
</ul>
<p>Yeah, self-promotion, I know but you can still check this out, no need to wait till October, go ahead and contribute to this and be more comfortable while doing other contributions during HacktoberFest.</p>
<blockquote>
<p>Note: During HacktoberFest, this repository accepts only 1 contribution per user.</p>
</blockquote>
<ul>
<li><strong><a target="_blank" href="https://github.com/firstcontributions/first-contributions">First Contributions</a></strong></li>
</ul>
<p>Another awesome repository for you to check. This project aims to simplify and guide the way beginners make their first contribution.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/zero-to-mastery/start-here-guidelines">Start Here Guidelines</a></strong></li>
</ul>
<p>Again, an awesome repository for you to start with. This is hosted by one of my favourite institutions, Zero To Mastery. They always create awesome projects for people to contribute to during HacktoberFest. You can check out their previous projects as well <a target="_blank" href="https://github.com/zero-to-mastery">here</a>.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/zero-to-mastery/resources">Resources</a></strong></li>
</ul>
<p>Add meaningful resources to the list and help others on their learning journey. This is one of the best resources repository available on GitHub. Do check it out and contribute that link to a course or article you feel is important for others to take note of.</p>
<h3 id="heading-for-css-enthusiasts">For CSS Enthusiasts</h3>
<ul>
<li><strong><a target="_blank" href="https://github.com/sButtons/sbuttons">sButtons</a></strong></li>
</ul>
<p>Simple buttons you can use easily for your next project. Check out this and contribute the next button design you have in mind.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/zero-to-mastery/CSS_Grid_LearnGame">CSS Grid Learn Game</a></strong></li>
</ul>
<p>This is a game to learn CSS Grid in a Game Mode Style, to make learning more fun! Contribute and make this even more interesting.</p>
<h3 id="heading-for-python-players">For Python Players</h3>
<ul>
<li><strong><a target="_blank" href="https://github.com/CiviWiki/OpenCiviWiki">OpenCiviWiki</a></strong></li>
</ul>
<p>It is an open-source, non-profit community, working to develop a democratic engagement web system. Check out their <code>README.md</code> file and give a head start to your contributions.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/python-babel/babel">Babel</a></strong></li>
</ul>
<p>Babel is a Python library that provides an integrated collection of utilities that assist with internationalizing and localizing Python applications (in particular web-based applications). An awesome library you can get your name on!</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/Kinto/kinto">Kinto</a></strong></li>
</ul>
<p>Kinto is a minimalist JSON storage service with synchronisation and sharing abilities. Check out their easy-pick issues.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/rbreaves/kinto">Kinto.sh</a></strong></li>
</ul>
<p>It provides Mac-style shortcut keys for Linux &amp; Windows. Seamless copy and paste with all apps and terminals. The zero effort solution. Well, go ahead and make your own shortcuts.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/borgbackup/borg">BorgBackup</a></strong></li>
</ul>
<p>BorgBackup (short: Borg) is a deduplicating backup program. Optionally, it supports compression and authenticated encryption. Search for easy label issues and backup like never before.</p>
<p><strong>Other Repositories (that you might already know)</strong></p>
<ul>
<li><a target="_blank" href="https://github.com/ansible/ansible">Ansible</a></li>
<li><a target="_blank" href="https://github.com/python/mypy">Mypy</a></li>
<li><a target="_blank" href="https://github.com/bokeh/bokeh">Bokeh</a></li>
<li><a target="_blank" href="https://github.com/pytest-dev/pytest">Pytest</a></li>
</ul>
<h3 id="heading-for-javascript-lovers">For JavaScript Lovers</h3>
<ul>
<li><strong><a target="_blank" href="https://github.com/osmlab/name-suggestion-index">Name Suggestion Index</a></strong></li>
</ul>
<p>The goal of this project is to maintain a canonical list of commonly used features for suggesting consistent spelling and tagging in OpenStreetMap. Well, this is your chance to be a contributor for OpenStreetMap.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/DAVFoundation/missioncontrol">MissionControl</a></strong></li>
</ul>
<p>Mission Control is a service running on the DAV network, and serving as a marketplace connecting DAV users, vehicles, and services. Go ahead and contribute to this awesome DAV running service and sharpen your networking skills using javascript.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/pouchdb/pouchdb">PouchDB</a></strong></li>
</ul>
<p>PouchDB is an open-source JavaScript database inspired by Apache CouchDB that is designed to run well within the browser. PouchDB was created to help web developers build applications that work as well offline as they do online. Help this awesome project grow with your innovative ideas.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/bevacqua/dragula">Dragula</a></strong></li>
</ul>
<p>Have you ever wanted a drag and drop library that just works? That doesn't just depend on bloated frameworks, that has great support? That actually understand where to place the elements when they are dropped? That doesn't need you to do a zillion things to get it to work? If so, then this is the right place for you to contribute your ideas.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/Kinto/kinto.js">Kinto.js</a></strong></li>
</ul>
<p>The idea is to persist data locally in the browser by default, then synchronizing them with the server explicitly when connectivity is guaranteed. It is an offline-first javascript client for kinto, do check it out and contribute.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/emberjs/ember.js">Ember.js</a></strong></li>
</ul>
<p>Ember.js is a JavaScript framework that greatly reduces the time, effort and resources needed to build any web application. It is focused on making you, the developer, as productive as possible by doing all the common, repetitive, yet essential, tasks involved in most web development projects. Contribute and help developers be more productive.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/TryGhost/Ghost">Ghost</a></strong></li>
</ul>
<p>Ghost gives creators tools to launch their own subscription business. They are redefining the creator economy. Go ahead if you are a creator or want to support their cause, it will be amazing.</p>
<p><strong>Other Repositories (that you might already know)</strong></p>
<ul>
<li><a target="_blank" href="https://github.com/vercel/hyper">Hyper</a></li>
<li><a target="_blank" href="https://github.com/moment/moment">Moment</a></li>
<li><a target="_blank" href="https://github.com/facebook/react">React</a></li>
<li><a target="_blank" href="https://github.com/facebook/react-native">React Native</a></li>
<li><a target="_blank" href="https://github.com/vercel/next.js">Next.js</a></li>
<li><a target="_blank" href="https://github.com/electron/electron">Electron</a></li>
<li><a target="_blank" href="https://github.com/facebook/jest">Jest</a></li>
</ul>
<h3 id="heading-for-scala-functionaries">For Scala Functionaries</h3>
<ul>
<li><strong><a target="_blank" href="https://github.com/scalameta/metals">Metals</a></strong></li>
</ul>
<p>Scala language server with rich IDE features 🚀. Go ahead and start contributing to this awesome repository.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/twitter/util">Twitter Util</a></strong></li>
</ul>
<p>This project is used in production at Twitter (and many other organizations) and is being actively developed and maintained. You can check out their contributing guidelines and become a part of the Twitter developer network.</p>
<ul>
<li><strong><a target="_blank" href="https://github.com/playframework/playframework">Play Framework</a></strong></li>
</ul>
<p>The Play Framework combines productivity and performance making it easy to build scalable web applications with Java and Scala. Play is developer-friendly with a "just hit refresh" workflow and built-in testing support. With Play, applications scale predictably due to a stateless and non-blocking architecture. By being RESTful by default, including assets compilers, JSON &amp; WebSocket support, Play is a perfect fit for the modern web &amp; mobile applications. Go ahead and contribute to this beast of a framework.</p>
<hr />
<p>There are so many repositories that I want to include, but that would just make this a messy article. Keeping things short and simple, let's move on to what you should do now.</p>
<p>Take this as homework and go over <a target="_blank" href="https://github.com/">GitHub</a> or <a target="_blank" href="https://about.gitlab.com/company/">GitLab</a> and search for beginners issues and repositories and see which resonates with you and just without thinking much, start with your first contributions during this HacktoberFest 2021! All The Best!</p>
<blockquote>
<p>Note: Do not do meaningless contributions like adding extra space or changing the font in documentation, add your programmer thoughts to it before making contributions and explore, give it as much time as it needs for your meaningful contributions to reflect in your choice of project.</p>
</blockquote>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Scala Vs Python Syntax Cheat Sheet]]></title><description><![CDATA[There are about 8 million Python developers around the world and it's also the top programming language people want to learn, but why is that? Why not any other language but Python? Let me tell you, Python offers a lean learning curve, with just 2-3 ...]]></description><link>https://chandraji.dev/scala-vs-python-syntax-cheat-sheet</link><guid isPermaLink="true">https://chandraji.dev/scala-vs-python-syntax-cheat-sheet</guid><category><![CDATA[Python]]></category><category><![CDATA[Scala]]></category><category><![CDATA[Developer]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[General Advice]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Tue, 14 Sep 2021 10:25:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1631614393503/8Ke5pWy6oB.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There are about 8 million Python developers around the world and it's also the top programming language people want to learn, but why is that? Why not any other language but Python? Let me tell you, Python offers a lean learning curve, with just 2-3 days of hands-on Python anyone can start developing applications (they might not be technically sound software initially), it's syntax is one of the easiest to learn due to its plain english like code, it offers flexibility from both domains either object-oriented or functional programming (not so much FP, but it has its benefits) and it is used in almost every field of software engineering.</p>
<p>The only drawback people face when working with Python is related to its speed of executing programs. But is there any other programming language as easy to understand and to get started to work with? Yep, there is, Scala comes to the rescue!</p>
<p>Python faces speed issues mainly due to its interpreted nature, whereas Scala is a compiled language that offers dynamic typing as well (close to 90%), many new features in Python like pattern matching are already present in Scala since the beginning, there are awesome syntactic sugars in Scala that allows us to write even less code when compared to Python and also Scala being a functional programming language does not shy away from object-oriented programming as it is run over JVM.</p>
<p>When it comes to the syntax of these programming languages, there are a lot of similar patterns and some differences as well, but overall they both offer a lean learning curve with endless opportunities in the software engineering world.</p>
<p>So, let's discuss those similarities and differences in the form of a cheat sheet, which not only helps in refreshing some concepts from Python/Scala but also acts as a guide to learn Python or Scala for someone coming from the Scala or Python background respectively.</p>
<p>This will be a to-the-point kind of article, with little to no explanation but with necessary links wherever needed.</p>
<p>So, let's get started!</p>
<hr />
<h3 id="heading-how-to-import">How To Import?</h3>
<p>In Python importing a library can look like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> math.*

<span class="hljs-comment"># OR</span>

<span class="hljs-keyword">import</span> math.pow

<span class="hljs-comment"># OR</span>

<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> pow, sqrt

<span class="hljs-comment"># OR</span>

<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> sqrt <span class="hljs-keyword">as</span> squareRoot
</code></pre>
<p>In Scala importing a library can look like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> scala.math._

<span class="hljs-comment">// OR</span>

<span class="hljs-keyword">import</span> scala.math.BigInt

<span class="hljs-comment">// OR</span>

<span class="hljs-keyword">import</span> scala.math.{BigInt, BigDecimal}

<span class="hljs-comment">// OR</span>

<span class="hljs-keyword">import</span> scala.math.{BigInt =&gt; BInt}
</code></pre>
<h3 id="heading-how-to-declare-variables">How To Declare Variables?</h3>
<p>Python offers dynamic typing so you don't need to declare variables beforehand like in C/C++, but you can just type out the variables and use them:</p>
<pre><code class="lang-python">some_variable = <span class="hljs-number">10</span>
</code></pre>
<p>Scala also offers dynamic typing to some extent and infer that type during compile time:</p>
<pre><code class="lang-java">val some_variable = <span class="hljs-number">10</span>  <span class="hljs-comment">// infers it as Int type</span>
</code></pre>
<h3 id="heading-how-to-define-conditionals">How To Define Conditionals?</h3>
<p>In Python and Scala defining conditionals are more or less similar:</p>
<pre><code class="lang-python">v = <span class="hljs-number">5</span>
<span class="hljs-keyword">if</span> v%<span class="hljs-number">2</span>==<span class="hljs-number">1</span>:
    print(<span class="hljs-string">"Odd"</span>)
<span class="hljs-keyword">elif</span> v==<span class="hljs-number">0</span>:
    print(<span class="hljs-string">"Zero"</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Even"</span>)
</code></pre>
<p>In Scala:</p>
<pre><code class="lang-java">val v = <span class="hljs-number">5</span>
<span class="hljs-keyword">if</span> (v%<span class="hljs-number">2</span>==<span class="hljs-number">1</span>) println(<span class="hljs-string">"Odd"</span>)
<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (v==<span class="hljs-number">0</span>) println(<span class="hljs-string">"Zero"</span>)
<span class="hljs-keyword">else</span> println(<span class="hljs-string">"Even"</span>)
</code></pre>
<p>The important thing to note in conditionals is that in Python conditionals are referred to as statements whereas in Scala these are expressions that evaluates to something or nothing.</p>
<h3 id="heading-how-to-define-loops">How To Define Loops?</h3>
<p>In Python a simple for-loop would look like this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
    <span class="hljs-comment"># do something here</span>
</code></pre>
<p>The same for-loop in Scala would look like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">for</span> {
    i &lt;- <span class="hljs-number">0</span> until <span class="hljs-number">10</span>
}   {
    <span class="hljs-comment">// do something here</span>
}
</code></pre>
<p>The difference in their respective working behind the scenes, in Scala, is the use of conjunction of <code>map</code> and <code>flatMap</code> methods whereas in Python it is simple iteration.</p>
<p>There is a <code>while</code> loop in Scala, but let's not discuss that, while coding in Scala it is not encouraged to use <code>while</code> loops.</p>
<p><a target="_blank" href="https://stackoverflow.com/questions/49552915/why-are-while-loops-not-recommended-in-scala#:~:text=The%20scala%20style%20checker%20says,%2Ddev.html%23org_scalastyle_scalariform_WhileChecker.">Why are while loops not recommended in Scala?</a></p>
<h3 id="heading-how-to-write-methods">How To Write Methods?</h3>
<p>In Python, we can simply use the <code>def</code> keyword to define functions, which are similar to methods in Scala.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">some_method</span>():</span>
    <span class="hljs-comment"># do something here</span>
</code></pre>
<p>In Scala we can define a method like:</p>
<pre><code class="lang-java"><span class="hljs-function">def <span class="hljs-title">someMethod</span><span class="hljs-params">()</span> </span>= {
    <span class="hljs-comment">// do something here</span>
}
</code></pre>
<p>To define functions in Scala, we can use <code>Function</code> objects or their respective syntactic sugars. To know more about functions and functional programming in Scala, do check <a target="_blank" href="scala-for-beginners-crash-course-part-3">this</a>.</p>
<h3 id="heading-how-to-define-classes-and-objects">How To Define Classes and Objects?</h3>
<p>In Python, we can define a class using the <code>class</code> keyword, the same keyword can be used to define a class in Scala.</p>
<p>Whereas objects in Scala are singleton instances and similar to what we call static class in other programming languages.</p>
<p>A class however in Scala can be instantiated using the <code>new</code> keyword, whereas in Python calling the class directly creates an instance for that.</p>
<p>In Python:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span>:</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment"># do something here</span>

student = Student()     <span class="hljs-comment"># creates an instance of class Student</span>
</code></pre>
<p>In Scala:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span>

<span class="hljs-title">val</span> <span class="hljs-title">student</span> </span>= <span class="hljs-keyword">new</span> Student()     <span class="hljs-comment">// creates an instance of class Student</span>

<span class="hljs-comment">// use Object keyword for singleton objects</span>

Object Student

val aParticularStudent = Student
</code></pre>
<p>To know more about classes and objects in Scala, I recommend checking out <a target="_blank" href="scala-for-beginners-crash-course-part-2">this</a> article.</p>
<h3 id="heading-miscellaneous">Miscellaneous</h3>
<p>Scala offers 2 more advantages over Python, namely <strong>traits</strong> and <strong>tail recursion</strong>. </p>
<p>Python does not offer tail recursive capabilities to its functions and suffers from stack overflow errors whenever functional programming goes wrong. To know more about why python does not offer tail recursion, you can read <a target="_blank" href="https://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html">this</a> article. However, there is a work-around as described in <a target="_blank" href="https://chrispenner.ca/posts/python-tail-recursion">this</a> article using decorators.</p>
<p>Similarly, Python does not have concepts like traits. A trait is used to describe the quality of a class, whereas in Python you would have to do multiple inheritances to get certain qualities or have to define certain methods within the class definition. Trait allows loose coupling.</p>
<p>How to define a trait in Scala?</p>
<pre><code class="lang-java">trait SomeQuality

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">SomeQuality</span></span>
</code></pre>
<h3 id="heading-wrap-up">Wrap Up</h3>
<p>Well, that wraps up this simple Scala Vs Python syntax cheat sheet.</p>
<p>What else would you add to this cheat sheet? Please let me know in the comments!</p>
<p>If you are looking to sharpen your coding skills in Python or Scala, then do consider buying these awesome books that go in-depth to let you understand the semantics of the language.</p>
<p>For Python:</p>
<ul>
<li><a target="_blank" href="https://amzn.to/3k4sVmN">Python - The Bible</a></li>
<li><a target="_blank" href="https://amzn.to/3959lR9">Python - The Complete Reference</a></li>
<li><a target="_blank" href="https://amzn.to/3hxhjqJ">Automate The Boring Stuff With Python</a></li>
<li><a target="_blank" href="https://amzn.to/3AcJgvc">Python Basics</a></li>
</ul>
<p>For Scala:</p>
<ul>
<li><a target="_blank" href="https://amzn.to/3C4rZ8a">Scala For The Impatient</a></li>
<li><a target="_blank" href="https://amzn.to/3tAluXH">Scala Programming Projects</a></li>
<li><a target="_blank" href="https://amzn.to/3hnZYAw">Functional Programming in Scala</a></li>
<li><a target="_blank" href="https://amzn.to/3k66Lk1">Programming Scala</a></li>
</ul>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Scala For Beginners - Crash Course - Part 5]]></title><description><![CDATA[Welcome to the 5th and last part of the Scala beginners crash course, here we will go through the concepts like collections, sequences and map, flatmap, filter in the Scala programming language. This will be a short article, so if you need much more ...]]></description><link>https://chandraji.dev/scala-for-beginners-crash-course-part-5</link><guid isPermaLink="true">https://chandraji.dev/scala-for-beginners-crash-course-part-5</guid><category><![CDATA[Tutorial]]></category><category><![CDATA[Scala]]></category><category><![CDATA[Functional Programming]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Mon, 13 Sep 2021 11:26:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1631529339828/ysmHxIuv8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the 5<sup>th</sup> and last part of the Scala beginners crash course, here we will go through the concepts like collections, sequences and map, flatmap, filter in the Scala programming language. This will be a short article, so if you need much more in-depth information you can check out the recommended books at the end of this article.</p>
<p>It will be a no-nonsense, to the point kind of article (like <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a>, <a target="_blank" href="scala-for-beginners-crash-course-part-2">part 2</a>, <a target="_blank" href="scala-for-beginners-crash-course-part-3">part 3</a> and <a target="_blank" href="scala-for-beginners-crash-course-part-4">part 4</a>) with all the necessary links wherever needed.</p>
<p>Without any further ado, let's get started.</p>
<hr />
<h3 id="heading-before-we-start">Before We Start</h3>
<p>Before we start coding out, first create a new object in the <code>crashcourse</code> package (please go through <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a> for more information on creating packages and objects).</p>
<p>Let's name it <code>Collections</code> like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531346691/e6CNxW3S3.png" alt="collections.png" /></p>
<p>Now, we can start coding out the examples on this Scala application.</p>
<h3 id="heading-collections">Collections</h3>
<p>Scala offers 2 sets of collections, one is mutable and the other one is immutable. Scala by default works with immutable collection objects.</p>
<p>But, we can import mutable collection objects whenever needed like:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> scala.collection.mutable
</code></pre>
<p>Also, if we want we can see all immutable collection objects in package <code>scala.collections.immutable</code>.</p>
<p>Following are some of the immutable collection objects provided in scala:</p>
<ul>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/HashSet.html">HashSet</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/SortedSet.html">SortedSet</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/Vector.html">Vector</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/StringLike.html">StringLike</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/Range.html">Range</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/List.html">List</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/Stream.html">Stream</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/Stack.html">Stack</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/Queue.html">Queue</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/HashMap.html">HasMap</a></li>
<li><a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/immutable/SortedMap.html">SortedMap</a></li>
</ul>
<p>Similar collection objects are available in the mutable set. This <a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/mutable/index.html">link</a> has all the mutable collection objects set.</p>
<p>The commonality between mutable and immutable collection objects is that both extends trait <a target="_blank" href="https://www.scala-lang.org/api/2.12.2/scala/collection/Traversable.html">Traversable</a>. It is a base trait for all collections and offers a great variety of methods.</p>
<p>Some of these collection objects are often sequenced in nature. Let's discuss sequences now.</p>
<h3 id="heading-sequences">Sequences</h3>
<p>Sequences in scala are a general interface for data structures that have a well-defined order and can be indexed.</p>
<p>These support various operations like:</p>
<ul>
<li><code>apply</code>, <code>iterator</code>, <code>length</code>, <code>reverse</code> for indexing and iterating.</li>
<li>Concatenation, appending, prepending.</li>
<li>A lot of others - grouping, sorting, zipping, searching and slicing.</li>
</ul>
<p>Let's see how to define a sequence:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531369496/8rbrbjIYW.png" alt="sequence.png" /></p>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531388160/8067-fcPJ.png" alt="sequence2.png" /></p>
<p><code>Range</code> is one of the sequences available, we can define a <code>Range</code> like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531407959/iaYGwXKJ4.png" alt="range.png" /></p>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531425930/J_O_pCi5I.png" alt="range2.png" /></p>
<p>There is another type of sequence, <code>LinearSeq</code> which is an immutable linked list with the following properties:</p>
<ul>
<li>Accessing head, tail and using methods like <code>isEmpty</code> are fast and takes <code>O(1)</code> time.</li>
<li>Most other operations like <code>length</code> or <code>reverse</code> takes <code>O(n)</code> time.</li>
</ul>
<p>Arrays in scala are equivalent to java arrays, these can be manually constructed with predefined lengths. These can be mutated, have fast indexing and are interoperable with java's arrays.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531440888/_h4W3tUUF.png" alt="array.png" /></p>
<p>Vectors are also present in scala, these are the default implementation for immutable sequences taking constant time for indexed based read/write, with fast append/prepend, shows good performance for large size vectors and are implemented using a fixed branched trie data structure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531455900/knizLYOg-.png" alt="vector.png" /></p>
<p>Tuples are finite ordered kinds of lists that can contain a maximum of 22 elements. A tuple value data type is defined similarly to a function like <code>TupleN[...]</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531475585/fR2ZmAxRN.png" alt="tuple.png" /></p>
<p>There is one more collection object, <code>Map</code>, which is a key-&gt;value pair data structure present in scala. Following are some ways to manipulate a map:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531488699/EIud6p632.png" alt="map.png" /></p>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531499216/dHUHeRySj.png" alt="map2.png" /></p>
<p>More on Scala collections can be found <a target="_blank" href="https://docs.scala-lang.org/overviews/collections/overview.html">here</a> or you can check the books provided in the last section for the more detailed in-depth working of collections.</p>
<h3 id="heading-map-flatmap-filter-and-for">map, flatMap, filter and for</h3>
<p>Finally, on the most important part of functional programming, that would become the daily need of a Scala programmer. I wanted to include these in the previous <a target="_blank" href="scala-for-beginners-crash-course-part-4">part</a> but to show how these work I needed to show collections in scala first, now that we know enough about collections, let's move on to these functions.</p>
<blockquote>
<p>Note: For the sake of examples, I will be showing these operations on the <code>List</code> sequence, you can try these on other collections as well.</p>
</blockquote>
<p>First, define our list collection like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531520453/GABMEV5EE.png" alt="list.png" /></p>
<p>What is the <code>map</code> method? It allows a certain function to be applied to all the elements present in the given sequence and evaluates to a sequence of updated values.</p>
<p>What is the <code>filter</code> method? It filters out the elements which do not meet a certain criterion defined as another function and evaluates to a sequence of filtered values.</p>
<p>What is the <code>flatMap</code> method? This is identical to the <code>map</code> method, but the only difference is that in <code>flatMap</code> the inner grouping of an item is removed and a sequence is generated. So, if <code>flatMap</code> is applied to a list then the generated output will be a list of lists, changing the inner grouping of integer elements to a list and later flattening it.</p>
<p>What is the <code>for</code> loop in scala? Yeah, you read it right 'What is' and not 'How to', in scala, writing a <code>for</code> loop is just a fancy way of writing a coupled <code>map</code> and <code>flatMap</code> methods. A <code>for</code> loop in scala can be written as:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531539746/H2GaxC-s3.png" alt="mapfilter.png" /></p>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1631531550914/FvTwmpzad.png" alt="mapfilter2.png" /></p>
<p>These are some important methods to remember while coding out in scala.</p>
<h3 id="heading-wrap-up">Wrap Up</h3>
<p>Well, that wraps up part 5 and the end of this crash course.</p>
<p>I hope it was something worth it for you as a reader and made you a scala enthusiast at the end of this course.</p>
<p>You can pick up any of the below books to master the art of programming in scala:</p>
<ul>
<li><a target="_blank" href="https://amzn.to/3C4rZ8a">Scala For The Impatient</a></li>
<li><a target="_blank" href="https://amzn.to/3tAluXH">Scala Programming Projects</a></li>
<li><a target="_blank" href="https://amzn.to/3hnZYAw">Functional Programming in Scala</a></li>
<li><a target="_blank" href="https://amzn.to/3k66Lk1">Programming Scala</a></li>
</ul>
<p>To keep in touch, you can follow me on here or subscribe to get the updates of the new blogs that I will write in the future or follow me on <a target="_blank" href="https://twitter.com/chandrajidev">Twitter</a> where I share my thoughts not only on programming but also on personal finance.</p>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Scala For Beginners - Crash Course - Part 4]]></title><description><![CDATA[Welcome to the 4th part of the scala beginners crash course, here we will go through the concepts like options, exception handling and pattern matching in the scala programming language. This will be a short article, so if you need much more in-depth...]]></description><link>https://chandraji.dev/scala-for-beginners-crash-course-part-4</link><guid isPermaLink="true">https://chandraji.dev/scala-for-beginners-crash-course-part-4</guid><category><![CDATA[Tutorial]]></category><category><![CDATA[Scala]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[course]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Mon, 06 Sep 2021 10:51:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1630924877734/rL8YXhmvL.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the 4<sup>th</sup> part of the scala beginners crash course, here we will go through the concepts like options, exception handling and pattern matching in the scala programming language. This will be a short article, so if you need much more in-depth information you can check out the recommended books at the end of this article.</p>
<p>It will be a no-nonsense, to the point kind of article (like <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a>, <a target="_blank" href="scala-for-beginners-crash-course-part-2">part 2</a> and <a target="_blank" href="scala-for-beginners-crash-course-part-3">part 3</a>) with all the necessary links wherever needed.</p>
<p>Without further ado, let's get started.</p>
<hr />
<h3 id="heading-before-we-start">Before We Start</h3>
<p>Before we start coding out, first create a new object in the <code>crashcourse</code> package (please go through <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a> for more information on creating packages and objects).</p>
<p>Let's name it <code>OptionErrorPattern</code> like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925030021/nVd9E9gnC.png" alt="optionerrorpattern.png" /></p>
<p>Now, we can start coding out examples on this scala application.</p>
<h3 id="heading-options">Options</h3>
<p>An option is a wrapper for a value that might be present or not.</p>
<p>As the name suggests it evaluates to an option of 2 values, either <code>Some</code> or <code>None</code>, when given an expression. In this way, when we are dealing with some unsafe APIs, we can always wrap that API calls within an <code>Option</code> object to keep our program safe and error-free that might otherwise result in a <code>Null</code> pointer kind of exception.</p>
<p>For example,</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925018987/sB1uRqqay.png" alt="option1.png" /></p>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925042862/-nK_ZfcMc.png" alt="option2.png" /></p>
<ul>
<li><code>Some</code> wraps a concrete value.</li>
<li><code>None</code> is a singleton for absent values.</li>
<li>It is better to use <code>Option</code> in APIs that we are creating.</li>
</ul>
<h3 id="heading-handling-exceptions">Handling Exceptions</h3>
<p>In scala, exceptions are handled inside try-catch blocks, like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925058053/hTqvEBrrBP.png" alt="trycatch1.png" /></p>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925069861/Esd5kD21N.png" alt="trycatch2.png" /></p>
<p>But, it comes with its drawbacks:</p>
<ul>
<li>Multiple/Nested try-catch blocks make the code hard to read/follow.</li>
<li>We can not chain multiple operations prone to failure.</li>
</ul>
<p>To overcome these limitations, scala introduced a <code>Try</code> object that can act as a wrapper to wrap an error-prone expression and evaluates to either a <code>Success</code> or a <code>Failure</code> as a result.</p>
<p>A <code>Try</code> is a wrapper for a computation that might fail or not. It wraps failed computations as <code>Failure</code> and successful computations as <code>Success</code>.</p>
<p>To use <code>Try</code>, <code>Success</code> and <code>Failure</code> objects, we have to import these first:</p>
<pre><code class="lang-java"><span class="hljs-keyword">import</span> scala.util.{Try, Success, Failure}
</code></pre>
<p>So, the above method <code>someErrorProneFunc</code> can be used with <code>Try</code> as follows:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925084602/6lmVG7jIU.png" alt="try1.png" /></p>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925093846/jtYL6zcZR.png" alt="try2.png" /></p>
<p>We can check if a <code>Try</code> is a <code>Success</code> or <code>Failure</code> using <code>isSuccess</code> or <code>isFailure</code> methods respectively.</p>
<p>We can use <code>Try</code> to handle exceptions for avoiding runtime crashes due to uncaught exceptions or just to avoid an endless amount of try-catch blocks.</p>
<h3 id="heading-pattern-matching">Pattern Matching</h3>
<p>Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the <code>switch</code> statement in Java and it can likewise be used in place of a series of if/else statements.</p>
<p>A match expression has a value, the <code>match</code> keyword, and at least one <code>case</code> clause.</p>
<p>For example,</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925111421/1pCDtmdXV.png" alt="pattern1.png" /></p>
<p>Output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630925120830/nW6vRfMZ8.png" alt="pattern2.png" /></p>
<p>Some important points to note on pattern matching:</p>
<ul>
<li>It is used to decompose values.</li>
<li>Cases are matched in the order given.</li>
<li>What if there was no case that matched the pattern, then it would result in <code>MatchError</code>.</li>
<li>Pattern matching works really well with case classes.</li>
</ul>
<h3 id="heading-wrap-up">Wrap Up</h3>
<p>Well, that wraps up part 4 of this crash course.</p>
<p>I know, it was a very short read, my motivation was to keep it short and simple and be able to provide ample impetus to you to explore it further. </p>
<p>Take it as a challenge or homework, explore advanced pattern matching, how you can use <code>Option</code> in conjunction with <code>Try</code> (it can do wonders to the API you are working on) and in the comments, mention what you know about on these concepts.</p>
<p>You can check these books to get more insights on these topics:</p>
<ul>
<li><a target="_blank" href="https://amzn.to/3C4rZ8a">Scala For The Impatient</a></li>
<li><a target="_blank" href="https://amzn.to/3tAluXH">Scala Programming Projects</a></li>
<li><a target="_blank" href="https://amzn.to/3hnZYAw">Functional Programming in Scala</a></li>
<li><a target="_blank" href="https://amzn.to/3k66Lk1">Programming Scala</a></li>
</ul>
<p>In the next and last part of this crash course, we will discuss the collections available in scala and most important of all, the map, flatmap and filter methods in scala.</p>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Scala For Beginners - Crash Course - Part 3]]></title><description><![CDATA[Welcome to the 3rd part of the scala beginners crash course, here we will go through the functional way of scala programming language and concepts like higher-order functions, curries and anonymous functions!
It will be a no-nonsense, to the point ki...]]></description><link>https://chandraji.dev/scala-for-beginners-crash-course-part-3</link><guid isPermaLink="true">https://chandraji.dev/scala-for-beginners-crash-course-part-3</guid><category><![CDATA[Scala]]></category><category><![CDATA[Functional Programming]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Thu, 02 Sep 2021 09:56:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1630575902470/ffLvQm1yq.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the 3<sup>rd</sup> part of the scala beginners crash course, here we will go through the functional way of scala programming language and concepts like higher-order functions, curries and anonymous functions!</p>
<p>It will be a no-nonsense, to the point kind of article (like <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a> and <a target="_blank" href="scala-for-beginners-crash-course-part-2">part 2</a>) with all necessary links wherever needed.</p>
<p>Without further ado, let's get started.</p>
<hr />
<h3 id="heading-what-is-functional-programming">What Is Functional Programming?</h3>
<p>The below is an excerpt from the <strong>Functional Programming in Scala</strong> book.</p>
<p>Functional programming (FP) is based on a simple premise with far-reaching implications: we construct our programs using only pure functions, in other words, functions that have no side effects. What are the side effects? A function has a side effect if it does something other than simply return a result, for example:</p>
<ul>
<li>Modifying a variable.</li>
<li>Modifying a data structure in place.</li>
<li>Setting a field on an object.</li>
<li>Throwing an exception or halting with an error.</li>
<li>Printing to the console or reading user input.</li>
<li>Reading from or writing to a file.</li>
<li>Drawing on the screen.</li>
</ul>
<p>We discussed side-effects also in <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a>.</p>
<blockquote>
<p>Note: Functional programming is a restriction on how we write programs, but not on what programs we can express.</p>
</blockquote>
<h3 id="heading-before-we-start">Before We Start</h3>
<p>Before we start coding out, first create a new object in the <code>crashcourse</code> package (please go through <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a> for more information on creating packages and objects).</p>
<p>Let's name it <code>FunctionalProgramming</code> like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630575945646/OC1gaLVh2.png" alt="functionalprog.png" /></p>
<p>Now, we can start coding out examples on this scala application.</p>
<h3 id="heading-creating-functions-in-scala">Creating Functions In Scala</h3>
<p>Before moving on to create functions in scala, please keep in mind that scala works on JVM and for JVM it needs classes/objects to work with, hence everything in scala will be an object, even the functions are objects.</p>
<blockquote>
<p>Note: Due to scala's syntactic sugar, we can still write functions in a more functional fashion.</p>
</blockquote>
<p>Let's create a function in scala:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630575959941/pcZ5h_BWX.png" alt="function1.png" /></p>
<p>Scala has a collection of functions namely <code>Function1</code> to <code>Function22</code>, which can be used out-of-the-box without any issues.</p>
<p>A function like <code>Function1[String, Int]</code> represents that it will take <code>String</code> as an input and evaluates to <code>Int</code> as an output. This function definition will be written in its <code>apply</code> method, as <code>Function1</code> is an object and we need to override its <code>apply</code> method to make it callable.</p>
<p>A simple syntactic sugar for a function like <code>Function2[Int, Int, Int]</code> would be <code>(Int, Int) =&gt; Int</code>, which is more functional while reading the code.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630575972248/l-jeLp22Hj.png" alt="function2.png" /></p>
<p>We should also note that while working in IntelliJ, it tells us that the given <code>Function1[String, Int]</code> can be converted to its respective syntactic sugar, we can do so by hovering over the yellow line and simply clicking <code>Replace FunctionN[A1, A1, ..., AN, R] with (A1, A1, ..., AN) =&gt; R</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630575985895/CLRREEfBc.png" alt="function1yellow.png" /></p>
<p>Converted to syntactic sugar:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630575997793/1s4T2rLe-.png" alt="function1syntax.png" /></p>
<p>Important points to note:</p>
<ul>
<li>All scala functions are objects, that is, instances of <code>Function1</code>, <code>Function2</code> and so on.</li>
<li>JVM was designed for object-oriented programming, but using it for scala function we need something like objects (like <code>Function1</code>) to instantiate them.</li>
<li>Functions are traits with maximum parameters to be 22.</li>
</ul>
<h3 id="heading-anonymous-functions">Anonymous Functions</h3>
<p>The anonymous function is something we saw in the previous example of <code>Function2[Int, Int, Int]</code> syntactic sugar.</p>
<p>So, the below expression:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630576036088/edN80uOpx.png" alt="anonfunc.png" /></p>
<p>can be written as:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630576046885/Pqc562saY.png" alt="anonfunc2.png" /></p>
<p>or as:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630576059186/SLHmwCK82r.png" alt="anonfunc3.png" /></p>
<p>Anonymous functions are just another way of writing functions as supported by scala's compiler, behind the scenes everything is the same.</p>
<p>More ways in which we can write anonymous functions:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630576079593/k_WNsN_7p.png" alt="anonfunc4.png" /></p>
<blockquote>
<p>Note: An anonymous function is also known as a function literal. A function that does not contain a name is known as an anonymous function in general.</p>
</blockquote>
<h3 id="heading-higher-order-functions-and-curries">Higher-Order Functions and Curries</h3>
<p>Higher-order functions have at least one of the following properties:</p>
<ol>
<li>Takes one or more functions as parameters.</li>
<li>Returns a function as a result.</li>
</ol>
<p>In scala, a general higher-order function declaration can look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630576093034/_ocWhLD0h.png" alt="hof.png" /></p>
<p>These are called Higher-Order Functions, which essentially takes one or more functions as input and/or returns a function as output.</p>
<p>Moving on to curries, currying means transforming a function that takes multiple arguments into a chain of calls to functions, each of which takes one argument. Each function returns another function that takes the subsequent argument.</p>
<p>A simple curry can be like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630576108908/ZoNJdX16A.png" alt="curry.png" /></p>
<p>Functions with multiple parameter list also act as curries:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630576119542/o5ECg8pcP.png" alt="curry2.png" /></p>
<h3 id="heading-wrap-up">Wrap Up</h3>
<p>Well, that wraps up part 3 of this crash course.</p>
<p>I highly recommend you to go through the books below to get a better and deeper understanding of functional programming:</p>
<p><a href="https://www.amazon.in/Functional-Thinking-Paradigm-Over-Syntax-ebook/dp/B00LEX6SP8?crid=2I35UGEUXLTHJ&amp;dchild=1&amp;keywords=functional+thinking&amp;qid=1630574749&amp;sprefix=functional+think%2Caps%2C317&amp;sr=8-1&amp;linkCode=li2&amp;tag=chandrajidev-21&amp;linkId=576c0c2c9e91856ea455b7baa167cbe1&amp;language=en_IN&amp;ref_=as_li_ss_il" target="_blank"><img src="//ws-in.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;ASIN=B00LEX6SP8&amp;Format=_SL160_&amp;ID=AsinImage&amp;MarketPlace=IN&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=chandrajidev-21&amp;language=en_IN" /></a><img src="https://ir-in.amazon-adsystem.com/e/ir?t=chandrajidev-21&amp;language=en_IN&amp;l=li2&amp;o=31&amp;a=B00LEX6SP8" alt /></p>
<p><a href="https://www.amazon.in/Grokking-Simplicity-software-functional-thinking-ebook/dp/B09781TWFL?dchild=1&amp;keywords=functional+thinking&amp;qid=1630574798&amp;sr=8-2&amp;linkCode=li2&amp;tag=chandrajidev-21&amp;linkId=54fce22f0619670582a2391a0daf4e0b&amp;language=en_IN&amp;ref_=as_li_ss_il" target="_blank"><img src="//ws-in.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;ASIN=B09781TWFL&amp;Format=_SL160_&amp;ID=AsinImage&amp;MarketPlace=IN&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=chandrajidev-21&amp;language=en_IN" /></a><img src="https://ir-in.amazon-adsystem.com/e/ir?t=chandrajidev-21&amp;language=en_IN&amp;l=li2&amp;o=31&amp;a=B09781TWFL" alt /></p>
<p><a href="https://www.amazon.in/Functional-Programming-Scala-Paul-Chiusano/dp/1617290653?crid=24RA56XW8MZX1&amp;dchild=1&amp;keywords=functional+programming+in+scala&amp;qid=1630574828&amp;sprefix=functional+prog%2Caps%2C322&amp;sr=8-1&amp;linkCode=li2&amp;tag=chandrajidev-21&amp;linkId=8928ebdaa8126f751f76a0612beeac4f&amp;language=en_IN&amp;ref_=as_li_ss_il" target="_blank"><img src="//ws-in.amazon-adsystem.com/widgets/q?_encoding=UTF8&amp;ASIN=1617290653&amp;Format=_SL160_&amp;ID=AsinImage&amp;MarketPlace=IN&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=chandrajidev-21&amp;language=en_IN" /></a><img src="https://ir-in.amazon-adsystem.com/e/ir?t=chandrajidev-21&amp;language=en_IN&amp;l=li2&amp;o=31&amp;a=1617290653" alt /></p>
<p>In the next part, we will discuss some topics specific to scala, like options, handling errors in a unique style and pattern matching (the most awesome thing in scala).</p>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Scala For Beginners - Crash Course - Part 2]]></title><description><![CDATA[Welcome to the 2nd part of scala beginners crash course, here we will go through the object-oriented way of scala programming language and concepts like anonymous class, case classes and traits!
It will be a no-nonsense, to the point kind of article ...]]></description><link>https://chandraji.dev/scala-for-beginners-crash-course-part-2</link><guid isPermaLink="true">https://chandraji.dev/scala-for-beginners-crash-course-part-2</guid><category><![CDATA[Functional Programming]]></category><category><![CDATA[Scala]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Tue, 31 Aug 2021 17:04:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1630427731200/vmXYNpyiq.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to the 2<sup>nd</sup> part of scala beginners crash course, here we will go through the object-oriented way of scala programming language and concepts like anonymous class, case classes and traits!</p>
<p>It will be a no-nonsense, to the point kind of article (like <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a>) with all necessary links wherever needed.</p>
<p>Without further ado, let's get started.</p>
<hr />
<h3 id="heading-before-we-start">Before We Start</h3>
<p>Before we start coding out, first create a new object in <code>crashcourse</code> package (please go through <a target="_blank" href="scala-for-beginners-crash-course-part-1">part 1</a> for more information on creating packages and objects).</p>
<p>Let's name it <code>ClassAndObject</code> like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428192859/oxQvO6f-0.png" alt="classandobject.png" /></p>
<p>Now, we can start coding out examples on this scala application.</p>
<hr />
<h3 id="heading-classes-and-objects">Classes And Objects</h3>
<p>In scala, to define a class we use the <code>class</code> keyword:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428208513/-YBKewovA.png" alt="classkeyword.png" /></p>
<p>We can directly use the <code>Student</code> class later in the program. That's it! that's how we can create a class in scala.</p>
<p>It is different from writing <code>object Student</code> as it is not instantiated right away, we have just defined it and are not using it anywhere. To instantiate a class we can use the <code>new</code> keyword.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428230819/rKcOjejYv.png" alt="newkeyword.png" /></p>
<p>A class can have parameters, like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428242656/aO-thvn6J.png" alt="classargs.png" /></p>
<blockquote>
<p>Note: Class parameters are not class fields, which means we can not use these parameters with instantiated objects.</p>
</blockquote>
<p>To make class parameters as class fields, we have to use the <code>val</code> keyword along with the name of the parameter, like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428319579/tsxrdzViI.png" alt="valclassargs.png" /></p>
<p>We can use class parameters within the class code block by using the <code>this</code> keyword if value name conflict occurs, like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428339539/wdMAz_16a.png" alt="usingthis.png" /></p>
<p>If value name conflict does not occur, then the class method by default (implicitly) uses the <code>this</code> operator on class parameters values.</p>
<p>Some other important concepts:</p>
<ul>
<li>Overloading occurs with only different signature methods. More on overloading in scala <a target="_blank" href="https://www.geeksforgeeks.org/method-overloading-in-scala/">here</a>.</li>
<li>Auxiliary constructor are generally used for default parameters. More on auxiliary constructor <a target="_blank" href="https://www.geeksforgeeks.org/scala-auxiliary-constructor/">here</a>.</li>
<li>Instances are fixed, whenever we want to do something with the given class, say creating/updating something, then we would need to instantiate a new class, it is the clause of immutability, useful in functional programming.</li>
</ul>
<p>Conceptually, scala does not provide class level functionality, like a static class. However, scala provides something called an <code>object</code>, using which we can obtain class level functionalities.</p>
<p>Scala objects are singleton instances by definition. We can create an object like the below code:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428399034/tswQeZPm90.png" alt="object.png" /></p>
<p>We can create an object with the same name as that of a class in the same scope, creating such an object/class is called companion object/class, known as companions.</p>
<p>Companions can be used to make a factory method in objects, that can help instantiate a class in a certain way. Using companions does not require using the <code>new</code> keyword to instantiate a scala class, we can define a method named <code>apply</code> within the object to handle instantiation.</p>
<p>We can create a companion like below:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428637173/s90e0_FRe.png" alt="companion.png" /></p>
<p>Well, that's about it on classes and objects in scala. You can check out official docs on scala classes <a target="_blank" href="https://docs.scala-lang.org/tour/classes.html">here</a> and on objects <a target="_blank" href="https://docs.scala-lang.org/tour/singleton-objects.html">here</a>.</p>
<h3 id="heading-anonymous-and-case-classes">Anonymous And Case Classes</h3>
<p>To create an anonymous class we can directly define the class like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428653602/AuZMDeqQt.png" alt="anonclass.png" /></p>
<p>Things to remember when creating an anonymous class:</p>
<ul>
<li>Pass proper parameters whenever required.</li>
<li>Anonymous class declaration works for abstract as well as for non-abstract classes. It works for traits as well.<blockquote>
<p>Note: We will discuss abstract classes and traits in the next section.</p>
</blockquote>
</li>
<li>Useful for on-spot declaration in some scenarios.</li>
</ul>
<p>Using the <code>case</code> keyword in front of the <code>class</code> keyword will make it a case class, like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428673599/WBzmt4Qjo.png" alt="caseclass.png" /></p>
<p>Case classes promote class parameters to fields, it has a predefined <code>toString</code> method that evaluates to a representation that is understandable.</p>
<p>Equality and hashcodes are implemented out-of-the-box with a handy <code>copy</code> method to copy instances. Case classes come with their companion objects predefined.</p>
<p>Things to remember when creating a case class:</p>
<ul>
<li>Case class is a quick lightweight data structure with little boilerplate.</li>
<li>Case classes are serializable and used with the Akka framework.</li>
<li>Case classes have extractor patterns that can be used in pattern matching.</li>
<li>Case objects are the same as case classes but don't get companion objects as they themselves are objects.</li>
</ul>
<p>Well, that's about it on anonymous class and case class in scala.</p>
<h3 id="heading-inheritance-abstract-class-and-traits">Inheritance, Abstract Class And Traits</h3>
<p>Scala offers single level inheritance. Inheriting a class inherits public methods and protected methods can be used within the child class.</p>
<p>Inheritance example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428695980/LGFCROTuq.png" alt="inheritance.png" /></p>
<p>Important notes on inheritance overriding:</p>
<ul>
<li>To override methods, use the <code>override</code> keyword. Override works for <code>val</code>, <code>var</code>, <code>def</code> or anything within in the class.</li>
<li>To prevent override, we have to use the <code>final</code> keyword.</li>
<li>Put a <code>final</code> keyword before <code>class</code> to altogether prevent the inheritance of a class.</li>
<li>Use the <code>sealed</code> keyword to restrict inheritance in different scopes of the program.</li>
</ul>
<p>Moving on to abstract classes in scala, we have to use the <code>abstract</code> keyword to make an abstract class and an abstract class cannot be instantiated, however, we can create an anonymous class using the <code>new</code> keyword and defining all the methods within that anonymous code block.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428722924/REIHImy5p.png" alt="abstractclass.png" /></p>
<p>Traits are similar to interfaces in java. They are also used to declare undefined or unimplemented methods. We have to use the <code>trait</code> keyword to define traits in scala.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1630428738822/-Gt2CDPkh.png" alt="trait.png" /></p>
<p>Important points to note for abstract classes and traits in scala:</p>
<ul>
<li>Abstract class can have both abstract and non-abstract methods. It is the same for traits.</li>
<li>Traits does not have constructor parameters.</li>
<li>Classes can inherit multiple traits, but not multiple classes.</li>
<li>Traits are used to define the behaviour of a class.</li>
<li>Abstract class is the type of thing itself.</li>
</ul>
<blockquote>
<p>Note: If you see <code>???</code> in abstract/trait methods, it means that method is not implemented and evaluates to <code>Nothing</code>.</p>
</blockquote>
<p>Well, that's about it on inheritance, abstract class and traits in scala.</p>
<h3 id="heading-external-links">External Links</h3>
<p>Below are some of the external links you can go through to get a more in-depth understanding of object-oriented programming in scala.</p>
<ul>
<li><a target="_blank" href="https://www.baeldung.com/scala/oop-intro#:~:text=Scala%20is%20a%20hybrid%20between,encapsulation%2C%20inheritance%2C%20and%20polymorphism">Object Oriented Programming in Scala</a></li>
<li><a target="_blank" href="https://www.scala-exercises.org/scala_tutorial/object_oriented_programming">Scala Exercises</a></li>
</ul>
<h3 id="heading-wrap-up">Wrap Up</h3>
<p>Well, that wraps up part 2 of this crash course.</p>
<p>In the next part, we will discuss functions, HOFs, curries and much more related to functional programming in scala.</p>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Scala For Beginners - Crash Course - Part 1]]></title><description><![CDATA[Welcome to this scala beginners crash course, here we will go through the basic syntax of scala programming language and some of the nuances available just for scala developers!
It will be a no-nonsense, to the point kind of article with all necessar...]]></description><link>https://chandraji.dev/scala-for-beginners-crash-course-part-1</link><guid isPermaLink="true">https://chandraji.dev/scala-for-beginners-crash-course-part-1</guid><category><![CDATA[Scala]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[course]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Sat, 22 May 2021 15:38:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621696897344/exdtGVh00.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to this scala beginners crash course, here we will go through the basic syntax of scala programming language and some of the nuances available just for scala developers!</p>
<p>It will be a no-nonsense, to the point kind of article with all necessary links wherever needed.</p>
<p>Without further ado, let's get started.</p>
<h3 id="heading-what-is-scala">What Is Scala?</h3>
<p>Scala is a programming language just like any other that is available out there but with a lot of sweetness and awesome features that opens our world to functional programming with easy to understand syntax, running on JVM under the hood, having all functionality that Java language offers with popularity ranging from being used in major FinTech companies to FAANG companies and as one of the major language for data engineering applications.</p>
<p>Need to know more about what is Scala, visit <a target="_blank" href="https://www.scala-lang.org/">here</a>.</p>
<h3 id="heading-how-to-install-scala">How To Install Scala?</h3>
<p>Well, there are a couple of ways, in which the shortest and easy to follow is:</p>
<ol>
<li>Install IntelliJ IDE from JetBrains. Check <a target="_blank" href="https://www.jetbrains.com/idea/download/">here</a>.</li>
<li>Select <code>IntelliJ IDEA | Preferences</code> for macOS ( Ctrl+Alt+S ) or <code>File | Settings</code> for Windows and Linux.</li>
<li>Select <code>Plugins</code> on the left pane.</li>
<li>Search for <code>Scala</code>, install the plugin and restart IDE.</li>
<li>Now, after it restarts, select <code>New Project</code> and then <code>Scala</code> -&gt; <code>IDEA</code> project, click <code>Next</code>, set project name and your project folder are ready with necessary scala features.</li>
</ol>
<blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621697251647/lECjG6zCA.png" alt="install_scala.png" />
Installing Scala</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621697268678/dtXJwQfg8.png" alt="setup_project.png" />
Creating a New Project</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621697291997/GWDVd0_-X.png" alt="project_name.png" />
Set Suitable Project Name</p>
</blockquote>
<h3 id="heading-how-to-start-working-with-scala">How To Start Working With Scala?</h3>
<p>After successful installation and creating a scala project, you would be seeing a nice project structure with the <code>src</code> folder.</p>
<p>We will create a package, inside that package we will continue our work. <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/concepts/package.html">What is a package?</a></p>
<p>To create a package, right-click on the <code>src</code> folder and select <code>New | Package</code> type, then fill in a name, whatever you like, for our case, let's name it <code>crashcourse</code>.</p>
<blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621697312670/NxpfJgmX3.png" alt="create_package.png" />
Create New Package</p>
</blockquote>
<p>Now, right-click the <code>crashcourse</code> then <code>New | Scala</code>, here we are creating a scala object (we will discuss what scala object is in a minute). Let's name it <code>BeginnersCrashCourse</code>. It will create a standard template of scala object like below:</p>
<blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621697340573/3icKtWx0Z.png" alt="object_creation.png" />
Select Scala Class</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1621697358744/E9Gci-BRM.png" alt="select_object.png" />
Select Scala Object</p>
</blockquote>
<p>Well, now we have all we need to get started with some code!</p>
<h3 id="heading-what-is-an-object">What Is An Object?</h3>
<p>Before moving to object, if you notice the created template have <code>package crashcourse</code> at the top, it means that whatever code we are going to write below this, will belong to this package and can be accessed by any code file within the same package or can be imported using <code>import crashcourse._</code> in some other package. <a target="_blank" href="https://docs.scala-lang.org/tour/packages-and-imports.html">How to do imports in scala?</a></p>
<p>Now, what is an object in scala?</p>
<p>The object is a class that has exactly one instance, it means it already is an instance with a defined class structure. What is the defined class structure for an object type? It is everything we write inside scala object.</p>
<p>Scala objects are singleton, which means if we say we have an object named <code>BeginnersCrashCourse</code> then it is an instance that is a singleton in nature and whenever I am accessing it in the same executing program then its behaviour is going to be the same at every place, containing same values, methods or functions.</p>
<p>Treat an object as something that has static class level functionality.</p>
<p>How to write an object? Simple, just use the <code>object</code> keyword before writing an object, like below:</p>
<pre><code class="lang-scala">package crashcourse

object BeginnersCrashCourse extends App {

}
</code></pre>
<p>What is <code>extends App</code>? We extend <code>App</code> level functionality to a scala object whenever we want it to be able to run something inside it. It is like saying, we have a prebuilt <code>public static void main(String[] args)</code> whenever we extend it.</p>
<p>The above code is equivalent to:</p>
<pre><code class="lang-scala">package crashcourse

object BeginnersCrashCourse {
  def main(args: Array[String]): Unit = {

  }
}
</code></pre>
<p>Just to avoid writing the <code>main</code> method we can simply extend <code>App</code> to an object.</p>
<p>It is called a Scala Application if the main object (here <code>BeginnersCrashCourse</code>) extends <code>App</code> and is executable in nature. The main code goes inside an object that has <code>App</code> level functionality. Make sure you have a single main application while creating a service. Each service will have its main application to execute scala code.</p>
<p>Need more on scala objects, visit <a target="_blank" href="https://docs.scala-lang.org/tour/singleton-objects.html">here</a>.</p>
<h3 id="heading-expressions-types-vars-vals-def-print-and-codeblocks">Expressions, Types, Vars, Vals, Def, Print and Codeblocks</h3>
<p>How to create a variable in scala?</p>
<p>Well, there are 2 ways in which we can create a variable in scala:</p>
<pre><code class="lang-scala">package crashcourse

object BeginnersCrashCourse extends App {
  var var1 = 1  //Mutable
  val var2 = 2  //Immutable
}
</code></pre>
<blockquote>
<p>Writing comments in Scala is the same as Java.</p>
</blockquote>
<p>The key difference between the 2 variables is that <code>var1</code> is mutable and <code>var2</code> is immutable and in functional programming, we will prefer to use immutable values.</p>
<p><code>val</code> - values and <code>var</code> - variables, the name suggest itself that <code>val</code> will be a definite value whereas <code>var</code> are variables.</p>
<p>We can also use the semicolon <code>;</code> at end of each line, but they are not needed. We can also define types to the variables, but for the above case, the compiler does this work for us, although it is best to explicitly define the type of each value we use in our code. So below code is similar to the above:</p>
<pre><code class="lang-scala">package crashcourse

object BeginnersCrashCourse extends App {
  var var1: Int = 1;  //Mutable
  val var2: Int = 2;  //Immutable
}
</code></pre>
<p>There are several data types available in scala, some of them are as below:</p>
<pre><code class="lang-scala">package crashcourse

object BeginnersCrashCourse extends App {
  var var1 = 1;  //Mutable
  val var2 = 2; //Immutable

  val bool: Boolean = true  //or false
  val chr: Char = 'a'   //Make sure you use single quotes for character type value
  val str: String = "String"    //And double quotes for a string type
  val int: Int = 123    //An int value
  val shrt: Short = 123   //A short value
  val lng: Long = 123     //A long value
  val lng2 = 123L   //Make sure to put L to let compiler know that it is of type Long
  val flt: Float = 123.0f   //Make sure to put f at the end of float values
  val dbl: Double = 123.0   //Otherwise compiler will infer it as a type of double
}
</code></pre>
<p>More on scala types, <a target="_blank" href="https://docs.scala-lang.org/tour/unified-types.html">here</a>.</p>
<p>Now, let's move on to defining methods in scala. It can be done so using the <code>def</code> keyword, methods can take arguments passed to them as parameters while calling them. We can define empty methods as well, those that take nothing.</p>
<p>Let's define some methods and call them:</p>
<pre><code class="lang-scala">package crashcourse

object BeginnersCrashCourse extends App {
  var var1 = 1;  //Mutable
  val var2 = 2; //Immutable

  val bool: Boolean = true  //or false
  val chr: Char = 'a'   //Make sure you use single quotes for character type value
  val str: String = "String"    //And double quotes for a string type
  val int: Int = 123    //A int value
  val shrt: Short = 123   //A short value
  val lng: Long = 123     //A long value
  val lng2 = 123L   //Make sure to put L to let compiler know that it is of type Long
  val flt: Float = 123.0f   //Make sure to put f at the end of float values
  val dbl: Double = 123.0   //Otherwise compiler will infer it as a type of double

  // Methods
  def greetings(name: String): String = "Hello " + name
  println(greetings("Siddharth"))

  def greetingsModified(name: String): Unit = println("Hello " + name)
  greetingsModified("Sid")

  def greetingsFromSystem: Unit = println("Hello, you are learning Scala!")
  greetingsFromSystem
}
</code></pre>
<p>There are a lot of things happening here, let's break it down for each method:</p>
<p><strong>1.</strong> We define a method using the <code>def</code> keyword, our first method named <code>greetings</code> takes a single parameter named <code>name</code> which of type <code>String</code> and the method returns a value of type <code>String</code> denoted by <code>: String</code> after <code>greetings(name: String)</code>, and this method evaluates to <code>"Hello " + name</code> with replacing with whatever name value we pass. We can print it to the console using the <code>println</code> method that conveniently puts a new line after printing the passed value to the console.</p>
<blockquote>
<p>A little detour before we move on to the next methods.</p>
</blockquote>
<ul>
<li><p>In scala everything we write gets evaluated to some value, those statements like <code>"Hello " + name</code> from above are called expressions. Everything in scala can be referred to as an expression, even assigning of values is called an expression evaluating in such a way that assign values to a given name.</p>
</li>
<li><p>Any expression that does not evaluate anything but does something, like printing to console or assigning a value or storing data, then data type of that whole expression is called <code>Unit</code>. So, whenever we assign a value within a method, and that's the last thing that method evaluated to then it will be of type <code>Unit</code>. Anything that evaluates to <code>Unit</code> type is called side-effect in scala.</p>
</li>
<li><p>We can use code blocks <code>{...}</code> instead of directly writing an expression for our methods. Methods are evaluated to the value returned by the last expression if it has a number of expressions. You can consider it to be the return value of the method but without needing to write <code>return</code> explicitly. <a target="_blank" href="https://tpolecat.github.io/2014/05/09/return.html">Why we should not use return in scala?</a>. A method code block would look something like this:</p>
</li>
</ul>
<pre><code class="lang-scala">def methodWithCodeBlock(name: String): String = {
  "Hello " + name    //Evaluates to String type
}

//Below method evaluates to same value as above method while doing something else, like printing something
def methodWithSomethingElse(name: String): String = {
  println("Inside methodWithSomethingElse")   //Evaluates to Unit type
  "Hello " + name    //Evaluates to String type, hence the type of method as it is the last expression evaluating
}
</code></pre>
<blockquote>
<p>Now, the remaining methods can be understood well.</p>
</blockquote>
<p><strong>2.</strong> We define the second method <code>greetingsModified</code> that takes a parameter named <code>name</code> of type <code>String</code> but evaluates to <code>Unit</code> as all this method does is print the greeting to the console as a side-effect.</p>
<p><strong>3.</strong> The last method we wrote <code>greetingsFromSystem</code> does not take any parameter and evaluates to <code>Unit</code> with the side-effect of printing to console. This is called a parameterless method, scala allows us to define such a method, awesome, right?</p>
<p>For each method call, the following is the output to the console (to run a scala application, right-click and run in IntelliJ):</p>
<pre><code class="lang-bash">Hello Siddharth
Hello Sid
Hello, you are learning Scala!
</code></pre>
<hr />
<p>More on <code>println</code>, visit <a target="_blank" href="https://www.geeksforgeeks.org/scala-console-println-printf-and-readline/">here</a>.</p>
<p>More on <code>Unit</code> type and other such types, visit <a target="_blank" href="https://www.geeksforgeeks.org/scala-null-null-nil-nothing-none-and-unit/">here</a>.</p>
<p>More on codeblocks in scala, visit <a target="_blank" href="https://www.includehelp.com/scala/code-blocks-in-scala.aspx">here</a>.</p>
<p>More on methods in scala, visit <a target="_blank" href="https://docs.scala-lang.org/overviews/scala-book/methods-first-look.html">here</a>.</p>
<h3 id="heading-wrap-up">Wrap Up</h3>
<p>Well, that wraps up part 1 of this crash course.</p>
<p>In the next part we will be discussing classes, more on objects, companions, case classes and much more related to object-oriented programming in Scala.</p>
<hr />
<ul>
<li><p>Make sure to follow me to get regular updates or subscribe so that you never miss my upcoming articles, ranging from <a target="_blank" href="series/python">Python</a> to <a target="_blank" href="series/computer-vision">Computer Vision</a> to <a target="_blank" href="series/scala">Scala</a>.</p>
</li>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[How To Convert Markdown To HTML Using Python]]></title><description><![CDATA[In this article, we are going to see how we can use python to convert GitHub flavoured markdown text to HTML. We will go through a python library, what are its benefits and how we can leverage it for automated conversion.
So, without any further ado,...]]></description><link>https://chandraji.dev/how-to-convert-markdown-to-html-using-python</link><guid isPermaLink="true">https://chandraji.dev/how-to-convert-markdown-to-html-using-python</guid><category><![CDATA[Python]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[markdown]]></category><category><![CDATA[automation]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Fri, 30 Apr 2021 10:13:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1619777451810/ZA8Qucyrp.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we are going to see how we can use python to convert GitHub flavoured markdown text to HTML. We will go through a python library, what are its benefits and how we can leverage it for automated conversion.</p>
<p>So, without any further ado, let's get started!</p>
<hr />
<h3 id="heading-what-are-we-going-to-use">What Are We Going To Use?</h3>
<p>We are going to use Python and one of its awesome 3rd party library, <a target="_blank" href="https://github.com/phseiff/github-flavored-markdown-to-html">gh-md-to-html</a>.</p>
<p>To install <code>gh-md-to-html</code> run the following command on terminal:</p>
<pre><code class="lang-bash">$ pip install gh-md-to-html
Collecting gh-md-to-html
  Downloading gh_md_to_html-1.11.4-py3-none-any.whl (59 kB)
     |████████████████████████████████| 59 kB 5.9 MB/s 
Collecting shellescape
  Downloading shellescape-3.8.1-py2.py3-none-any.whl (3.1 kB)
Collecting Pillow&gt;=8.0.1
  Downloading Pillow-8.2.0-cp38-cp38-macosx_10_10_x86_64.whl (2.8 MB)
     |████████████████████████████████| 2.8 MB 4.8 MB/s 
Collecting webcolors
  Downloading webcolors-1.11.1-py3-none-any.whl (9.9 kB)
Collecting requests
  Using cached requests-2.25.1-py2.py3-none-any.whl (61 kB)
Collecting beautifulsoup4
  Using cached beautifulsoup4-4.9.3-py3-none-any.whl (115 kB)
Collecting soupsieve&gt;1.2
  Downloading soupsieve-2.2.1-py3-none-any.whl (33 kB)
Collecting idna&lt;3,&gt;=2.5
  Using cached idna-2.10-py2.py3-none-any.whl (58 kB)
Collecting certifi&gt;=2017.4.17
  Using cached certifi-2020.12.5-py2.py3-none-any.whl (147 kB)
Collecting chardet&lt;5,&gt;=3.0.2
  Using cached chardet-4.0.0-py2.py3-none-any.whl (178 kB)
Collecting urllib3&lt;1.27,&gt;=1.21.1
  Using cached urllib3-1.26.4-py2.py3-none-any.whl (153 kB)
Installing collected packages: urllib3, soupsieve, idna, chardet, certifi, webcolors, shellescape, requests, Pillow, beautifulsoup4, gh-md-to-html
Successfully installed Pillow-8.2.0 beautifulsoup4-4.9.3 certifi-2020.12.5 chardet-4.0.0 gh-md-to-html-1.11.4 idna-2.10 requests-2.25.1 shellescape-3.8.1 soupsieve-2.2.1 urllib3-1.26.4 webcolors-1.11.1
$
</code></pre>
<p>As we can see, this library depends on a lot of other libraries and is not a pure library like <code>pytube</code> discussed <a target="_blank" href="download-youtube-videos-using-python-your-own-youtube-downloader">here</a>.</p>
<h3 id="heading-advantages">Advantages</h3>
<p>Advantages include (from its official documentation):</p>
<ul>
<li>Let's you specify the markdown to convert as a string, as a repository path, as a local file name or as a hyperlink.</li>
<li>Pulls any images referenced in the markdown files from the web/ your local storage and places them in a directory relative to your specified website root, so the resulting file structure is host-ready for static sites. Multiple arguments allow the customization of the saving locations, but the images will always be referenced correctly in the resulting HTML files. This is especially useful since it reflects GitHub's behaviour to serve cached copies of README images instead of linking to them directly, reducing tracking and possibly downscaling overlarge images in the process.</li>
<li>Creates all links as root-relative hyperlinks and lets you specify the root directory as well as the locations for CSS and images, but uses smart standard values for everything.</li>
<li>Supports inline LaTeX-formulas (use <code>$</code>-formula-<code>$</code> to use them), which GitHub usually doesn't. gh-md-to-html uses <a target="_blank" href="https://www.tug.org/texlive/">LaTeX</a> and <a target="_blank" href="https://dvisvgm.de/">dvisvgm</a> if they are both installed (advantage: fast, requires no internet), and otherwise the <a target="_blank" href="https://latex.codecogs.com/">Codecogs EqnEditor</a> (advantage: doesn't require you to install 3 GB of LaTeX libraries) to achieve this.</li>
<li>Supports exporting to pdf with or without Github styling, using the <a target="_blank" href="https://pypi.org/project/pdfkit/">pdfkit</a> python module (if it is installed).</li>
<li>Tested and optimized to look good when using <a target="_blank" href="https://github.com/darkreader/darkreader">DarkReader</a> (the .js-module as well as the browser extension). This is especially relevant considering that DarkReader doesn't usually shift the colours of SVG images, and the formulas added by gh-md-to-html's formula support are embedded as inline svg. gh-md-to-html ensured that the formulas are the same colour as the text, shifted in accordance with DarkReader's current/enabled colorscheme.</li>
<li>Supports umlauts and other non-ascii-characters in plain text as well as in multiline code blocks, which the github REST api usually doesn't.</li>
<li>Allows you to choose which tool or module to use at its core for the basic markdown to html conversion.</li>
<li>Styles its output with github's README-css (can be turned off).</li>
</ul>
<p>Whilst using pandoc to convert from markdown to pdf usually yields more beautiful results (pandoc uses LaTeX, after all), gh-md-to-html has its own set of advantages when it comes to quickly converting complex files for a homework assignment or other purposes where reliability weights more than beauty. pandoc's md-to-pdf-conversion acts quite unusual when it comes to images, nested lists, multiline bullet point entries, or formulas, and gh-md-to-html does not.</p>
<h3 id="heading-converting-markdown-to-html">Converting Markdown To HTML</h3>
<p>Now, let's create a simple script that converts markdown text to HTML using <code>gh-md-to-html</code>.</p>
<p>Add the following code to a file, name it whatever you like, say <code>mdtohtmldemo.py</code>:</p>
<pre><code class="lang-python"><span class="hljs-comment">#./ mdtohtmldemo.py</span>

<span class="hljs-keyword">import</span> gh_md_to_html

html = gh_md_to_html.main(<span class="hljs-string">'md-to-html/sample.txt'</span>)
print(html)
</code></pre>
<p>Where the markdown contents are as follows (notice that we are using it as a text file, but it is not necessary, we can use <code>.md</code> files directly):</p>
<pre><code class="lang-text"># This is a sample markdown

Hello World!

&gt; Feel free to add your own markdown here.
</code></pre>
<p>After running the above script for given markdown content, we get the below output:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;?xml version='1.0' encoding='UTF-8'?&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/github-markdown-css/github-css.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>/&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"text/html"</span>/&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"gist"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">style</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"formula-style"</span>&gt;</span><span class="css">
        <span class="hljs-selector-tag">svg</span><span class="hljs-selector-class">.gh-md-to-html-formula</span> {
            <span class="hljs-attribute">fill</span>: black;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"gist-file"</span>&gt;</span> <span class="hljs-comment">&lt;!-- This is the class that is responsible for the boxing! --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"gist-data"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"js-gist-file-update-container js-task-list-container file-box"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"article-sample"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"Box-body readme blob js-code-block-container p-5 p-xl-6"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"file-docker-image-pull-md-readme"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"margin-left: 40px; margin-right: 40px; margin-top: 20px; margin-bottom: 20px"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">article</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"markdown-body entry-content container-lg"</span> <span class="hljs-attr">itemprop</span>=<span class="hljs-string">"text"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user-content-this-is-a-sample-markdown"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">aria-hidden</span>=<span class="hljs-string">"true"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"anchor"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#user-content-this-is-a-sample-markdown"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user-content-this-is-a-sample-markdown"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">aria-hidden</span>=<span class="hljs-string">"true"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"octicon octicon-link"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>This is a sample markdown<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">blockquote</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Feel free to add your own markdown here.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">blockquote</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>If we notice, it created a CSS <code>/github-markdown-css/github-css.css</code> in our local directory where we ran the script similar to what github uses.</p>
<p>There is an output HTML file also created with the same name as <code>sample.html</code>, if we open it in a browser, we get the following output:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1619777354750/rohnVAw8s.png" alt="samplehtml.png" /></p>
<hr />
<p>Well, that's it from me. If you followed this, you would be seeing an autogenerated HTML file for your markdown file.</p>
<p>Try different functions, methods and utilities it provides and use them with your projects as needed.</p>
<hr />
<ul>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Download YouTube Videos Using Python - Your Own YouTube Downloader]]></title><description><![CDATA[Do you find it troublesome to always look for a YouTube video downloader with your privacy at risk? Downloading a YouTube video using an external extension might be maddening because of the mouse click ads and other issues while using that extension....]]></description><link>https://chandraji.dev/download-youtube-videos-using-python-your-own-youtube-downloader</link><guid isPermaLink="true">https://chandraji.dev/download-youtube-videos-using-python-your-own-youtube-downloader</guid><category><![CDATA[Python]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[youtube]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[learning]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Thu, 29 Apr 2021 13:26:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1619702191990/tw7mwb4BJ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Do you find it troublesome to always look for a YouTube video downloader with your privacy at risk? Downloading a YouTube video using an external extension might be maddening because of the mouse click ads and other issues while using that extension.</p>
<p>So, why not we create our own bot that can download any YouTube video with just simply running a Python script? Everything would be in our control then, awesome, right?</p>
<p>In this article, we are going to see how we can make a Python script to automate the YouTube video downloading activity.</p>
<p>After going through this article, you can say <code>NO</code> to all those annoying ads, privacy issues, authorisation to different extensions and can finally have total control.</p>
<p>Let's get started!</p>
<hr />
<h3 id="heading-what-are-we-going-to-use">What Are We Going To Use?</h3>
<p>We are going to use Python and one of its amazing 3rd party library, <a target="_blank" href="https://pypi.org/project/pytube/">pytube</a>.</p>
<p>To install pytube:</p>
<pre><code class="lang-bash">$ pip install pytube
Collecting pytube
  Downloading pytube-10.7.2-py3-none-any.whl (42 kB)
     |████████████████████████████████| 42 kB 3.4 MB/s 
Installing collected packages: pytube
Successfully installed pytube-10.7.2
$
</code></pre>
<p>More on pytube:</p>
<ul>
<li>pytube is a very serious, lightweight, dependency-free Python library (and command-line utility) for downloading YouTube Videos.</li>
<li>pytube is a lightweight library written in Python. It has no third-party dependencies and aims to be highly reliable.</li>
<li>pytube also makes pipelining easy, allowing you to specify callback functions for different download events, such as <code>on progress</code> or <code>on complete</code>.</li>
<li>Finally, pytube also includes a command-line utility, allowing you to quickly download videos right from the terminal.</li>
</ul>
<p>Features:</p>
<ul>
<li>Support for both progressive &amp; DASH streams.</li>
<li>Support for downloading complete playlist.</li>
<li>Easily register <code>on_download_progress</code> &amp; <code>on_download_complete</code> callbacks.</li>
<li>Command-line interfaced included.</li>
<li>Caption track support.</li>
<li>Outputs caption tracks to <code>.srt</code> format (SubRip Subtitle).</li>
<li>Ability to capture thumbnail URL.</li>
<li>Extensively documented source code.</li>
<li>No third-party dependencies (written in pure Python).</li>
</ul>
<p>On a high level, to download a video using the library in a script, we'll need to first import the YouTube class from the library, and pass it an argument of the video URL. Then we can download different streams present on that YouTube object.</p>
<p>Now, let's move on to use this information to build our first YouTube video downloader.</p>
<h3 id="heading-get-the-streams">Get The Streams</h3>
<p>First, we will make a simple script to get all the available streams for the given YouTube video URL. Open a file name it whatever you like with the <code>.py</code> extension, let's say for our case we name it <code>pytube_demo.py</code>, add the following code in it and run:</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./pytube_demo.py</span>

<span class="hljs-keyword">from</span> pytube <span class="hljs-keyword">import</span> YouTube

video_url = input(<span class="hljs-string">"Enter YouTube Video URL: "</span>)
youtube_obj = YouTube(video_url)
print(youtube_obj.streams)
</code></pre>
<p>After you hit run, when the terminal prompts you to enter a video URL, enter this <code>https://www.youtube.com/watch?v=fibIyvTleqc</code>, it is one of my favourite songs <code>Daydreamer</code> by <code>AURORA</code>.</p>
<blockquote>
<p><em>Note: You can enter any YouTube video URL here, what we are going to explore further doesn't depend on which URL you enter.</em></p>
</blockquote>
<pre><code class="lang-bash">Enter YouTube Video URL: https://www.youtube.com/watch?v=fibIyvTleqc
[&lt;Stream: itag=<span class="hljs-string">"18"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"360p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.42001E"</span> acodec=<span class="hljs-string">"mp4a.40.2"</span> progressive=<span class="hljs-string">"True"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"137"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"1080p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.640028"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"248"</span> mime_type=<span class="hljs-string">"video/webm"</span> res=<span class="hljs-string">"1080p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"vp9"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"136"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"720p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.4d401f"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"247"</span> mime_type=<span class="hljs-string">"video/webm"</span> res=<span class="hljs-string">"720p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"vp9"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"135"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"480p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.4d401e"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"244"</span> mime_type=<span class="hljs-string">"video/webm"</span> res=<span class="hljs-string">"480p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"vp9"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"134"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"360p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.4d401e"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"243"</span> mime_type=<span class="hljs-string">"video/webm"</span> res=<span class="hljs-string">"360p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"vp9"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"133"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"240p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.4d4015"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"242"</span> mime_type=<span class="hljs-string">"video/webm"</span> res=<span class="hljs-string">"240p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"vp9"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"160"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"144p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.4d400c"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"278"</span> mime_type=<span class="hljs-string">"video/webm"</span> res=<span class="hljs-string">"144p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"vp9"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"140"</span> mime_type=<span class="hljs-string">"audio/mp4"</span> abr=<span class="hljs-string">"128kbps"</span> acodec=<span class="hljs-string">"mp4a.40.2"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"audio"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"249"</span> mime_type=<span class="hljs-string">"audio/webm"</span> abr=<span class="hljs-string">"50kbps"</span> acodec=<span class="hljs-string">"opus"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"audio"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"250"</span> mime_type=<span class="hljs-string">"audio/webm"</span> abr=<span class="hljs-string">"70kbps"</span> acodec=<span class="hljs-string">"opus"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"audio"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"251"</span> mime_type=<span class="hljs-string">"audio/webm"</span> abr=<span class="hljs-string">"160kbps"</span> acodec=<span class="hljs-string">"opus"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"audio"</span>&gt;]
</code></pre>
<p>So, we got a list of <code>Stream</code> objects, each stream object giving us information about different aspects of a video.</p>
<p>If we see <code>res</code> attribute of stream object, we see that we have <code>360p</code>, <code>1080p</code>, <code>720p</code>, <code>480p</code>, <code>240p</code> and <code>144p</code> with different <code>vcodec</code> attribute. This <code>res</code> represents the resolution of a video, we can select any stream of desired resolution to download.</p>
<p>Also, notice that we have only audio option streams available as well to download.</p>
<p>Next, we will create a filter for video resolution and to keep it simple we will not dive into audio downloadable streams.</p>
<h3 id="heading-filter-stream-based-on-resolution">Filter Stream Based On Resolution</h3>
<p>Update the code in the <code>pytube_demo.py</code> file to the below code:</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./pytube_demo.py</span>

<span class="hljs-keyword">from</span> pytube <span class="hljs-keyword">import</span> YouTube

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_stream_for_res</span>(<span class="hljs-params">streams, res</span>):</span>
    <span class="hljs-string">"""
    Filter on the basis of a given resolution. Return a list of filtered streams.
    """</span>
    stream = list(filter(<span class="hljs-keyword">lambda</span> x: x.resolution == res, streams))
    <span class="hljs-keyword">return</span> stream

video_url = input(<span class="hljs-string">"Enter YouTube Video URL: "</span>).strip()
youtube_obj = YouTube(video_url)

video_res = input(<span class="hljs-string">f"Enter YouTube Video Resolution for <span class="hljs-subst">{youtube_obj.title}</span>: "</span>).strip()
req_stream_obj = get_stream_for_res(youtube_obj.streams, video_res)
print(req_stream_obj)
</code></pre>
<p>Hit run and we can see following output in the terminal:</p>
<pre><code class="lang-bash">Enter YouTube Video URL: https://www.youtube.com/watch?v=fibIyvTleqc
Enter YouTube Video Resolution <span class="hljs-keyword">for</span> AURORA - Daydreamer (Audio): 720p
[&lt;Stream: itag=<span class="hljs-string">"136"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"720p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.4d401f"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;, &lt;Stream: itag=<span class="hljs-string">"247"</span> mime_type=<span class="hljs-string">"video/webm"</span> res=<span class="hljs-string">"720p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"vp9"</span> progressive=<span class="hljs-string">"False"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;]
</code></pre>
<p>First, we take the video URL and creates the <code>YouTube</code> object, then we take custom input from the user while displaying the title of the video using <code>youtube_obj.title</code>. After receiving the resolution, say <code>720p</code>, we call the function <code>get_stream_for_res</code> that filters the given list of streams on the given resolution. At last, we can see the output, it contains 2 stream objects in a list, both objects have different values for some attributes but have the same resolution.</p>
<p>Without diving deep on what all other attribute means, let's just simply take the first element of the list and download the video.</p>
<h3 id="heading-download-stream-based-on-resolution">Download Stream Based On Resolution</h3>
<p>Now update the code to the following to download the YouTube video (complete script):</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./pytube_demo.py</span>

<span class="hljs-keyword">from</span> pytube <span class="hljs-keyword">import</span> YouTube

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_stream_for_res</span>(<span class="hljs-params">streams, res</span>):</span>
    stream = list(filter(<span class="hljs-keyword">lambda</span> x: x.resolution == res, streams))
    <span class="hljs-keyword">return</span> stream

video_url = input(<span class="hljs-string">"Enter YouTube Video URL: "</span>).strip()
youtube_obj = YouTube(video_url)

video_res = input(<span class="hljs-string">f"Enter YouTube Video Resolution for <span class="hljs-subst">{youtube_obj.title}</span>: "</span>).strip()
req_stream_obj = get_stream_for_res(youtube_obj.streams, video_res)[<span class="hljs-number">0</span>]

req_stream_obj.download()
print(<span class="hljs-string">f"YouTube Video <span class="hljs-subst">{youtube_obj.title}</span> Downloaded With Resolution <span class="hljs-subst">{video_res}</span>"</span>)
</code></pre>
<p>When we run the above script, we get the following output and a downloaded video:</p>
<pre><code class="lang-bash">Enter YouTube Video URL: https://www.youtube.com/watch?v=fibIyvTleqc
Enter YouTube Video Resolution <span class="hljs-keyword">for</span> AURORA - Daydreamer (Audio): 720p
YouTube Video AURORA - Daydreamer (Audio) Downloaded With Resolution 720p
</code></pre>
<p>Now, if we check our directory where we ran the script, we can find the downloaded video.</p>
<p><strong>Note:</strong></p>
<blockquote>
<p>You may notice that some streams listed have both a video codec and audio codec, while others have just video or just audio, this is a result of YouTube supporting a streaming technique called Dynamic Adaptive Streaming over HTTP (DASH).</p>
<p>In the context of pytube, the implications are for the highest quality streams; you now need to download both the audio and video tracks and then post-process them with software like FFmpeg to merge them.</p>
<p>The legacy streams that contain the audio and video in a single file (referred to as “progressive download”) are still available, but only for resolutions 720p and below.</p>
</blockquote>
<p>The video downloaded from the given code has a Stream object whose attribute <code>progressive</code> is <code>False</code>. The given video URL does not have legacy streams available for <code>720p</code> but if you notice there is one stream with <code>progressive</code> as <code>True</code> and <code>res</code> as <code>360p</code>.</p>
<pre><code class="lang-bash">&lt;Stream: itag=<span class="hljs-string">"18"</span> mime_type=<span class="hljs-string">"video/mp4"</span> res=<span class="hljs-string">"360p"</span> fps=<span class="hljs-string">"25fps"</span> vcodec=<span class="hljs-string">"avc1.42001E"</span> acodec=<span class="hljs-string">"mp4a.40.2"</span> progressive=<span class="hljs-string">"True"</span> <span class="hljs-built_in">type</span>=<span class="hljs-string">"video"</span>&gt;
</code></pre>
<p>So, go ahead and experiment with it and don't forget to check out the <code>progressive</code> attribute.</p>
<h3 id="heading-what-next">What Next?</h3>
<p>Well, that's it from me. If you followed this and ran the final script, you would be seeing a downloaded video in your working directory.</p>
<p>You can take it to the next level by creating a UI for this utility. You can host this as a service that would be strictly private to you.</p>
<p>What are you waiting for then? Use Tkinter, PyQT, Kivy, Flask or Django and make a UI with more functions like a select option for audio and video, for video resolution and for audio ABR, etc. and say <code>NO</code> to all those annoying ads, privacy issues, several authorisations to different extensions and have total control over your downloaded videos.</p>
<hr />
<ul>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Python - List Vs Tuple Memory Management]]></title><description><![CDATA[This article is going to be a short read, we will focus on how memory is managed in Python for objects like list and tuple and what can be the key takeaways.
Let's get started!

List
Python list as we all know is a mutable dynamic array that behaves ...]]></description><link>https://chandraji.dev/python-list-vs-tuple-memory-management</link><guid isPermaLink="true">https://chandraji.dev/python-list-vs-tuple-memory-management</guid><category><![CDATA[Python]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[Productivity]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Wed, 28 Apr 2021 14:05:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1619618298035/OLC2xHwSy.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is going to be a short read, we will focus on how memory is managed in Python for objects like <code>list</code> and <code>tuple</code> and what can be the key takeaways.</p>
<p>Let's get started!</p>
<hr />
<h3 id="heading-list">List</h3>
<p>Python list as we all know is a mutable dynamic array that behaves like a linked list as well. Let's look at some code for creating and updating a list:</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./list_1.py</span>

l = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]     <span class="hljs-comment"># A new list gets created</span>
print(<span class="hljs-string">'Initial List'</span>, l)

l.append(<span class="hljs-number">4</span>)     <span class="hljs-comment"># Updating list using in-built append method</span>
print(<span class="hljs-string">'Append 4, List updated to'</span>, l)

l.pop()         <span class="hljs-comment"># Pop last item</span>
print(<span class="hljs-string">'Pop, List updated to'</span>, l)

l += [<span class="hljs-number">5</span>, <span class="hljs-number">6</span>]     <span class="hljs-comment"># Updating list by adding a new list to given list</span>
print(<span class="hljs-string">'Add new list, List updated to'</span>, l)
</code></pre>
<p>Following will be the output:</p>
<pre><code class="lang-bash">Initial List [1, 2, 3]
Append 4, List updated to [1, 2, 3, 4]
Pop, List updated to [1, 2, 3]
Add new list, List updated to [1, 2, 3, 5, 6]
&gt;&gt;&gt;
</code></pre>
<p>Now let's see what happens in memory when we run the above script, here we will be using <code>sys</code> to help us out on viewing system-related information:</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./list_2.py</span>

<span class="hljs-keyword">import</span> sys
l = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]     <span class="hljs-comment"># A new list gets created</span>
print(<span class="hljs-string">'Initial List'</span>, l)
print(<span class="hljs-string">'Initial List Address'</span>, id(l))
print(<span class="hljs-string">'Initial List Memory'</span>, sys.getsizeof(l))

l.append(<span class="hljs-number">4</span>)     <span class="hljs-comment"># Updating list using in-built append method</span>
print(<span class="hljs-string">'Append 4, List updated to'</span>, l)
print(<span class="hljs-string">'Append 4, List Address'</span>, id(l))
print(<span class="hljs-string">'Append 4, List Memory'</span>, sys.getsizeof(l))

l.pop()         <span class="hljs-comment"># Pop last item</span>
print(<span class="hljs-string">'Pop, List updated to'</span>, l)
print(<span class="hljs-string">'Pop, List Address'</span>, id(l))
print(<span class="hljs-string">'Pop, List Memory'</span>, sys.getsizeof(l))

l += [<span class="hljs-number">5</span>, <span class="hljs-number">6</span>]     <span class="hljs-comment"># Updating list by adding a new list to given list</span>
print(<span class="hljs-string">'Add new list, List updated to'</span>, l)
print(<span class="hljs-string">'Add new list, List Address'</span>, id(l))
print(<span class="hljs-string">'Add new list, List Memory'</span>, sys.getsizeof(l))
</code></pre>
<p>Let's look at the output first:</p>
<pre><code class="lang-bash">Initial List [1, 2, 3]
Initial List Address 139688582615624
Initial List Memory 88
Append 4, List updated to [1, 2, 3, 4]
Append 4, List Address 139688582615624
Append 4, List Memory 120
Pop, List updated to [1, 2, 3]
Pop, List Address 139688582615624
Pop, List Memory 120
Add new list, List updated to [1, 2, 3, 5, 6]
Add new list, List Address 139688582615624
Add new list, List Memory 120
&gt;&gt;&gt;
</code></pre>
<p>Following points we can find out after looking at the output:</p>
<ul>
<li>Initially, when the list got created, it had a memory of <code>88</code> bytes, with 3 elements.</li>
<li>Later on, after appending an element <code>4</code> to the list, the memory changes to <code>120</code> bytes, meaning more memory blocks got linked to list <code>l</code>.</li>
<li>Even after popping out the last element the created blocks memory remains the same and still attached to list <code>l</code>. And when we add another list with 2 more elements to the given list <code>l</code>, we see that occupied memory is still the same <code>120</code> bytes. Hence, we can conclude that it is behaving more like a dynamic array, which updates the size of the list to contain more elements at once to avoid repetitive callbacks (to create and attach new memory address) at every insertion of the new element.</li>
<li>We also notice that the list address remains the same, even if we do append, pop or add a new list to it (as long as we don't assign it to a new variable). This advocates the nature of the mutability of python lists (it means, more or less, that at the same address we are able to update values or extend it further).</li>
</ul>
<p>Now, let's look at the tuples.</p>
<h3 id="heading-tuple">Tuple</h3>
<p>Python tuple as we all know are immutable and do not extend in the memory further after the initial declaration. Now, let's look at the above same scenario but for tuples:</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./tuple_1.py</span>

<span class="hljs-keyword">import</span> sys
t = (<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>)     <span class="hljs-comment"># A new tuple gets created</span>
print(<span class="hljs-string">'Initial Tuple'</span>, t)
print(<span class="hljs-string">'Initial Tuple Address'</span>, id(t))
print(<span class="hljs-string">'Initial Tuple Memory'</span>, sys.getsizeof(t))

t += (<span class="hljs-number">5</span>, <span class="hljs-number">6</span>,)     <span class="hljs-comment"># Updating tuple by adding a new tuple to given tuple</span>
print(<span class="hljs-string">'Add new tuple, Tuple updated to'</span>, t)
print(<span class="hljs-string">'Add new tuple, Tuple Address'</span>, id(t))
print(<span class="hljs-string">'Add new tuple, Tuple Memory'</span>, sys.getsizeof(t))
</code></pre>
<p>Output:</p>
<pre><code class="lang-bash">Initial Tuple (1, 2, 3)
Initial Tuple Address 140452527817280
Initial Tuple Memory 72
Add new tuple, Tuple updated to (1, 2, 3, 5, 6)
Add new tuple, Tuple Address 140452528572728
Add new tuple, Tuple Memory 88
&gt;&gt;&gt;
</code></pre>
<p>Following points we notice after looking at the output:</p>
<ul>
<li>Since, tuples are immutable, once created cannot be updated unless a new tuple gets added to the previous one, resulting in the creation of a new tuple.</li>
<li>Once a tuple gets created, its allocated memory will not be changed.</li>
<li>Updating a tuple after adding another tuple to it, updates the address of the resulting tuple, this advocated its immutability property.</li>
<li>We can see it allocates <code>72</code> bytes for 3 values and <code>88</code> for 6 values, it does not allocate the unnecessary amount of memory, only what is required is allocated.</li>
</ul>
<p>Let's look at some miscellaneous points.</p>
<h3 id="heading-misc">MISC</h3>
<p>What happens when we create an empty list and empty tuple?</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./misc.py</span>

<span class="hljs-keyword">import</span> sys

t1 = ()
t2 = ()

l1 = []
l2 = []

print(<span class="hljs-string">'List l1 address'</span>, id(l1))
print(<span class="hljs-string">'List l2 address'</span>, id(l2))
print(<span class="hljs-string">'List l1 memory'</span>, sys.getsizeof(l1))
print(<span class="hljs-string">'List l2 memory'</span>, sys.getsizeof(l2))

print(<span class="hljs-string">'List t1 address'</span>, id(t1))
print(<span class="hljs-string">'List t2 address'</span>, id(t2))
print(<span class="hljs-string">'List t1 memory'</span>, sys.getsizeof(t1))
print(<span class="hljs-string">'List t2 memory'</span>, sys.getsizeof(t2))
</code></pre>
<p>What did we get?</p>
<pre><code class="lang-bash">List l1 address 139766851756616
List l2 address 139766851761800
List l1 memory 64
List l2 memory 64
List t1 address 139766871547976
List t2 address 139766871547976
List t1 memory 48
List t2 memory 48
&gt;&gt;&gt;
</code></pre>
<p>What did we find?</p>
<ul>
<li>Creating 2 empty lists have the same amount of memory allocated, whereas the address of both lists is different. It makes sense because, list address will have to act as mutable and cannot be the same at a given time, which means 2 different lists will be different unless they are the same (not in value but in reference point of view).</li>
<li>Creating 2 empty tuples have the same amount of memory allocated and will point to the same address initially. It makes sense because of its immutability property. Consider integer <code>1</code> value in python that is immutable and always point to the same address unless changed to some other integer. Similarly, the initial empty tuple will always point to the same address unless changed to some other tuple.</li>
</ul>
<hr />
<p>Well, that's it from me.</p>
<p>We explored quite a few points on how memory is allocated and how it could be managed in Python.</p>
<p>To know more about memory management, I encourage you to explore their code available on python's <a target="_blank" href="https://github.com/python/cpython">repo</a>.</p>
<p>Feeling it's difficult to go through the source code of python? Don't worry, we can always use available <code>sys</code> module methods and other functions like <code>id</code> to develop an understanding of what could be happening behind the scenes.</p>
<hr />
<ul>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[Shell Script Basics]]></title><description><![CDATA[The best thing about GNU/Linux is that it’s packed with utilities that improve productivity immensely. One such utility is a shell that can help accomplish complex tasks with just a few sequences of commands. Most of the time, users operate shell in ...]]></description><link>https://chandraji.dev/shell-script-basics</link><guid isPermaLink="true">https://chandraji.dev/shell-script-basics</guid><category><![CDATA[shell]]></category><category><![CDATA[Script]]></category><category><![CDATA[basics]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Mon, 26 Apr 2021 04:27:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1619410959444/zRf2a1H8t.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The best thing about GNU/Linux is that it’s packed with utilities that improve productivity immensely. One such utility is a shell that can help accomplish complex tasks with just a few sequences of commands. Most of the time, users operate shell in an interactive way. </p>
<p>However, it becomes really productive when we leverage the scripting capabilities of the shell.</p>
<p>In this article, we are going to explore the basics of shell scripting, how simple <code>echo</code> command can be used in a shell script file, how to write comments, working with variables and conditionals.</p>
<p>Keeping it short and simple, let's get started!</p>
<hr />
<h3 id="heading-shell-script-printing">Shell Script Printing</h3>
<p>When we are working with shell scripts printing on the output screen is called echoing which can be done using <code>echo</code>.</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello Shell"</span>
Hello Shell
</code></pre>
<p>Let's do this inside a shell script file. Follow the below steps:</p>
<ol>
<li>Create a file, name it whatever you want with the <code>.sh</code> extension. Let's say <code>echo_script.sh</code>.</li>
<li>Add following inside the file - <code>echo "Hello Shell"</code>, hit <code>Save</code> and open a terminal on the file location.</li>
<li>On the terminal, write - <code>$ bash echo_script.sh</code> and hit enter, you should be able to see - <code>Hello Shell</code>.</li>
</ol>
<h3 id="heading-shell-script-comments">Shell Script Comments</h3>
<p>Comments are used to improve the readability of the script. Shell uses the pound <code>#</code> symbol for comments. A line beginning with the pound <code>#</code> symbol is ignored by the shell interpreter during execution. </p>
<p>The script given below shows the usage of the comment:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Display Hello Shell using echo command of shell, filename.sh</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello Shell"</span>
</code></pre>
<p>Go to terminal and type - <code>$ bash filename.sh</code> (replace <code>filename</code> with whatever name you have given) and hit enter. You should be able to see - <code>Hello Shell</code> without printing anything given after the <code>#</code> symbol.</p>
<h3 id="heading-shell-script-variables">Shell Script Variables</h3>
<p>We can define variables to store information, which can be accessed within the shell script. There are certain rules we need to follow while defining variables:</p>
<ol>
<li>The variable name can contain any combination of letters from A-Z or a-z, digits from 0-9 or an underscore (_) character.</li>
<li>The variable name should start with a letter or an underscore character.</li>
<li>Variables are case sensitive.</li>
</ol>
<p>By convention, shell variables are defined in the upper case. Given below is a simple script, which shows the usage of a variable within it:</p>
<pre><code class="lang-bash">$ cat hello.sh
NAME=<span class="hljs-string">"CodeKaro"</span>
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Hello <span class="hljs-variable">$NAME</span>"</span>
</code></pre>
<p><code>cat</code> command is used to display the content of a file given after that. Try your hands on it.</p>
<p>So, we have a file <code>hello.sh</code> which contains a variable <code>NAME</code> which we used in the <code>echo</code> statement as <code>$NAME</code> that is after the <code>$</code> symbol. Here we saw variable declaration and how inside double quotes a variable can be used.</p>
<p>If you hit - <code>$ bash hello.sh</code> and hit enter, you should be able to see - <code>Hello CodeKaro</code> on the terminal.</p>
<h3 id="heading-shell-script-conditionals">Shell Script Conditionals</h3>
<p>Like other programming languages, shell supports conditional expressions like – <em>if</em>, <em>if-else</em> and <em>case</em>. Let us understand this with simple examples:</p>
<ol>
<li><code>if</code> expression: In case we want to verify whether a file exists or not, we can use the if expression, as follows:</li>
</ol>
<pre><code class="lang-bash">$ touch file.txt <span class="hljs-comment">#this creates a file</span>

$ cat file_existance.sh
<span class="hljs-keyword">if</span> [ -e file.txt ]; <span class="hljs-keyword">then</span>
<span class="hljs-built_in">echo</span> “file.txt file exists”
<span class="hljs-keyword">fi</span>
</code></pre>
<p>The script given above generates the following output when it is executed:</p>
<pre><code class="lang-bash">$ bash file_existance.sh
file.txt file exists
</code></pre>
<ol>
<li><code>if-else</code> expression: Let us modify the above script to generate output when the file does not exist:</li>
</ol>
<pre><code class="lang-bash">$ rm file.txt
$ cat file_existance.sh
<span class="hljs-keyword">if</span> [ -e file.txt ]; <span class="hljs-keyword">then</span>
<span class="hljs-built_in">echo</span> “file.txt file exists”
<span class="hljs-keyword">else</span>
<span class="hljs-built_in">echo</span> “file.txt file does not exists”
<span class="hljs-keyword">fi</span>
</code></pre>
<p>Type following and hit enter:</p>
<pre><code class="lang-bash">$ bash file_existance.sh
file.txt file does not exists
</code></pre>
<ol>
<li><code>case</code> statement: Shell provides a switch statement-like functionality using the case statement. Let us understand this with the example given below:</li>
</ol>
<pre><code class="lang-bash">$ cat case_statement.sh
<span class="hljs-built_in">read</span> -p “Enter the day: “ DAY

<span class="hljs-keyword">case</span> <span class="hljs-variable">$DAY</span> <span class="hljs-keyword">in</span>
Mon) <span class="hljs-built_in">echo</span> “Today is Monday”
;;

Tue) <span class="hljs-built_in">echo</span> “Today is Tuesday”
;;

Wed) <span class="hljs-built_in">echo</span> “Today is Wednesday”
;;

*) <span class="hljs-built_in">echo</span> “Unknown day”
;;
<span class="hljs-keyword">esac</span>
</code></pre>
<p>The script given above generates the following output when it is executed:</p>
<pre><code class="lang-bash">$ bash case_statement.sh
Enter the day: Mon
Today is Monday
</code></pre>
<pre><code class="lang-bash">$ bash case_statement.sh
Enter the day: Tue
Today is Tuesday
</code></pre>
<pre><code class="lang-bash">$ bash case_statement.sh
Enter the day: Invalid
Unknown day
</code></pre>
<p>In the <code>case</code> statement, an asterisk (*) denotes a default case.</p>
<p>Well, that's it from me. </p>
<p>We covered printing, variables, comments and conditionals, not too much, right? </p>
<hr />
<ul>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
<blockquote>
<p><em>Image Credits - <a href="https://www.freepik.com/vectors/book">pch.vector</a></em></p>
</blockquote>
]]></content:encoded></item><item><title><![CDATA[How To Make A SlideShow Using OpenCV]]></title><description><![CDATA[We have been making slideshows for most of our college/office presentations to look great while presenting using Microsoft PowerPoint, let's take this as an image processing activity and see how we can achieve slide show utility using Python's OpenCV...]]></description><link>https://chandraji.dev/how-to-make-a-slideshow-using-opencv</link><guid isPermaLink="true">https://chandraji.dev/how-to-make-a-slideshow-using-opencv</guid><category><![CDATA[Python]]></category><category><![CDATA[image processing]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[opencv]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Sun, 25 Apr 2021 10:48:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1619346933261/kQQfa1Nb9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We have been making slideshows for most of our college/office presentations to look great while presenting using Microsoft PowerPoint, let's take this as an image processing activity and see how we can achieve slide show utility using Python's OpenCV library in this article.</p>
<p>It could be a pass time activity or something new to learn or just to show off your friends or juniors, so without any further ado, let's get started!</p>
<blockquote>
<p><em>Note: If you do not have OpenCV installed, I suggest you visit <a target="_blank" href="lets-draw-opencv-logo-using-opencv">here</a> and check <strong>Prerequisites</strong> steps on the process of installation.</em></p>
</blockquote>
<hr />
<h3 id="heading-necessary-imports">Necessary Imports</h3>
<p>First, create a python file, name it whatever you like, for this article let's say <code>slideshow.py</code>. Now add the following imports to the file created:</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./slideshow.py</span>

<span class="hljs-keyword">import</span> cv2
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> ceil
<span class="hljs-keyword">import</span> os
</code></pre>
<ul>
<li>We import <code>cv2</code> for all image processing tasks, <code>numpy</code> with alias <code>np</code> to create an initial window for display (all things in OpenCV works with numpy under the hood), <code>ceil</code> from <code>math</code> to satisfy a future condition (how do I know if need it or not?, well you don't, during the process of making an app there would be times when you will have to continuously improve your program and it's fine, but for this article, I want to keep everything at one place from starting, so don't worry just know that we will need this import) and lastly we import <code>os</code> to extract all image files that we need in a slideshow.</li>
</ul>
<blockquote>
<p><em>Note: You also need a set of images you would want to view as a slideshow. Collect them and keep them in the <code>./images</code> folder and don't worry about the size of images.</em></p>
</blockquote>
<h3 id="heading-variables-image-window-and-alpha-beta">Variables, Image Window and Alpha-Beta</h3>
<p>Add the following code to the same file:</p>
<pre><code class="lang-python">
dst = <span class="hljs-string">"./images/"</span>       <span class="hljs-comment"># Images destination</span>
images = os.listdir(dst)    <span class="hljs-comment"># Get their names in a list</span>
length = len(images)

result = np.zeros((<span class="hljs-number">360</span>,<span class="hljs-number">360</span>,<span class="hljs-number">3</span>), np.uint8)        <span class="hljs-comment"># Image window of size (360, 360)</span>
i = <span class="hljs-number">1</span>

a = <span class="hljs-number">1.0</span>     <span class="hljs-comment"># alpha</span>
b = <span class="hljs-number">0.0</span>     <span class="hljs-comment"># beta</span>
img = cv2.imread(dst + images[i])
img = cv2.resize(img, (<span class="hljs-number">360</span>, <span class="hljs-number">360</span>))
</code></pre>
<ul>
<li>First 3 lines find out the image name of all the images present in the <code>./images</code> folder. We use the <code>os.listdir</code> method to list all the contents of a directory and then keep them in the <code>images</code> variable and also we keep the length as a measure for total available images.</li>
<li>Next, we create an image window of size <code>(360, 360, 3)</code>, which is a 3 channel image. Initially, it will all be black (filled with zeros).</li>
<li>Then we define some more constants, <code>i</code> to be used to loop over images, <code>a</code> to keep initial alpha value and <code>b</code> for initial beta value, we will see how these are used for image transition that ultimately will give the slideshow effect.</li>
<li>At last, we take the first image from the list of images, resize it to fit the window, this will be the first image to appear on the slideshow.</li>
</ul>
<h3 id="heading-slideshow-loop">SlideShow Loop</h3>
<p>Let's create our slideshow, add the following code to the same file:</p>
<pre><code class="lang-python">
<span class="hljs-comment"># Slide Show Loop</span>
<span class="hljs-keyword">while</span>(<span class="hljs-literal">True</span>):

    <span class="hljs-keyword">if</span>(ceil(a)==<span class="hljs-number">0</span>):
        a = <span class="hljs-number">1.0</span>
        b = <span class="hljs-number">0.0</span>
        i = (i+<span class="hljs-number">1</span>)%length    <span class="hljs-comment"># Getting new image from directory</span>
        img = cv2.imread(dst + images[i])
        img = cv2.resize(img, (<span class="hljs-number">360</span>, <span class="hljs-number">360</span>))

    a -= <span class="hljs-number">0.01</span>
    b += <span class="hljs-number">0.01</span>

    <span class="hljs-comment"># Image Transition from one to another</span>
    result = cv2.addWeighted(result, a, img, b, <span class="hljs-number">0</span>)
    cv2.imshow(<span class="hljs-string">"Slide Show"</span>, result)
    key = cv2.waitKey(<span class="hljs-number">1</span>) &amp; <span class="hljs-number">0xff</span>
    <span class="hljs-keyword">if</span> key==ord(<span class="hljs-string">'q'</span>):
        <span class="hljs-keyword">break</span>

cv2.destroyAllWindows()
</code></pre>
<ul>
<li>Now, we create a while infinite loop. Inside it, there is a conditional that checks for <code>ceil(a)</code> if it reaches <code>0</code> (zero) then we reset the <code>a</code> and <code>b</code> values, update <code>i</code> in a circular fashion using modulus operator <code>%</code> on the length of the list of images to get the index of next image, and update <code>img</code> variable to contain a new image and resize it.</li>
<li>Outside of the conditional, we use <code>a</code> and <code>b</code> to decrease and increase alpha and beta values respectively. This variation will give us the transition effect that seems to be smooth. We will use these with the <code>cv2.addWeighted</code> method that just overlaps one image over another depending on the weight of the given images.</li>
<li><code>result</code> stores the new updated image that we will display using the <code>cv2.imshow</code> method of the OpenCV. At last, we wait for a key event and breaks out of the while loop if it happens and destroy all windows created during execution using the <code>cv2.destroyAllWindow</code> method.</li>
</ul>
<p><code>cv2.addWeighted</code> method is what helps us to achieve the slideshow effect that we wanted. Here, the alpha <code>a</code> value is the weight for the resulting image (that was initially a black window) and the beta <code>b</code> value is for a new image that will overlap the <code>result</code> window. Make sure that sum of <code>a</code> and <code>b</code> remains equal to<code>1</code> (one). For more information on this, please visit <a target="_blank" href="https://docs.opencv.org/3.4/d5/dc4/tutorial_adding_images.html">here</a>.</p>
<h3 id="heading-demo-how-it-looks">Demo - How It Looks</h3>
<p>The images I took are logos of my favourite programming languages - Python, Scala and ReactJS (currently learning).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1619347152591/cjuu6ZS_W.gif" alt="demo.gif" /></p>
<blockquote>
<p><em>For complete script, visit <a target="_blank" href="https://github.com/siddharth2016/Opencv-Python-Computer-Vision/blob/master/imageSlideShow.py">here</a>.</em></p>
</blockquote>
<h3 id="heading-what-next">What Next?</h3>
<p>Well, that's it from me. If you followed this, you might be seeing a wonderful slideshow of your collection of images. As for the next steps, you can enhance this application by adding the following:</p>
<ul>
<li>Add buttons to change the type of slideshow. Currently, it is only doing a smooth transition, try to implement a different animated transition.</li>
<li>Add a utility to select a number of images and not all, as we did, we just took every image. Also, you can try to handle exception like what if a non-image comes from the folder.</li>
</ul>
<hr />
<ul>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Want to showcase your Python project or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item><item><title><![CDATA[10 Most Popular GitHub Repositories]]></title><description><![CDATA[Open Source Software (OSS) has been getting a lot of traction in recent years. Right now, there are approximately 200,000 open source projects worth billions of dollar, being worked on across the globe.
GitHub hosts software for development and versi...]]></description><link>https://chandraji.dev/10-most-popular-github-repositories</link><guid isPermaLink="true">https://chandraji.dev/10-most-popular-github-repositories</guid><category><![CDATA[Open Source]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Python]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Thu, 22 Apr 2021 15:50:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1619106430581/la8-RR8bF.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Open Source Software (OSS) has been getting a lot of traction in recent years. Right now, there are approximately 200,000 open source projects worth billions of dollar, being worked on across the globe.</p>
<p>GitHub hosts software for development and version control. The main repository can have many branches or forks. GitHub is widely used by developers to test code and to collaborate with other developers in the software development life cycle.</p>
<p>In this article, we will go through the ten most popular open-source repositories on GitHub.</p>
<hr />
<h3 id="heading-freecodecamphttpsgithubcomfreecodecampfreecodecamp"><a target="_blank" href="https://github.com/freeCodeCamp/freeCodeCamp">FreeCodeCamp</a></h3>
<p>This is one of the biggest repositories on GitHub because it offers newcomers the means to learn how to code effectively, for free. As the name suggests, it is a user-friendly and safe environment for coders to learn skills.</p>
<p>Any learner can build his or her own project, learn to code and adopt best practices. Since its inception, the page has collected more than <code>320K</code> stars on GitHub. This community is the best example of OSS - a place where everyone can contribute and learn for free.</p>
<h3 id="heading-vscodehttpsgithubcommicrosoftvscode"><a target="_blank" href="https://github.com/microsoft/vscode">VSCode</a></h3>
<p>Visual Studio Code is a free and open-source code editor developed by Microsoft for Windows, Linus and macOS. It is an all-purpose code editor and its focus is to provide developers with a single stop solution for all their coding needs, including editing and debugging.</p>
<p>VSCode is an extremely well-liked open-source repository on GitHub, with more than <code>110K</code> stars and <code>1.4K</code> contributors. This repository is used to work on code and can also be used as a publishing platform. It gets updated every month with bug fixes, new features and some enhancements.</p>
<h3 id="heading-flutterhttpsgithubcomflutterflutter"><a target="_blank" href="https://github.com/flutter/flutter">Flutter</a></h3>
<p>This software development kit made by Google is one of the fastest-growing open source communities on GitHub. It permits applications to be developed from a single codebase with a user interface toolkit. The applications created by Flutter are attuned with PC and mobile platforms and their appearance creates aesthetic and efficient end-user experiences.</p>
<p>Flutter is pushed by Skia, and the hardware-accelerated 2D graphics library by Android and Chrome. It also employs a layered architecture for building applications, which allows developers to flawlessly add text, graphics, video and animated content as overlays without disturbing the source code. Its GitHub page has over <code>117K</code> stars.</p>
<h3 id="heading-ansiblehttpsgithubcomansibleansible"><a target="_blank" href="https://github.com/ansible/ansible">Ansible</a></h3>
<p>This open-source IT engine automates application operation and cloud provisioning. It was created in 2012 by AnsibleWorks and is now owned by Red Hat. Ansible is developed in Python, is lightweight and has fast deployment. As Python is used to build most Linux and UNIX systems, getting Ansible up and running is very quick, and its agentless feature makes it easy to be set up and used.</p>
<p>It can also be run from CLI commands without using configuration files. For comparatively difficult tasks, its configuration is handled by the YAML syntax in the configuration file known as <code>playbook</code>. Ansible commands can be written in any programming language and sent over in JSON format. It has also recently started supporting Windows. It has over <code>46K</code> stars on GitHub.</p>
<h3 id="heading-kuberneteshttpsgithubcomkuberneteskubernetes"><a target="_blank" href="https://github.com/kubernetes/kubernetes">Kubernetes</a></h3>
<p>The powerful open-source system was initially developed by Google for managing containerised applications in a cluster environment. Kubernetes was launched in 2014 after more than a decade of experience running production workloads at Google with Google's internal container cluster managers Borg and Omega.</p>
<p>It aims to provide better ways of managing related and distributed components and services across varied infrastructures. Kubernetes has now become the <em>de facto</em> standard for deploying containerised applications at scale in private, public and hybrid cloud environments. The largest public cloud platforms - including AWS, Google Cloud, Azure, IBM Cloud and Oracle Cloud - now provide managed services for Kubernetes. Its repository has more than <code>76K</code> stars.</p>
<h3 id="heading-react-nativehttpsgithubcomfacebookreact-native"><a target="_blank" href="https://github.com/facebook/react-native">React Native</a></h3>
<p>React Native is a JavaScript framework that is used in many social media platforms, including Facebook, Twitter, and so on. This framework allows the user to build native applications using JavaScript. It brings React's declarative user interface build to mobile platforms as well as allows the developer to use native UI controls to gain full access to the platforms.</p>
<p>React Native has a lively GitHub community with several contributors and over <code>94K</code> stars. This platform understood and modified more easily. It also makes it simple to build component-based complex UIs and allows any local changes to replicate quickly on the project. Developers use the GitHub community to interact, collaborate and contribute to the program, making it a popular choice for JavaScript coders.</p>
<h3 id="heading-tensorflowhttpsgithubcomtensorflowithtensorflow"><a target="_blank" href="https://github.com/tensorflow/tensorflow">TensorFlow</a></h3>
<p>This is a popular open-source machine learning framework. It contains a large number of useful libraries, tools, and community resources focused on making ML capabilities available for developers looking to use them in their projects. With TensorFlow, developers can easily create and deploy ML models as part of their application and also use them on their system, on the cloud or from a mobile platform.</p>
<p>Developed by experts working in the Google Brain team, the system is compatible with all major operating systems. The GitHub page has more than <code>150K</code> stars and more than <code>2.9K</code> contributors.</p>
<h3 id="heading-definitelytypedhttpsgithubcomdefinitelytypeddefinitelytyped"><a target="_blank" href="https://github.com/DefinitelyTyped/DefinitelyTyped">DefinitelyTyped</a></h3>
<p>This is a library of TypeScript type definitions maintained on GitHub. In this open-source repository, developers can share and keep TypeScript type definitions for JS libraries. It mainly serves as a translator for JS developers to work with TypeScript. Using DefinitelyTyped and its declaration statements, they can discover TypeScript equivalents for existing JS libraries.</p>
<p>Developers can contribute to the repository by adding definitions, testing, and so on. This is an extremely popular page, with thousands of contributors and many times more users. It has more than <code>33K</code> stars and <code>13K</code> active contributors.</p>
<h3 id="heading-azurehttpsgithubcommicrosoftdocsazure-docs"><a target="_blank" href="https://github.com/MicrosoftDocs/azure-docs">Azure</a></h3>
<p>This is a cloud computing service developed by Microsoft. The GitHub repository of Microsoft Azure is devoted to its open-source documentation. The page calls developers to contribute to the project by giving feedback, reporting issues and similar helpful ways. The page has more than <code>7K</code> contributors and is one of the most active repositories on the platform.</p>
<h3 id="heading-home-assistanthttpsgithubcomhome-assistantcore"><a target="_blank" href="https://github.com/home-assistant/core">Home Assistant</a></h3>
<p>This open-source home automation software is intended to the central system for controlling smart homes. The system is built using a modular approach so support for other devices or actions can be implemented easily. Homes Assistant core application software is written in Python and its main aim is local control and privacy, powered by a worldwide community of tinkerers and DIY enthusiasts. Perfect to run on a Raspberry Pi or a local server. It has more than <code>42K</code> stars and more than <code>2.4K</code> active contributors.</p>
<hr />
<ul>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Need inspiration or a different perspective on the Python projects or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
<p><em>Image Credits - <a href="https://www.freepik.com/vectors/abstract">vectorjuice</a></em></p>
]]></content:encoded></item><item><title><![CDATA[How To Create A Paint Brush Application Using OpenCV]]></title><description><![CDATA[Creating a paintbrush application is one of the most fun activity while learning computer vision and image processing with a little bit of GUI concepts. Using OpenCV for such an application saves us a lot of time by not needing to know the basics of ...]]></description><link>https://chandraji.dev/how-to-create-a-paint-brush-application-using-opencv</link><guid isPermaLink="true">https://chandraji.dev/how-to-create-a-paint-brush-application-using-opencv</guid><category><![CDATA[Python]]></category><category><![CDATA[Computer Vision]]></category><category><![CDATA[image processing]]></category><category><![CDATA[opencv]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Siddharth Chandra]]></dc:creator><pubDate>Tue, 20 Apr 2021 11:59:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1618919151441/jv7QucdZC.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Creating a paintbrush application is one of the most fun activity while learning computer vision and image processing with a little bit of GUI concepts. Using OpenCV for such an application saves us a lot of time by not needing to know the basics of GUI programming, so we can only be left with image processing tasks at hand.</p>
<p>In this article, we are going to make a paint application that features the brush functionality with customizations like:</p>
<ul>
<li>Changing brush size using a trackbar.</li>
<li>Changing paint colour using a trackbar.</li>
<li>Viewing the selected colour on the window.</li>
</ul>
<p>We will also see how current trackbar values can be displayed on the window, so we have a general idea of the colour variation.</p>
<p><em>Note: We are going to make this application on macOS and somehow the in-built create trackbar method of OpenCV does not show selected trackbar values, hence the need to display these values on the image window itself.</em></p>
<p><em>If you do not have OpenCV installed, I suggest you visit <a target="_blank" href="lets-draw-opencv-logo-using-opencv">here</a> and check <strong>Prerequisites</strong> steps on the process of installation.</em></p>
<p>Without any further ado, let's start making our first paintbrush application.</p>
<hr />
<h3 id="heading-imports-and-variables">Imports and Variables</h3>
<p>Create a python file, name it whatever you like. Add below code in it (make sure you have OpenCV installed):</p>
<pre><code class="lang-python"><span class="hljs-comment"># ./paintApplication.py</span>

<span class="hljs-keyword">import</span> cv2
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np

draw = <span class="hljs-literal">False</span>
window_name = <span class="hljs-string">"Paint Brush Application"</span>
bgr_track = {<span class="hljs-string">'B'</span>: <span class="hljs-number">0</span>, <span class="hljs-string">'G'</span>: <span class="hljs-number">0</span>, <span class="hljs-string">'R'</span>: <span class="hljs-number">0</span>}

img = np.zeros((<span class="hljs-number">512</span>,<span class="hljs-number">512</span>,<span class="hljs-number">3</span>), np.uint8)
cv2.namedWindow(window_name)

<span class="hljs-comment"># Initial color window, showing black color, same as paint area</span>
cv2.rectangle(img, color_win_position[<span class="hljs-number">0</span>], color_win_position[<span class="hljs-number">1</span>], (<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>), <span class="hljs-number">-1</span>)
</code></pre>
<ul>
<li>First 2 lines import necessary libraries. Here, we are going to import <code>cv2</code> and <code>numpy</code> with an alias <code>np</code>.</li>
<li>Next 3 lines define some constants that we are going to use later. <code>draw</code> says if the mouse is drawing on image window, <code>window_name</code> describes the name of the application window that is <code>Paint Brush Application</code> and <code>bgr_track</code> is a dictionary that we will use to keep track of previous <code>BGR</code> values (you will know later why we are doing this).</li>
<li>Next 2 lines create an area for our paint application and set a name to the window. <code>img</code> contains a numpy array of 3 dimensions where each value is zero, meaning it will be a black coloured area. <code>cv2.namedWindow</code> attaches a name to the image we just created, we can later use this window name to place all other things like trackbar.</li>
<li>The last line of this code snippet creates a rectangle window which we will be using for viewing our colour that we are choosing from the trackbar.</li>
</ul>
<p>Now, add the below code:</p>
<pre><code class="lang-python">
font = cv2.FONT_HERSHEY_SIMPLEX
img = cv2.putText(img, <span class="hljs-string">"R: "</span>, (<span class="hljs-number">10</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)
img = cv2.putText(img, <span class="hljs-string">"G: "</span>, (<span class="hljs-number">90</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)
img = cv2.putText(img, <span class="hljs-string">"B: "</span>, (<span class="hljs-number">170</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)

img = cv2.putText(img, <span class="hljs-string">"0"</span>, (<span class="hljs-number">30</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)
img = cv2.putText(img, <span class="hljs-string">"0"</span>, (<span class="hljs-number">110</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)
img = cv2.putText(img, <span class="hljs-string">"0"</span>, (<span class="hljs-number">190</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)
</code></pre>
<ul>
<li>Now, we put text on the image window that will work as the counter for values of the BGR trackbar. Since on macOS, the track bar is not showing selected values, so we need this functionality. Also, take it as a side activity that we can do.</li>
<li>We put text using the <code>cv2.putText</code> method of OpenCV and set a font as well. We can set any font we want, here we are using Hershey simplex font.</li>
<li>We are placing text like <code>R:</code> and <code>0</code> separately because we need to change only number values and not constants like <code>R:</code>.</li>
<li>We can select any random position for these counters on the image and check which best suits our needs.</li>
</ul>
<p>So far, we have all the variables that we need, now let's move onto creating some interesting functions!</p>
<h3 id="heading-functions-all-we-need">Functions - All We Need</h3>
<p>Add below python code snippet to the same file where we left above:</p>
<pre><code class="lang-python">
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">nothing</span>(<span class="hljs-params">x</span>):</span>
    <span class="hljs-keyword">pass</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_R_value</span>(<span class="hljs-params">x</span>):</span>
    <span class="hljs-keyword">global</span> font, img, bgr_track
    img = cv2.putText(img, <span class="hljs-string">f"<span class="hljs-subst">{bgr_track[<span class="hljs-string">'R'</span>]}</span>"</span>, (<span class="hljs-number">30</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>), <span class="hljs-number">1</span>)
    img = cv2.putText(img, <span class="hljs-string">f"<span class="hljs-subst">{x}</span>"</span>, (<span class="hljs-number">30</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)
    bgr_track[<span class="hljs-string">'R'</span>] = x

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_G_value</span>(<span class="hljs-params">x</span>):</span>
    <span class="hljs-keyword">global</span> font, img, bgr_track
    img = cv2.putText(img, <span class="hljs-string">f"<span class="hljs-subst">{bgr_track[<span class="hljs-string">'G'</span>]}</span>"</span>, (<span class="hljs-number">110</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>), <span class="hljs-number">1</span>)
    img = cv2.putText(img, <span class="hljs-string">f"<span class="hljs-subst">{x}</span>"</span>, (<span class="hljs-number">110</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)
    bgr_track[<span class="hljs-string">'G'</span>] = x

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_B_value</span>(<span class="hljs-params">x</span>):</span>
    <span class="hljs-keyword">global</span> font, img, bgr_track
    img = cv2.putText(img, <span class="hljs-string">f"<span class="hljs-subst">{bgr_track[<span class="hljs-string">'B'</span>]}</span>"</span>, (<span class="hljs-number">190</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">0</span>,<span class="hljs-number">0</span>,<span class="hljs-number">0</span>), <span class="hljs-number">1</span>)
    img = cv2.putText(img, <span class="hljs-string">f"<span class="hljs-subst">{x}</span>"</span>, (<span class="hljs-number">190</span>, <span class="hljs-number">30</span>), font, <span class="hljs-number">0.5</span>, (<span class="hljs-number">255</span>,<span class="hljs-number">255</span>,<span class="hljs-number">255</span>), <span class="hljs-number">1</span>)
    bgr_track[<span class="hljs-string">'B'</span>] = x
</code></pre>
<ul>
<li>We create a function like <code>nothing</code> that does nothing just do a simple pass. We can use it to fulfil our need to pass it as a parameter where it is required but we want it to not do anything.</li>
<li>Next 3 functions are the same with just a difference of <code>B</code>, <code>G</code> and <code>R</code>. Let's explore <code>update_R_value</code>.</li>
<li>Here we are trying to update the counter value of <code>R: 0</code> on the image window.</li>
<li>First, we get all global variables and try to replace the already present value of <code>0</code> against <code>R:</code>. In OpenCV, there is no feature that lets <code>cv2.putText</code> keep track of previous text on the same position so it could just replace it. Here we need to first put the same text as the previous value, like <code>0</code> in this case, and change colour similar to the background of the paint area (here it is black) so that it is like that it vanished from the paint area. Now we just put a new trackbar value, which is passed to the function as <code>x</code> with the colour white in the same place. Lastly, we update the <code>bgr_track</code> dictionary that keeps the track history of the last value it put and the same process repeats.</li>
</ul>
<p>The same kind of thing is going on with the other 2 functions, just for different colour trackbar values.</p>
<p>In simple terms, take the below scenario:</p>
<ul>
<li>Let's say we have a list - <code>l = [0, 0, 0]</code>. Here all the values were <code>-1</code> initially representing the start stage of the list. It is a special kind of list where we can only change its values only if they are <code>-1</code> first and nothing else. </li>
<li>What we are going to do now is that, replace the first index (<code>R</code> colour value let's say) with a new value.</li>
<li>So we try to replace <code>0</code> knowing its position with <code>-1</code> because if we replace it directly it overlaps and doesn't work. So what we do instead is <code>l[0] = -1</code> and then after setting it to <code>-1</code>, it is back to its original state from where we can do anything to its value. Now we do the actual replace <code>l[0] = x</code>.</li>
</ul>
<p>So what just happened? If you need more insight on this please visit my answer on StackOverflow <a target="_blank" href="https://stackoverflow.com/a/67161084/9219103">here</a>.</p>
<p>Let's move on to mouse events, which will help us to draw using a paintbrush.</p>
<pre><code class="lang-python">
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">draw_circle</span>(<span class="hljs-params">event, x, y, flags, param</span>):</span>
    <span class="hljs-keyword">global</span> draw, img

    <span class="hljs-keyword">if</span> event == cv2.EVENT_LBUTTONDOWN:
        draw = <span class="hljs-literal">True</span>

    <span class="hljs-keyword">elif</span> event == cv2.EVENT_MOUSEMOVE:
        <span class="hljs-keyword">if</span> draw:
            cv2.circle(img, (x,y), cv2.getTrackbarPos(<span class="hljs-string">"Brush Size"</span>, window_name),
                       (cv2.getTrackbarPos(<span class="hljs-string">"B"</span>, window_name),
                        cv2.getTrackbarPos(<span class="hljs-string">"G"</span>, window_name),
                        cv2.getTrackbarPos(<span class="hljs-string">"R"</span>, window_name)),
                       <span class="hljs-number">-1</span>)

    <span class="hljs-keyword">elif</span> event==cv2.EVENT_LBUTTONUP:
        draw = <span class="hljs-literal">False</span>
        cv2.circle(img, (x,y), cv2.getTrackbarPos(<span class="hljs-string">"Brush Size"</span>, window_name),
                       (cv2.getTrackbarPos(<span class="hljs-string">"B"</span>, window_name),
                        cv2.getTrackbarPos(<span class="hljs-string">"G"</span>, window_name),
                        cv2.getTrackbarPos(<span class="hljs-string">"R"</span>, window_name)),
                       <span class="hljs-number">-1</span>)
</code></pre>
<ul>
<li>This method <code>draw_circle</code> will be passed to the mouse event callback method of OpenCV. It takes 5 parameters - <code>event</code> that gives what is the event type, <code>x</code> and <code>y</code> the position of mouse, <code>flags</code> that can give us any flags that mouse events raise and some other <code>param</code> related to mouse callbacks. We can ignore <code>flags</code> and <code>params</code> for this case.</li>
<li>We have 3 conditions here. <code>if event == cv2.EVENT_LBUTTONDOWN</code> checks for if the left mouse button down event occurred or not, if it happens then we will set <code>draw</code> to <code>True</code>.</li>
<li><code>elif event == cv2.EVENT_MOUSEMOVE</code> this condition checks if the mouse is moving, we simply don't want a moving mouse to draw on the paint area but we want a left button down moving the mouse to draw on the paint area, that's where the <code>draw</code> variable comes in, which will be checked to see if a left mouse button is actually down or not. Then it creates a circle of defined radius that it gets from the <code>Brush Size</code> trackbar, the colour of the circle from the <code>BGR</code> trackbar and colour fill is done via the last <code>-1</code> parameter value. This creates a circle while moving a mouse and this happens so smoothly that it shows an effect of a paintbrush.</li>
<li><code>elif event==cv2.EVENT_LBUTTONUP</code> is for when the mouse button is not clicked and we don't want to draw on the paint area. Here, we set <code>draw</code> to <code>False</code> and draw the last circle on positions given.</li>
</ul>
<p>Now, let's put trackbar and mouse event callback. Also, we will create a loop to continuous display the changes to the image window.</p>
<h3 id="heading-trackbar-mouse-event-call-and-main-loop">Trackbar, Mouse Event Call and Main Loop</h3>
<p>Add the following code to the same file:</p>
<pre><code class="lang-python">
cv2.createTrackbar(<span class="hljs-string">"R"</span>, window_name, <span class="hljs-number">0</span> ,<span class="hljs-number">255</span>, update_R_value)
cv2.createTrackbar(<span class="hljs-string">"G"</span>, window_name, <span class="hljs-number">0</span>, <span class="hljs-number">255</span>, update_G_value)
cv2.createTrackbar(<span class="hljs-string">"B"</span>, window_name, <span class="hljs-number">0</span>, <span class="hljs-number">255</span>, update_B_value)
cv2.createTrackbar(<span class="hljs-string">"Brush Size"</span>, window_name, <span class="hljs-number">1</span>, <span class="hljs-number">8</span>, nothing)
cv2.setMouseCallback(window_name, draw_circle)
</code></pre>
<ul>
<li>Here, we create a trackbar for <code>R</code>, <code>G</code>, <code>B</code> colour values and for <code>Brush Size</code> adjustment. <code>cv2.createTrackbar</code> method takes the following arguments, trackbar name <code>R</code>, window name where the trackbar needs to be put (here <code>window_name</code>), start value <code>0</code>, end value <code>255</code> of trackbar and last is a callback function which calls <code>update_R_value</code> whenever trackbar value gets changed. All 4 trackbars are similar to this structure and are self-explanatory now.</li>
<li><code>cv2.setMouseCallback</code> takes 2 parameters to set a mouse callback event, first one is the image window <code>window_name</code> on which this callback event should be tracked and the second is the callback function to call when a mouse event occurs.</li>
</ul>
<p><em>Notice here, that we don't have separate callback methods for MOUSE_UP or MOUSE_DOWN, but only a single one that captures all events with a passed parameter to callback function <code>event</code> and later we can use conditionals to filter them out.</em></p>
<p>Now, add the following code to the same file for our main loop:</p>
<pre><code class="lang-python">
<span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>):
    cv2.imshow(window_name, img)
    key = cv2.waitKey(<span class="hljs-number">1</span>) &amp; <span class="hljs-number">0xff</span>
    <span class="hljs-keyword">if</span> key==ord(<span class="hljs-string">'q'</span>):
        <span class="hljs-keyword">break</span>

    b = cv2.getTrackbarPos(<span class="hljs-string">"B"</span>, window_name)
    g = cv2.getTrackbarPos(<span class="hljs-string">"G"</span>, window_name)
    r = cv2.getTrackbarPos(<span class="hljs-string">"R"</span>, window_name)
    cv2.rectangle(img, color_win_position[<span class="hljs-number">0</span>], color_win_position[<span class="hljs-number">1</span>], (b,g,r), <span class="hljs-number">-1</span>)

cv2.destroyAllWindows()
</code></pre>
<ul>
<li>Here, we want the loop to continue until it encounters a keyboard keypress event. We are going to quit the application whenever the <code>Q</code> key is clicked.</li>
<li>Inside the loop, we are checking for keyboard quit condition and also getting <code>BGR</code> values and displaying them in a rectangle at <code>color_win_position</code>.</li>
<li>At last, if the program exits the loop, then we simple destroy the unwanted image window using the <code>cv2.destroyAllWindows</code> method of OpenCV.</li>
</ul>
<p>Well, that's complete our code.</p>
<p>For complete script, please visit <a target="_blank" href="https://github.com/siddharth2016/Opencv-Python-Computer-Vision/blob/master/paintApplication.py">here</a>.</p>
<p>Now, let's look at the demo.</p>
<h3 id="heading-conclusion-demo">Conclusion Demo</h3>
<h4 id="heading-displaying-colour-trackbar-values">Displaying colour trackbar values.</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1618918273706/tzJAGC7px.gif" alt="display_color_value.gif" /></p>
<h4 id="heading-displaying-colour-trackbar-colours">Displaying colour trackbar colours.</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1618918287732/a_DSuP5dQ.gif" alt="color_trackbar.gif" /></p>
<h4 id="heading-changing-brush-size">Changing brush size.</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1618918301839/aefBGvmmj.gif" alt="brush_size.gif" /></p>
<h4 id="heading-hello-world-codekaro">Hello World, CodeKaro!</h4>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1618918315829/xoXv0xxCx.gif" alt="miscellaneous.gif" /></p>
<p>I know, my paint skills are very poor!</p>
<h3 id="heading-what-next">What Next?</h3>
<p>Well, that's it from me. If you want to explore further, the following activities can be done to add more feature to the paint application:</p>
<ul>
<li>Add utility to select brush type. Add rectangle, diamond, hexagon, etc shaped brushes.</li>
<li>Try to include no-fill brush utility.</li>
<li>Try to add a function that creates a circle or rectangle with a given size with a double click of the mouse on the paint area.</li>
<li>Add a utility to clear the area and restart the work, by not having to close and restart the program.</li>
</ul>
<hr />
<ul>
<li><p>Just starting your Open Source Journey? Don't forget to check <a target="_blank" href="https://github.com/siddharth2016/hello-open-source">Hello Open Source</a></p>
</li>
<li><p>Need inspiration or a different perspective on the Python projects or just out there to explore? Check <a target="_blank" href="https://github.com/siddharth2016/awesome-python-repos">Awesome Python Repos</a></p>
</li>
<li><p>Want to make a simple and awesome game from scratch? Check out <a target="_blank" href="https://github.com/siddharth2016/PongPong">PongPong</a></p>
</li>
<li><p>Want to <code>++</code> your GitHub Profile README? Check out <a target="_blank" href="https://github.com/marketplace/actions/quote-readme">Quote - README</a></p>
</li>
</ul>
<p>Till next time!</p>
<p>Namaste 🙏</p>
]]></content:encoded></item></channel></rss>