<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ramki Pitchala on Medium]]></title>
        <description><![CDATA[Stories by Ramki Pitchala on Medium]]></description>
        <link>https://medium.com/@ramapitchala?source=rss-b162eedcaf8a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VnDB1h6MLvzfjmavhNk1bA.jpeg</url>
            <title>Stories by Ramki Pitchala on Medium</title>
            <link>https://medium.com/@ramapitchala?source=rss-b162eedcaf8a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:00:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramapitchala/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Go Basics: Filesystem IO]]></title>
            <link>https://medium.com/geekculture/go-basics-filesystem-io-1762cecc601c?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1762cecc601c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Mon, 26 Apr 2021 03:34:07 GMT</pubDate>
            <atom:updated>2021-04-27T23:17:32.926Z</atom:updated>
            <content:encoded><![CDATA[<h4>A basic guide to working with files &amp; directories in Go</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OfSBe8PmgwGLmScd.png" /><figcaption>Image on <a href="https://www.technotification.com/2019/02/new-popular-programming-languages.html">technotification.com</a></figcaption></figure><h3>Introduction</h3><p>Reading and writing to disk and navigating the filesystem is a staple in any language. Let’s learn how to do it in Go with <a href="https://golang.org/pkg/os/#pkg-overview">os</a>, a package that lets us interact with operating system functionality.</p><h3>Agenda</h3><pre><a href="#cbc9"><strong>Files</strong></a><br>   <a href="#3f72">Creating &amp; Opening Files</a><br>   <a href="#abbc">Reading Files</a><br>   <a href="#e16c">Writing &amp; Appending to Files</a><br>   <a href="#0016">Removing Files</a></pre><pre><a href="#47ff"><strong>Directories</strong></a><strong><br>   </strong><a href="#e92d">Creating Directories</a><br>   <a href="#e3b0">Navigating &amp; Reading Directories</a><br>   <a href="#8dc5">Walking through a Directory</a></pre><h3>Files</h3><h4>Creating &amp; Opening Files</h4><p>File creation can be done with <a href="https://golang.org/pkg/os/#Create">os.Create</a> and opening a file is done with <a href="https://golang.org/pkg/os/#Open">os.Open</a>. Both take in a file path and return a <a href="https://golang.org/pkg/os/#File">File</a> struct and a non-nill error if unsuccessful.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23dcc632c9ade1025d3f1a9e5295dafb/href">https://medium.com/media/23dcc632c9ade1025d3f1a9e5295dafb/href</a></iframe><p>If you call os.Create on an existing file, it will truncate the file: the file’s data is erased. In contrast, calling os.Open on a non-existing file will result in an error.</p><p>If successful, we can then use the returned File struct to write and read data to the file (<em>There will be an example of opening a file, reading it chunk by chunk, and closing it in the next section</em>).</p><p>Finally, it is good to close the returned file after interacting with it by using <a href="https://golang.org/pkg/os/#File.Close">File.Close</a>.</p><h4>Reading Files</h4><p>One way we can process a file is by reading all its data at one time. We can do this with <a href="https://golang.org/pkg/os/#ReadFile">os.ReadFile</a>. The input is the file path and the output is a byte array of the file’s data and an error if unsuccessful.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a17407de75be7511238365e546a92454/href">https://medium.com/media/a17407de75be7511238365e546a92454/href</a></iframe><p>If we are processing a text file, we need to convert the output byte array into a string in order to get the file text.</p><p>Keep in mind that os.ReadFile will read the entire file and load its data into memory. If the file is large, using os.ReadFile will consume large amounts of memory.</p><p>A memory performant approach is to process the file chunk by chunk, which can be done using os.Open.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa0c438fa853e7fda69560a79d3a20a0/href">https://medium.com/media/aa0c438fa853e7fda69560a79d3a20a0/href</a></iframe><p>After opening the file, <a href="https://golang.org/pkg/os/#File.Read">File.Read</a> is repeatedly called till EOF (end of file).</p><p>File.Read takes in a byte array, b and loads up to len(b) bytes from the file into b. It then returns the number of bytes read, bytesRead and an error if something goes wrong. If bytesRead is 0, that means we hit EOF, and are done processing the file.</p><p>In the above code, we are loading a max of 10 bytes from the file, processing the bytes, and repeating this process till EOF.</p><p>For larger files, this approach consumes a lot less memory than loading the entire file once.</p><h4>Writing &amp; Appending to Files</h4><p>Analogous to os.ReadFile , there is <a href="https://golang.org/pkg/os/#WriteFile">os.WriteFile</a> , a function to write bytes to a file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a19ff424f350a525b98beaf6c389bc6b/href">https://medium.com/media/a19ff424f350a525b98beaf6c389bc6b/href</a></iframe><p>Things to note about os.WriteFile</p><ul><li>Be sure to convert the data you want to write into []byte before passing it into os.WriteFile.</li><li>The <a href="https://www.calleluks.com/flags-bitmasks-and-unix-file-system-permissions-in-ruby/">permission bits</a> are needed to create the file if it doesn’t already exist. <em>Don’t worry too much about them.</em></li><li>If the file path already exists, os.WriteFile will override the initial data in the file with the new data that is being written.</li></ul><p>os.WriteFile is a neat way to make a new file or override it, but it doesn’t work when we need to append to a file’s existing contents. In order to append to a file, we will need to leverage <a href="https://golang.org/pkg/os/#OpenFile">os.OpenFile</a> .</p><p>According to the <a href="https://golang.org/pkg/os/#OpenFile">docs</a>, os.OpenFile is a more generalized version of os.Open and os.Create. Both os.Create and os.Open internally call it.</p><p>In addition to the file path, os.OpenFile takes in an int flags and an int perm, the permission bits, and returns a File struct. In order to perform operations like reading and writing, the right combination of flags must be provided to os.OpenFile.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7930abf14801a340c4cd6123aa0460fc/href">https://medium.com/media/7930abf14801a340c4cd6123aa0460fc/href</a></iframe><p>We can combine O_APPEND and O_WRONLY with a bitwise OR and pass it into os.OpenFile to get a File struct. If we then call File.Write with whatever data we pass in, the data will get appended to the end of the file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a87245690e513a4328061a21a900b36/href">https://medium.com/media/7a87245690e513a4328061a21a900b36/href</a></iframe><h4>Removing Files</h4><p><a href="https://golang.org/pkg/os/#Remove">os.Remove</a> takes in a path to a file or an empty directory and deletes the file/directory. If the file doesn’t exist, a non-nil error will be returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4861f7b959710d0e73dad4fdfbb4b092/href">https://medium.com/media/4861f7b959710d0e73dad4fdfbb4b092/href</a></iframe><p>Now that we learned the basics of working with files, let’s dive into working with directories.</p><h3>Directories</h3><h4>Creating Directories</h4><p>In order to create a new directory, we can use <a href="https://golang.org/pkg/os/#Mkdir">os.Mkdir</a>. os.Mkdir takes in the directory name and the permission bits, and makes a new directory. A non-nil error will be returned if the function cannot make the directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b86f8e7f5ed82bd0220b0cf71ee42b4e/href">https://medium.com/media/b86f8e7f5ed82bd0220b0cf71ee42b4e/href</a></iframe><p>In some situations, we may need temporary directories which exist only during the execution of the program. <a href="https://golang.org/pkg/os/#MkdirTemp">os.MkdirTemp</a> can be utilized to make such directories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dedba30418c4bbf295405d816d962861/href">https://medium.com/media/dedba30418c4bbf295405d816d962861/href</a></iframe><p>os.MkdirTemp ensures that the temp directories created have unique names even when called by multiple goroutines or programs (<a href="https://golang.org/pkg/os/#Mkdir">source</a>). Moreover, once you are done working with the temp directory, ensure to delete it and its contents with <a href="https://golang.org/pkg/os/#RemoveAll">os.RemoveAll</a>.</p><h4>Navigating &amp; Reading Directories</h4><p>To begin, we can get the current working directory with <a href="https://golang.org/pkg/os/#Getwd">os.Getwd</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bc40ecbd143db32f28add4f3d4977fa/href">https://medium.com/media/8bc40ecbd143db32f28add4f3d4977fa/href</a></iframe><p>Then, <a href="https://golang.org/pkg/os/#Chdir">os.Chdir</a> can be used to change the working directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7b18946ccb2d4c6b68b56ddf8b6c910/href">https://medium.com/media/c7b18946ccb2d4c6b68b56ddf8b6c910/href</a></iframe><p>In addition to changing the working directory, we can get directory children with <a href="https://golang.org/pkg/os/#ReadDir">os.ReadDir</a>. os.ReadDir takes in a directory path and returns an array of DirEntry structs and a non-nill error if unsuccessful.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fec3d38e0e1faa88083e9ac3f24fece/href">https://medium.com/media/8fec3d38e0e1faa88083e9ac3f24fece/href</a></iframe><p>Here is its usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/333a0b301b886228f6fb3c27da53d794/href">https://medium.com/media/333a0b301b886228f6fb3c27da53d794/href</a></iframe><h4>Walking through a Directory</h4><p>With os.Chdir &amp; os.ReadDir , we can walk through all the files and sub-directories in a parent directory, but the <a href="https://golang.org/pkg/path/filepath/">path/filepath</a> package provides an elegant way of doing this with the <a href="https://golang.org/pkg/path/filepath/#WalkDir">filepath.WalkDir</a> function.</p><p>filepath.WalkDir takes in root , the directory where will walk from, and a callback function fn of the following type:</p><pre>type WalkDirFunc func(path <a href="https://golang.org/pkg/builtin/#string">string</a>, d <a href="https://golang.org/pkg/io/fs/#DirEntry">DirEntry</a>, err <a href="https://golang.org/pkg/builtin/#error">error</a>) <a href="https://golang.org/pkg/builtin/#error">error</a></pre><p>fn will be called on each file and sub-directory in root. Here is an example of counting all the files in a root directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ee0cee21271e4ba0f57b830d23f8216/href">https://medium.com/media/5ee0cee21271e4ba0f57b830d23f8216/href</a></iframe><p>path/filepath provides another function called <a href="https://gist.github.com/Ramko9999/d49a3f944a6530c099367395f9dace68">filepath.Walk</a> which has the same behavior as filepath.WalkDir. However, the docs state that filepath.Walk is less efficient than filepath.WalkDir. As a result, using filepath.WalkDir may be more ideal.</p><h3>Conclusion</h3><p>I wrote this article as an exercise for learning Go, and with it, I hoped to introduce you to the basics of working with files &amp; directories. As an exercise, I recommend implementing your own version of filepath.WalkDir.</p><p><strong>Thank you for your reading!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1762cecc601c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/go-basics-filesystem-io-1762cecc601c">Go Basics: Filesystem IO</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Deep Dive Into JavaScript Objects]]></title>
            <link>https://medium.com/better-programming/a-deeper-dive-into-javascript-objects-c18ce52869eb?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c18ce52869eb</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 13:44:13 GMT</pubDate>
            <atom:updated>2021-04-19T17:40:43.095Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore the finer details of objects in JavaScript</h4><figure><img alt="Code" src="https://cdn-images-1.medium.com/max/1024/1*VkeHODGG7N6fnBgRFUbJ6Q.png" /><figcaption>Photo by the author.</figcaption></figure><p>JavaScript objects are fundamental. Taking the time to dig deeper into them will result in cleaner and more performant code.</p><p><em>Note: This article assumes that you know the basics of objects. If you want a quick refresher on objects, check out </em><a href="https://blog.bitsrc.io/the-chronicles-of-javascript-objects-2d6b9205cd66"><em>The Chronicles of JavaScript Objects</em></a> <em>by </em><a href="https://medium.com/u/74153188d515"><em>Arfat Salman</em></a><em>.</em></p><p>Let’s get cracking!</p><h3>Agenda</h3><ul><li><a href="#8a35">Read-Only Objects</a></li><li><a href="#6b8a">Shallow vs. Deep</a></li><li><a href="#a453">Objects As Primitives</a></li><li><a href="#b8cc">Objects vs. Maps</a></li></ul><h3>Read-Only Objects</h3><p>Suppose we want to create an enum to represent the cardinal directions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd19e860c2316795c8d0f03f9e9689f6/href">https://medium.com/media/fd19e860c2316795c8d0f03f9e9689f6/href</a></iframe><p>However, existing properties/keys can be altered and new properties can be added into DIRECTIONS. This can be hazardous in larger code bases since the chances of accidentally editing enums/read-only objects will be greater.</p><pre>DIRECTIONS.NORTH = &quot;south&quot;; //nothing stopping this from happening</pre><p>Enter <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">Object.freeze</a>.</p><pre>Object.freeze(DIRECTIONS);</pre><p>Object.freeze gets rid of the ability to add new properties and edit/remove existing properties.</p><pre>Object.freeze(DIRECTIONS);</pre><pre>/*The below either fail silently or a TypeError will be thrown*/<br>DIRECTIONS.NORTH = &quot;south&quot;;<br>DIRECTIONS.UP = &quot;up&quot;;<br>del DIRECTIONS.SOUTH;</pre><p>Object.freeze also restricts the capability to alter the <a href="https://javascript.info/property-descriptors">property descriptors</a> of an object’s individual properties. A property descriptor is like the “settings” of a property. Here are the four fields it consists of:</p><ul><li>value: The actual of the property.</li><li>enumerable: Determines whether a property will appear when iterating/enumerating over the properties of an object. If enumerable is true for a property, it will show up when we iterate over an object with for _ in and it will be included in Object.keys().</li><li>configurable: Determines whether a property can be deleted from an object or if an object’s property descriptor can be changed.</li><li>writable:<strong> </strong>Determines whether a property’s value can be changed through assignment.</li></ul><pre>const obj = {&#39;a&#39;: 1, &#39;b&#39;:2};<br>console.log(Object.getOwnPropertyDescriptors(obj));<br>/*<br>Here is the output of the property descriptors of obj:<br>{<br>a: {value: 1, writable: true, enumerable: true, configurable: true},<br>b: {value: 2, writable: true, enumerable: true, configurable: true}<br>}<br>*/</pre><p>Object.freeze will keep enumerable as is but will setconfigurable and writable to false for the properties in an object. As a result, we can no longer edit the property descriptor (we can no longer change writable, enumerable, or configurable) and can no longer alter the value of the property.</p><p><em>Caveat: </em><em>Object.freeze only puts these restrictions on top-level properties.</em></p><pre>const o = {a: 0, b: {c: 5}};<br>Object.freeze(o);</pre><pre>o.b.c = 10; // this is valid</pre><p>These mentioned restrictions will hold true for properties a and b, but not for property c. We can edit the value of c even after we freeze the object.</p><p>You may have to recursively call Object.freeze on child objects to ensure the entire object is frozen.</p><h3>Shallow vs. Deep</h3><p>Unlike primitives, JavaScript objects are passed around by reference, where a reference is a pointer to where the object “resides” in memory.</p><pre>const myPet = {<br>  name: &quot;Doggie&quot;,<br>  type: &quot;Dog&quot;<br>}</pre><p>myPet stores the reference to the object it is assigned to — not the object itself.</p><pre>const yourPet = myPet;<br>yourPet.name = &quot;Cattie&quot;;<br>console.log(myPet);</pre><pre>/*<br>Here is the output of myPet:<br>{ name: &#39;Cattie&#39;, type: &#39;Dog&#39; }<br>*/</pre><p>Assignment in this fashion will copy the reference myPet stores to yourPet. As a result, yourPet and myPet still reference the same object.</p><p>Basically, if I edit a property in yourPet, that edit will be reflected in myPet since they are still referencing the same object.</p><p>When we have two variables storing references to the same object, we can call them <em>shallow</em> copies.</p><p>As seen above, one way of creating a shallow copy is through assignment.</p><pre>const obj = {&quot;a&quot;: 0};<br>const anotherObj = obj; // shallow copy</pre><p>We can test for shallow equality by using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is">Object.is</a>. Object.is tests if both variables have a reference to the same object.</p><pre>const obj = {&quot;a&quot;: 0};<br>const anotherObj = obj;<br>Object.is(obj, anotherObj); // returns true</pre><p>But wait! Why does the following return false?</p><pre>const histo1 = {&quot;a&quot;: 0};<br>const histo2 = {&quot;a&quot;: 0};<br>Object.is(histo1, histo2); // returns false</pre><p>Though the contents of the objects of histo1 and histo2 are the same, this doesn’t mean histo1 and histo2 refer to the same object in memory. As a result, histo1 and histo2 are not shallow copies since their references point to different objects that happen to have the same contents.</p><p>histo1 and histo2 are <em>deep</em> copies.</p><p>There are a couple of options for creating deep copies.</p><h4>Deep copy with JSON</h4><pre>const me = {&quot;name&quot;: &quot;Ramki&quot;};<br>const you = JSON.parse(JSON.stringify(me));</pre><p>The idea is to convert the object to a string using JSON.stringify and then parse the string with JSON.parse to retrieve the encoded object. The main limitation is that objects with properties that are functions will not be copied properly, as JSON.stringify cannot encode functions (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.Stringify</a>).</p><h4>Deep copy with Lodash</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2106545aa1a81fe5217d499d4fad38/href">https://medium.com/media/eb2106545aa1a81fe5217d499d4fad38/href</a></iframe><p>We can import <a href="https://www.tutorialspoint.com/lodash/lodash_clonedeep.htm">cloneDeep</a> from <a href="https://lodash.com/">lodash</a>. It’s a method that recursively clones the properties of a passed-in object. The returned object will be a deep copy. The main drawback is that we must install an external library, adding to the total size of the application, in order to create a deep copy.</p><p>In cases where your object’s values are JSON-compatible, it might be simpler to use the JSON.stringify approach. Otherwise, lodash.cloneDeep is the best approach.</p><h3>Objects As Primitives</h3><p>Though the variables bound to an object store its reference, it is still possible to get primitive values of objects by overriding<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf">Object.prototype.valueOf</a>.</p><p>Object.prototype.valueOf is a function that returns the primitive value of an object. By default, it returns the object itself, but it can be overridden to return something else.</p><pre>const result = 1 + new Number(14);<br>console.log(result);</pre><pre>// result: 15</pre><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number">Number</a> is a wrapper object of numbers. Interestingly, when we add a primitive (1) to an object (new Number(14)), we still end up getting the correct result of 15.</p><p>When we add 1 to new Number(14), JavaScript will auto-convert new Number(14) to its primitive value, 14. This primitive value is retrieved from Number.prototype.valueOf(), which is overridden to provide the actual numerical value that the Number object stores.</p><p>Let’s look at another example: Suppose we have a StringBuilder object to efficiently concatenate strings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72985fbed1f079613ffe61e8597175f8/href">https://medium.com/media/72985fbed1f079613ffe61e8597175f8/href</a></iframe><p>Suppose we want to use it the following manner:</p><pre>const builder = new StringBuilder();<br>builder.add(&quot;B&quot;);<br>builder.add(&quot;C&quot;);</pre><pre>const result = &quot;A&quot; + builder; <br>//result: want it to be &quot;ABC&quot; but is &quot;A[object Object]&quot;</pre><p>In order to have result equal to “ABC”, we can override StringBuilder.prototype.valueOf to provide the concatenation of builder.strings.</p><pre>StringBuilder.prototype.valueOf = function() {<br>   return this.concat();<br>}</pre><p>Whenever a StringBuilder object is converted into a primitive, the primitive will be the concatenation of all the strings we added into the object.</p><p>We can override Object.prototype.valueOf to provide custom primitive values for objects when they are converted into primitives.</p><h3>Objects vs. Maps</h3><p>Although JavaScript provides a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">Map</a> class, many frequently use objects to map keys and values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b59c8cc2a668a3612ad36895e40f0da/href">https://medium.com/media/5b59c8cc2a668a3612ad36895e40f0da/href</a></iframe><p>twoSumCount using the Map data structure:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ee6e9c2c5618ab7f7122690286764be/href">https://medium.com/media/0ee6e9c2c5618ab7f7122690286764be/href</a></iframe><p>Though their usage looks similar, there are a few differences.</p><h4>Keys</h4><p>The key of an object can only either be a string or a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">Symbol</a>.</p><p>Wait a second. Didn’t we just use numbers as keys in twoSumCount?</p><pre>const obj = {};<br>obj[1] = &quot;Something&quot;;<br>console.log(Object.keys(obj));</pre><pre>//output: [&quot;1&quot;]</pre><p>The integer keys we are using will get auto-converted into strings. This can be problematic if we want to use other objects as keys.</p><pre>obj = {};<br>obj[{}] = {};<br>console.log(Object.keys(obj));</pre><pre>//output: [&#39;[object Object]&#39;]</pre><p>However, with Map, the key types will not be restricted to strings or Symbol. We can have objects, functions, numbers, etc. as keys.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51a42f295f9967ebcee0b52bc8803d63/href">https://medium.com/media/51a42f295f9967ebcee0b52bc8803d63/href</a></iframe><p>In addition, objects can have default keys upon instantiation.</p><pre>const map = {};<br>console.log(map[&#39;toString&#39;]); </pre><pre>//output: [Function: toString]</pre><p>Even though our obj is empty, it still inherits from Object.prototype. As a result, keys such as toString and valueOf exist in obj at initialization. In order to remove these default keys, it is best to use objects that don’t inherit from anything.</p><pre>const map = Object.create(null);<br>console.log(map[&#39;toString&#39;]);</pre><pre>//output: undefined</pre><p>Using Object.create(null) ensures that there aren’t keys from prototypical inheritance in the object at initialization, reducing the chance of keys colliding.</p><h4>Performance</h4><p>According to the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map">Mozilla docs</a>, Map is said to perform better than objects in scenarios where frequent additions and removals occur. Despite that, I decided to performance-test both objects and maps.</p><p>The performance test is split into four parts: adding, retrieving, enumerating over, and deleting keys. The number of keys will be 1 million. The REPL link to the code is below:</p><p><a href="https://replit.com/@ramapitchala/KlutzyAlarmingLanservers">KlutzyAlarmingLanservers</a></p><p>Surprisingly, I found that the performance tests favored the object over the map when run in the REPL.</p><pre>Node Version: 12.22.1</pre><pre>Map: Adding Keys: 676.662ms<br>Map: Getting Keys: 437.161ms<br>Map: Enumeration: 4580.738ms<br>Map: Deleting Keys: 699.071ms<br>=============================<br>Object: Adding Keys: 135.423ms<br>Object: Getting Keys: 92.645ms<br>Object: Enumeration: 4123.763ms<br>Object: Deleting Keys: 266.606ms</pre><p>Here are the results on Node version 14.16.0 on a Razor Stealth computer:</p><pre>Node Version: 14.16.0</pre><pre>Map: Adding Keys: 163.153ms <br>Map: Getting Keys: 130.77ms <br>Map: Enumeration: 53.908ms <br>Map: Deleting Keys: 212.994ms <br>============================= <br>Object: Adding Keys: 28.134ms <br>Object: Getting Keys: 9.936ms <br>Object: Enumeration: 157.712ms <br>Object: Deleting Keys: 61.353ms</pre><p>Object seems to have Map beat in all areas other than enumeration, according to my benchmarks. Based on this, using Map when storing non-string keys and using objects otherwise would be the best approach.</p><p>I find it odd that a map was slower than an object in the performance tests. Please let me know if you have any data that suggests otherwise.</p><h3>Conclusion</h3><p>I hope you learned something new about JavaScript objects from this article.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c18ce52869eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/a-deeper-dive-into-javascript-objects-c18ce52869eb">A Deep Dive Into JavaScript Objects</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Polyfills?]]></title>
            <link>https://javascript.plainenglish.io/polyfills-what-the-hell-are-they-596baaab4a0e?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/596baaab4a0e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Tue, 13 Apr 2021 13:43:05 GMT</pubDate>
            <atom:updated>2021-04-18T17:27:53.884Z</atom:updated>
            <content:encoded><![CDATA[<h4>And how do you create a Polyfill?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vqzJMrEKxV_oFugT" /><figcaption>Photo by <a href="https://www.pexels.com/@deepanker70">Deepanker Verma</a> on <a href="https://www.pexels.com/photo/black-google-smartphone-on-box-1482061/">Pexels</a></figcaption></figure><h3>Introduction</h3><p>When building a website, it is important to make sure it works consistently on all the major browsers. After all, each browser is unique in the development features it provides.</p><p>For example, check this diagram out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4x8bQmojT63xdtkeV6dQZw.png" /><figcaption>Diagram by <a href="https://github.com/guybedford">guybedford</a> on <a href="https://github.com/guybedford/es-module-shims">Github</a></figcaption></figure><p>The above diagram is a list of ECMAScript module features and their support on Chrome, Firefox, Safari, and Edge. Notice how features are supported in some browsers and lack support in others. For instance, if Import Maps were a key component in your application, your application would break in all browsers other than Chrome.</p><p><strong>This is where polyfills come in.</strong></p><h3>What are Polyfills/Polyfilling?</h3><p>To provide an example, let’s say that fetch is not supported on all browsers, and we use it frequently in our application.</p><pre>/* <br>Let&#39;s say that Chrome supported the fetch api, but Firefox didn&#39;t.<br>*/<br>fetch(&#39;https://BACKEND/ROUTE&#39;).then((response) =&gt; {<br>   console.log(&quot;Got Response&quot;);<br> });</pre><p>As a result, our application would break in Firefox. To remedy this, we can create our own implementation of fetch for browsers that don’t natively support it and set it to window.fetch (<a href="https://github.com/github/fetch">example of a fetch polyfill</a>). This is what polyfilling is.</p><p><strong>If a certain feature doesn’t exist in an environment, we can patch it with our implementation.</strong></p><p>Polyfills enable us to support multiple environments with the same codebase. Although we would need to implement the polyfill, it would be quicker and easier, in the long run, to create the polyfill than to maintain separate versions of the application for each browser/environment.</p><h3>Making a Polyfill</h3><p>Let’s implement a polyfill for Array.prototype.forEach for the web in vanilla JavaScript.</p><pre>let fruits = [&quot;Strawberry&quot;, &quot;Melon&quot;, &quot;Orange&quot;];</pre><pre>// super convienent way of iterating through a collection<br>fruits.forEach((fruit) =&gt; {<br>    console.log(&quot;I ate&quot;, fruit);<br>});</pre><p>Let’s break this into 2 steps:</p><ul><li>Coding up the Polyfill</li><li>Importing the Polyfill</li></ul><h4>Coding up the Polyfill</h4><p>First, let’s check whether Array.prototype.forEach is supported on the current browser.</p><pre>const isForEachSupported = !Array.prototype.forEach;</pre><p>If .forEach is supported, let’s leave the native implementation as-is. If it is not supported, then we need to add our custom implementation.</p><p>Let’s bind Array.prototype.forEach to our implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50fc254ecb939dd61b6fbc329f309a24/href">https://medium.com/media/50fc254ecb939dd61b6fbc329f309a24/href</a></iframe><p><em>Disclaimer: I left out </em>thisArg<em> in</em>Array.prototype.forEach<em> for simplicity&#39;s sake.</em></p><p>We can now support browsers that don’t have Array.prototype.forEach with our own implementation.</p><h4>Import the Polyfill</h4><p>To finish it off, we need to import the polyfill in our HTML files. The polyfill file must be before any files or script tags that use Array.prototype.forEach. Suppose the following was our initial HTML file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecae93a2237ac458f59feaad7e7449dd/href">https://medium.com/media/ecae93a2237ac458f59feaad7e7449dd/href</a></iframe><p>And the above polyfill was in forEachPolyfill.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab49f372af559dbb114cefc02f29046/href">https://medium.com/media/5ab49f372af559dbb114cefc02f29046/href</a></iframe><p><strong>Congrats! You wrote your first polyfill! </strong>However, not all polyfills are done in the same way nor are they of the same difficulty. For instance, check out these polyfills for <a href="https://github.com/taylorhakes/promise-polyfill">ES6 Promise</a> and <a href="https://github.com/github/fetch">fetch</a>.</p><p>All in all, polyfilling involves patching features that aren’t natively supported in environments to provide greater backward compatibility and usability. We only dipped our toes into polyfilling in this article, if you would like to go deeper, check out <a href="https://github.com/search?utf8=%E2%9C%93&amp;q=polyfill&amp;type=">Github Polyfills</a>.</p><p><strong>With that, Thank you for reading!</strong></p><p><em>More content at </em><a href="https://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=596baaab4a0e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/polyfills-what-the-hell-are-they-596baaab4a0e">What are Polyfills?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for Interviewing: An Overview of the Core Data Structures]]></title>
            <link>https://python.plainenglish.io/python-for-interviewing-an-overview-of-the-core-data-structures-666abdf8b698?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/666abdf8b698</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 02:59:37 GMT</pubDate>
            <atom:updated>2021-03-09T07:15:13.130Z</atom:updated>
            <content:encoded><![CDATA[<h4>Must-know data structures to kill your interview!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*vcd5DO2UmF-PRxwh" /><figcaption>Photo by <a href="https://unsplash.com/@itsrahbee">Mark Rabe</a> on <a href="https://unsplash.com/photos/zCJrolkwRyE">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Algorithms &amp; Data Structures interviews are notoriously difficult. Coming up with an optimal approach to a problem is already time-consuming. So, if you become stuck on the implementation, you may not even finish the problem! As a result, understanding how to use each of the core data structures and knowing the Python-specific caveats about them will make the implementation seamless.</p><h3>Agenda</h3><ul><li><a href="#8b5e">Stack</a></li><li><a href="#9069">Queue</a></li><li><a href="#8e70">Priority Queue/Heap</a></li><li><a href="#a9ae">Dictionary (Default Dict)</a></li></ul><h3>Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*OiauBCKde1HZ87-i.png" /><figcaption>Photo on <a href="https://holycoders.com/data-structures-stack/">holycoders</a></figcaption></figure><p>To recap, a stack allows us to push and pop elements of the top, and get the top element in O(1) time. Though there isn’t an explicit stack class in Python, we can use a list instead.</p><p>We can use append and pop to add and remove elements off the end in amortized O(1) time (<a href="https://wiki.python.org/moin/TimeComplexity">Time Complexity</a>). Python lists are implemented as dynamic arrays. Once the array is full, Python will allocate more memory for a larger array and copy the old elements to it. Since this reallocation doesn’t happen too often, append will still be O(1) in most cases.</p><p>Also, we can index into the list with -1 to get the last element in a list. Basically, the end of the list will be the “top of the stack”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce26ac0a8b17cdf914dfe7f24a7c3e9e/href">https://medium.com/media/ce26ac0a8b17cdf914dfe7f24a7c3e9e/href</a></iframe><h3>Queue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*TS4VaSoVa_jpkrjm" /><figcaption>Photo by <a href="https://unsplash.com/@adriendlf">Adrien Delforge</a> on <a href="https://unsplash.com/photos/CrHG_ZYn1Dw">Unsplash</a></figcaption></figure><p>Using a stack is simple, but what if we wanted to process data in FIFO (First In First Out) order. In the <a href="https://docs.python.org/3/library/collections.html">collections</a> package, Python provides <a href="https://docs.python.org/3/library/collections.html#collections.deque">deque</a> , a double-ended queue class. With deque, we can insert and remove from both ends in O(1) time. The deque constructor takes in an iterable: we can pass in an empty list to create an empty deque.</p><pre>from collections import deque</pre><pre>queue = deque([])</pre><p>The main methods are append, appendleft, pop and popleft . As the names suggest, append and pop will add and remove elements from the end, whereas appendleft and popleft do the same at the front. In order to emulate a queue, we add from one side and remove from the other.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bc54857295eb4f41833735199be13e5/href">https://medium.com/media/1bc54857295eb4f41833735199be13e5/href</a></iframe><p>If you noticed, we can also use deque to emulate a stack: we add and remove from the same side.</p><p>On a different note, I want to highlight a common mistake in interviews: using lists as queues.</p><p>Let’s consider 2 ways we can use lists as queues.</p><p>We can add to the front of the list and remove from the end. This requires using <a href="https://www.tutorialspoint.com/python/list_insert.html">insert</a> at index 0 and pop.</p><pre>queue = [2,3,4,5]<br><br># add 1 at index 0, [1,2,3,4,5]<br>queue.insert(0, 1), [1,2,3,4,5]<br><br># pop 5 from the end, [1,2,3,4]<br>element = queue.pop()</pre><p>The problem is that inserting an element at the front of a list is O(N), since all the other elements must be shifted to the right (<a href="https://wiki.python.org/moin/TimeComplexity">Time Complexity</a>).</p><p>Let’s say instead we decided to add at the end and remove from the front.</p><pre>queue = [5,4,3,2]<br><br># add 1 to the end, [5,4,3,2,1]<br>queue.append(1)<br><br># pop 5 from the front, [4,3,2,1]<br>element = queue.pop(0)</pre><p>The problem still remains, since popping from the front of the list will be O(N) as everything to the right must shift to the left.</p><p>Even though using lists as queues is fine if the lists are relatively small, using them over the more efficient deque in an interview setting where time complexity is important is not ideal.</p><h3>Priority Queue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*CMDWhSmIn-PDgIDM.png" /><figcaption>Photo on <a href="https://www.geeksforgeeks.org/heap-data-structure/">geeksforgeeks</a></figcaption></figure><p>Similar to stacks, there is no explicit class to create a priority queue or a heap in Python. Instead, we have <a href="https://docs.python.org/3/library/heapq.html">heapq</a>, a collection of methods that allows us to use lists as heaps.</p><p>Allow me to demonstrate.</p><pre>import heapq</pre><pre># create a new &#39;heap&#39;. it is really just a list<br>heap = []</pre><p>We can add elements to our heap with <a href="https://docs.python.org/3/library/heapq.html#heapq.heappush">heapq.heappush</a> and pop elements out of our heap with <a href="https://docs.python.org/3/library/heapq.html#heapq.heappop">heapq.heappop</a>.</p><pre># push the value 1 into the heap<br>heapq.heappush(heap, 1)</pre><pre># pop the value on top of the heap: 1. The heap is now empty<br>element = heapq.heappop(heap)</pre><p>heapq.heappush and heapq.heappop will maintain the <a href="https://docs.python.org/3/library/heapq.html"><strong>min-heap invariant</strong></a> in the list that we use as a heap.</p><p>Here is what I mean:</p><pre>heap = []<br>numbers = [9,2,4,1,3,11]<br>k = 3<br>ksmallest = []<br>for number in numbers:<br>    heapq.heappush(heap, number)</pre><pre>for i in range(k):<br>    ksmallest.append(heapq.heappop(heap))</pre><pre># ksmallest is [1,2,3]<br>print(ksmallest) </pre><p>If I were to push all the elements in numbers into heap and pop out 3 times, I would get the 3 smallest elements, or [1,2,3]. There is no “setting” that tells the heapq functions to treat our heap as a max-heap:<strong> the functions “assume” that the passed in heap is a min-heap and only provide the expected results if it is</strong>.</p><h4><strong>How can I make a list of elements into a min-heap?</strong></h4><p>As shown above, one approach is to make an additional empty list and push the elements into that list with heapq.heappush . The time complexity of this approach is O(NlogN) where N is the number of elements in the list.</p><p>A more efficient approach is to use <a href="https://docs.python.org/3/library/heapq.html">heapq.heapify</a> . Given a list, this function will swap its elements in place to make the list a min-heap. Moreover, heapq.heapify only takes O(N) time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d9b41274f15cbc8f7a2690694989256/href">https://medium.com/media/2d9b41274f15cbc8f7a2690694989256/href</a></iframe><h4><strong>But… What do I do if I want a max-heap?</strong></h4><p>As previously stated, we cannot directly use a max-heap with heapq. Instead, we can try to invert our elements in the min-heap so that the larger elements get popped out first.</p><p>For example, say I have a list of numbers, and I wanted the K largest numbers. To begin, we can invert the numbers by multiplying by -1. The numbers that were the largest are now the smallest. We can now turn this collection of numbers into a min-heap. When we pop our inverted numbers from the heap, we simply multiply by -1 again to get our initial number back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2971032cb0e33574bad202d87091b73/href">https://medium.com/media/d2971032cb0e33574bad202d87091b73/href</a></iframe><p>In situations where you need a max-heap, consider how you can reverse the order of the elements, turning the largest elements into the smallest.</p><h4><strong>Wait… How do I compare across multiple fields?</strong></h4><p>Suppose we had the age and height (in inches) of students stored in a list.</p><pre># each entry is a tuple (age, height)<br>students = [(12,54),(18,78),(18,62),(17,67),(16,67),(21, 76)]</pre><p>Let’s say we wanted to get the K youngest students, and if two students had the same age, let’s consider the one who is shorter to be younger. Unfortunately, there is no way for us to use a custom comparator function to handle cases where two students have the same age. Instead, we can use tuples to allow the heapq functions to compare multiple fields.</p><p>To provide an example, consider the students at indices 0 and 1. Since, student 0’s age, 12, is less than student 1’s, 18, student 0 will be considered smaller and will be closer to the top of the heap than student 1.</p><p>Let’s now consider student 1 and student 2. Since both of their ages are the same, the heapq functions will compare the next field in the tuple, which is height. Student 2 has a smaller height, so student 2 will be considered smaller and will be closer to the top.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f745cd3f504ee2620b824209ae1befa2/href">https://medium.com/media/f745cd3f504ee2620b824209ae1befa2/href</a></iframe><p>If you need to compare against multiple fields to find out which element is smaller or bigger, consider having the heap’s elements be tuples.</p><h3>Dictionary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Z-ksaWHExlffMWsE.jpg" /><figcaption>Photo on <a href="https://codenuclear.com/difference-between-hashmap-hashtable/">codenuclear</a></figcaption></figure><p>Dictionaries are the Python equivalent to Hash Maps and are an overpowered data structure. In most cases, we can look up, add, delete and update keys in O(1) time. Let’s go over the basics of dictionaries.</p><pre># empty dict<br>d = {}</pre><pre># dict with some keys and values<br>d = {<br>    &quot;name&quot;: &quot;James&quot;,<br>    &quot;age&quot;: 29<br>    5: 29.3<br>}</pre><p>When declaring a dictionary, we put the keys on the left and values on the right, separated by a colon. In Python, the keys of a dictionary can only be hashable values, like int, str, tuple, and more (<a href="https://www.pythonforthelab.com/blog/what-are-hashable-objects/">Hashable Objects</a>). In addition, a dictionary can have keys and values of multiple types as shown above.</p><p>We can also add, update and delete keys with [].</p><pre># add key &quot;numbers&quot; to d<br>d[&quot;numbers&quot;] = [1,2,4,12]</pre><pre># update key &quot;numbers&quot; of d<br>d[&quot;numbers&quot;] = [1,3,6,18]</pre><pre># delete key &quot;numbers&quot; of d<br>del d[&quot;numbers&quot;]</pre><p>We can also easily check if a key is in a dictionary with in .</p><pre>doesNumbersExist = &quot;numbers&quot; in d</pre><p>Python also provides a nice way of iterating over the keys inside a dictionary.</p><pre>d = {&quot;a&quot;: 0, &quot;b&quot;: 5, &quot;c&quot;: 6, &quot;d&quot;: 7, &quot;e&quot;: 11, &quot;f&quot;: 19}</pre><pre># iterate over each key in d<br>for key in d:<br>    print(d[key])</pre><p>When you are iterating over keys in this manner, remember that you cannot add new keys or delete any existing keys, as this will result in an error.</p><h4>What happens if I try to access a key which doesn’t exist?</h4><pre>d = {&quot;a&quot;: 0, &quot;b&quot;: 7}</pre><pre>c_count = d[&quot;c&quot;] # KeyError: &#39;c&#39;</pre><p>In the above snippet, “c” does not exist. We will get a KeyError when we run the code. As a result, in many situations, we need to check if the key exists in a dictionary before we try to access it.</p><p>Although this check is simple, it can be a hassle in an interview if we need to do it many times. Alternatively, if we use <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict">collections.defaultdict</a>, there is no need for this check. defaultdict operates in the same way as a dictionary in nearly all aspects except for handling missing keys. When accessing keys that don’t exist, defaultdict automatically sets a default value for them. The factory function to create the default value can be passed in the constructor of defaultdict.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9684c3d701083c6acf786a36e84f88f4/href">https://medium.com/media/9684c3d701083c6acf786a36e84f88f4/href</a></iframe><p>We can also pass in a lambda as the factory function to return custom default values. Let’s say for our default value we return the tuple (0, 0).</p><pre>pair_dict = defaultdict(lambda: (0,0))</pre><pre># prints True<br>print(pair_dict[&#39;point&#39;] == (0,0))</pre><p>Using a defaultdict can help reduce the clutter in your code, speeding up your implementation.</p><h3>Conclusion</h3><p>The main goal of this article was to explain the core data structures in Python, and to make you aware of their caveats so you can kill the implementation portion of your interview! <strong>I hope you walked away learning something new and thank you for reading!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666abdf8b698" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/python-for-interviewing-an-overview-of-the-core-data-structures-666abdf8b698">Python for Interviewing: An Overview of the Core Data Structures</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Server Performance with Client-Side Image Compression]]></title>
            <link>https://medium.com/swlh/boost-server-performance-with-client-side-image-compression-cdefba1c1c0d?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdefba1c1c0d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Mon, 01 Mar 2021 04:40:17 GMT</pubDate>
            <atom:updated>2021-03-01T07:14:36.622Z</atom:updated>
            <content:encoded><![CDATA[<h4>Reduce upload time by compressing first!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Unio-qOFPrQMLqH0" /><figcaption>Photo by <a href="https://unsplash.com/@benjaminsweet">Ben Sweet</a> on <a href="https://unsplash.com/photos/2LowviVHZ-E">Unsplash</a></figcaption></figure><p><em>Huge shoutout to </em><a href="https://www.youtube.com/watch?v=bXf_UdyDzSA"><em>Codú Community</em></a><em> for inspiring this blog. All the code for this project is linked on </em><a href="https://github.com/Ramko9999/Medium-Image-Compression-Client-Side"><em>GitHub</em></a><em>.</em></p><h3>Introduction</h3><p>There are multiple ways of optimizing server performance. One way is to make the client do some of the work. Consider uploading images for profile pictures. Since high-quality images take up several MB, it is costly to send them over the network to the server. Also, since profile pictures don’t need to be extremely detailed, it would be nice to compress them and save space. Thankfully, with HTML Canvas, we can compress our images right upon an upload by resizing them. After the compression, we can then send the images to the server, reducing upload time and the work the server must do.</p><h3>Agenda</h3><ul><li><a href="#3e69">Setup demo HTML page</a></li><li><a href="#5a44">Listen to the image input</a></li><li><a href="#d14f">Resize and compress image with HTML Canvas</a></li><li><a href="#79a8">Demo of the compression working</a></li></ul><h3>Setup demo HTML page</h3><p>To follow along, create a new project with the following files:</p><pre>- index.html<br>- main.js</pre><p>We will create the basic UI in index.html.</p><p>Put the following in index.html:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/248375dd022d171d600761caaabbfffe/href">https://medium.com/media/248375dd022d171d600761caaabbfffe/href</a></iframe><p>In addition to accepting file uploads, we will preview both the initial image the user uploads and our compressed version in the UI.</p><p>Let’s go to main.js to handle when a user inputs an image.</p><h3>Listen to the image input</h3><p>In main.js, let’s first define getImageDimensions , which returns a Promise of an input image’s width and height. We need the initial image’s dimensions to maintain the aspect ratio when we resize.</p><pre>function getImageDimensions(image){<br>    return new Promise((resolve, reject) =&gt; {<br>        image.onload = function(e){<br>            const width = this.width;<br>            const height = this.height;<br>            resolve({height, width});<br>        }<br>    });<br>}</pre><p>Let’s now add an event listener to handle when our input tag, image-input , changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d788a4b99b5576481115a76aa04a97b/href">https://medium.com/media/4d788a4b99b5576481115a76aa04a97b/href</a></iframe><p>The above listener will trigger whenever a user uploads an image. We take the uploaded image, display it to the user, and acquire its dimensions. All that is left is to resize and compress the image.</p><h3>Resize and compress image with HTML Canvas</h3><p>Let’s get to the fun part and make the compressImage function in main.js.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3d54dc971d99c958c54390f28588780/href">https://medium.com/media/e3d54dc971d99c958c54390f28588780/href</a></iframe><p><strong>This is the magic!</strong></p><p>Given an HTML image, the scale factor, and the initial width and height of the image, the function creates an HTML Canvas, canvas , and draws the image downscaled on the canvas . Finally, we turn the downscaled image into a blob and resolve it from the Promise. The resolved blob represents our compressed image. We can now use this function to compress whatever image we want.</p><p>Let’s integrate this into the event listener we created earlier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bead5431c156d7694e16e98d1c1913c9/href">https://medium.com/media/bead5431c156d7694e16e98d1c1913c9/href</a></iframe><p>Let’s break this down.</p><p>First, we create two compressed images with differing scales: the ratio of MAX_WIDTH and the initial image’s width and the ratio of MAX_HEIGHT and the initial image’s height (You can parameterize MAX_WIDTH and MAX_HEIGHT based on the use case).</p><p>Then, we pick the smaller blob out of the two to be our compressed output and display it to the user. Finally, we check if our compressed version is smaller than the initial image. If the initial image was smaller, we can use it instead.</p><p>We now can compress images whenever the user inputs an image on the client. optimalBlob represents the image with the smallest size among both the compressed versions and the initial image.</p><h3>Demo of the compression working</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*7Zyw0voQ2rRuPgQ1" /><figcaption>Photo by <a href="https://unsplash.com/@joshuaearle">Joshua Earle</a> on <a href="https://unsplash.com/photos/-87JyMb9ZfU">Unsplash</a></figcaption></figure><p>I took the above image and submitted it into our file input.</p><p>Here is what occurred:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FPogRtj4%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FPogRtj4&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="633" frameborder="0" scrolling="no"><a href="https://medium.com/media/10e868851604cdb9fea40f23d3de8404/href">https://medium.com/media/10e868851604cdb9fea40f23d3de8404/href</a></iframe><p>Here is the compressed result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*rYgb4t-aEgmjfd36MqG9EA.png" /><figcaption>Compressed Result</figcaption></figure><p>The initial size of the image was roughly 299 KB and the compressed result was only 45 KB, a huge reduction. With this reduction in size, it will be much faster to send the image to the server, and the server doesn’t need to worry about compressing it either. <strong>It is a win-win situation! </strong>However,<strong> </strong>if image quality is important, this approach is not a good idea, since resizing through HTML Canvas is lossy. Despite that, this is a great way to handle the uploads of profile pictures.</p><p><strong>That’s all I got. Thanks for reading!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdefba1c1c0d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/boost-server-performance-with-client-side-image-compression-cdefba1c1c0d">Boost Server Performance with Client-Side Image Compression</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Tips to Write Memory Efficient Python Code]]></title>
            <link>https://medium.com/swlh/3-tips-to-write-memory-efficient-python-code-9ce8b3926081?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ce8b3926081</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 00:06:01 GMT</pubDate>
            <atom:updated>2021-02-22T12:35:58.193Z</atom:updated>
            <content:encoded><![CDATA[<h4>Optimize memory efficiency with these simple tips &amp; tricks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*OFjRbNJ8gkv9HIgL" /><figcaption>Photo by <a href="https://unsplash.com/@harrisonbroadbent">Harrison Broadbent</a> on <a href="https://unsplash.com/photos/ING1Uf1Fc30">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Most of the time, there is no need for us to optimize memory usage in Python. Either our programs are too small to consume significant memory or we are are storing the data in databases outside the program. Regardless, there may exist cases where we must retain excessively large structures or a large number of objects in memory. As a result, I hope to illustrate practices that can decrease program memory usage.</p><h3>Agenda</h3><ul><li><a href="#ecf7">Restrict class fields with </a><a href="#ecf7">__slots__</a></li><li><a href="#386c">Lazily evaluate with generators</a></li><li><a href="#4799">Constrain element types with </a><a href="#4799">array</a></li></ul><h3>Restrict class fields with __slots__</h3><p>By default, whenever you create an object in Python, you will have the ability to add new fields to the object even after its creation.</p><p>For instance, suppose I had a class called Dog :</p><pre>class Dog:</pre><pre>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age</pre><pre>def main():<br>    dog = Dog(&quot;James&quot;, 5)<br>    dog.breed = &quot;Pitbull&quot;<br>    print(dog.breed)</pre><pre>main()</pre><p>Although name and age are the only fields I pass into the constructor, notice how we can initialize a new field called breed after creating dog. Essentially, the fields of dog are stored in an internal dictionary, accessed via .__dict__, and when we initialize dog.breed , we are adding the field “breed” with the value “Pitbull” to its internal dictionary.</p><pre>def main():<br>    dog = Dog(&quot;James&quot;, 5)<br>    print(dog.__dict__) </pre><pre>    &#39;&#39;&#39;<br>    output: {&#39;name&#39;: &#39;James&#39;, &#39;age&#39;: 5}<br>    &#39;&#39;&#39;</pre><pre>    dog.breed = &quot;Pitbull&quot;<br>    print(dog.__dict__)</pre><pre>    &#39;&#39;&#39;<br>    output: {&#39;name&#39;: &#39;James&#39;, &#39;age&#39;: 5, &#39;breed&#39;: &#39;Pitbull&#39;}<br>    &#39;&#39;&#39;</pre><pre>main()</pre><p>Although this offers flexibility, most of the time we won’t need to add new fields outside of instantiation. To save our memory footprint, we can set the <a href="https://book.pythontips.com/en/latest/__slots__magic.html">__slots__</a> attribute of Dog to predefine its fields.</p><pre>class Dog:</pre><pre>    __slots__ = (&quot;name&quot;, &quot;age&quot;)<br>    def __init__(self, name, age):<br>        self.name = name<br>        self.age = age</pre><p>Using __slots__ prevents the creation of the internal dictionary, allowing us to store the instance fields more compactly. However, now, we can no longer create new fields on the fly.</p><pre>def main():<br>    dog = Dog(&quot;James&quot;, 5)<br>    dog.breed = &quot;Pitbull&quot; <br>    &#39;&#39;&#39;<br>    output: AttributeError:&#39;Dog&#39; object has no attribute &#39;breed&#39;<br>    &#39;&#39;&#39;<br>  <br>main()</pre><p>In order to test the memory usage of __slots__, I created 100,000 Dog and SlotDog objects.</p><pre>class Dog:<br>  <br>  def __init__(self, name, age):<br>    self.name = name<br>    self.age = age</pre><pre>class SlotDog:<br>    <br>   __slots__=(&quot;name&quot;, &quot;age&quot;)<br>   def __init__(self, name, age):<br>     self.name = name<br>     self.age = age</pre><p>I then used the <a href="https://pypi.org/project/memory-profiler/">memory_profiler</a> to break down how the memory usage increased after the creation of 100,000 objects. The memory usage increased by 16.5 MiB after the creation of the Dog objects, and 5.8 MiB for the SlotDog objects, showing a large improvement for using __slots__. You can check out the creation code on <a href="https://github.com/Ramko9999/Medium-Memory-Efficient-Python/blob/main/slots_perf.py">GitHub</a>.</p><p>Using __slots__ would be beneficial in situations where large amounts of objects with pre-determined fields have to be instantiated.</p><h3>Lazily evaluate with generators</h3><p>When working with large files or collections, it may not be possible to load the whole file or maintain the collection in memory. It would be nice if we could process the file in chunks or the collection one element at a time.</p><p><strong>Enter generators!</strong></p><p>Let’s consider an example. Say I need to get the first n odd numbers for processing. Naturally, we can create a list and append the first n odd numbers.</p><pre>def get_odds_list(n):<br>    odds = []<br>    num = 1<br>    for i in range(n):<br>        odds.append(num)<br>        num += 2<br>    return odds</pre><p>However, if we wanted to process the first million odds, it would become expensive to maintain this list in memory. A better approach would be to utilize a generator to iterate through the odds as we compute them rather than computing and storing all million odds.</p><p>Here is how the above function would look like as a generator:</p><pre>def get_odds_generator(n):<br>    num = 1<br>    for i in range(n):<br>        yield num<br>        num += 2</pre><pre>odds = get_odds_generator(1000000)</pre><p>When we initialize odds , none of the odd numbers are computed yet. odds at the moment is just an <a href="https://www.w3schools.com/python/python_iterators.asp">iterator</a>, a sequence of values. In order to visit the elements in an iterator, we have to call next on the iterator. As the name suggests, next returns the next value in the sequence.</p><p>The magic is in the yield keyword: it makes the function a generator. Essentially, when next is called on odds, the generator, get_odds_generator, will evaluate its code until it hits yield. The generator will then return the value and its state will freeze. Then once next is called again, the generator will resume evaluating its code from the state it left off at.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31a681f3c6d2aecf91d01d0acd6c1a52/href">https://medium.com/media/31a681f3c6d2aecf91d01d0acd6c1a52/href</a></iframe><p>We can also walk through the values produced by a generator in the following manner.</p><pre>odds = get_odds_generator(1000000)<br>for odd in odds:<br>    pass //process the odd</pre><p><strong>We can process our odds as we compute them with a generator. Therefore, we don’t need any extra memory to store the odds.</strong></p><p>One caveat of using generators is that we won’t be able to get previous elements or jump around the sequence of elements. If you need to access previous elements, it might be better to simply use lists instead.</p><h3>Constrain element types with array</h3><p>Although many consider lists to be arrays in Python, there actually exists a separate <a href="https://docs.python.org/3/library/array.html">array</a> module. The core difference between lists and arrays is that arrays are constrained to elements of only one type.</p><p>We can create lists in Python with values of multiple types.</p><pre>lst = [1.0, 1, {}, &quot;hi&quot;]</pre><p>This is not the case with arrays. We have to specify the type of the elements in an array with a type code. The type code is a character representing the type of the array: ‘i’ represents an integer, ‘b’ represents a char and etc...</p><pre>from array import array</pre><pre>arr = array(&#39;i&#39;, []) # create an array of integers</pre><pre>arr.append(4) # append 4 to arr</pre><pre>arr.append(&#39;&#39;) # type error: integer is required not string</pre><p>Arrays have a lot of the methods in common with lists, like append and pop (<a href="https://docs.python.org/3/library/array.html#array.array.append">Documentation</a>). The main advantage of arrays is that they are a lot more compact. To test this, I made a list and array with 1 million integers and found that the memory usage increased by 19.5 MiB with the list and only 4 MiB with the array. Check out the code for the measurements (<a href="https://github.com/Ramko9999/Medium-Memory-Efficient-Python/blob/main/arr_perf.py">Code</a>).</p><p>Consider using arrays if you have large sequences of data of the same type.</p><h3>Conclusion</h3><blockquote>Premature optimization is the root of all evil.</blockquote><blockquote>― <strong>Donald Ervin Knuth</strong></blockquote><p>I have shown multiple practices you can implement to reduce your memory footprint, ranging from using __slots__ to arrays. <strong>Only consider using these practices in the worst case where you truly need to optimize for memory. </strong>In most situations, there is no need for __slots__, and arrays. On the other hand, the standard APIs most likely already use generators, so you can rest easy.</p><p><strong>With that, I would like to thank you for taking the time to read this blog!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ce8b3926081" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/3-tips-to-write-memory-efficient-python-code-9ce8b3926081">3 Tips to Write Memory Efficient Python Code</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Host and Use Redis for Free]]></title>
            <link>https://medium.com/swlh/host-and-use-redis-for-free-b70d65a13edd?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b70d65a13edd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 02:26:05 GMT</pubDate>
            <atom:updated>2021-02-16T22:23:10.927Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a project on a budget? This is for you!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*pTXCb9DovKP8rgCZ.png" /><figcaption>Photo on <a href="https://www.inovex.de/blog/redis-cli/">invokex</a></figcaption></figure><h3>Introduction</h3><p>Although building software projects can be challenging, deployment can be a pain. In fact, in situations where speed is necessary, deployment must be seamless. For that reason, I want to show you how to deploy Redis for free and use Redis remotely. <a href="https://redislabs.com/">Redis Labs</a>, a Redis cloud hosting service, offers a free plan with simple deployment steps. We will leverage that plan to create an instance and integrate that instance with Node.js.</p><h3>Walk Through</h3><blockquote>Do everything quickly and well.<br>― G.I. Gurdjieff</blockquote><p>To start, head over to <a href="https://redislabs.com/">https://redislabs.com/</a> and sign up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wErfShGOjlbPVbnTmvDCrA.png" /><figcaption>Photo by Author</figcaption></figure><p>Once you create and verify your account, you will end up on this screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tEXz40I048vjI9P0WXuBA.png" /><figcaption>Photo by Author</figcaption></figure><p>Click “Create your subscription”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9s4XRGY6NGnvH-Dcmn_z9w.png" /></figure><p>Scroll down to “Fixed size” and pick the free option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZJae6g3-D98R0n7cZ8lS0g.png" /><figcaption>Photo by Author</figcaption></figure><p>Click “Create”. We now need to create our database under the subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MiFD4JsIghT7Q0ZWI_KSVA.png" /><figcaption>Photo by Author</figcaption></figure><p>Enter in the database name. Be sure to copy “Redis Password”. Once you are ready, click “Activate”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujM1mWiIt2UuHuTuzxg2dA.png" /><figcaption>Photo by Author</figcaption></figure><p>We can use the endpoint to connect to our remote instance so be sure to copy it down. For security reasons, be careful with who you expose your endpoint to.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FRl9Yqavfj2Ula%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Feasy-Rl9Yqavfj2Ula&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2FRl9Yqavfj2Ula%2Fgiphy.gif%3Fcid%3D790b7611f9e820e1b634578d9046c219f02449686871dcbe%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/4537c9bd9b809c0494d4abdca06eb145/href">https://medium.com/media/4537c9bd9b809c0494d4abdca06eb145/href</a></iframe><p><strong>It is really that quick!</strong></p><h3>Integration</h3><p>Let’s connect to our remote Redis instance! Although I will use Node.js, the connection process will most likely be similar to the other technologies.</p><p>Start by creating a new npm project.</p><pre>npm init</pre><p>After filling out the project details, cd into your project and install <a href="https://redis.js.org/">redis</a>, a Node.js client for Redis, and <a href="https://www.npmjs.com/package/dotenv">dotenv</a>, an environment variable loader.</p><pre>npm install redis</pre><pre>npm install dotenv --save-dev</pre><p>In the root directory, create a file called .env . In it, let’s put our Redis instance hostname, port, and password.</p><p><em>We can find the hostname, port, and password in the View Database section:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ynXHj7nEJLLnEOxXq7OSrg.png" /><figcaption>Photo by Author</figcaption></figure><p>Contents of .env:</p><pre>REDIS_HOSTNAME=YOUR REDIS HOSTNAME<br>REDIS_PORT=YOUR REDIS PORT<br>REDIS_PASSWORD=YOUR REDIS PASSWORD</pre><p>Create index.js . Let’s say this is where we want to connect to our remote instance. Let’s create a client and test if we can connect to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d62a2d809cdd9ed6471dba46cdcaf2da/href">https://medium.com/media/d62a2d809cdd9ed6471dba46cdcaf2da/href</a></iframe><p><strong>Now we can connect to our Redis instance from Node.js!</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUA7aQOxkz00lvCAOQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FxUA7aQOxkz00lvCAOQ&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FxUA7aQOxkz00lvCAOQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/28da9e73abae1487772293252601e35c/href">https://medium.com/media/28da9e73abae1487772293252601e35c/href</a></iframe><h3>Conclusion</h3><p>I wanted to show a simple way to deploy and use Redis for free, whether it be for demoing a project at a hackathon or evaluating a proof of concept idea.</p><p><strong>Thank you for taking the time to read this blog!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b70d65a13edd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/host-and-use-redis-for-free-b70d65a13edd">Host and Use Redis for Free</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set a Time Limit on Async Actions in JavaScript]]></title>
            <link>https://medium.com/swlh/set-a-time-limit-on-async-actions-in-javascript-567d7ca018c2?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/567d7ca018c2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Wed, 10 Feb 2021 05:07:18 GMT</pubDate>
            <atom:updated>2021-02-10T08:06:21.130Z</atom:updated>
            <content:encoded><![CDATA[<h4>Some pieces of code will never finish…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*MSpq6HMhip5BbmHI" /><figcaption>Photo by <a href="https://unsplash.com/@aronvisuals">Aron Visuals</a> on <a href="https://unsplash.com/photos/BXOXnQ26B7o">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Asynchronous programming is incredible! With it, we can run our IO-intensive tasks without having to block the execution of other code. However, in situations where the code after a blocking task depends on the task’s result, we must wait. Now, imagine if the blocking task took a long time to finish or it never finished. This could be problematic in the context of the application. We can solve this issue by setting a time limit on our task. If our task doesn’t finish in the span of the time limit, we can return a failure value instead. Let me elaborate.</p><h3>Concept</h3><p>Let’s suppose that the blocking task is a promise called longTask , and it was used in the following function:</p><pre>async function doSomething(){<br>   let data = await longTask;<br>   doSomethingImportantWithData(data);<br>}</pre><p>If the time it takes longTask to settle is longer than our requirements or if longTask is never settled, we won’t be able to execute the code after longTask in a timely manner.</p><p>However, imagine if we could set a time limit on our blocking tasks. In the case that the blocking task doesn’t settle within the time limit, we can return a failure value from the task. In the scenario the task resolves, we can return the value it resolved to.</p><p>To elaborate, suppose there was a function called fulfillWithTimeLimit which takes in milliseconds, the time limit, task , the task promise we would like to set a time limit on, and failureValue, the value that would be resolved from fulfillWithTimeLimit if task never completes within the time limit.</p><p>In the case that longTask is resolved before the time limit, fulfillWithTimeLimit returns with the value resolved from longTask . In the case that longTask never finishes within the span of the time limit, the function should immediately return failureValue. With this approach, we ensure that we never have to wait on longTask for more than the specified time limit.</p><p>Let’s dig into the approach.</p><h3>Code</h3><p>In order to “set a time limit” on the task, we can create another promise, timeoutPromise, which resolves to failureValue after the time limit. After that, we can race both our timeoutPromise and task with <a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">Promise.race</a>. Promise.race takes in a list of promises and resolves or rejects to the value of the promise in the list that is settled first.</p><p>To provide an example, suppose I had the two following promises:</p><pre>const a = new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        resolve(&quot;A finished before!&quot;);<br>    }, 100);<br>});</pre><pre>const b = new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        resolve(&quot;B finished!&quot;);<br>    }, 1000);<br>});</pre><p>Suppose I raced these promises and got the value.</p><pre>const finishString = await Promise.race([a, b]);</pre><p>Since a resolves after 100 milliseconds while b resolves after 1000 milliseconds, a will be the first promise to resolve. As a result, finishString will be equal to “A finished before!”. If you would like to learn more about Promise.race, please check out the following:</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">Promise.race() - JavaScript | MDN</a></p><p>Nonetheless, let’s apply the promise racing idea to create the fulfillWithTimeLimit function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0c51ef76ec4bc7ae3cb3cb1088e5492/href">https://medium.com/media/d0c51ef76ec4bc7ae3cb3cb1088e5492/href</a></iframe><p>To begin, we create our timeoutPromise and ensure it resolves with the failureValue after the time limit. Then, we race to see whether our task or timeoutPromise finishes first. For safety, we can clear the timeout and return response, the resolved value of the race.</p><p>Here is how doSomething looks now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f030c5e40f1a6795d12e680394a8f28/href">https://medium.com/media/0f030c5e40f1a6795d12e680394a8f28/href</a></iframe><p>In the above example, I set failureValue to null. However, it may be better to set it to a value of the same type as what is resolved from the task. In fact, it may be better to call reject in the timeoutPromise than to resolve with a failureValue.</p><p><strong>That’s it!</strong> We can easily reuse fulfillWithTimeLimit in our application code where we need a time limit.</p><h3>Conclusion</h3><p>In this blog, I aimed to show a solution with Promise.race to handle situations where blocking tasks may fail to settle or take too long to settle. Though I did not cover all the functionalities of promises, I hope this article amplifies your curiosity to explore them more.</p><p><strong>Thank you for taking the time to read this blog! Below are some other cool blogs you might be interested in.</strong></p><h3>Cool Blogs</h3><ul><li><a href="https://medium.com/javascript-in-plain-english/zero-to-hero-chrome-extensions-4060520daf59">Zero to Hero: Chrome Extensions</a></li><li><a href="https://medium.com/python-in-plain-english/crunch-pokemon-data-with-deta-base-bd9c97d96ad3">Crunch Pokemon Data with Python and Deta Base</a></li><li><a href="https://medium.com/javascript-in-plain-english/visualize-website-usage-with-a-react-dashboard-fb2b206ec0cc">Visualize Website Usage with a React Dashboard</a></li></ul><h3>Resources</h3><p><strong>Promises:</strong></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise - JavaScript | MDN</a></p><p><strong>Racing Promises:</strong></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race">Promise.race() - JavaScript | MDN</a></p><p><strong>setTimeout:</strong></p><p><a href="https://www.tutorialspoint.com/what-is-settimeout-method-in-javascript">What is setTimeout() Method in javascript?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=567d7ca018c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/set-a-time-limit-on-async-actions-in-javascript-567d7ca018c2">Set a Time Limit on Async Actions in JavaScript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunch Pokemon Data with Python and Deta Base]]></title>
            <link>https://python.plainenglish.io/crunch-pokemon-data-with-deta-base-bd9c97d96ad3?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd9c97d96ad3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 00:51:20 GMT</pubDate>
            <atom:updated>2021-02-08T16:07:14.636Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setup and work on a datastore faster than Pikachu</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*c2l5Bfc5dK9J3Tox" /><figcaption>Photo by <a href="https://unsplash.com/@michaelrivera_ph">Michael Rivera 🇵🇭</a> on <a href="https://unsplash.com/photos/DypO_XgAE4Y">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Performance is a must when it comes to building software. However, in certain situations, the speed to set up and integrate new services for proof of concept evaluation or infrastructure is overlooked. Specifically, in the realm of databases, there are many options, but I find <a href="https://www.deta.sh/">Deta</a> to be most seamless to set up and use. Deta offers Deta Base (I will refer to it as Base), a NoSQL data store optimized for developer simplicity. In this article, I aim to show how to set up a Deta project and interact with your Base to store and manipulate Pokemon data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F139JVKQ8m6GeuQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fpokemon-team-rocket-meowth-139JVKQ8m6GeuQ&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2F139JVKQ8m6GeuQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="287" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc5beb6830b98198991762a5b58b87d9/href">https://medium.com/media/dc5beb6830b98198991762a5b58b87d9/href</a></iframe><p><strong>Let’s get started!</strong></p><h3>Agenda</h3><ul><li>Setup</li><li>CRUD</li><li>Querying</li></ul><h3>Setup</h3><p>To begin, navigate to <a href="https://web.deta.sh/">Sign Up</a>, create a new account, and verify your account. Once you sign in, you should be on the following page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgHKkBFeHYKwAqqRvEuaXg.png" /><figcaption>Photo by Author</figcaption></figure><p>Click the arrow in the top left, we will create a new project from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1mNYmNDwpWs8PAHjxTN1w.png" /><figcaption>Photo by Author</figcaption></figure><p>Enter a name of your choice and hit create! A popup with your project key and project id will appear. Make sure you save the key!</p><p>With the project key saved, create a new directory, walk into it and run the following command.</p><pre>pip install flask deta</pre><p><a href="https://flask.palletsprojects.com/en/1.1.x/">Flask</a> is a web framework that we will use to create endpoints to listen to incoming requests. Based on the requests, we will interact with our remote database using the deta package.</p><p>Here is how the folder structure will look like:</p><pre>app.py</pre><pre>config.py</pre><p>In config.py , we will store our project key</p><pre>DETA_KEY= &quot;YOUR_COPIED_KEY&quot;</pre><p>In our project, we will create a Base called pokemon and utilize it to store, access, and manipulate Pokemon data. Before that, let’s go over the schema for a record in pokemon :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa1e37354acad1e41eea2abc1ad43a57/href">https://medium.com/media/fa1e37354acad1e41eea2abc1ad43a57/href</a></iframe><p>Each record in a Base must correspond to a unique identifier called key. When we insert a Pokemon record into our Base, we will provide name as our key. As a result, if we needed to get information on Charizard, we just have to ask pokemon to find the associated record with Charizard as its key.</p><p>In app.py, let’s set up the Flask app and our connection to our Base, pokemon .</p><pre>from config import DETA_KEY<br>from flask import Flask, request<br>from deta import Deta<br>from json.decoder import JSONDecoder</pre><pre>app = Flask(__name__)</pre><pre>deta_project = Deta(DETA_KEY)<br>db = deta_project.Base(&quot;pokemon&quot;)<br>decoder = JSONDecoder()</pre><pre>if __name__ == &quot;__main__&quot;:<br>    app.run()</pre><p>All the data access and manipulations will occur through db .</p><p>Our setup is now complete! Onto the CRUD!</p><h3>CRUD</h3><p>CRUD is an acronym for creating, reading, updating, and deleting data in a database. We will explore how to perform each of the above operations in our pokemon Base. All the work will be done in app.py .</p><h4>Insertion</h4><p>Deta provides 2 ways of inserting data. The first is through the <a href="https://docs.deta.sh/docs/base/sdk#put">put</a> method. put is the faster method of insertion. If you call put on a record that already exists in the base, put will overwrite the record. In contrast, <a href="https://docs.deta.sh/docs/base/sdk#put">insert</a> is 2x slower than put . In the case that you try to insert into the Base with an already existing key, it will throw an error.</p><p>Let’s create an endpoint to insert a new Pokemon with put.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce2101419e33f1299cacf6bffccfa7b4/href">https://medium.com/media/ce2101419e33f1299cacf6bffccfa7b4/href</a></iframe><p>Here is what the endpoint would look like using insert :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/457efa89955f8bb0c0a6239e5b12583d/href">https://medium.com/media/457efa89955f8bb0c0a6239e5b12583d/href</a></iframe><p>Deta also supports inserting multiple records at the same time with put_many . According to the documentation, it is possible to insert at most 25 items into the Base in a single call (<a href="https://docs.deta.sh/docs/base/sdk#put-many">Deta Base SDK</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41ea1eaf20d607953528bb08b7acc82b/href">https://medium.com/media/41ea1eaf20d607953528bb08b7acc82b/href</a></iframe><p>Let’s test out what we have so far. Let’s insert the data for Pichu into the Base via an HTTP POST through /pokemon on Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXuk1uvzHgw_Oc54okwsqg.png" /></figure><p>Once you hit send, navigate back to <a href="https://web.deta.sh/home/Ramko9999/default">Deta</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kelCdjWliRDu4ORQ2KUJSw.png" /><figcaption>Photo by Author</figcaption></figure><p>Click on your Base under the <strong>Bases</strong> section. You will now be able to view the data in your Base.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saJ77wMEGlkTT5rq2vl_fw.png" /><figcaption>Photo by Author</figcaption></figure><p>As you can see, Pichu is in our pokemon Base!</p><h4>Access</h4><p>We can use the <a href="https://docs.deta.sh/docs/base/sdk/#get">get</a> method to access the record of a given key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b48a9ed01b2d618693f5be1ecd3b985/href">https://medium.com/media/9b48a9ed01b2d618693f5be1ecd3b985/href</a></iframe><p>Since our Pokemon name is the key, we can directly access its record by providing its name. We can test it with the following GET request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*97_qFgHmoKagFg7Dtknp0w.png" /><figcaption>Photo by Author</figcaption></figure><h4>Updation</h4><p>As stated previously in <strong>Insertion</strong>, the put function can be used for overwriting records. However, put completely overwrites the record and can remove prior fields that are not part of the new updates. As result, if we want to partially update the record, we can use the <a href="https://docs.deta.sh/docs/base/sdk#update">update</a> function. In fact, update also allows for fine-grained updations like incrementing values and appending, prepending, and removing elements in a list (<a href="https://docs.deta.sh/docs/base/sdk#update">Deta Base SDK</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fb7bbd603212aca3994cbdba5592492/href">https://medium.com/media/5fb7bbd603212aca3994cbdba5592492/href</a></iframe><p>Let’s make sure updating works with an example. First, I will insert the following data for Charizard.</p><pre>{<br>    &quot;region&quot;: &quot;Johto&quot;, # Charizard is from Kanto region<br>    &quot;name&quot;: &quot;Charizard&quot;,<br>    &quot;height&quot;: 1.7,<br>    &quot;weight&quot;: 90.5,<br>    &quot;type&quot;: [&quot;Fire&quot;], # Charizard also Flying type<br>    &quot;evolution&quot;: &quot;&quot;<br>}</pre><p>region should be Kanto, and Charizard is also a flying type. Let’s update Charizard with a POST request to /pokemon/update/Charizard .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Os_Wp85latc_fOM2FQ0Lg.png" /><figcaption>Photo by Author</figcaption></figure><p>After a GET request to /pokemon/Charizard , it is clear that region and type are updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mm-besOPWb3zpVmVk2NjhA.png" /><figcaption>Photo by Author</figcaption></figure><h4>Deletion</h4><p>Deta provides <a href="https://docs.deta.sh/docs/base/sdk#delete">delete</a> , a function that takes in a key and deletes the record associated with the key.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66eb1e1ac960756f8c8bc6ff00ad951f/href">https://medium.com/media/66eb1e1ac960756f8c8bc6ff00ad951f/href</a></iframe><p>If I wanted to delete Charizard, I would make an HTTP DELETE request to /pokemon/delete/Charizard .</p><p>We have now explored how to insert, access, update and delete from our Base. Let’s learn how to query our Base.</p><h3>Querying</h3><p>Prior to querying, make sure to fill up your Base with some more Pokemon.</p><p>Querying is done through the <a href="https://docs.deta.sh/docs/base/sdk#fetch">fetch</a> method. To elaborate, fetch takes in a <a href="https://docs.deta.sh/docs/base/sdk/#queries">query</a> or a list of queries and accumulates a list of records whose fields match the query or queries.</p><p>A query is nothing more than a dictionary where the mapping between the keys and values represents the query condition. For instance, suppose I wanted to get Blastoise’s record with a query instead of get, here is how it would work:</p><pre>query = {&quot;name&quot;: &quot;Blastoise&quot;} <br>results = next(db.fetch(query))<br>blastoise = results[0]</pre><p>We accumulate all the records with name equal to Blastoise.</p><p>It is also possible to query based on inequalities. For instance, we can query for all Pokemon that weigh greater than 100kg and are less than 1 meter tall.</p><pre>query = {&quot;weight?gt&quot;: 100, &quot;height?lt&quot;: 1}<br>pokemon = next(db.fetch(query))</pre><p>We can append “?gt” and “?lt” at the end of numerical fields to query for records with respective values greater than or less than a threshold. There are a lot more suffixes that can be added to the end of a query field, so I recommend reading the documentation for your specific use case (<a href="https://docs.deta.sh/docs/base/sdk/#queries">Deta Base SDK</a>).</p><p>Let’s create an endpoint that will return Pokemon which are of a parameter type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b12cbf0cb9e78870f2df3c63d01105c/href">https://medium.com/media/7b12cbf0cb9e78870f2df3c63d01105c/href</a></iframe><p>“?contains” checks if a provided query element exists in the list associated with the field. To provide an example, if I wanted all the fire-type Pokemon, I would send a GET request to /pokemon/type/Fire .</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2FMO2GmcG%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2FMO2GmcG&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="659" frameborder="0" scrolling="no"><a href="https://medium.com/media/72d6b509851eac242182d35319faa4aa/href">https://medium.com/media/72d6b509851eac242182d35319faa4aa/href</a></iframe><p><em>There are 13 Pokemon returned from the above request.</em></p><p>This is a little overwhelming since this query will return all the fire-type Pokemon in our Base. Deta also provides us with the ability to limit the number of query results with <a href="https://docs.deta.sh/docs/base/sdk/#example-using-buffer-pages-1">buffer</a>. Let’s set the buffer arg in fetch to 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d072ad33bda076b15c42c60fac55a0a/href">https://medium.com/media/9d072ad33bda076b15c42c60fac55a0a/href</a></iframe><p>Now, we only get two records back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-BgZLjSFIdWVceL8tqY-Q.png" /><figcaption>Photo by Author</figcaption></figure><p>Finally, by changing the pages argument in fetch , it is possible to spread the result data over multiple pages.</p><h3>Conclusion</h3><p>My primary goal with this writing was to shed greater light on a database that you can set up and work on in the blink of an eye. It took hardly much time to create the project and based on the above examples, CRUD and Querying are as simple as they can get. For these reasons, Deta Base is perfect for proof of concepts, serverless applications, hackathons, and many more situations and projects that require simplicity and speed.</p><p><strong>Thank you for taking the time to read this blog! Below are some other cool blogs you might be interested in.</strong></p><h4>Further reading</h4><ul><li><a href="https://medium.com/javascript-in-plain-english/visualize-website-usage-with-a-react-dashboard-fb2b206ec0cc">Visualize Website Usage with a React Dashboard</a></li><li><a href="https://medium.com/javascript-in-plain-english/zero-to-hero-chrome-extensions-4060520daf59">Zero to Hero: Chrome Extensions</a></li><li><a href="https://medium.com/swlh/build-a-dynamic-portfolio-with-the-github-api-6d74081e5164">Build a Dynamic Portfolio With the Github API</a></li></ul><h4>Resources</h4><p><strong>Deta (Home):</strong></p><p><a href="https://www.deta.sh/">Deta - The cloud for makers and dreamers.</a></p><p><strong>Flask:</strong></p><p><a href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/">Flask-SQLAlchemy - Flask-SQLAlchemy Documentation (2.x)</a></p><p><strong>Deta SDK:</strong></p><p><a href="https://docs.deta.sh/docs/base/sdk">Deta Base SDK | Deta Docs</a></p><p><strong>Bulbapedia:</strong></p><p><a href="https://bulbapedia.bulbagarden.net/wiki/Main_Page">Bulbapedia, the community-driven Pokémon encyclopedia</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd9c97d96ad3" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/crunch-pokemon-data-with-deta-base-bd9c97d96ad3">Crunch Pokemon Data with Python and Deta Base</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Track Website Usage with PostgreSQL and Flask]]></title>
            <link>https://python.plainenglish.io/track-website-usage-with-postgresql-and-flask-53f583249911?source=rss-b162eedcaf8a------2</link>
            <guid isPermaLink="false">https://medium.com/p/53f583249911</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Ramki Pitchala]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 04:01:21 GMT</pubDate>
            <atom:updated>2021-02-03T06:59:52.515Z</atom:updated>
            <content:encoded><![CDATA[<h4>How many views are you getting on your website? Let’s build a tracker!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*gDPzksb7TD2IfVS0" /><figcaption>Photo by <a href="https://unsplash.com/@adeolueletu">Adeolu Eletu</a> on <a href="https://unsplash.com/photos/unRkg2jH1j0">Unsplash</a></figcaption></figure><p><em>This article is the prequel to </em><a href="https://ramapitchala.medium.com/visualize-website-usage-with-a-react-dashboard-fb2b206ec0cc"><em>Visualize Website Usage with a React Dashboard</em></a><em>. In this article, we build out a service to track and store usage. In </em><a href="https://ramapitchala.medium.com/visualize-website-usage-with-a-react-dashboard-fb2b206ec0cc"><em>Visualize Website Usage with a React Dashboard</em></a><em>, we build a dashboard to put the usage data in perspective.</em></p><h3>Introduction</h3><p>What is the most valuable resource in the modern era? Personally, I think that data triumphs in value over any other entity in the current world. In fact, data is the primary driver of decisions and actions in many lucrative industries of the present world.</p><p>To provide a bit of context, I created a personal <a href="https://ramki-pitch.web.app/">website/portfolio</a> to showcase my projects and experience. Over time, I became curious as to how many visitors viewed my website, how long they stayed, and how many times they viewed the site. Although my website is basic, I am still interested in this information. As a result, feeling inspired by the value of data, we will build a basic analytics tracking system using <a href="https://flask.palletsprojects.com/en/1.1.x/">Flask</a>, a Python web framework, and <a href="https://www.postgresql.org/">PostgreSQL</a>, a relational database.</p><h3>Agenda</h3><ul><li>Conceptual Idea</li><li>Setup</li><li>Building the Backend</li><li>Conclusion</li></ul><h3>Conceptual Idea</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*f52kAdeRh2_lMhFm" /><figcaption>Photo by <a href="https://unsplash.com/@juniorferreir_">Júnior Ferreira</a> on <a href="https://unsplash.com/photos/7esRPTt38nI">Unsplash</a></figcaption></figure><p>Let’s first consider the various attributes we will track.</p><h4>View</h4><p>Every time our website is loaded, that counts as a view. This is the standard unit we can use to measure how many times visitors are coming to our website.</p><h4>Read</h4><p>In many situations, visitors will open up a site and quickly close it if it doesn’t meet their expectations. For that reason, it is important to account for situations where a visitor stays on the site for some time. In the case that a visitor remains on the website for more than ten seconds, we will count that as a read.</p><h4>Unique Viewer</h4><p>Finally, it would also be interesting to note how many unique visitors are coming to our website.</p><p>We need to store the above statistics for each day independently. Here is an example of what the data can look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*xX26sc6TD8R_DgdkBCdU4w.png" /><figcaption>Photo by Author</figcaption></figure><p>We can track these attributes by exposing API endpoints the website can call. For example, let’s say that we have two endpoints, /view and /read. The /view endpoint, when called, can increment the number of views, and depending on if the request came from a new visitor, can increment the number of unique viewers for that day. Similarly, when the endpoint /read is requested, the endpoint handler can increment the number of reads for that day.</p><p>Let’s consider the above idea in the context of the website.</p><p>Right after the website is done loading, it can immediately call the /view endpoint to increment our views and unique viewers. We can use the IP address of the client request to uniquely identify viewers. Moreover, it can also schedule a function which calls the /read endpoint after ten seconds. In the case that the website is closed before the ten seconds, the function will never fire and the daily reads would not be incremented.</p><p>Here is the diagram depicting the above-mentioned events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*vkltjcj8r4ZSzG_KGjBqTQ.png" /><figcaption>Photo by Author</figcaption></figure><p>Now that we have a process of counting the views, reads, and unique viewers, let’s dive into how the endpoints will be hosted and where the data will be stored.</p><p>We will be using Flask to create the endpoints and PostgreSQL to store the views, reads, and unique viewers (You can use any web framework or database of your choice). We can manipulate our SQL database directly from our Flask app thanks to <a href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/">flask_sqlalchemy</a> (we will touch a bit more on this in the setup). For now, let’s dig into how our database schema will look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*I_kbRUE2T4th6ZCCrNqE6w.png" /><figcaption>Photo by Author</figcaption></figure><p>To begin, the field id of table day will simply be a date string of the following format: yyyy-mm-dd. It is the primary key for the day table and allows us to independently store the views and reads for each day. To elaborate, to track the reads and views for a given day, we will increment the reads and views fields when /read and /view requests come in. Finally, we can account for the number of unique visitors each day through the ip_view table. ip_view has 2 primary keys, ip , the IP address of the visitor, and date_id, a date string with a foreign key referencing the id attribute on the day table. We can join both tables together based on the date_id foreign key to get the number of unique visitors per day.</p><h3>Setup</h3><p>Before we dive into implementing the above ideas, let’s ensure that we have the correct technologies installed and setup.</p><h4><strong>Flask</strong></h4><p>First, let’s run the pip install command to install the following Python packages: flask, flask_sqlalchemy, andpyscopg2 .</p><pre>pip install flask flask_sqlalchemy psycopg2</pre><p>The flask_sqlalchemy package enables us to use <a href="https://docs.sqlalchemy.org/en/14/">sqlalchemy</a>, an object-relational mapper (ORM), in our app. As a result, interacting with PostgreSQL from our app will be seamless. During the coding section, you will see how easy it is to insert and update rows.</p><p>The <a href="https://www.psycopg.org/docs/">psycopg2</a> package is a PostgreSQL adapter for Python and is required for flask_sqlalchemy to work. It is a low-level package, and we won’t directly invoke it in this article.</p><h4>PostgreSQL</h4><p>To install and configure PostgreSQL, I recommend checking out the following videos. We will continue once you are back!</p><p>Windows Edition (Watch until the 7-minute mark):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBLH3s5eTL4Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBLH3s5eTL4Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBLH3s5eTL4Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/567425eec33e9de4b27c36e556ca2745/href">https://medium.com/media/567425eec33e9de4b27c36e556ca2745/href</a></iframe><p>Mac Edition:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEZAa0LSxPPU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEZAa0LSxPPU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEZAa0LSxPPU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/77285e9e30705f2cafcc33a49a44bb14/href">https://medium.com/media/77285e9e30705f2cafcc33a49a44bb14/href</a></iframe><p>Now that PostgreSQL is installed, let’s create a database to store our analytical data via the PSQL shell.</p><pre>postgres=# CREATE DATABASE analytics;</pre><p>After the database is created, we have to first connect to it.</p><pre>postgres=# \c analytics</pre><p>Let’s work on making the tables. Let’s start with the day table.</p><pre>analytics=# CREATE TABLE day(id DATE PRIMARY KEY, views INT, reads INT);</pre><p>Let’s end with the ip_view table.</p><pre>analytics=# CREATE TABLE ip_view(ip VARCHAR(20), date_id DATE, PRIMARY KEY(ip, date_id), FOREIGN KEY(date_id) REFERENCES day(id));</pre><p>With that, our database setup is now complete. We can now build out the functionality.</p><h3>Building the Backend</h3><p>Here is the folder structure for the project:</p><pre>- model/    <br>    - day.py    <br>    - ip_view.py<br>- config.py<br>- app.py<br>- main.py</pre><h4>Config</h4><p>Open up the config.py file first. We will place our sensitive details, such as our database connection URI, in this file. Here is the format for the PostgreSQL connection URI.</p><pre>&quot;postgres://USER:PASSWORD@HOST:PORT/DB_NAME&quot;</pre><p>For instance, if the user was “postgres”, the password for that user was “password12”, the host was “localhost”, the port was 5432, and the name of the database was “analytics”. Here is how the URI string would look.</p><pre>&quot;postgres://postgres:password12@localhost:5432/analytics&quot;</pre><p>Let’s put this URI string into config.py .</p><pre>DATABASE_URI=&quot;postgres://postgres:password12@localhost:5432/analytics&quot;</pre><p>If you are going to push this project to version control, make sure to git ignore config.py in case you are connecting to a remote PostgreSQL instance.</p><h4>App</h4><p>With config.py taken care of, we now need to create a Flask app in app.py .</p><pre>from flask import Flask<br>from flask_sqlalchemy import SQLAlchemy<br>from config import DATABASE_URI</pre><pre>app = Flask(__name__)<br>app.config[&#39;SQLALCHEMY_DATABASE_URI&#39;] = DATABASE_URI<br>db = SQLAlchemy(app)</pre><p>To summarize, we are importing DATABASE_URI , our PostgreSQL connection URI, and updating our app config to include it. From there, we can create db , and it is through this variable we can interact with our database. Let’s now create our models.</p><h4>Models</h4><p>One of the core benefits that ORMs like SQLAlchemy provide is the ability to manipulate and access the database through objected-oriented notation. Models are python objects that directly map to the tables in our database, and we can use these models to directly insert, delete, update and query our tables.</p><p>Let’s move into the model folder and create a model for the day table in day.py .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1ec7f1983e882d2a80b68f4867c795c/href">https://medium.com/media/d1ec7f1983e882d2a80b68f4867c795c/href</a></iframe><p>To put it briefly, we are essentially defining our table as a Python object. The fields of the Day object are the same as the columns of the day table. We also specify the types of the fields and indicate which field in the table is the primary key.</p><p>Let’s do the same in the ip_view.py file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b07528800e0feed793fc73cdd263bdd6/href">https://medium.com/media/b07528800e0feed793fc73cdd263bdd6/href</a></iframe><p>Notice how we define the date_id field. Since date_id is a foreign key, we must specify what table and field it refers to. To create the reference, we just have to import the Day class and wrap its id attribute with the ForeignKey constructor. It&#39;s all done via objects.</p><h4>Endpoints</h4><p>With the models finished, let’s head over to main.py. We will put our endpoints in this file.</p><p>Start by importing the following packages into main.py</p><pre>from app import app, db<br>from flask import request<br>from model.day import Day<br>from model.ip_view import IpView<br>from sqlalchemy.sql.functions import count<br>import datetime</pre><p>Let’s first create a function to get the current date in the yyyy-mm-dd format.</p><pre>def get_current_day():<br>    today = datetime.date.today()<br>    return today.strftime(&quot;%Y-%m-%d&quot;)</pre><p>We will create three endpoints: /view, /read, and /analytics . /analytics will take in a start and end date and output the views, reads, and unique viewers for each day and the total views, total reads and total unique viewers in the timespan.</p><p>Here is the code for the /view endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54a30940a40bbf304b2be033fab77f98/href">https://medium.com/media/54a30940a40bbf304b2be033fab77f98/href</a></iframe><p>Let’s break this down.</p><p>Initially, we are getting the date string for the current day and querying if the current day exists in our database. In the case that it already exists, we can update it by incrementing the views field of current_day on line 11. If the contrary is true, then we create a new Day object and insert it into the day table on lines 14–15. Then, from lines 17–20, we check whether a visitor with the same IP address already viewed the website on the current day. We will only insert a new IpView if it is the visitor’s first time for the day. Finally, we commit all our changes to the database.</p><p>Notice how we never write any raw SQL, but simply query, insert and update through the objects themselves.</p><p>Let’s now add the /read endpoint. It should be much simpler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa2d63705dff2e2a210dfd32c09acf99/href">https://medium.com/media/fa2d63705dff2e2a210dfd32c09acf99/href</a></iframe><p>The code is quite similar to the /view endpoint. We first try to assert that the current day already exists in the database. In the case it exists, we can increment the reads field and commit these changes to the database.</p><p>We are on our final endpoint: /analytics. Here is an example of how we call the endpoint and what it is expected to return:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gbckPd60vvxMbkd5.png" /><figcaption>Photo by Author</figcaption></figure><p>Here is the code for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffa59b6492742a3b210879fd598e55d0/href">https://medium.com/media/ffa59b6492742a3b210879fd598e55d0/href</a></iframe><p>We first retrieve the start and end date from the request parameters. Then, we join the day table with the ip_view table. After that, we filter to find the valid days, group the entries with the same id to get a unique viewer count and sort the days from earliest to latest. That is all there is!</p><p>At the end of main.py, add the following:</p><pre>if __name__ == &quot;__main__&quot;:<br>   app.run()</pre><p>With this, we can run our application and listen to the website’s incoming requests. If you made your website programmatically, then you can make requests to the endpoints we have created to track the views, reads, and unique viewers.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1xoKRWhU72sqM4OOQK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fsad-rupauls-drag-race-rupaul-1xoKRWhU72sqM4OOQK&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2F1xoKRWhU72sqM4OOQK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="391" frameborder="0" scrolling="no"><a href="https://medium.com/media/dffcc2893ec0cd71f74001a1ed4abe0b/href">https://medium.com/media/dffcc2893ec0cd71f74001a1ed4abe0b/href</a></iframe><p><strong>That was a journey!</strong></p><h3>Conclusion</h3><p>In this article, we developed an API to track website usage with Flask and PostgreSQL. We are now able to collect information on the number of views, reads, and unique viewers the site gets each day. However, our job is not done. In the next article, we will create a dashboard with React to visualize the usage. Check it out: <a href="https://ramapitchala.medium.com/visualize-website-usage-with-a-react-dashboard-fb2b206ec0cc"><em>Visualize Website Usage with a React Dashboard</em></a><em>.</em></p><p><strong>Regardless, thank you so much for sticking around!</strong></p><h4>Resources</h4><p><strong>PostgreSQL:</strong></p><p><a href="https://www.postgresql.org/">PostgreSQL</a></p><p><strong>Flask:</strong></p><p><a href="https://flask.palletsprojects.com/en/1.1.x/">Welcome to Flask - Flask Documentation (2.0.x)</a></p><p><strong>flask_sqlalchemy:</strong></p><p><a href="https://flask-sqlalchemy.palletsprojects.com/en/2.x/">Flask-SQLAlchemy - Flask-SQLAlchemy Documentation (2.x)</a></p><p><strong>sqlalchemy:</strong></p><p><a href="https://docs.sqlalchemy.org/en/14/">SQLAlchemy 1.4 Documentation</a></p><p><strong>pyscopg2:</strong></p><p><a href="https://www.psycopg.org/docs/">Psycopg 2.9.5 documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53f583249911" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/track-website-usage-with-postgresql-and-flask-53f583249911">Track Website Usage with PostgreSQL and Flask</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>