<?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 Ranvir Singh on Medium]]></title>
        <description><![CDATA[Stories by Ranvir Singh on Medium]]></description>
        <link>https://medium.com/@ranvirsingh_75067?source=rss-ceb74e8587f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*IrmDZlw4fGfj3BmW.</url>
            <title>Stories by Ranvir Singh on Medium</title>
            <link>https://medium.com/@ranvirsingh_75067?source=rss-ceb74e8587f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 12:54:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ranvirsingh_75067/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[Achieving asynchronous behavior using asyncio in Python]]></title>
            <link>https://levelup.gitconnected.com/achieving-asynchronous-behavior-using-asyncio-in-python-e09153defbd9?source=rss-ceb74e8587f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e09153defbd9</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Ranvir Singh]]></dc:creator>
            <pubDate>Mon, 14 Sep 2020 03:52:46 GMT</pubDate>
            <atom:updated>2020-09-14T16:26:10.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wjojNkhTHSa-wREU.png" /></figure><p>A lot has changed since I last published my post on handling long-running async tasks in Python using celery. Last time we used it to run a few async tasks to fetch data from some service <a href="https://ranvir.xyz/blog/using-celery-to-run-long-running-task-asynchronously">which took around 1–5 minutes</a>.</p><p>Although I will still use celery for these types of long-running tasks, there is a subset of tasks that are better handled inside the execution thread itself. Today we will discuss a way of handling such operations.</p><p>To the people who know me, I switched to a new role which allowed me to write Node.js over a year ago and I have been working on it since then. During my time working and building APIs using it, I have started falling for the way in which Node handles <a href="https://ranvir.xyz/blog/basic-introduction-to-node.js-async-await">Async behavior and long-running tasks</a>.</p><p>The idea is simple, if the task is waiting for some IO, we can run some other task in the mean-time. Only the part that needs it, will wait for it.</p><p>I wanted to use the same concept in Python.</p><p>Fortunately, in the Python version 3.4, they have introduced asyncio for the same purpose. In this post, we are going to talk a little about it and try to understand its importance.</p><p>By the end of the post, you will be able to understand the importance of async functions and will be able to start using them into your codebase.</p><h3>Prerequisite</h3><p>I am using Python 3.8 for this tutorial and you might want to use the same to run and try out examples. You can try them <a href="https://www.python.org/shell/">online as well</a>.</p><h3>Basic async function in Python</h3><p>This is how we write a basic async function in Python.</p><pre>import asyncio</pre><pre>async def func1(a):<br>    print(f&quot;started func 1: {a + 1}&quot;)<br>    await asyncio.sleep(1)<br>    return a + 1</pre><pre>asyncio.run(func1(1))</pre><p><strong>Response</strong></p><pre>started func 1: 2<br>2</pre><p>You have to start by importing the asyncio module. Async functions are defined just like a normal function, you just have to add the keyword, async. If you want to wait for the execution of some <a href="https://docs.python.org/3/library/asyncio-task.html#coroutines">coroutine</a>, you have to use the keyword, await. Finally, you can run the function using asyncio.run method.</p><blockquote><em>Anytime you use the await keyword inside the async function, the thread will not move forward until we get a response from the called function.</em></blockquote><p>This simple implementation will not help you understand the advantage of using async functions. In the next section, we will talk about the time taken for the execution and there you will really start to see the difference.</p><h3>Time taken for the full execution</h3><p>To understand the benefits of using async functions, we will compare the time taken to run the same code in async and sync behavior.</p><p>Let’s first write the async code.</p><pre>import asyncio<br>import time<br>start = time.time()</pre><pre>async def async_sleep():<br>    await asyncio.sleep(1)</pre><pre>async def func1(a):<br>    print(f&quot;started func 1: {a + 1}&quot;)<br>    await async_sleep()<br>    return a + 1</pre><pre>async def func2(a):<br>    print(f&quot;started func 2: {a + 2}&quot;)<br>    await async_sleep()<br>    return a + 2</pre><pre>async def func3(a):<br>    print(f&quot;started func 3: {a + 3}&quot;)<br>    await async_sleep()<br>    return a + 3</pre><pre>async def func4(a):<br>    print(f&quot;started func 4: {a + 4}&quot;)<br>    await async_sleep()<br>    return a + 4</pre><pre>async def main():<br>    tasks = (func1(1), func2(1), func3(1), func4(1))<br>    await asyncio.gather(*tasks)<br>    print(f&quot;Completed after: {time.time() - start}&quot;)</pre><pre>asyncio.run(main())</pre><p>I have defined 4 different functions doing almost the same thing. Let’s assume there is a long-running function called async_sleep which is doing some IO operation. For example: Fetching data from the database.</p><blockquote><em>asyncio.gather() is used to run the tasks passed to it concurrently.</em></blockquote><p>The response after running this code is as follows.</p><pre>started func 1: 2<br>started func 2: 3<br>started func 3: 4<br>started func 4: 5<br>Completed after: 1.1852593421936035</pre><p>The function completes the execution somewhere between 1–2 seconds for every execution. (Ran it 5 times to check).</p><p>Now let’s try to run the sync version of the same code.</p><pre>import time<br>start = time.time()</pre><pre>def sync_sleep():<br>    time.sleep(1)</pre><pre>def func1(a):<br>    print(f&quot;started func 1: {a + 1}&quot;)<br>    sync_sleep()<br>    return a + 1</pre><pre>def func2(a):<br>    print(f&quot;started func 2: {a + 2}&quot;)<br>    sync_sleep()<br>    return a + 2</pre><pre>def func3(a):<br>    print(f&quot;started func 3: {a + 3}&quot;)<br>    sync_sleep()<br>    return a + 3</pre><pre>def func4(a):<br>    print(f&quot;started func 4: {a + 4}&quot;)<br>    sync_sleep()<br>    return a + 4</pre><pre>def main():<br>    func1(1)<br>    func2(1)<br>    func3(1)<br>    func4(1)<br>    print(f&quot;Completed after: {time.time() - start}&quot;)</pre><pre>main()</pre><p>The response that we got after executing this was:</p><pre>started func 1: 2<br>started func 2: 3<br>started func 3: 4<br>started func 4: 5<br>Completed after: 4.168870687484741</pre><p>This saved us ~3 seconds for executing 4 functions. Now if we wanted to run 10000 such functions, we would save ourselves ~2000 seconds/ i.e. 35-40 minutes.</p><p>That’s awesome, right.</p><p>Even if we are just running 2–3 such functions in each iteration these small savings can be very important to provide better user experience to your customers.</p><p>Now that we have understood the advantage of using async functions, we must know a few more things about it.</p><h3>Order of execution for async functions</h3><p>We should understand that while running the functions in async mode, we don’t really know about the order in which functions are executed. Let’s understand the concept with an example.</p><p>The functions will return as soon as the execution is completed. We can mock the different execution time by sleeping for a random time between 0 and 1 using, random.randint(0, 10) * 0.1.</p><p>Here is the full code.</p><pre>import asyncio<br>import time<br>import random<br>start = time.time()</pre><pre>def random_sleep_time():<br>    return random.randint(0, 10) * 0.1</pre><pre>async def async_sleep():<br>    await asyncio.sleep(random_sleep_time())</pre><pre>async def func1(a):<br>    await async_sleep()<br>    print(f&quot;completed func {a}: {a + 1}&quot;)<br>    return a + 1</pre><pre>async def main():<br>    tasks = [func1(a) for a in range(0, 5)]<br>    await asyncio.gather(*tasks)<br>    print(f&quot;Completed after: {time.time() - start}&quot;)</pre><pre>asyncio.run(main())</pre><p>The response to the following code is,</p><pre>completed func 0: 1<br>completed func 3: 4<br>completed func 1: 2<br>completed func 2: 3<br>completed func 4: 5<br>Completed after: 0.9764895439147949</pre><h3>Practical Usage</h3><p>After the release of Python 3.8, which moved the asyncio.run() method to stable API, you can start using it without any problem.</p><p>The only issue with moving from a synchronous approach to an async one, is to change the way of thinking about the problems. You have to change the way you think about every little detail. Once you reach that point of thinking in terms of async functions, believe me, you will love it.</p><h3>How does it work under the hood?</h3><p>Let’s check the type of the async function.</p><pre>type(main())</pre><pre># &lt;class &#39;coroutine&#39;&gt;</pre><p>So, the async function is of type coroutine.</p><p>This <a href="https://www.geeksforgeeks.org/coroutine-in-python/">GeeksForGeeks article</a> does a very good job of explaining coroutines.</p><p>To sum up what they wrote in the post, <strong>subroutines</strong> are the set of instructions that have one entry point and are executed serially.</p><p>On the other hand, <strong>Coroutines</strong> can suspend or give away the control to other Coroutines, allowing multiple tasks to run at the same time.</p><p>Python uses this concept to allow async behavior.</p><h3>Handling timeout in async functions</h3><p>It is necessary to have a timeout for waiting for the task to get completed. We are not supposed to wait forever for it to complete. asyncio also provided the ability to add a timeout to the async function so that you can skip the execution before its completion.</p><p>A practical application of this can be a case when you are calling a third party API in your application and the third party itself is down. In that case, you don’t want to wait for a long time.</p><p>You can use the timeout method to solve your problem.</p><p>See the code for example:</p><pre>async def async_sleep():<br>    await asyncio.sleep(2)<br>    print(&#39;Execution completed&#39;)</pre><pre>async def main():<br>    try:<br>        await asyncio.wait_for(async_sleep(), timeout=1.0)<br>    except asyncio.TimeoutError:<br>        print(&#39;Timeout error&#39;)</pre><pre>asyncio.run(main())</pre><p>The async function will raise TimeoutError if the coroutine doesn&#39;t return before the given timeout is passed. Response after executing the above code is</p><pre>Timeout error</pre><p>There are other awesome methods in the asyncio module. You can check them at <a href="https://docs.python.org/3/library/asyncio-task.html">python&#39;s official website</a>.</p><h3>Conclusion</h3><p>If you want to provide a better and faster experience to your users, you can start using the asyncio module in your application. This will definitely help you find cases in which you can reduce the execution time of your API or whatever else that you are doing.</p><p>Just forcing yourself to write in this way for a few months can yield big returns in the future.</p><p><em>Originally published at </em><a href="https://ranvir.xyz/blog/asynchronous-behaviour-using-asyncio-in-python/"><em>https://ranvir.xyz</em></a><em> on August 30, 2020.</em></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! <a href="https://www.youtube.com/channel/UC3v9kBR_ab4UHXXdknz8Fbg?sub_confirmation=1"><strong>Subscribe to our YouTube channel</strong></a> or join the <a href="https://skilled.dev/"><strong>Skilled.dev coding interview course</strong></a>.</p><p><a href="https://skilled.dev/">Coding Interview Questions + Land Your Dev Job | Skilled.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e09153defbd9" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/achieving-asynchronous-behavior-using-asyncio-in-python-e09153defbd9">Achieving asynchronous behavior using asyncio in Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to KNN | K-nearest neighbor algorithm using Examples]]></title>
            <link>https://medium.com/@ranvirsingh_75067/introduction-to-knn-k-nearest-neighbor-algorithm-using-examples-b6d4de11a281?source=rss-ceb74e8587f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6d4de11a281</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <dc:creator><![CDATA[Ranvir Singh]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 18:30:00 GMT</pubDate>
            <atom:updated>2020-04-06T20:36:00.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w9CpL1nPp6jFHXBn.png" /></figure><p>This was originally posted on my blog as <a href="https://ranvir.xyz/blog/k-nearest-neighbor-algorithm-using-sklearn-distance-metric/">KNN Algorithm</a>.</p><p>KNN also known as K-nearest neighbor is a <a href="https://ranvir.xyz/blog/how-to-evaluate-your-machine-learning-model-like-a-pro-metrics/#supervised-learning-and-classification-problems">supervised and pattern classification learning algorithm</a> which helps us to find which class the new input(test value) belongs to when k nearest neighbors are chosen and distance is calculated between them.</p><blockquote><em>It attempts to estimate the conditional distribution of </em><em>Y given </em><em>X, and classify a given observation(test value) to the class with highest estimated probability.</em></blockquote><p>It first identifies the k points in the training data that are closest to the test value and calculates the distance between all those categories. The test value will belong to the category whose distance is the least.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*Dik-XeUX7LKLWaql.png" /></figure><h3>Probability of classification of test value in KNN</h3><p>It calculates the probability of test value to be in class j using this function</p><p>See the equation in the <a href="https://ranvir.xyz/blog/k-nearest-neighbor-algorithm-using-sklearn-distance-metric/">main article</a>.</p><h3>Ways to calculate the distance in KNN</h3><p>The distance can be calculated using different ways which include these methods,</p><ul><li>Euclidean Method</li><li>Manhattan Method</li><li>Minkowski Method</li><li>etc…</li></ul><p>For more information on distance metrics which can be used, please read <a href="https://www.saedsayad.com/k_nearest_neighbors.htm">this post on KNN</a>. You can use any method from the list by passing metric parameter to the KNN object. Here is an answer on <a href="https://stackoverflow.com/questions/21052509/sklearn-knn-usage-with-a-user-defined-metric">Stack Overflow which will help</a>. You can even use some random distance metric. Also <a href="https://stackoverflow.com/questions/34408027/how-to-allow-sklearn-k-nearest-neighbors-to-take-custom-distance-metric">read this answer as well</a> if you want to use your own method for distance calculation.</p><h3>The process of KNN with Example</h3><p>Let’s consider that we have a dataset containing heights and weights of dogs and horses marked properly. We will create a plot using weight and height of all the entries. Now whenever a new entry comes in from the test dataset, we will choose a value of k. For the sake of this example, let&#39;s assume that we choose 4 as the value of k. We will find the distance of the nearest four values and the one having the least distance will have more probability and is assumed as the winner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*nwGM-UBYi6EhlyS3.png" /></figure><h3>KneighborsClassifier: KNN Python Example</h3><p>GitHub Repo: <a href="https://github.com/singh1114/ml/blob/master/datascience/Machine%20learning/knn/knn.ipynb">KNN GitHub Repo</a> Data source used: <a href="https://github.com/singh1114/ml/blob/master/datascience/Machine%20learning/knn/KNN_Project_Data">GitHub of Data Source</a> In K-nearest neighbors algorithm most of the time you don’t really know about the meaning of the input parameters or the classification classes available. In case of interviews, this is done to hide the real customer data from the potential employee.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8TgeRE6JwXXSabvm.png" /></figure><p>The head of the data clearly says that we have a few variables and a target class that contain different classes for given parameters.</p><h3>Why normalize/ standardize the variables for KNN</h3><p>As we can already see that the data in the data frame is not standardized, if we don’t normalize the data the outcome will be fairly different and we won’t be able to get the correct results. This happens because some feature has a good amount of deviation in them (values range from 1–1000). This will lead to a very bad plot producing a lot of defects in the model. For more info on normalization, check this answer on <a href="https://stats.stackexchange.com/a/287439">stack exchange</a>. Sklearn provides a very simple way to standardize your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*267WDOmYYM7YlRwD.png" /></figure><h3>Test/Train split using sklearn</h3><p>We can simply <a href="https://ranvir.xyz/blog/how-to-evaluate-your-machine-learning-model-like-a-pro-metrics/#test-train-split-using-sklearn">split the data using sklearn</a>.</p><h3>Using KNN and finding an optimal k value</h3><p>Choosing a good value of k can be a daunting task. We are going to automate this task using Python. We were able to find a good value of k which can minimize the error rate in the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RQcpI1lqjzTp-4p_.png" /></figure><p>Seeing the graph, we can see that k=30 gives a very optimal value of error rate.</p><h3>Evaluating the KNN model</h3><p>Read the following post to learn more about evaluating a machine learning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*IqSNv9Je_Tj4FnA4.png" /></figure><h3>Benefits of using KNN algorithm</h3><ul><li>KNN algorithm is widely used for different kinds of learnings because of its uncomplicated and easy to apply nature.</li><li>There are only two metrics to provide in the algorithm. value of k and distance metric.</li><li>Work with any number of classes not just binary classifiers.</li><li>It is fairly easy to add new data to algorithm.</li></ul><h3>Disadvantages of KNN algorithm</h3><ul><li>The cost of predicting the k nearest neighbors is very high.</li><li>Doesn’t work as expected when working with a big number of features/parameters.</li><li>Hard to work with categorical features.</li></ul><p>A good read that <a href="https://jakevdp.github.io/blog/2013/04/29/benchmarking-nearest-neighbor-searches-in-python/">benchmarks various options present in sklearn for Knn</a> Hope you liked the post. Feel free to share any issues or any questions that you have in the comments below.</p><p><em>Originally published at </em><a href="https://ranvir.xyz/blog/k-nearest-neighbor-algorithm-using-sklearn-distance-metric/"><em>https://ranvir.xyz</em></a><em> on March 22, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6d4de11a281" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Call a function periodically in Javascript (with memory leak analysis)]]></title>
            <link>https://medium.com/@ranvirsingh_75067/call-a-function-periodically-in-javascript-with-memory-leak-analysis-d4ac8bee4224?source=rss-ceb74e8587f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4ac8bee4224</guid>
            <category><![CDATA[analysis]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ranvir Singh]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 19:34:00 GMT</pubDate>
            <atom:updated>2020-01-04T21:17:56.898Z</atom:updated>
            <content:encoded><![CDATA[<p>This post was originally posted on <a href="https://ranvir.xyz/blog/running-a-function-after-quick-intervals-in-vanilla-javascript/">my blog.</a></p><p>In a production system, we run a lot of scripts periodically either to sync data from some third-party source or spit data to some source. Although there are a lot of solutions to achieve such periodic behavior, in this post we are going to discuss one such solution using vanilla JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gOdE1DF-JJj_h9_T.jpg" /></figure><h3>Use cases</h3><ul><li>Taking backups of the database.</li></ul><p>Taking a backup of the database can be done once or twice a day depending upon the use case.</p><p>If you get a lot of users you can take this backup multiple times a day.</p><p><strong>AWS</strong> takes automatic backups so you don’t have to worry about it.</p><ul><li>Sending newsletters to your customers.</li></ul><p>Sending newsletters to customers can also be one of the use cases of running things periodically.</p><h3>Possible Solutions</h3><h3>Crontab</h3><p>Most of the organizations tend to use crontab for handling any such requests for running periodic tasks.</p><p>Each and every language has it’s own implementation of handling periodic tasks.</p><h3>A periodic task in Vanilla JavaScript</h3><p>Let’s write a simple function that can log the current time after every minute. Save this code in the file time_tell.js.</p><pre>const tellTime = async function () {<br>    console.log(new Date());<br>}<br><br>const minutes = 0.5;<br>const interval = minutes * 60 * 1000;<br><br>setInterval(function() {<br>    // catch all the errors.<br>    tellTime().catch(console.log);<br>}, interval);</pre><p>First of all, we declare an async function tellTime which logs the time whenever it is called.</p><p>It is important to declare this function async so that we can run .then or .catch after this function.</p><p>setInterval is the inbuilt function that can run any statements after every given interval.</p><p>It takes two arguments, first is the definition of the function being run itself and next is the interval after which we want to run the function again( <strong>In milliseconds</strong>).</p><p>In this example, we have set the interval to one minute. Run the file using the command, node time_tell.js Here is how the output is going to look like,</p><pre>2019-11-18T18:40:27.286Z<br>2019-11-18T18:40:57.293Z<br>...</pre><p>Although this is a pretty straight forward example you can extend this to do anything that you want.</p><h3>Update regarding Memory leak</h3><p>When I posted the same on <a href="https://dev.to/singh1114/run-a-function-periodically-in-vanilla-javascript-8gk">dev.to</a>, some of the programmers reached out in the comment section asking about the potential memory leak in the program.</p><p>While building the program, I was not thinking about the memory leak because I was going to run it for a few hours only for a particular use case.</p><p>I searched online to find a solution for finding ways to discover any memory leaks in the program. <a href="https://www.nearform.com/blog/how-to-self-detect-a-memory-leak-in-node/">This nearform article</a> was very helpful in finding more about it.</p><p>The article suggested three ways to find out the memory leaks. I have only tried two of them. Let me know if you have any other way of finding it out as well.</p><h3>Node’s inspect flag</h3><p>Node’s --inpect flag attaches a debugger with the program and allows you to run all types of analysis on the program running in the chrome. Try running the following command.</p><p>node --inspect time_tell.js This will open a new tab in the chrome with the attached debugger,</p><pre>Debugger listening on ws://127.0.0.1:9229/2ee7271d-04e2-4711-9df5-99777bdb7ca4<br>For help see https://nodejs.org/en/docs/inspector<br><br>Debugger attached.</pre><p>Go to the memory tab of the devtool in the chrome and click on the take snapshot button. You will be able to see the memory being used when you take the snapshot.</p><p>Take another snapshot after 10 seconds of the initial snapshot. If the memory size is increasing you will know that there is a function in your code which is leaking memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*75f06rhdqTT1YUT7.jpg" /></figure><p>Since the memory used in the given program was consistent, I believe there was no memory leak in the program.</p><h3>Using memwatch-next module</h3><p>The memwatch-next module is used to find the memory leaks in a program.</p><p>Let&#39;s install it using, npm install memwatch-next Now change the program accordingly,</p><pre>const memwatch = require(&#39;memwatch-next&#39;);<br><br>const tellTime = async function () {<br>    console.log(new Date());<br>}<br><br>const minutes = 0.01;<br>const interval = minutes * 60 * 1000;<br><br>setInterval(function() {<br>    // catch all the errors.<br>    tellTime().catch(console.log);<br>}, interval);<br><br>memwatch.on(&#39;leak&#39;, (info) =&gt; {<br>  console.error(&#39;Memory leak detected:\n&#39;, info);<br>});</pre><p>Run the program simply, if you see the message memory leak being printed, you will know that there is some memory leak.</p><p>Hopefully, this will help you to find memory leaks in your program in the future as well.</p><p>Thanks for stopping by and do consider <a href="https://ranvir.xyz/blog/subscribe">subscribing</a> to the weekly newsletter.</p><p><em>Originally published at </em><a href="https://ranvir.xyz/blog/running-a-function-after-quick-intervals-in-vanilla-javascript/"><em>https://ranvir.xyz</em></a><em> on November 17, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4ac8bee4224" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How contributing to open-source can improve your programming skills]]></title>
            <link>https://medium.com/@ranvirsingh_75067/how-contributing-to-open-source-can-improve-your-programming-skills-c49cd29520c0?source=rss-ceb74e8587f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c49cd29520c0</guid>
            <category><![CDATA[gsoc]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[advice]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Ranvir Singh]]></dc:creator>
            <pubDate>Sat, 09 Nov 2019 22:08:00 GMT</pubDate>
            <atom:updated>2020-01-09T12:32:26.549Z</atom:updated>
            <content:encoded><![CDATA[<p>Open source is one of the best ways to get started with the real-world experience of the programming world and learning quickly. Also, open-source organizations are very keen and welcoming to new contributors to their platforms.</p><p>Lately, I have heard a lot of people saying that contributing to open-source projects is very difficult. So, I decided to come up with this post just to break the myth.</p><p>I know it can be hard at first but believe me, there are far harder things in the programming world than starting to contribute in the open-source.</p><p>In this post, I am going to share the motivation and plan to write your first patch for the open-source organization that you love to use in your personal time.</p><h3>Why should you contribute to open source?</h3><p>I have been doing open source for quite some time now( Going on and off). My first interaction with the open-source was back in 2016–17 when I was writing my first proposal for Google Summer of code-2017.</p><p>I was trying a lot of organizations back then. I started out with the chat-based organization whose name I don’t remember now.</p><p>They were writing a chat-based client using XMPP protocol and we wanted to implement this chatting system in our college so that everyone in the college can chat with one another using the roll numbers.</p><p>Although I was able to know the process of writing the code I don’t think it ever got merged with the main code. What I learned in there was how to read and navigate through the large codebase quickly.</p><p>I tried a few others and finally, I ended up spending my summer writing code for an organization called <a href="https://www.nexb.com/">AboutCode</a>.</p><p>You can read about the experience <a href="https://singh1114.github.io/blog/gsoc_2017/">here.</a></p><p>Long story short, I know how to start off and write pull requests that organizations want to merge to there main code.</p><p>Before starting that let’s discuss why we would want to do any open-source development at all.</p><h3>Learning to build an end to end solutions.</h3><p>Well, the first and foremost advantage of doing open-source is that you learn different things.</p><p>When you are doing open-source you have to complete the PRs which involve writing <em>code</em>, <em>tests</em> and <em>documentation</em> for the feature that you are building.</p><p>Sometimes you have to become the tester to test out the feature that other build to find out bugs and find mistakes to fix.</p><p>Mostly you will have to architect your own solution for the problems that you are solving as well.</p><h3>Learning how to communicate properly with the team</h3><p>Open-source involves communicating with all the people in the organizations in a public channel. This will help you a lot about how to communicate your concerns better.</p><p>How to ask questions and what questions to ask is very important to learn.</p><p>This skill will help you throughout your life.</p><h3>Getting recommended and increase visibility</h3><p>As the name suggests, your code is going to stay there for a long time to come and people will judge you with the code that you have written for these organizations.</p><p>Since most of the organizations have a high standard for the type of code they merge to the repository, you will be rated highly among your peers for participating in some open-source organization.</p><h3>Good for your career</h3><p>Doesn’t matter what you want to do after the open-source gig is over. Maybe you want to do open-source throughout your life, starting out with an organization will always be good for you.</p><p>Generally, open-source organizations tend to recommend the org participators which end up helping you in your interview with some big company.</p><h3>Sense of pride behind building something</h3><p>You also get a sense of pride while you build something that people use.</p><p>You also get good feedback from the users who directly use the feature that you build.</p><p>Those are all the reasons why one should be doing open-source as a project over the holidays or in their free time.</p><p><strong>Note:</strong> I am sure I must have missed something, do let me know about your motivation behind doing open-source.</p><h3>How to start contributing to the open-source</h3><p>Now that we have talked about the reasons why one should do open-source development, let’s talk a bit about how you start with that.</p><h3>Choose the organization</h3><p>Choosing an organization is very important. Always try to choose the organizations whose product you might have used in the past.</p><p>This helps you to build a sense of how the product should work.</p><p>Otherwise, you can find the organization whose tech stack involves something that you know.</p><p>Just go to the GitHub search page and find out the organization with the programming languages or any other thing that you want to learn about.</p><h3>Join all communication channels</h3><p>The next step is to figure out all the communication channels which the organization uses and join all of them.</p><p>Introduce yourself as quickly as possible. Communicate your intentions of joining early. If you are there to participate in GSoC, best to tell them right from the start that you are doing it for the reason.</p><p>Sometimes, they are thinking of not participating in the GSoC for the next season and it’s always good to know earlier rather regretting your decision later.</p><h3>Setup the project</h3><p>Quickly set up the project on local following the instruction from the organizers or READMEs and let them know if READMEs are wrong anywhere.</p><p>Sometimes, people figure out something wrong in the READMEs and its a great point to start and write a patch for them.</p><h3>Figure out the good-first issues to start with</h3><p>Most organizations mark easy issues as good-first issues. You can pick any one of those issues and start solving them.</p><p>Just remember to tell the organizers that you working on that issue so that no one else picks it up at the same time.</p><h3>Just start</h3><p>My final and most important recommendation is to just start. Get up and pick up your organization and start building things that you love and make an impact.</p><p>Thanks, guys for coming this long and reading through the post. Please leave your valuable comments down below and share this post with your peers and let them know that it exists.</p><p>Follow me on <a href="https://twitter.com/ranvirsingh1114">twitter</a> and <a href="https://dev.to/singh1114">dev.to</a> for more such articles.</p><p><em>Originally published at </em><a href="https://ranvir.xyz/blog/how-to-contribute-to-open-source-and-land-a-better-job/"><em>https://ranvir.xyz</em></a><em> on November 9, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c49cd29520c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration testing of APIs in Spring-Boot( Java) with Junit | For Beginners]]></title>
            <link>https://medium.com/@ranvirsingh_75067/integration-testing-of-apis-in-spring-boot-java-with-junit-for-beginners-ac7e00696c73?source=rss-ceb74e8587f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac7e00696c73</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ranvir Singh]]></dc:creator>
            <pubDate>Fri, 18 Oct 2019 22:48:00 GMT</pubDate>
            <atom:updated>2020-04-13T23:32:29.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mvhgFIpNbB8UmgAn.png" /></figure><p>Shipping your product without testing is like buying a car without turning on the engine. We have to run a few tests again and again during the development of the product and if those tests are not automated, we will have a hard time testing our application.</p><p>Here is a post that will help you to understand the <a href="https://ranvir.xyz/blog/writing-unit-tests-for-the-models/">importance of writing tests</a>?</p><p>This post is in continuation of the last post we shared related to Spring boot in which we talked about writing <a href="https://ranvir.xyz//blog/building-restful-apis-with-java-spring-boot-framework-for-beginners/">Rest APIs in Spring Boot</a>.</p><p>Please go through that post if you want to learn how to create rest APIs using Spring Boot. In this post, we are going to discuss how we can test our spring boot application from start to end without any mocking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/0*csZr2ageohRVIAeA.jpg" /></figure><p>First, we have to add the test libraries to the pom.xml, so that the Maven can install them for us. Here is the <a href="https://github.com/singh1114/java_tutorial">GitHub repo</a> that contains the code for this tutorial. Here is the code to add testing libraries to pom.xml</p><pre>        ...<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>        &lt;/dependency&gt;<br>        &lt;dependency&gt;<br>        ...</pre><h3>Using separate config for testing purposes</h3><p>We don’t want to add the data to the same database as of the production one. So, we will start by creating a separate configuration for handling the test cases. Also, its always a good practice to have separate configurations anyway.</p><p>Create a new resource file, src/main/resources/application-test.properties and add the following data to it.</p><pre>spring.datasource.url=jdbc:mysql://localhost:3306/<br>springtestguidespring.datasource.username=root<br>spring.datasource.password=&lt;password&gt;<br>spring.jpa.hibernate.ddl-auto=update</pre><p><strong>Note:</strong> We will have to create the database in our local system to make it work. Now that we have a separate configuration file, we have to export it as an App configuration so that we can use it in the tests itself. Add the following code to the file, src/main/java/io/singh1114/springboottut/AppConfigurationTest.java</p><pre>package io.singh1114.springboottut;<br>import org.springframework.context.annotation.ComponentScan;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.context.annotation.Profile;<br>import org.springframework.context.annotation.PropertySource; </pre><pre>@Configuration@ComponentScan(&quot;io.singh1114.springboottut&quot;)<br>@Profile(&quot;test&quot;)<br>@PropertySource(value = {&quot;classpath:application-test.properties&quot;,&quot;classpath:application.properties&quot;})<br>public class AppConfigurationTest { }</pre><h3>Writing Controller test for Spring Boot API.</h3><p>Now since we are going to test the application from end to end, let’s create a controller test. Add the following code to src/test/java/io/singh1114/springboottut/SchoolControllerTest.java</p><pre>package io.singh1114.springboottut;<br><br>import io.singh1114.springboottut.school.School;<br>import io.singh1114.springboottut.school.SchoolRepository;<br>import org.json.JSONException;<br>import org.junit.Test;<br>import org.junit.runner.RunWith;<br>import org.skyscreamer.jsonassert.JSONAssert;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.boot.test.context.SpringBootTest;<br>import org.springframework.boot.test.web.client.TestRestTemplate;<br>import org.springframework.boot.web.server.LocalServerPort;<br>import org.springframework.http.HttpEntity;<br>import org.springframework.http.HttpHeaders;<br>import org.springframework.http.HttpMethod;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.test.context.ActiveProfiles;<br>import org.springframework.test.context.junit4.SpringRunner;<br><br>import javax.transaction.Transactional;<br><br>@ActiveProfiles(&quot;test&quot;)<br>@RunWith(SpringRunner.class)<br>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)<br>@Transactional<br>public class SchoolControllerTest {<br><br>    @LocalServerPort<br>    private int port;<br><br>    @Autowired<br>    private SchoolRepository repository;<br><br>    TestRestTemplate restTemplate = new TestRestTemplate();<br><br>    HttpHeaders headers = new HttpHeaders();<br><br>    @Test<br>    public void testGetSchoolData () throws JSONException {<br>        HttpEntity&lt;String&gt; entity = new HttpEntity&lt;String&gt;(null, headers);<br><br>        ResponseEntity&lt;String&gt; response = restTemplate.exchange(<br>                createURLWithPort(&quot;/schools&quot;),<br>                HttpMethod.GET, entity, String.class);<br><br>        School testSchool = new School(1, &quot;First Location&quot;, &quot;Mr. Ranvir&quot;, &quot;California&quot;);<br>        repository.save(testSchool);<br><br>        String expected = &quot;[{\&quot;id\&quot;:1,\&quot;name\&quot;:\&quot;First Location\&quot;,\&quot;principle\&quot;:\&quot;Mr. Ranvir\&quot;,\&quot;address\&quot;:\&quot;California\&quot;}]&quot;;<br>        JSONAssert.assertEquals(expected, response.getBody(), false);<br>    }<br><br>    private String createURLWithPort(String uri) {<br>        return &quot;http://localhost:&quot; + port + uri;<br>    }<br>}</pre><p>Let&#39;s go through the file and understand this.</p><p>@ActiveProfiles, is used to let the framework know that we are going to use the given profile. As we have already declared the test Profile in the Configuration file, we can use it here directly.</p><p>@RunWith and @SpringBootTest is used to start a simple server to carry out the tests using the SpringBootFramework.</p><h3>Running on a random port</h3><p>With SpringBootTest.WebEnvironment.RANDOM_PORT we are telling the framework to launch the application on a Random PORT.</p><h3>Removing any change made to the database after test completion.</h3><p>@Transactional will help us to clean the database once tests are completed. We don&#39;t want to keep adding stuff to the database and want to clean it after every test run.</p><p>Wrapping something with Transaction is a very general programming concept that is present in almost every Database. According to this, if you run any number of SQL commands inside the transaction and if it fails on any step, the whole transaction will be reverted.</p><p>This is fairly useful when you are running related commands, for example, reducing the inventory size and adding stuff to someone brought a list. The same concept is used here, the only hack is that anything you run inside@Transactional is rolled back in the end.</p><p>Read more about this on <a href="https://docs.spring.io/spring/docs/4.2.5.RELEASE/spring-framework-reference/html/integration-testing.html#testcontext-tx">Spring boot logs</a>.</p><h3>Creating the API endpoint</h3><p>These are used to create the URL for a given endpoint to hit.</p><pre>    @LocalServerPort<br>    private int port;<br><br>    private String createURLWithPort(String uri) {<br>        return &quot;http://localhost:&quot; + port + uri;<br>    }</pre><h3>Creating the School Object</h3><p>This code is used to create the object in the database.</p><pre>    @Autowired<br>    private SchoolRepository repository;<br>    ...<br>        School testSchool = new School(1, &quot;First Location&quot;, &quot;Mr. Ranvir&quot;, &quot;California&quot;);<br>        repository.save(testSchool);<br>    ...</pre><h3>Sending the request and getting the response</h3><pre>    TestRestTemplate restTemplate = new TestRestTemplate();<br><br>    HttpHeaders headers = new HttpHeaders();<br>    ...<br>        HttpEntity&lt;String&gt; entity = new HttpEntity&lt;String&gt;(null, headers);<br><br>        ResponseEntity&lt;String&gt; response = restTemplate.exchange(<br>                createURLWithPort(&quot;/schools&quot;),<br>                HttpMethod.GET, entity, String.class);<br>    ...</pre><h3>Checking if the response is equal to the object created</h3><p>Here we are checking if the body of the response is equal to the expected response.</p><pre>JSONAssert.assertEquals(expected, response.getBody(), false);</pre><h3>Run the tests</h3><pre>mvn test</pre><p>Use can use the following command to run the tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KHEr5U4DDFUvjZZ5.png" /></figure><p>I hope you liked the post. Please share your views in the comment section below.</p><p><em>Originally published at </em><a href="https://ranvir.xyz/blog/testing-in-spring-boot-java-with-junit-for-beginners/"><em>https://ranvir.xyz</em></a><em> on October 18, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac7e00696c73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Soft deletion: An industry standard]]></title>
            <link>https://medium.com/@ranvirsingh_75067/soft-deletion-an-industry-standard-4969621c28c8?source=rss-ceb74e8587f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4969621c28c8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Ranvir Singh]]></dc:creator>
            <pubDate>Sat, 12 May 2018 18:06:09 GMT</pubDate>
            <atom:updated>2018-05-12T18:06:09.711Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I came to know about one of the industry standard “Soft deletion” about which I was completely unaware before. Soft deletion is nothing but a way to tell the users that your data is deleted from the database but in real the data is not deleted. It is still in the database only a flag is set for the entry that the user should not see this data again. Sounds <strong>shady, </strong>right? Still it is the industry standard.</p><p>Let’s dive right in and see how can we implement this thing. Only from the first few lines it is clear that for every entry in the database, we need to see if the data is deleted by the user or not. If the data is deleted by the user mark it as deleted or something.</p><p>There are a ton of ways to implement in any programming language. A naive programming will go forward and add another column to the database named <strong>deleted</strong> that can take boolean values. He will add some methods that will check if the value of deleted is set to <strong>False( I am a Python programmer, if you know what I mean) </strong>that he will not show it to the user.</p><p>That is the naive way of doing things and I after gaining some experience with the programming languages you don’t do such things. You try to make it a little reusable. So that next time someone tries to implement the same thing in the database he doesn’t need to write the whole code again.</p><p>I would share the code snippets of Python, but I am sure about the easiness of python that a person without even a single day experience of writing code will be able to understand( <strong>You only need to know the concept of inheritance). </strong>This is one of the hundred-thousand ways in which you can implement it.</p><pre># models.py</pre><pre>import arrow </pre><pre>from django.db import models</pre><pre>class BaseModel(models.Model):</pre><pre>    deleted_at = models.DateTimeField(blank=True, null=True)</pre><pre>    class Meta:<br>        abstract = True</pre><pre># dbio.py<br># this file is the basic file from where you can ask for model<br># objects.</pre><pre>from django.utils import timezone<br>from django.core.exceptions import ObjectDoesNotExist</pre><pre>class BaseDb:<br>    def __init__(self, model_name):<br>         self.model = model<br>    <br>    def delete(self, obj):<br>         # in here you will update the db object with the time at<br>         # which the object was deleted.<br>         obj(deleted_at=timezone.now())<br>         obj.save()</pre><p>Now every model of your project must inherit from BaseModel and every time you want to delete the object, you will use this delete method. This way the object will never deleted from the database.</p><p>More efficient implementations are also available for this task. Please comment if you know about some other efficient implementations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4969621c28c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a blog on GitHub in 2 minutes]]></title>
            <link>https://medium.com/@ranvirsingh_75067/recently-i-coded-a-web-app-that-can-be-used-to-launch-your-own-blog-using-your-github-account-fae343d03697?source=rss-ceb74e8587f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fae343d03697</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[jekyll]]></category>
            <dc:creator><![CDATA[Ranvir Singh]]></dc:creator>
            <pubDate>Sat, 21 Apr 2018 07:09:36 GMT</pubDate>
            <atom:updated>2018-04-21T07:11:21.454Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I coded a web app that can be used to launch your own blog using your github account.</p><p>I made use of Django for creating this web app. The processes involved in creating your blog are fairly simple.</p><p><a href="http://jeklog.com/login/">Visit the following to login using your github account. http://jeklog.com/login/</a>. Make sure your email is verified otherwise you won’t be able to create repositories.</p><p>Next step is to create a repository. It is best to keep the name very simple. This step will create your repository and create a simple blog boilerplate for you.</p><p>After this, you will be redirected to your home screen. The user button in the right can be used to make changes for the blog.</p><p>The first and foremost thing is to add your details and your social media details which will be reflected in your blog.</p><p>Now you can visit your blog. Please make sure to make at least one change before making a change otherwise you will 404.</p><p>Please use the service and let me know about the things you liked and the things you hated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fae343d03697" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>