<?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 Jimit Dholakia on Medium]]></title>
        <description><![CDATA[Stories by Jimit Dholakia on Medium]]></description>
        <link>https://medium.com/@jimit105?source=rss-5450f46b772d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q7JctZZG_Bi1LL1k4wZXTw.jpeg</url>
            <title>Stories by Jimit Dholakia on Medium</title>
            <link>https://medium.com/@jimit105?source=rss-5450f46b772d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Mar 2026 02:13:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jimit105/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[Labeled vs Unlabeled Break Statements in Java]]></title>
            <link>https://medium.com/geekculture/labeled-vs-unlabeled-break-statements-in-java-90a8ff99e459?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a8ff99e459</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java-programming]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 17:01:01 GMT</pubDate>
            <atom:updated>2026-03-01T17:01:01.892Z</atom:updated>
            <content:encoded><![CDATA[<h4>Java Programming</h4><h4>Difference between labeled and unlabeled break statements in Java with examples for loops, switch blocks, and nested loops.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Io1oBQxA0V0BdCAJ.jpeg" /></figure><p>The break statement in Java is used to terminate the execution of a loop or a switch block. Most developers are familiar with the basic unlabeled form - you hit a condition, you break out. But Java also supports a labeled variant that lets you break out of a specific outer loop in nested structures.</p><p>In this article, we will explore both forms with examples and compare when to use each.</p><h3>Unlabeled Break Statement</h3><p>An unlabeled break terminates the innermost for, while, do-while, or switch statement that encloses it. Control transfers to the first statement after the terminated block.</p><h4>Break in a Loop</h4><p><strong><em>Example-1:</em></strong></p><pre>public class UnlabeledBreakLoop {<br>    public static void main(String[] args) {<br>        int[] numbers = {10, 20, 30, 40, 50};<br><br>        for (int num : numbers) {<br>            if (num == 30) {<br>                System.out.println(&quot;Found 30, breaking out of loop&quot;);<br>                break;<br>            }<br>            System.out.println(&quot;Current number: &quot; + num);<br>        }<br><br>        System.out.println(&quot;Loop ended&quot;);<br>    }<br>}</pre><pre>Output:<br>Current number: 10<br>Current number: 20<br>Found 30, breaking out of loop<br>Loop ended</pre><p>The loop iterates through the array and terminates as soon as it encounters the value 30. The remaining elements ( 40, 50) are never processed.</p><h4>Break in a Switch Statement</h4><p><strong><em>Example-2:</em></strong></p><pre>public class UnlabeledBreakSwitch {<br>    public static void main(String[] args) {<br>        int day = 3;<br><br>        switch (day) {<br>            case 1:<br>                System.out.println(&quot;Monday&quot;);<br>                break;<br>            case 2:<br>                System.out.println(&quot;Tuesday&quot;);<br>                break;<br>            case 3:<br>                System.out.println(&quot;Wednesday&quot;);<br>                break;<br>            case 4:<br>                System.out.println(&quot;Thursday&quot;);<br>                break;<br>            default:<br>                System.out.println(&quot;Other day&quot;);<br>                break;<br>        }<br>    }<br>}</pre><pre>Output:<br>Wednesday</pre><p>Without the break statements, execution would &quot;fall through&quot; to subsequent cases. For instance, removing the break after case 3 would print both &quot;Wednesday&quot; and &quot;Thursday&quot;.</p><h3>Labeled Break Statement</h3><p>A labeled break terminates an outer loop that is marked with a label. The label is an identifier followed by a colon (e.g., outerLoop:), placed before the loop statement.</p><p>This is particularly useful in nested loops where an unlabeled break would only exit the inner loop.</p><h4>Syntax</h4><pre>labelName:<br>for (...) {<br>    for (...) {<br>        if (condition) {<br>            break labelName;  // exits the outer loop<br>        }<br>    }<br>}</pre><h4>Breaking Out of Nested Loops</h4><p><strong><em>Example-1:</em></strong></p><pre>public class LabeledBreakNested {<br>    public static void main(String[] args) {<br>        int[][] matrix = {<br>            {1, 2, 3},<br>            {4, 5, 6},<br>            {7, 8, 9}<br>        };<br><br>        int target = 5;<br>        boolean found = false;<br><br>        search:<br>        for (int i = 0; i &lt; matrix.length; i++) {<br>            for (int j = 0; j &lt; matrix[i].length; j++) {<br>                System.out.println(&quot;Checking matrix[&quot; + i + &quot;][&quot; + j + &quot;] = &quot; + matrix[i][j]);<br>                if (matrix[i][j] == target) {<br>                    found = true;<br>                    System.out.println(&quot;Found &quot; + target + &quot; at position [&quot; + i + &quot;][&quot; + j + &quot;]&quot;);<br>                    break search;<br>                }<br>            }<br>        }<br><br>        if (!found) {<br>            System.out.println(&quot;Target not found&quot;);<br>        }<br>    }<br>}</pre><pre>Output:<br>Checking matrix[0][0] = 1<br>Checking matrix[0][1] = 2<br>Checking matrix[0][2] = 3<br>Checking matrix[1][0] = 4<br>Checking matrix[1][1] = 5<br>Found 5 at position [1][1]</pre><p>The break search statement exits both the inner and outer loops as soon as the target is found. Without the label, only the inner loop would terminate, and the outer loop would continue iterating through the remaining rows unnecessarily.</p><h4>Labeled Break with While Loops</h4><p>Labels are not limited to for loops — they work with while and do-while as well.</p><p><strong><em>Example-2:</em></strong></p><pre>public class LabeledBreakWhile {<br>    public static void main(String[] args) {<br>        int i = 0;<br><br>        outer:<br>        while (i &lt; 3) {<br>            int j = 0;<br>            while (j &lt; 3) {<br>                if (i == 1 &amp;&amp; j == 1) {<br>                    System.out.println(&quot;Breaking at i=&quot; + i + &quot;, j=&quot; + j);<br>                    break outer;<br>                }<br>                System.out.println(&quot;i=&quot; + i + &quot;, j=&quot; + j);<br>                j++;<br>            }<br>            i++;<br>        }<br><br>        System.out.println(&quot;Done&quot;);<br>    }<br>}</pre><pre>Output:<br>i=0, j=0<br>i=0, j=1<br>i=0, j=2<br>i=1, j=0<br>Breaking at i=1, j=1<br>Done</pre><h3>Without a Labeled Break</h3><p>To appreciate what labeled breaks give you, consider the same nested-loop search without one. You’d typically use a boolean flag:</p><pre>boolean found = false;<br><br>for (int i = 0; i &lt; matrix.length &amp;&amp; !found; i++) {<br>    for (int j = 0; j &lt; matrix[i].length &amp;&amp; !found; j++) {<br>        if (matrix[i][j] == target) {<br>            found = true;<br>            System.out.println(&quot;Found &quot; + target + &quot; at [&quot; + i + &quot;][&quot; + j + &quot;]&quot;);<br>        }<br>    }<br>}</pre><p>This works, but the flag check clutters both loop conditions. The labeled break version is more direct and easier to read.</p><h3>Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEQHglvRBZdDOletHhtvSg.png" /></figure><h3>When to Use Each</h3><p>Use an <strong>unlabeled break</strong> for the common cases — exiting a single loop when a condition is met, or preventing fall-through in switch blocks.</p><p>Use a <strong>labeled break</strong> when you have nested loops and need to exit more than just the innermost one. The classic scenario is searching through a multi-dimensional structure. That said, if the nested logic is complex, extracting it into a separate method and using return is often cleaner than a labeled break.</p><h3>Conclusion</h3><p>In this article, we explored the difference between labeled and unlabeled break statements in Java. The unlabeled form handles the majority of cases - terminating a single loop or switch block. The labeled form fills a specific gap: cleanly exiting nested loops without resorting to flag variables. Both are simple tools, but knowing when to reach for each one can make your loop logic noticeably cleaner.</p><h3>References</h3><ul><li><a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html">The break Statement — Oracle Java Tutorials</a></li><li><a href="https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.15">Java Language Specification — break Statements</a></li></ul><h3>Let’s Connect</h3><ul><li>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a></li><li>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a></li><li>Substack: <a href="https://jimit105.substack.com/p/labeled-vs-unlabeled-break-statements">https://jimit105.substack.com</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a8ff99e459" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/labeled-vs-unlabeled-break-statements-in-java-90a8ff99e459">Labeled vs Unlabeled Break Statements in Java</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[How to integrate Firebase with Angular Applications?]]></title>
            <link>https://medium.com/geekculture/how-to-integrate-firebase-with-angular-applications-5f57a05d38e0?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f57a05d38e0</guid>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Wed, 07 Dec 2022 05:13:30 GMT</pubDate>
            <atom:updated>2025-02-04T19:01:44.434Z</atom:updated>
            <content:encoded><![CDATA[<h4>Programming</h4><h4>A guide to integrating Firestore database with Angular applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mjxMdcTtOmav-vQSa8fs_w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Caspar Camille Rubin</a> on <a href="https://unsplash.com/s/photos/databases?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this short article, we will walk through the process of setting up a Remote Firebase Database i.e. Firestore with an Angular Application.</p><p>I will divide this guide into 2 sections as follows:</p><ol><li>Creating a project on Firebase</li><li>Integrating Firebase with Angular Application</li></ol><h4>Section 1: Creating a project on Firebase</h4><p>First, go to <a href="https://console.firebase.google.com/">Firebase Console</a></p><p>Then, select “Add Project” and give a name to the project.</p><p>Once the project is created on Firebase, select “Web” from the options to add Firebase to your Angular Application as shown in the below screenshot, give a nickname for your app, and then click “Register app”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*Qc_6AsattByoL-82xHRhmQ.png" /></figure><h4>Section 2: Integrating Firebase with Angular Application</h4><p>Now, go to your Angular app, open the terminal, and run the following command to install Firebase SDK.</p><pre>npm install firebase</pre><p>After installing the SDK, copy the Firebase configuration details (as shown on the console) and paste them into the environment.ts file, as shown below:</p><pre>export const environment = {<br>  production: false,<br>  firebase: {<br>    apiKey: &quot;xxxxxxxxx&quot;,<br>    authDomain: &quot;angular-demo-1234a.firebaseapp.com&quot;,<br>    projectId: &quot;angular-demo-1234a&quot;,<br>    storageBucket: &quot;angular-demo-1234a.appspot.com&quot;,<br>    messagingSenderId: &quot;xxxxxxxxxx&quot;,<br>    appId: &quot;1:xxxxxxxxxx:web:dexxxxxxyyyxxx&quot;<br>  }<br>};</pre><p>The next step is to install AngularFire using the following command:</p><pre>ng add @angular/fire</pre><blockquote>If you receive an Authentication error that asks you to enter an authorization code, then follow the steps given in <a href="https://stackoverflow.com/questions/70657254/how-to-get-authorisation-code-during-angularfire-installation">this pos</a>t to receive the authorization code.</blockquote><p>After running the ng add @angular/fire command, select the features you would like to add to your application. Eg. ng deploy --hosting, Authentication, Firestore, Realtime Database.</p><p>Select the account associated with your Firebase application and the project created on Firebase.</p><p>The associated configuration and code changes will be automatically made in the Angular application code.</p><p>Now, go to app.module.ts and import the following:</p><pre>import { FIREBASE_OPTIONS } from &#39;@angular/fire/compat&#39;;</pre><p>and make the following changes in the providers:</p><pre>providers: [<br>  {provide: FIREBASE_OPTIONS, useValue: environment.firebase}<br>]</pre><p>Now, your application is ready to use the Firestore database with Angular Applications.</p><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4>Connect with me</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f57a05d38e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/how-to-integrate-firebase-with-angular-applications-5f57a05d38e0">How to integrate Firebase with Angular Applications?</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[Monitoring Python Applications with Elastic APM]]></title>
            <link>https://python.plainenglish.io/monitoring-flask-fastapi-python-applications-with-elastic-apm-33237a39d7b6?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/33237a39d7b6</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[elastic-apm]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Mon, 01 Mar 2021 13:59:51 GMT</pubDate>
            <atom:updated>2025-04-14T05:06:51.362Z</atom:updated>
            <content:encoded><![CDATA[<h4>Programming</h4><h4>A guide to monitoring Flask, FastAPI, and Python Applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5cpyPF0pN_DMYgdB51wJw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is Elastic APM?</h3><blockquote>Elastic APM is an application performance monitoring system built on the Elastic Stack. It allows you to monitor software services and applications in real-time, by collecting detailed performance information on response time for incoming requests, database queries, calls to caches, external HTTP requests, and more. This makes it easy to pinpoint and fix performance problems quickly.</blockquote><blockquote>Elastic APM also automatically collects unhandled errors and exceptions. Errors are grouped based primarily on the stacktrace, so you can identify new errors as they appear and keep an eye on how many times specific errors happen.</blockquote><p><a href="https://www.elastic.co/guide/en/apm/get-started/current/overview.html">-Elastic</a></p><p>This article consists of three parts:</p><ol><li>Monitoring Flask / Flask-RESTPlus Applications</li><li>Monitoring FastAPI Applications</li><li>Monitoring Python Applications</li></ol><h3>Monitoring Flask / Flask-RESTPlus Applications</h3><h4>Installation</h4><p>Elastic APM has built-in support for Flask. Since Flask-RESTPlus and Flask-RESTful are extensions for Flask, the same steps apply for Flask-RESTPlus as well as Flask-RESTful.</p><p>Install Elastic APM agent using pip:</p><pre>pip install elastic-apm[flask]</pre><h4>Implementation</h4><p>Let’s first import the required packages:</p><pre>from flask import Flask<br><br>from elasticapm.contrib.flask import ElasticAPM<br>import elasticapm</pre><p>Now, let&#39;s create an instance of Flask, which will be our WSGI application.</p><pre>app = Flask(__name__)</pre><p>We can initialize the APM agent by using either environment variables or our application code itself. In this article, we will initialize the APM agent in our code itself.</p><p>To create an instance of Elastic APM agent, we need the following parameters:</p><p>server_url → The URL of the Elastic APM</p><p>service_name → Name of the application</p><p>environment → The environment in which the application is running e.g. dev, qa, or prod</p><pre>server_url = &#39;http://localhost:8200&#39;<br>service_name = &#39;DemoFlask&#39;<br>environment = &#39;dev&#39;</pre><p>Next, we will initialize the APM Agent. <br>We need to pass the Flask instance app as the first argument for initializing the APM agent, along with the parameters that we defined above.</p><pre>apm = ElasticAPM(app, server_url=server_url, <br>      service_name=service_name, environment=environment)</pre><p>Our APM agent is now ready.</p><p>Now, let’s open Kibana (e.g. http://localhost:5601/) to see the logged data.</p><p>Open the Kibana dashboard and go to the APM tab. You can see our service DemoFlask listed there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2sTNEKzrK1iqbTKf3kVIvQ.png" /></figure><p>Click on the service name and go to Metrics, where you can track the CPU and Memory Usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*5gkshJqPB0VO_Gnqae0m_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*w-W7-AVetmCFKmrzDSGR8w.png" /></figure><p>In the transactions tab, you can see the visualization related to each request your application receives, such as Transaction duration and Requests per minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*FCWZtyAcq-SWaA5l_-EuLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*zUMTMVhOBT-Knj_qXRtk2w.png" /></figure><p>You can also view the list of all the endpoints along with their average duration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_c1tWK4_d3MpRJN8twx-FQ.png" /></figure><p>Click on a transaction to see more details about the transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQkCVni1Xn-Pt_5oP9OUYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzkBFyZhJ6x-d1AwkLZKRA.png" /></figure><p>You can also add additional information about the transaction by using <a href="https://www.elastic.co/guide/en/apm/get-started/7.4/metadata.html#labels-fields">labels</a>.</p><pre>elasticapm.label(platform=&#39;DemoPlatform&#39;)</pre><p>To add default labels to all transactions, we can use Flask’s app.before_request decorator.</p><pre>@app.before_request<br>def apm_log():<br>    elasticapm.label(platform = &#39;DemoPlatform&#39;,                     <br>                     application = &#39;DemoApplication&#39;)</pre><p>The information of the labels will be visible in the metadata tab in the trace sample of the transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*WFK3ANF7JiK14C3xXK_Zuw.png" /></figure><p><em>Note that, by default, the transaction and error data will be recorded only when the application is </em><strong><em>not </em></strong><em>in debug mode.</em></p><p><em>The sample code can be found in the link mentioned in the </em><strong><em>Resources </em></strong><em>section.</em></p><h3>Monitoring FastAPI Applications</h3><p>To monitor FastAPI/Starlette Applications properly using Elastic APM, you need to use Python 3.7+</p><h4>Installation</h4><p>Install the Elastic APM agent using pip:</p><pre>pip install elastic-apm</pre><h4>Implementation</h4><p>First, let’s import the required packages:</p><pre>import uvicorn<br>from fastapi import FastAPI<br>from elasticapm.contrib.starlette import make_apm_client, ElasticAPM</pre><p>Next, we will create an APM client using the SERVICE_NAME , SERVER_URL and ENVIRONMENT. Also, we will specify the global labels at the same time using GLOBAL_LABELS.</p><pre>apm_config = {<br> &#39;SERVICE_NAME&#39;: &#39;DemoFastAPI&#39;,<br> &#39;SERVER_URL&#39;: &#39;http://localhost:8200&#39;,<br> &#39;ENVIRONMENT&#39;: &#39;dev&#39;,<br> &#39;GLOBAL_LABELS&#39;: &#39;platform=DemoPlatform, application=DemoApplication&#39;<br>}<br>apm = make_apm_client(apm_config)</pre><p>Now, let’s initialize the Elastic APM agent.</p><pre>app = FastAPI()<br>app.add_middleware(ElasticAPM, client=apm)</pre><p>The FastAPI application is now ready to send the logs to Elastic Server.</p><p><em>The sample code can be found in the link mentioned in the </em><strong><em>Resources </em></strong><em>section.</em></p><h3>Monitoring Python Applications</h3><p>We can create an Elastic APM Client to monitor Python applications that do not use a framework (e.g. Flask, Django, or FastAPI). An example of these applications could be schedulable code.</p><h4>Installation</h4><p>Install Elastic APM agent using pip:</p><pre>pip install elastic-apm</pre><h4>Implementation</h4><p>First, we will create an Elastic APM Client</p><pre>from elasticapm import Client<br>import elasticapm<br>client = Client(<br>    {&#39;SERVICE_NAME&#39;: &#39;DemoPython&#39;,<br>     &#39;SERVER_URL&#39;: &#39;http://localhost:8200&#39;,<br>     &#39;ENVIRONMENT&#39;: &#39;dev&#39;}<br>)</pre><p>For frameworks like Flask and FastAPI, Elastic APM automatically instruments the application and also begins and ends the transactions.</p><p>However, for Python applications that do not use such frameworks, we need to manually instrument the application and also begin and end the transactions.</p><p>To automatically instrument your application to capture HTTP requests, database queries, etc., add the following line</p><pre>elasticapm.instrumentation.control.instrument()</pre><p>To begin a transaction, use begin_transaction method with the appropriate transaction type as the parameter.</p><p>For example,</p><pre>client.begin_transaction(&#39;schedule&#39;)</pre><p>To complete a transaction, use the <em>end_transaction </em>method which takes two arguments viz. transaction name and result.</p><p>For example,</p><pre>client.end_transaction(&#39;demo-transaction&#39;, &#39;success&#39;)</pre><p><em>The sample code for monitoring Python applications can be found in the link mentioned in the </em><strong><em>Resources </em></strong><em>section.</em></p><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4>Resources</h4><p>All the code snippets of this article are available on my <a href="https://jimit105.github.io/medium-articles/Monitoring%20Python%20Applications%20with%20Elastic%20APM.html">GitHub page</a>.</p><h4>References</h4><ul><li><a href="https://www.elastic.co/guide/en/apm/agent/python/current/configuration.html">https://www.elastic.co/guide/en/apm/agent/python/current/configuration.html</a></li><li><a href="https://www.elastic.co/guide/en/apm/agent/python/current/flask-support.html">https://www.elastic.co/guide/en/apm/agent/python/current/flask-support.html</a></li><li><a href="https://www.elastic.co/guide/en/apm/get-started/7.4/metadata.html">https://www.elastic.co/guide/en/apm/get-started/7.4/metadata.html</a></li><li><a href="https://www.elastic.co/guide/en/apm/agent/python/current/starlette-support.html">https://www.elastic.co/guide/en/apm/agent/python/current/starlette-support.html</a></li></ul><h4>Let’s Connect</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33237a39d7b6" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/monitoring-flask-fastapi-python-applications-with-elastic-apm-33237a39d7b6">Monitoring Python Applications with Elastic APM</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[Dead Letter Queue (DLQ) in Kafka]]></title>
            <link>https://medium.com/data-science/dead-letter-queue-dlq-in-kafka-29418e0ec6cf?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/29418e0ec6cf</guid>
            <category><![CDATA[kafka-dlq]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Thu, 28 Jan 2021 13:32:24 GMT</pubDate>
            <atom:updated>2025-02-04T19:03:17.901Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Programming</h4><h4>Introduction to Kafka DLQ and its implementation in Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waoJAf5XZnY6EdlUSO2QIA.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/dakub-8222964/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3217049">DaKub</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3217049">Pixabay</a></figcaption></figure><p><strong>Dead Letter Queue</strong> is a secondary Kafka topic that receives the messages which the Kafka Consumer failed to process due to certain errors like improper deserialization of messages, improper message format, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n37QSTazdDtLq3-sLCRsYg.png" /><figcaption>Image by the author (<a href="https://www.linkedin.com/in/jimit105/">Jimit Dholakia</a>)</figcaption></figure><h3>Installation</h3><p>There are various libraries in Python that can be used to connect to Kafka Cluster. Some of them are:</p><ol><li><a href="https://kafka-python.readthedocs.io/en/master/">kafka-python</a></li><li><a href="https://docs.confluent.io/clients-confluent-kafka-python/current/index.html">confluent-kafka</a></li><li><a href="https://pykafka.readthedocs.io/en/latest/">PyKafka</a></li></ol><p>I’ll be using kafka-python to connect to Kafka Cluster and to create Kafka Producer and Consumer Clients.</p><p>Install kafka-python using pip:</p><pre>pip install kafka-python</pre><h3>Implementation</h3><p>We will first import the necessary packages and define the bootstrap servers, primary topic name, and DLQ topic name to create instances of Kafka Producer and Consumer.</p><pre>from kafka import KafkaProducer, KafkaConsumer<br>import json<br>bootstrap_servers = [&#39;localhost:9092&#39;]<br>primary_topic = &#39;primary-topic-name&#39;<br>dlq_topic = &#39;dlq-topic-name&#39;</pre><p>Now, let&#39;s create a Producer for the DLQ Topic, where the malformed messages will be sent.</p><pre>dlq_producer = KafkaProducer(<br>    bootstrap_servers=bootstrap_servers,<br>    value_serializer=lambda x: x.encode(&#39;utf-8&#39;),<br>    acks=&#39;all&#39;<br>)</pre><p>Next, we will create Kafka Consumer to consume the messages from the primary topic.</p><pre>consumer = KafkaConsumer(<br>    primary_topic,<br>    bootstrap_servers=bootstrap_servers,<br>    auto_offset_reset=&#39;latest&#39;,<br>    enable_auto_commit=True,<br>    value_deserializer=lambda x: x.decode(&#39;utf-8&#39;)<br>)</pre><p>Now, we will enclose our code in the try-except block. If the message received is not in JSON format or any exception occurs, then the message will be sent to the DLQ topic.</p><pre>for msg in consumer:<br>    print(f&#39;\nReceived:\nPartition: {msg.partition} \tOffset: {msg.offset}\tValue: {msg.value}&#39;)<br>    <br>    try:<br>        data = json.loads(msg.value)<br>        print(&#39;Data Received:&#39;, data)<br>            <br>    except:<br>        print(f&#39;Value {msg.value} not in JSON format&#39;)<br>        dlq_producer.send(dlq_topic, value=msg.value)<br>        print(&#39;Message sent to DLQ Topic&#39;)</pre><h3>Conclusion</h3><p>Creating a DLQ topic helps to identify the malformed messages without disturbing other messages. DLQ topic also helps us to analyze the malformed messages and can be used for reporting purposes.</p><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4>Resources</h4><p>The code snippets of this article are available on <a href="https://jimit105.github.io/medium-articles/Dead%20Letter%20Queue%20%28DLQ%29%20in%C2%A0Kafka.html">my GitHub page</a>.</p><h4>Reference</h4><ul><li><a href="https://kafka-python.readthedocs.io/en/master/install.html">https://kafka-python.readthedocs.io/en/master/install.html</a></li></ul><h4>Let’s Connect</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29418e0ec6cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/dead-letter-queue-dlq-in-kafka-29418e0ec6cf">Dead Letter Queue (DLQ) in Kafka</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Ways to Merge Dictionaries in Python]]></title>
            <link>https://python.plainenglish.io/merge-dictionaries-in-python-d4e9ce137374?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e9ce137374</guid>
            <category><![CDATA[merge-dictionaries]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 13:38:01 GMT</pubDate>
            <atom:updated>2025-04-14T05:06:56.283Z</atom:updated>
            <content:encoded><![CDATA[<h4>Programming</h4><h4>Different ways to merge Python dictionaries along with the new operators in Python 3.9</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*383ADMsLmALfFDCWF3jaUA.png" /><figcaption>Image by <a href="https://pixabay.com/users/Clker-Free-Vector-Images-3736/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=39400">Clker-Free-Vector-Images</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=39400">Pixabay</a></figcaption></figure><p>In Python, a dictionary is a data structure that contains elements in the form of a key-value pair where keys are used to access the values of the dictionary. Python dictionaries are unordered and mutable i.e. the elements of the dictionaries can be changed.</p><p>In this article, we will explore five different ways to merge two or more dictionaries, along with a crude way.</p><p>For this article, let us create two dictionaries d1 and d2 which we want to concatenate into a single dictionary:</p><pre>d1 = {&#39;India&#39;: &#39;Delhi&#39;,<br>      &#39;Canada&#39;: &#39;Ottawa&#39;,<br>      &#39;United States&#39;: &#39;Washington D. C.&#39;}<br><br>d2 = {&#39;France&#39;: &#39;Paris&#39;,<br>      &#39;Malaysia&#39;: &#39;Kuala Lumpur&#39;}</pre><h4>The Crude Way</h4><p>You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.</p><pre>d3 = d1.copy()<br>for key, value in d2.items():<br>    d3[key] = value<br>    <br>print(d3)</pre><pre>Output:<br><br>{&#39;India&#39;: &#39;Delhi&#39;,<br> &#39;Canada&#39;: &#39;Ottawa&#39;,<br> &#39;United States&#39;: &#39;Washington D. C.&#39;,<br> &#39;France&#39;: &#39;Paris&#39;,<br> &#39;Malaysia&#39;: &#39;Kuala Lumpur&#39;}</pre><p>Now, let us see cleaner and better ways of merging the dictionaries:</p><h4>Method 1: Using the update method</h4><p>Dictionary has a method <a href="https://docs.python.org/3/library/stdtypes.html#dict.update">update()</a> which merges the dictionary with the items from the other dictionary in place and overwrites existing keys.</p><pre>d4 = d1.copy()<br>d4.update(d2)<br><br>print(d4)</pre><pre>Output:<br>{&#39;India&#39;: &#39;Delhi&#39;,<br> &#39;Canada&#39;: &#39;Ottawa&#39;,<br> &#39;United States&#39;: &#39;Washington D. C.&#39;,<br> &#39;France&#39;: &#39;Paris&#39;,<br> &#39;Malaysia&#39;: &#39;Kuala Lumpur&#39;}</pre><p>The update method modifies the current dictionary. So you might want to create a copy of the dictionary before operating on the dictionary.</p><h4>Method 2: Using the unpacking operator</h4><p>We can merge dictionaries in one line by simply using the unpacking operator (**).</p><pre>d5 = {**d1, **d2}<br><br>print(d5)</pre><pre>Output:<br>{&#39;India&#39;: &#39;Delhi&#39;,<br> &#39;Canada&#39;: &#39;Ottawa&#39;,<br> &#39;United States&#39;: &#39;Washington D. C.&#39;,<br> &#39;France&#39;: &#39;Paris&#39;,<br> &#39;Malaysia&#39;: &#39;Kuala Lumpur&#39;}</pre><p>We can also merge multiple dictionaries using this method.</p><pre>{**dict1, **dict2, **dict3}</pre><h4>Method 3: Using collections.ChainMap</h4><p>This is, perhaps, the least known method to merge dictionaries. <br><a href="https://docs.python.org/3/library/collections.html#collections.ChainMap">ChainMap</a> class from the Collections module groups multiple dictionaries in a single view.</p><pre>from collections import ChainMap<br>d6 = ChainMap(d1, d2)<br><br>print(d6)</pre><pre>Output:<br>ChainMap({&#39;Canada&#39;: &#39;Ottawa&#39;,<br>          &#39;India&#39;: &#39;Delhi&#39;,<br>          &#39;United States&#39;: &#39;Washington D. C.&#39;},<br>         {&#39;France&#39;: &#39;Paris&#39;,<br>          &#39;Malaysia&#39;: &#39;Kuala Lumpur&#39;})</pre><p>This method returns an object of the ChainMap class. We can, still, use this object as we would use any other dictionary. e.g. d6[’India’] will return &#39;Delhi’.</p><p>However, in the case of the same keys in two dictionaries, this method will return the value of the first dictionary, unlike the other methods which return the value from the second dictionary.</p><pre>x = {&#39;A&#39;: 1, &#39;B&#39;: 2}<br>y = {&#39;B&#39;: 10, &#39;C&#39;: 20}<br><br>z = ChainMap(x, y)<br>z[&#39;B&#39;]<br><br># outputs 2</pre><h4>Method 4: Unpacking the second dictionary</h4><p>We can merge the dictionaries by unpacking the second dictionary.</p><pre>d7 = dict(d1, **d2)<br><br>print(d7)</pre><pre>Output:<br>{&#39;India&#39;: &#39;Delhi&#39;,<br> &#39;Canada&#39;: &#39;Ottawa&#39;,<br> &#39;United States&#39;: &#39;Washington D. C.&#39;,<br> &#39;France&#39;: &#39;Paris&#39;,<br> &#39;Malaysia&#39;: &#39;Kuala Lumpur&#39;}</pre><p>However, this method only works if the keys of the second dictionary are strings.</p><pre>x = {1: &#39;A&#39;, 2: &#39;B&#39;}<br>y = {3: &#39;C&#39;, 4: &#39;D&#39;}<br><br>z = dict(x, **y)</pre><pre>Output:<br>TypeError: keyword arguments must be strings</pre><h4>Method 5: Using the merge operator</h4><p>Python 3.9 has introduced the <a href="https://docs.python.org/3.9/whatsnew/3.9.html#dictionary-merge-update-operators">merge</a> operator (|) in the dict class. <br>Using the merge operator, we can combine dictionaries in a single line of code.</p><pre>d8 = d1 | d2<br><br>print(d8)</pre><pre>Output:<br>{&#39;India&#39;: &#39;Delhi&#39;,<br> &#39;Canada&#39;: &#39;Ottawa&#39;,<br> &#39;United States&#39;: &#39;Washington D. C.&#39;,<br> &#39;France&#39;: &#39;Paris&#39;,<br> &#39;Malaysia&#39;: &#39;Kuala Lumpur&#39;}</pre><p>We can also merge the dictionaries in place by using the update operator (|=).</p><pre>d1 |= d2</pre><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4>Resources</h4><p>The code snippets used in this article can be found on my <a href="https://jimit105.github.io/medium-articles/5%20Ways%20to%20Merge%20Dictionaries%20in%20Python.html">GitHub page</a>.</p><h4>Let’s Connect</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e9ce137374" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/merge-dictionaries-in-python-d4e9ce137374">5 Ways to Merge Dictionaries in Python</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[Introduction to Logging in Python]]></title>
            <link>https://medium.com/data-science/logging-in-python-a1415d0b8141?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1415d0b8141</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Fri, 03 Jul 2020 15:50:12 GMT</pubDate>
            <atom:updated>2025-02-04T19:03:56.188Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Programming</h4><h4>How to log messages in Python and avoid print statements?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*z01yUxHC_fhR8LWT06n1sw.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/xresch-7410129/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3088958">xresch</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3088958">Pixabay</a></figcaption></figure><p>Logging is, perhaps, the most underrated aspect of any software development. Logging helps to develop robust programs by recording the events of the program. Logging is used for various purposes — from debugging to monitoring the application.</p><p>Python’s standard library provides a module for logging. In this article, I will show you how to add logging to your programs and develop better applications.</p><p>To use logging in your applications, import the logging module</p><pre>import logging</pre><h4>Logging Levels</h4><p>The logging module comes predefined with 5 levels of severity which are as follows:</p><pre>┌──────────┬───────┐<br>│  <strong>Level   </strong>│ <strong>Value </strong>│<br>├──────────┼───────┤<br>│ CRITICAL │    50 │<br>│ ERROR    │    40 │<br>│ WARNING  │    30 │<br>│ INFO     │    20 │<br>│ DEBUG    │    10 │<br>└──────────┴───────┘</pre><p>The default level is WARNING, which means only the events of this level and above will be logged.</p><p>The logging module provides a set of functions for simple usage. These are shown in the example below:</p><pre>import logging<br><br>logging.debug(&#39;Debug message&#39;)<br>logging.info(&#39;Info message&#39;)<br>logging.warning(&#39;Warning message&#39;)<br>logging.error(&#39;Error message&#39;)<br>logging.critical(&#39;Critical message&#39;)</pre><p>The output of the above example will be:</p><pre>WARNING:root:Warning message<br>ERROR:root:Error message<br>CRITICAL:root:Critical message</pre><p>This is because the default logging level is set to WARNING.</p><h4>Change Logging Level</h4><p>The logging module provides a function to set the basic configuration for the logger.</p><p>To change the level of the logger, pass the level argument for basicConfig() .</p><p><strong><em>Example:</em></strong></p><pre>import logging<br><br>logging.basicConfig(level=logging.INFO)<br><br>logging.debug(&#39;Debug message&#39;)<br>logging.info(&#39;Info message&#39;)<br>logging.error(&#39;Error message&#39;)</pre><p>The output of the above example would be:</p><pre>INFO:root:Info message<br>ERROR:root:Error message</pre><p>In this example, the logging level is set to INFO. So the ‘Info message’ will be logged but the ‘Debug message’ won’t be logged since the level of INFO is greater than DEBUG.</p><h4>Log to a file</h4><p>To log the messages to a file, simply pass the name of the file in the filename parameter of the basicConfig()</p><p><strong><em>Example:</em></strong></p><pre>import logging<br><br>logging.basicConfig(filename=&#39;sample.log&#39;, level=logging.INFO)<br><br>logging.debug(&#39;Debug message&#39;)<br>logging.info(&#39;Info message&#39;)<br>logging.error(&#39;Error message&#39;)</pre><p>The contents of the file would be:</p><pre>INFO:root:Info message<br>ERROR:root:Error message</pre><h4>Change logging Format</h4><p>The default logging format is %(levelname)s:%(name):%(message)s.</p><p>To change the default format, we need to specify the format parameter in the basicConfig().</p><p><strong><em>Example:</em></strong></p><pre>FORMAT = &#39;%(asctime)s:%(name)s:%(levelname)s - %(message)s&#39;<br><br>logging.basicConfig(format=FORMAT, level=logging.INFO)<br>logging.info(&#39;Info message&#39;)</pre><p>The corresponding output would be:</p><pre>2020-07-03 00:48:00,106:root:INFO - Info message</pre><p>The complete list of formatting attributes can be found in the <a href="https://docs.python.org/3/library/logging.html#logrecord-attributes">official documentation</a>.</p><h4>Change date format</h4><p>To change the date format displayed in the logs, we need to change the datefmt parameter.</p><p><strong><em>Example:</em></strong></p><pre>FORMAT = &#39;%(asctime)s:%(name)s:%(levelname)s - %(message)s&#39;<br><br>logging.basicConfig(format=FORMAT, <br>                    level=logging.INFO, <br>                    datefmt=&#39;%Y-%b-%d %X%z&#39;)<br><br>logging.info(&#39;Info message&#39;)</pre><p><strong><em>Output:</em></strong></p><pre>2020-Jul-03 00:56:31+0530:root:INFO - Info message</pre><p>The list of available date formats can be found in the <a href="https://docs.python.org/3/library/time.html#time.strftime">documentation</a>.</p><h4>Logging for exceptions</h4><p>To log the trace of the exception, you can either use logging.exception or use logging.error with exc_info=True.</p><p><strong><em>Example-1: with logging.error</em></strong></p><pre>try:<br>    5/0<br><br>except:<br>    logging.error(&#39;Exception occured&#39;)</pre><p><strong><em>Output-1:</em></strong></p><pre>ERROR:root:Exception occured</pre><p><strong><em>Example-2: with logging.error and exc_info=True</em></strong></p><pre>try:<br>    5/0<br><br>except:<br>    logging.error(&#39;Exception occured&#39;, exc_info=True)</pre><p><strong><em>Output-2:</em></strong></p><pre>ERROR:root:Exception occured<br>Traceback (most recent call last):<br>  File &quot;&lt;ipython-input-2-933e0f6b1879&gt;&quot;, line 11, in &lt;module&gt;<br>    5/0<br>ZeroDivisionError: division by zero</pre><p><strong><em>Example-3: with logging.exception</em></strong></p><pre>try:<br>    5/0<br><br>except:<br>    logging.exception(&#39;Exception occured&#39;)</pre><p><strong><em>Output-3:</em></strong></p><pre>ERROR:root:Exception occured<br>Traceback (most recent call last):<br>  File &quot;&lt;ipython-input-3-e7d1d57e6056&gt;&quot;, line 11, in &lt;module&gt;<br>    5/0<br>ZeroDivisionError: division by zero</pre><h4>Conclusion</h4><p>I hope you were able to understand the basics of Logging in Python. Using this article, you can start using logging for any application for various purposes such as debugging, usage monitoring, and performance monitoring. You can refer to the <a href="https://docs.python.org/3/library/logging.html">official documentation</a> for the complete list of available methods.</p><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4><strong>Resources</strong></h4><p>The code snippets used in this article are available on my <a href="https://jimit105.github.io/medium-articles/Introduction%20to%20Logging%20in%20Python.html">GitHub page</a>.</p><h4>References</h4><ul><li><a href="https://docs.python.org/3/library/logging.html">https://docs.python.org/3/library/logging.html</a></li><li><a href="https://docs.python.org/3/howto/logging.html">https://docs.python.org/3/howto/logging.html</a></li></ul><h4>Let’s Connect</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1415d0b8141" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/logging-in-python-a1415d0b8141">Introduction to Logging in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 PyTorch functions for your next Machine Learning project]]></title>
            <link>https://medium.com/data-science/useful-pytorch-functions-356de5f31a1e?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/356de5f31a1e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Thu, 28 May 2020 14:46:47 GMT</pubDate>
            <atom:updated>2025-02-04T19:04:17.977Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Machine Learning</h4><h4>Exploring various PyTorch Functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*yfMzZipUVEITSGagEIxQHQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/geralt-9301/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1995786">Gerd Altmann</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1995786">Pixabay</a></figcaption></figure><p>PyTorch is a Machine Learning library with increasing popularity. In this article, we will explore seven functions available in PyTorch.</p><p>First, we will import PyTorch using import torch</p><h4>Function 1: torch.linspace</h4><p>torch.linspace is used to create a 1D equally spaced tensor between the values start and end . We can specify the size of the tensor with the steps parameters. The default is steps=100</p><p><strong><em>Example-1:</em></strong></p><pre>torch.linspace(1, 10)</pre><pre><strong>Output:</strong><br>tensor([ 1.0000, 1.0909, 1.1818, 1.2727, 1.3636, 1.4545, 1.5455, 1.6364, 1.7273, 1.8182, 1.9091, 2.0000, 2.0909, 2.1818, 2.2727, 2.3636, 2.4545, 2.5455, 2.6364, 2.7273, 2.8182, 2.9091, 3.0000, 3.0909, 3.1818, 3.2727, 3.3636, 3.4545, 3.5455, 3.6364, 3.7273, 3.8182, 3.9091, 4.0000, 4.0909, 4.1818, 4.2727, 4.3636, 4.4545, 4.5455, 4.6364, 4.7273, 4.8182, 4.9091, 5.0000, 5.0909, 5.1818, 5.2727, 5.3636, 5.4545, 5.5455, 5.6364, 5.7273, 5.8182, 5.9091, 6.0000, 6.0909, 6.1818, 6.2727, 6.3636, 6.4545, 6.5455, 6.6364, 6.7273, 6.8182, 6.9091, 7.0000, 7.0909, 7.1818, 7.2727, 7.3636, 7.4545, 7.5455, 7.6364, 7.7273, 7.8182, 7.9091, 8.0000, 8.0909, 8.1818, 8.2727, 8.3636, 8.4545, 8.5455, 8.6364, 8.7273, 8.8182, 8.9091, 9.0000, 9.0909, 9.1818, 9.2727, 9.3636, 9.4545, 9.5455, 9.6364, 9.7273, 9.8182, 9.9091, 10.0000])</pre><p><strong><em>Example-2:</em></strong></p><pre>torch.linspace(start=1, end=10, steps=5)</pre><pre><strong>Output:</strong><br>tensor([ 1.0000,  3.2500,  5.5000,  7.7500, 10.0000])</pre><h4>Function 2: torch.eye</h4><p>torch.eye returns a 2D tensor with the values of diagonals as 1 and other values as 0<br>The function expects two parameters — n and m . If m is not specified, then it returns a 2D tensor of size nxn</p><p><strong><em>Example-1:</em></strong></p><pre>torch.eye(n=4, m=5)</pre><pre><strong>Output:<br></strong>tensor([[1., 0., 0., 0., 0.],<br>        [0., 1., 0., 0., 0.],<br>        [0., 0., 1., 0., 0.],<br>        [0., 0., 0., 1., 0.]])</pre><p><strong><em>Example-2:</em></strong></p><pre>torch.eye(n=3)</pre><pre><strong>Output:</strong><br>tensor([[1., 0., 0.],<br>        [0., 1., 0.],<br>        [0., 0., 1.]])</pre><h4>Function 3: torch.full</h4><p>torch.full returns a tensor of size size with the values filled with fill_value <br>The size can be a list or a tuple.</p><p><strong><em>Example-1:</em></strong></p><pre>torch.full(size=(3,2), fill_value=10)</pre><pre><strong>Output:<br></strong>tensor([[10., 10.],<br>        [10., 10.],<br>        [10., 10.]])</pre><p><strong><em>Example-2:</em></strong></p><pre>torch.full(size=[2, 3, 4], fill_value=5)</pre><pre><strong>Output:</strong><br>tensor([[[5., 5., 5., 5.],<br>         [5., 5., 5., 5.],<br>         [5., 5., 5., 5.]],</pre><pre>[[5., 5., 5., 5.],<br>         [5., 5., 5., 5.],<br>         [5., 5., 5., 5.]]])</pre><h4>Function 4: torch.cat</h4><p>torch.cat concatenates a sequence of tensors over the specified dimension dim. All the tensors must be of the same shape</p><p><strong><em>Example-1:</em></strong></p><pre>a = torch.ones(3,2)<br>b = torch.zeros(3,2)<br>torch.cat((a, b)) # default dim=0</pre><pre><strong>Output:<br></strong>tensor([[1., 1.],<br>        [1., 1.],<br>        [1., 1.],<br>        [0., 0.],<br>        [0., 0.],<br>        [0., 0.]])</pre><p><strong><em>Example-2:</em></strong></p><pre>x = torch.full((3,3), fill_value=4)<br>y = torch.full((3,3), fill_value=7)<br>torch.cat((x, y), dim=1)</pre><pre><strong>Output:<br></strong>tensor([[4., 4., 4., 7., 7., 7.],<br>        [4., 4., 4., 7., 7., 7.],<br>        [4., 4., 4., 7., 7., 7.]])</pre><h4>Function 5: torch.take</h4><p>torch.take returns a tensor with the elements of the input tensors at the given indices. The input tensor is treated as a 1D tensor to return the values.</p><p><strong><em>Example-1:</em></strong></p><pre># 1D input Tensor<br>b = torch.tensor([10, 20, 30, 40, 50])<br>torch.take(b, torch.tensor([2]))</pre><pre><strong>Output:</strong><br>tensor([30])</pre><p><strong><em>Example-2:</em></strong></p><pre># 2D input tensor<br>a = torch.tensor([[1, 2, 3],<br>                  [4, 5, 6]])<br>torch.take(a, torch.tensor([3,4]))</pre><pre><strong>Output:<br></strong>tensor([4, 5])</pre><h4>Function 6: torch.unbind</h4><p>torch.unbind removes a tensor dimension along the given dimension dim <br>The default dimension is 0 i.e. dim=0</p><p><strong><em>Example-1:</em></strong></p><pre>a = torch.tensor([[1, 2, 3],<br>                  [4, 5, 6]])<br>torch.unbind(a)</pre><pre><strong>Output:</strong><br>(tensor([1, 2, 3]), tensor([4, 5, 6]))</pre><p><strong><em>Example-2:</em></strong></p><pre>a = torch.tensor([[1, 2, 3],<br>                  [4, 5, 6]])<br>torch.unbind(a, dim=1)</pre><pre><strong>Output:</strong><br>(tensor([1, 4]), tensor([2, 5]), tensor([3, 6]))</pre><h4>Function 7: torch.Tensor.clone</h4><p>torch.Tensor.clone returns a copy of the tensor with the same size and data type.</p><p>When we create a copy of the tensor using x=y , changing one variable also affects the other variable since it points to the same memory location.</p><p>For example,</p><pre>a = torch.tensor([[1., 2.],<br>                  [3., 4.],<br>                  [5., 6.]])<br>b = a<br>a[1,0]=9<br>b</pre><pre><strong>Output:</strong><br>tensor([[1., 2.],<br>        [9., 4.],<br>        [5., 6.]])</pre><p>To avoid this, we can create a deepcopy of the tensor using .clone method.</p><p><strong><em>Example:</em></strong></p><pre>a = torch.tensor([[1., 2.],<br>                  [3., 4.],<br>                  [5., 6.]])<br>b = a.clone()<br>a[1,0]=9<br>b</pre><pre><strong>Output:</strong><br>tensor([[1., 2.],<br>        [3., 4.],<br>        [5., 6.]])</pre><h3>Conclusion</h3><p>In this article, we saw the working of seven functions available in PyTorch. Hope this article helped you understand these functions. There are a number of other useful functions. You can refer to the <a href="https://pytorch.org/docs/stable/index.html">official documentation</a> for the complete list of available functions.</p><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4>References</h4><ul><li><a href="https://pytorch.org/docs/stable/torch.html">https://pytorch.org/docs/stable/torch.html</a></li><li><a href="https://pytorch.org/docs/stable/tensors.html">https://pytorch.org/docs/stable/tensors.html</a></li></ul><h4>Resources</h4><p>The code snippets used in this article are available on my <a href="https://jimit105.github.io/medium-articles/7%20PyTorch%20functions%20for%20your%20next%20Machine%20Learning%20project.html">GitHub Page</a>.</p><h4>Let’s Connect</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=356de5f31a1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/useful-pytorch-functions-356de5f31a1e">7 PyTorch functions for your next Machine Learning project</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scraping Tabular Data with Pandas]]></title>
            <link>https://medium.com/data-science/scraping-tabular-data-with-pandas-python-10cf2a133cbf?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/10cf2a133cbf</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Sun, 24 May 2020 16:57:17 GMT</pubDate>
            <atom:updated>2025-02-04T19:04:37.102Z</atom:updated>
            <content:encoded><![CDATA[<h4>Programming</h4><h4>Web Scraping using Python and Pandas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*RgNuJ_R-7DzaqYvUjOVuKQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/photos/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=731198">Free-Photos</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=731198">Pixabay</a></figcaption></figure><p>Web Scraping is a technique to fetch data from websites. BeautifulSoup and Scrapy are the two widely used libraries in Python to perform Web Scraping. However, working with these libraries can be cumbersome since we need to find the element tags, extract text from them, and then clean the data.</p><p>This article will show guide you to an easy way of extracting tabular data using Pandas. Yes! Pandas!</p><h4><strong>Extracting tables from HTML page</strong></h4><p>For this tutorial, we will extract the details of the Top 10 Billionaires in the world from <a href="https://en.wikipedia.org/wiki/The_World%27s_Billionaires">this Wikipedia Page</a>.</p><p>We will use the <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html">read_html</a> method of Pandas library to read the HTML tables.</p><pre>import pandas as pd<br><br>url = &#39;https://en.wikipedia.org/wiki/The_World%27s_Billionaires&#39;<br><br>df_list = pd.read_html(url)</pre><p>This script returns HTML tables into a list of DataFrame objects.</p><p>Let’s check the total number of tables found:</p><pre>len(df_list)<br><br># Output:<br># 32</pre><p>To access a particular table, simply access that element of the list.<br>For example, df_list[2] will return the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*6QFP4r9NNHKPuKlFKeLx2w.png" /></figure><h4>Set a particular column as an index</h4><p>We can select a particular column to the index of the table by using the index_col parameter.</p><p><strong><em>Example:</em></strong></p><pre>pd.read_html(url, index_col=1)[2]</pre><p>returns the following table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*VuTBmdbcfdxvkkJJbXG1Tg.png" /></figure><h4>Return tables containing a string or regex</h4><p>We can also specify to return the list of tables containing a particular string or a regular expression by using the match parameter.</p><p><strong><em>Example:</em></strong></p><pre>pd.read_html(url, match=&#39;Number and combined net worth of billionaires by year&#39;)[0].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*vjfpdaGMhUdPlGAi1DW8LQ.png" /></figure><h4>Specify strings to recognize as NA/NaN</h4><p>We can specify the list of strings to recognize as NA/NaN by using the na_values parameter.</p><p><strong><em>Example:</em></strong></p><ul><li>without specifying na_values :</li></ul><pre>pd.read_html(url)[0].tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*BZUGoqpyyZ1zjv7bFSI56A.png" /><figcaption>without specifying na_values</figcaption></figure><ul><li>after specifying na_values :</li></ul><pre>pd.read_html(<br>    url, <br>    na_values=[&quot;Forbes: The World&#39;s Billionaires website&quot;]<br>    )[0].tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*M5F7drAHnqGjadIxY64UNw.png" /><figcaption>after specifying na_values</figcaption></figure><h4>Other Parameters</h4><ul><li>skiprows parameter allows us to skip the starting ‘n’ rows</li><li>header parameter can be used to make the specified row as the column header</li></ul><p><strong><em>Example:</em></strong></p><pre>pd.read_html(url, skiprows=3, header=0)[0].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*cTZy4uv1CHDoFL2hV2A_5w.png" /></figure><h3>Conclusion</h3><p>In this article, we learned how to easily scrape HTML tables from pages using the read_html method. Also, we learned some of the important parameters which can further help us in scraping the desired table.</p><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4>References</h4><ul><li><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html">https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_html.html</a></li></ul><h4>Resources</h4><p>The code snippets used in this article are available on my <a href="https://jimit105.github.io/medium-articles/Scraping%20Tabular%20Data%20with%20Pandas.html">GitHub page</a>.</p><h4>Let’s Connect</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10cf2a133cbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/scraping-tabular-data-with-pandas-python-10cf2a133cbf">Scraping Tabular Data with Pandas</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub URL Shortener]]></title>
            <link>https://medium.com/data-science/github-url-shortener-f1e0aeaf83b6?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1e0aeaf83b6</guid>
            <category><![CDATA[git-io]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[url-shorteners]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Thu, 21 May 2020 17:22:17 GMT</pubDate>
            <atom:updated>2025-02-04T19:05:03.792Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Tips &amp; Tricks</h4><h4>URL Shortener for GitHub.com using curl and Python</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*f-oEsqIWHJea8zII7wIVJQ.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/suju-165106/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4088111">Susanne Jutzeler, suju-foto</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=4088111">Pixabay</a></figcaption></figure><p>GitHub is the most popular Git repository hosting service for source codes. However, the URLs can get pretty long since we might have long names for repositories and files. Also, it will look messy when we need to share the URLs with others, on email and social networks.</p><p>Short URLs look much better when we need to share the projects with colleagues. GitHub has provided a service to turn these long, messy URLs into shorter, cleaner URLs. The answer is <a href="https://git.io/">git.io</a>.</p><p>Git.io is a service provided by GitHub to shorten URLs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*P6Q3jnJzgKh-Qh5j3CUGng.png" /></figure><p>To shorten the URLs, simply go to <a href="https://git.io/">https://git.io/</a> and enter your GitHub URL. The URLs can be GitHub repositories and even GitHub Pages URLs.</p><p><em>Note: This URL shortener can only be used for GitHub URLs and not for other URLs.</em></p><h3>Shorten URL using curl</h3><h4>To create shortened URL</h4><p>You can also use the curl command to shorten the URL:</p><pre>curl -i https://git.io -F &quot;url=GITHUB_URL&quot;</pre><p><strong><em>Example:</em></strong></p><pre>curl -i https://git.io -F &quot;url=https://github.com/jimit105/Sentiment-Analysis-of-Movie-Reviews-using-NLP&quot;<br><br>Output:<br>Location: https://git.io/JfzQJ</pre><p>To get a custom shortened URL, pass the custom text with the code parameter</p><pre>curl -i https://git.io -F &quot;url=GITHUB_URL&quot; -F &quot;code=CUSTOM_TEXT&quot;</pre><p><strong><em>Example:</em></strong></p><pre>curl -i https://git.io -F &quot;url=https://github.com/jimit105/Intro-to-Deep-Learning-with-PyTorch&quot; -F &quot;code=pytorch&quot;<br><br>Output:<br>Location: https://git.io/pytorch</pre><p>The shortened URL will appear in the Location field of the response header.</p><p>If you get SSL Error, then pass the --insecure flag along with the command to skip certificate verification.</p><h4>To retrieve the full URL</h4><p>Use the following command to retrieve the complete URL from the shortened URL:</p><pre>curl -i SHORTENED-URL</pre><p><strong><em>Example:</em></strong></p><pre>curl -i https://git.io/JfzQJ<br><br>Output:<br>Location: https://github.com/jimit105/Sentiment-Analysis-of-Movie-Reviews-using-NLP</pre><h3>Shorten URL using Python</h3><p>You can also use the following Python scripts to shorten the URL and to retrieve the complete URL from the shortened URL</p><h4>To create shortened URL</h4><pre>import requests<br><br>url = &#39;https://git.io/&#39;<br>data = {&#39;url&#39;: &#39;https://github.com/jimit105/Intro-to-Deep-Learning-with-PyTorch&#39;, <br>        &#39;code&#39;: &#39;pytorch&#39;}<br><br>r = requests.post(url, data=data)<br>print(r.headers.get(&#39;Location&#39;))<br><br># Output:<br># https://git.io/pytorch</pre><p>If you get SSLError while running the above script, add the parameter verify=False in the requests.post method to skip certificate validation.</p><h4>To retrieve the full URL</h4><pre>import requests<br><br>r = requests.head(&#39;https://git.io/pytorch&#39;)<br>print(r.headers.get(&#39;Location&#39;))<br><br># Output:<br># https://github.com/jimit105/Intro-to-Deep-Learning-with-PyTorch</pre><p><strong>Note:</strong> You can create only one shortened URL for each URL. You cannot create another shortened URL if that GitHub URL has already been shortened. If you try to shorten the same URL again, it will return the existing shortened URL.</p><h4>Conclusion</h4><p>In this article, we saw how we can use git.io to shorten GitHub’s URLs. This service is exclusive for GitHub websites i.e. you can only shorten GitHub URLs and not any other. So when you share the shortened URL with others, they can trust that the link will point to a GitHub website (just like g.co is Google’s official URL shortener for Google websites which will take you to a Google product or service).</p><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4>References</h4><ul><li><a href="https://github.blog/2011-11-10-git-io-github-url-shortener/">https://github.blog/2011-11-10-git-io-github-url-shortener/</a></li></ul><h4>Resources</h4><p>All the code snippets used in this article are available on my <a href="https://jimit105.github.io/medium-articles/GitHub%20URL%20Shortener.html">GitHub Page</a>.</p><h4>Let’s Connect</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1e0aeaf83b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/github-url-shortener-f1e0aeaf83b6">GitHub URL Shortener</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Python APIs with Flask, Flask-RESTPlus and Swagger UI]]></title>
            <link>https://medium.com/analytics-vidhya/swagger-ui-dashboard-with-flask-restplus-api-7461b3a9a2c8?source=rss-5450f46b772d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7461b3a9a2c8</guid>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[flask-restplus]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jimit Dholakia]]></dc:creator>
            <pubDate>Wed, 06 May 2020 19:14:25 GMT</pubDate>
            <atom:updated>2025-02-04T19:05:28.543Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Programming</h4><h3>Building Python APIs with Flask, Flask-RESTPlus / Flask-RESTX, and Swagger UI</h3><h4>How to build an interactive API dashboard in Python?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qNObOeuqBv9nsFvuA2MWfA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@paytonctuttle?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Payton Tuttle</a> on <a href="https://unsplash.com/s/photos/laptop-book?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>What is Swagger UI?</h3><p>Swagger UI is a tool to visualize and interact with APIs which is automatically generated using the OpenAPI specification. It generates a webpage that helps us to document and interact with various APIs.</p><h3>What is Flask-RESTPlus?</h3><p>Flask-RESTPlus is an extension for Flask which encourages best practices with minimal setup. It provides a collection of decorators and tools to describe API and expose its documentation using Swagger.</p><blockquote><strong>Note:</strong> Flask-RESTPlus is no longer maintained. Consider using <a href="https://flask-restx.readthedocs.io/en/latest/index.html">Flask-RESTX</a>, a fork of Flask-RESTPlus</blockquote><h3>Installation</h3><p>You can install <a href="https://flask-restplus.readthedocs.io/">Flask-RESTPlus</a> with pip</p><pre>pip install flask-restplus</pre><p>Or install <a href="https://flask-restx.readthedocs.io/en/latest/index.html">Flask-RESTX</a> using pip (recommended):</p><pre>pip install flask-restx</pre><h3>Minimal API</h3><pre>from flask import Flask<br>from flask_restplus import Api, Resource<br><br>app = Flask(__name__)<br>api = Api(app)<br><br>@api.route(&#39;/hello/&#39;)<br>class HelloWorld(Resource):<br>    def get(self):<br>        return &quot;Hello World&quot;<br>    <br>if __name__ == &#39;__main__&#39;:<br>    app.run()</pre><blockquote><strong>Note:</strong> If you are using Flask-RESTX then change the import from flask_restplus import Api, Resource to from flask_restx import Api, Resource. The rest of the code remains the same.</blockquote><p>Save this file as app.py <em>(or any other filename you want)</em>, go to the terminal, and type python app.py (i.e. python &lt;filename&gt;.py) to start the program.</p><p>If you get the following error while deploying:</p><pre>from werkzeug import cached_property<br>ImportError: cannot import name &#39;cached_property&#39;</pre><p>Add this line before importing flask_restplus:</p><pre>import werkzeug<br>werkzeug.cached_property = werkzeug.utils.cached_property</pre><p>Now, launch a browser and go to http://localhost:5000 and you should see this screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnNBsvokfRnrChioj3umxw.png" /></figure><p>This is the Swagger UI screen. It allows you to view all the endpoints and test the APIs using the <strong>Try it out </strong>button.</p><p>You can also view the contents of the Swagger file by visiting http://localhost:5000/swagger.json. The Swagger file generated for the above code is as follows:</p><pre>{<br>    &quot;swagger&quot;: &quot;2.0&quot;,<br>    &quot;basePath&quot;: &quot;/&quot;,<br>    &quot;paths&quot;: {<br>        &quot;/hello/&quot;: {<br>            &quot;get&quot;: {<br>                &quot;responses&quot;: {<br>                    &quot;200&quot;: {<br>                        &quot;description&quot;: &quot;Success&quot;<br>                    }<br>                },<br>                &quot;operationId&quot;: &quot;get_hello_world&quot;,<br>                &quot;tags&quot;: [<br>                    &quot;default&quot;<br>                ]<br>            }<br>        }<br>    },<br>    &quot;info&quot;: {<br>        &quot;title&quot;: &quot;API&quot;,<br>        &quot;version&quot;: &quot;1.0&quot;<br>    },<br>    &quot;produces&quot;: [<br>        &quot;application/json&quot;<br>    ],<br>    &quot;consumes&quot;: [<br>        &quot;application/json&quot;<br>    ],<br>    &quot;tags&quot;: [<br>        {<br>            &quot;name&quot;: &quot;default&quot;,<br>            &quot;description&quot;: &quot;Default namespace&quot;<br>        }<br>    ],<br>    &quot;responses&quot;: {<br>        &quot;ParseError&quot;: {<br>            &quot;description&quot;: &quot;When a mask can&#39;t be parsed&quot;<br>        },<br>        &quot;MaskError&quot;: {<br>            &quot;description&quot;: &quot;When any error occurs on mask&quot;<br>        }<br>    }<br>}</pre><h3>Fetching Request Parameters</h3><p>You can fetch the parameters passed during the API call using reqparse</p><pre>from flask import Flask<br>from flask_restplus import Api, Resource, reqparse<br><br>app = Flask(__name__)<br>api = Api(app)<br><br>parser = reqparse.RequestParser()<br>parser.add_argument(&#39;name&#39;, help=&#39;Specify your name&#39;)<br><br>@api.route(&#39;/hello/&#39;)<br>class HelloWorld(Resource):<br>    @api.doc(parser=parser)<br>    def get(self):        <br>        args = parser.parse_args()<br>        name = args[&#39;name&#39;]<br>        return &quot;Hello &quot; + name<br>    <br>if __name__ == &#39;__main__&#39;:<br>    app.run()</pre><p>In the above code, parser.parse_args() returns a dictionary with the key as the argument&#39;s name and value as the value passed in the query.</p><p>This generates the Swagger UI as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2egoYJoZMh9-f3Vf86UAfg.png" /></figure><p>Click on the <strong>Try it out</strong> button to check the API. It will result in the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKNXRcS0KWe3spdpvLflkg.png" /></figure><h3>File Upload</h3><p>To use File Upload, set the location to files and type to FileStorage</p><pre>from flask import Flask<br>from flask_restplus import Api, Resource<br>from werkzeug.datastructures import FileStorage<br><br>app = Flask(__name__)<br>api = Api(app)<br><br>upload_parser = api.parser()<br>upload_parser.add_argument(&#39;file&#39;, <br>                           location=&#39;files&#39;,<br>                           type=FileStorage)<br><br>@api.route(&#39;/upload/&#39;)<br>@api.expect(upload_parser)<br>class UploadDemo(Resource):<br>    def post(self):<br>        args = upload_parser.parse_args()<br>        file = args.get(&#39;file&#39;)<br>        print(file.filename)<br>        return &quot;Uploaded file is &quot; + file.filename<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run()</pre><p>The Swagger UI generated for the above code will be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZOXhN-C3zixr2u0et-P6A.png" /></figure><h3>API parameters</h3><pre>api = Api(app,<br>          version=&#39;10.5&#39;,<br>          title=&#39;Flask Restplus Demo&#39;,<br>          description=&#39;Demo to show various API parameters&#39;,<br>          license=&#39;MIT&#39;,<br>          contact=&#39;Jimit Dholakia&#39;,<br>          contact_url=&#39;https://in.linkedin.com/in/jimit105&#39;,<br>          doc = &#39;/docs/&#39;,<br>          prefix=&#39;/test&#39;<br>          )</pre><p>version → API Version (for Swagger Documentation)</p><p>title → API title (for Swagger Documentation)</p><p>description → API Description (for Swagger Documentation)</p><p>license → Specify License for the API (for Swagger Documentation)</p><p>license_url → Specify the License page URL (for Swagger Documentation)</p><p>contact → Specify contact person (for Swagger Documentation)</p><p>contact_email → Specify the email address of contact person (for Swagger Documentation)</p><p>contact_url → Specify URL to contact person (for Swagger Documentation)</p><p>doc → Specify the path for Swagger UI Documentation. Defaults to &#39;/&#39;</p><p>prefix → Specify a prefix for all endpoints of the URL</p><p>The Swagger UI generated for the above code is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*dT5Up8teEqrUPQSSLY5ecA.png" /></figure><p><strong>Subscribe to my newsletter:</strong> <a href="https://jimit105.medium.com/subscribe">https://jimit105.medium.com/subscribe</a></p><h4>References</h4><ul><li><a href="https://flask-restplus.readthedocs.io/en/stable/">https://flask-restplus.readthedocs.io/en/stable/</a></li><li><a href="https://flask-restplus.readthedocs.io/en/stable/index.html">https://flask-restplus.readthedocs.io/en/stable/index.html</a></li><li><a href="https://flask-restx.readthedocs.io/en/latest/index.html">https://flask-restx.readthedocs.io/en/latest/index.html</a></li></ul><h4>Resources</h4><p>All the code snippets of this article are available on my <a href="https://jimit105.github.io/medium-articles/Building%20Python%20APIs%20with%20Flask,%20Flask-RESTPlus%20and%20Swagger%20UI.html">GitHub Page</a>.</p><h4>Suggested Reading</h4><p><a href="https://medium.com/p/655bad51b24">Creating RESTful Web APIs using Flask and Python</a></p><h4>Let’s Connect</h4><p>LinkedIn: <a href="https://www.linkedin.com/in/jimit105/">https://www.linkedin.com/in/jimit105/</a><br>GitHub: <a href="https://github.com/jimit105">https://github.com/jimit105</a><br>Twitter: <a href="https://twitter.com/jimit105">https://twitter.com/jimit105</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7461b3a9a2c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/swagger-ui-dashboard-with-flask-restplus-api-7461b3a9a2c8">Building Python APIs with Flask, Flask-RESTPlus and Swagger UI</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>