<?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 Muskan Modi on Medium]]></title>
        <description><![CDATA[Stories by Muskan Modi on Medium]]></description>
        <link>https://medium.com/@modimuskan397?source=rss-76b587ab08b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*V_ZE-xtORbqFvXCK</url>
            <title>Stories by Muskan Modi on Medium</title>
            <link>https://medium.com/@modimuskan397?source=rss-76b587ab08b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:07:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@modimuskan397/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[AI Isn’t Magic: A Beginner’s Guide to Understanding AI — What the Heck is AI ?]]></title>
            <link>https://medium.com/@modimuskan397/ai-isnt-magic-a-beginner-s-guide-to-understanding-ai-what-the-heck-is-ai-b1b4992ab727?source=rss-76b587ab08b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1b4992ab727</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-for-beginners]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Muskan Modi]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 12:04:59 GMT</pubDate>
            <atom:updated>2026-08-18T12:04:59.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4oDoq-PVQ51C9LldFOhBg.png" /></figure><p>AI seems to be the buzzword everywhere.</p><p>Back in 2022, when I was job hunting, there were relatively limited job roles specifically focused on AI. Fast-forward a few years, and almost every company wants to integrate AI into its workflow. We have AI-powered products everywhere, courses promising to make us “AI-ready,” and endless tips and hacks on how to increase our productivity with AI.</p><p>But what actually is AI?</p><p>Is it some kind of magic where we tell a computer what to do… and it simply does it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*8aMX7cS9Rjcysynt" /><figcaption>Image Source: Instagram</figcaption></figure><p>How does it work behind the scenes? And, more importantly, what do we actually need to understand about it to make good use of it?</p><p>This blog is meant to answer some of the most basic questions about AI and give you a mental map of how the different pieces fit together.</p><p>We won’t be diving into complicated mathematics or writing neural networks from scratch just yet.</p><p>Think of this as <strong>AI 101</strong>.</p><h3>Is AI new?</h3><p>First of all, <strong>AI is not new.</strong></p><p>In fact, the term <em>Artificial Intelligence</em> was coined in 1956, when a group of researchers gathered at the Dartmouth Summer Research Project on Artificial Intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wb4-iw2bI9CFvBqm4va1hQ.png" /></figure><p>That’s about 70 years ago.</p><p>So what changed?</p><p>The technology, computing power, amount of available data, and algorithms have evolved tremendously. What has changed most visibly in the last few years is not the existence of AI itself, but the <strong>scale and accessibility of AI</strong>.</p><p>AI research has existed for decades. We have had expert systems, rule-based systems, neural networks, machine learning algorithms, recommendation systems, speech recognition, computer vision and much more.</p><p>So why does it suddenly feel like AI appeared overnight?</p><p>Because we have reached a point where incredibly powerful AI systems are available to almost everyone.</p><p>You don’t need to be a researcher anymore.</p><p>You can simply open ChatGPT, Claude, Gemini or another AI application and start interacting with a model using natural language.</p><p>And that brings us to an important question:</p><p><strong>What exactly is AI?</strong></p><h3>AI is an umbrella term</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cF8jI5L0ly6m36_MkFfBBQ.png" /></figure><p>One of the first things I want you to remember is:</p><blockquote><strong><em>AI is not the same thing as ChatGPT.</em></strong></blockquote><p>And AI is not the same thing as Machine Learning either.</p><p>Artificial Intelligence is a broad field concerned with building systems that can perform tasks that we associate with <strong>human intelligence</strong> — such as understanding language, recognising patterns, making decisions, solving problems, perceiving the world and generating content.</p><p>There are many different approaches to building AI systems.</p><p>Machine Learning is one of those approaches.</p><p>Deep Learning is a subset of Machine Learning.</p><p>And modern systems such as large language models are built using many of these ideas together.</p><p>A simplified way of looking at the modern AI landscape is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWxJ7uDcLlAWzoe2JNkOSA.png" /></figure><p>This is not a perfect hierarchy — AI is much broader than this — but it gives us a useful starting point for understanding how we got from traditional AI to the systems we use today.</p><p>So let’s imagine AI as if it were growing up.</p><h3>The Foundations: What is AI built on?</h3><p>Before we get to the “baby,” let’s talk about its foundations.</p><p>At the core of modern AI are <strong>mathematical models, algorithms and data</strong>.</p><p>Some of the mathematics that becomes important as you go deeper into AI includes:</p><ul><li>Probability and Statistics</li><li>Linear Algebra</li><li>Matrices</li><li>Calculus</li><li>Optimization</li><li>Discrete Mathematics</li></ul><p>And then there is something arguably even more important:</p><p><strong>Data.</strong></p><p>The AI systems we use today learn patterns from enormous amounts of data.</p><p>Whether the system is learning to identify an object in an image, predict whether a transaction might be fraudulent, recommend a product, or generate a paragraph of text, there are mathematical operations happening underneath the interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*UNQQET5Js83MZm-3.jpg" /><figcaption>Image source: <a href="https://blog.jetbrains.com/wp-content/uploads/2022/01/dog.jpg">https://blog.jetbrains.com/wp-content/uploads/2022/01/dog.jpg</a></figcaption></figure><p>It may look like magic from the outside.</p><p>Underneath, it is a lot of numbers, mathematical operations, algorithms and learned patterns.</p><p>Of course, there is much more to AI than mathematics. AI also has deep roots in computer science, algorithms, logic, linguistics, neuroscience and other fields.</p><p>But mathematics and data are two of the most important foundations of modern AI.</p><h3>AI as a Baby: Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5sDhg5QaIRslaK0ess-VQ.png" /></figure><p>Now let’s imagine that AI is a baby.</p><p>The baby doesn’t know everything when it is born.</p><p>It has to <strong>learn from experience</strong>.</p><p>This is where Machine Learning comes in.</p><p>Machine Learning is a way of building systems that <strong>learn patterns from data and use those learned patterns to make predictions, classifications, recommendations or decisions on new data.</strong></p><p>Instead of explicitly programming every possible rule, we provide the system with data and allow an algorithm to learn useful patterns from it.</p><p>For example, imagine an online shopping company.</p><p>Instead of manually writing rules for every possible customer, the company could use machine learning to analyse historical data and answer questions such as:</p><ul><li>Which products are selling the most in a particular region?</li><li>Which customers are likely to buy a particular product?</li><li>Which customers behave similarly and can be grouped into different segments?</li><li>Does a transaction look suspicious enough to be potentially fraudulent?</li><li>What factors are associated with higher or lower risk?</li></ul><p>These predictions and patterns can help businesses make better decisions, improve their operations, reduce risk and ultimately increase their profits.</p><p>And Machine Learning isn’t limited to predicting the future.</p><p>It can also be used to <strong>find patterns that we didn’t explicitly know were there.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*BAdPIsTUP1WKK2VeP3fuOA.png" /></figure><p>For example, if we give an algorithm information about thousands of customers, it may discover groups of customers with similar behaviours. This is commonly known as <strong>customer segmentation</strong>.</p><p>We’ll explore the different types of Machine Learning in much more detail later in this series.</p><p>For now, remember:</p><blockquote><strong><em>Machine Learning allows computers to learn patterns from data instead of relying entirely on explicitly programmed rules.</em></strong></blockquote><h3>AI as a Toddler: Deep Learning</h3><p>Our AI baby has grown a little.</p><p>Now comes <strong>Deep Learning</strong>.</p><p>A simple way to think about it is:</p><blockquote><strong><em>Machine Learning, but with a much more powerful pattern-learning system.</em></strong></blockquote><p>Deep Learning is a branch of Machine Learning that uses <strong>multi-layered artificial neural networks</strong> to learn complex patterns from data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*pVWb2oEwlBrIEBu6tiDFdA.png" /><figcaption>A small neural network</figcaption></figure><p>You may have heard the term <em>neural network</em> before.</p><p>Neural networks were partly inspired by the way biological neurons are organised, which is why we use terms like “neurons” and “layers.”</p><p>But don’t take the analogy too literally.</p><p>A modern neural network is not a digital recreation of the human brain. It is a mathematical model made up of interconnected computational units that can learn useful patterns from data.</p><p>Deep Learning became particularly powerful as we gained access to:</p><ul><li>enormous datasets,</li><li>more powerful GPUs and other computing hardware,</li><li>and better training techniques.</li></ul><p>It is now heavily used in areas such as:</p><p><strong>Computer Vision</strong> — understanding images and video.</p><p><strong>Natural Language Processing (NLP)</strong> — working with human language.</p><p><strong>Speech and Audio</strong> — recognising and generating spoken language and other sounds.</p><p>And many other applications.</p><p>So if Machine Learning is our AI baby learning from examples, Deep Learning is the stage where it has developed a much more sophisticated ability to learn complex patterns.</p><h3>Transformers: The Architecture That Changed Modern AI</h3><p>Now we reach one of the most important developments in modern AI.</p><p><strong>Transformers.</strong></p><p>In 2017, researchers introduced a new neural network architecture called the <strong>Transformer</strong> in a paper titled <em>Attention Is All You Need</em>.</p><p>The important idea behind Transformers was <strong>attention</strong>.</p><p>Very simply, attention allows a model to determine which parts of an input are more relevant to understanding another part of the input.</p><p>Think about this sentence:</p><blockquote><em>“Muskan put the laptop on the table because it was getting hot.”</em></blockquote><p>To understand what “it” refers to, you need to consider the relationship between different words in the sentence.</p><p>Transformers introduced a powerful way for neural networks to model these relationships.</p><p>They also made it much easier to process many parts of a sequence in parallel during training, which was extremely important as models began to scale.</p><p>This architecture became one of the key building blocks behind modern language models.</p><p>And this is where things start getting interesting.</p><p>Because once we combine powerful neural network architectures, enormous datasets and massive amounts of computing power, we can train something much larger.</p><h3>Foundation Models and Large Language Models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mCKWH599_X3wEP8YLeEXg.png" /></figure><p>Before jumping straight to ChatGPT, there’s another concept worth knowing:</p><p><strong>the model.</strong></p><p>Think of a model as a mathematical system that has learned patterns from data and can use those learned patterns to produce an output.</p><p>When you open ChatGPT and type a question, the ChatGPT application is the interface you’re interacting with.</p><p>Underneath that interface is a trained AI model.</p><p>Some modern AI models are trained on such broad datasets and at such large scales that they can be adapted to perform many different tasks. These are often referred to as <strong>foundation models</strong>.</p><p>A Large Language Model, or <strong>LLM</strong>, is a type of model designed primarily around understanding and generating language.</p><p>And this brings us to Generative AI.</p><h3>Finally: Generative AI</h3><p>Generative AI, or <strong>GenAI</strong>, is pretty much what the name suggests.</p><p>It refers to AI systems capable of <strong>generating new content</strong>.</p><p>That content could be:</p><ul><li>Text</li><li>Images</li><li>Audio</li><li>Music</li><li>Video</li><li>Code</li></ul><p>This is the technology behind many of the AI applications that have become popular in recent years.</p><p>Different types of generative models use different techniques.</p><p>For Large Language Models such as GPT, however, one of the fundamental ideas is <strong>next-token prediction</strong>. The model receives the tokens that came before and predicts what token is likely to come next.</p><p>For example, imagine the model receives:</p><blockquote><em>“The capital of France is…”</em></blockquote><p>It assigns probabilities to possible next tokens.</p><p>“<strong>Paris</strong>” would have a very high probability.</p><p>The model selects a token, adds it to the sequence, and then predicts the next one. And it keeps doing this, one token at a time, until it has generated the response. This sounds almost ridiculously simple.</p><p>And yet, when you scale this idea up using enormous datasets, billions or even trillions of parameters, powerful neural network architectures and huge amounts of computation…</p><p>You get systems capable of writing essays, explaining programming concepts, summarising documents, analysing data, translating languages and much more.</p><p>We’ll take apart this “simple” next-token prediction mechanism later in the series.</p><h3>So where does ChatGPT fit?</h3><p>Let’s put everything together.</p><p>When you use ChatGPT, you aren’t “using AI” in some abstract sense.</p><p>You’re interacting with an <strong>AI application</strong> that uses one or more trained models underneath it.</p><p>Those models are based on machine learning.</p><p>Modern language models rely heavily on deep learning.</p><p>Many of them are based on Transformer architectures.</p><p>And language models are trained to learn patterns from huge amounts of data, with next-token prediction being a fundamental training objective for many autoregressive language models.</p><p>So:</p><p><strong>AI</strong> → the broad field</p><p><strong>Machine Learning</strong> → a major approach to building AI</p><p><strong>Deep Learning</strong> → machine learning using multi-layer neural networks</p><p><strong>Transformers</strong> → a powerful neural network architecture</p><p><strong>Foundation Models / LLMs</strong> → large pretrained models capable of performing many tasks</p><p><strong>Generative AI</strong> → AI capable of generating new content</p><p><strong>ChatGPT / Claude / Gemini</strong> → applications that let us interact with powerful AI models</p><p>Now the whole AI landscape should hopefully feel a little less intimidating.</p><h3>Training vs. Using AI</h3><p>There is one more distinction that is important before we move on.</p><p><strong>Training a model is not the same as using a model.</strong></p><p>Before you ever type a prompt into ChatGPT, the underlying model has already gone through a training process.</p><p>During training, the model processes enormous amounts of data and adjusts its internal parameters to learn useful patterns.</p><p>Once the model has been trained, you can give it an input — such as a question or a prompt — and ask it to generate an output.</p><p>This stage is generally called I<strong>nference</strong>.</p><p>A very simplified version of the process looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGrZo4Vo4i7vii7FZAIPYw.png" /></figure><p>This basic pipeline is going to appear again and again throughout this series.</p><h3>And what about prompting?</h3><p>Now we come to the part most people interact with directly:</p><p><strong>Prompting.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9Q49eQ3hQyBHhRBGlyz6w.png" /></figure><p>A prompt is essentially the instruction, question, context or information that you provide to an AI model.</p><p>For example:</p><blockquote><em>“Explain photosynthesis.”</em></blockquote><p>That’s a prompt.</p><p>But you could give the model more context:</p><blockquote><em>“I’m a high-school student preparing for an exam. Explain photosynthesis in simple language, using an analogy and ending with five questions I can use to test myself.”</em></blockquote><p>The second prompt gives the model much more information about:</p><ul><li>who you are</li><li>what you want</li><li>how you want the answer explained</li><li>and what format you want the result in.</li></ul><p>A well-structured prompt can significantly improve the quality and consistency of an AI’s response.</p><p>But there’s an important lesson here:</p><blockquote><strong><em>A longer prompt is not necessarily a better prompt.</em></strong></blockquote><p>The goal isn’t to throw as many words at the model as possible.</p><p>The goal is to give it enough <strong>context, instructions, constraints and examples</strong> to understand what you actually want.</p><p>We’ll explore prompting properly in the next part of this series, because knowing how to communicate with AI is becoming an increasingly useful skill.</p><h3>So… is AI magic?</h3><p>No.</p><p>But I can understand why it feels like it.</p><p>We have built systems that can look at an image and describe it, listen to speech and transcribe it, write code, generate an image from a sentence, analyse a document, or have a conversation with us.</p><p>From the outside, it can look almost magical.</p><p>But underneath that interface are:</p><p><strong>Data. Mathematics. Algorithms. Neural networks.</strong></p><p><strong>Models. Training. Inference.</strong></p><p>And a <em>lot</em> of computation.</p><p>The more we understand what is happening underneath, the less mysterious AI becomes.</p><p>And that’s exactly where we’re going next.</p><p>. . .</p><p>Thank you for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1b4992ab727" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Cleaner, Efficient Code — Part 2: Understanding Decorators]]></title>
            <link>https://medium.com/@modimuskan397/how-to-write-cleaner-efficient-code-part-2-understanding-decorators-5fd211465f2c?source=rss-76b587ab08b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fd211465f2c</guid>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[advance-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Muskan Modi]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 10:07:35 GMT</pubDate>
            <atom:updated>2025-08-08T10:07:35.741Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Write Cleaner, Efficient Code — Part 2: Understanding Decorators</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igOE7YOTDJnL-aXZaerksg.png" /></figure><p>In the last part of this series, we learned that it’s not enough to just write code that works — we also need to write <strong>clean, efficient, and readable code</strong>. Code that not only functions well but can also be understood and reused easily.</p><p>This idea of being <strong>clear and concise</strong> doesn’t just apply to coding. It’s important in many fields — writing, advertising, teaching — anywhere you need to communicate your ideas clearly and effectively.</p><p>Now, in this part of the series, let’s dive into a very cool and powerful Python concept: <strong>Decorators</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aACQcblxAl9TmsKFTlc26w.png" /></figure><h3>What Are Decorators?</h3><p>At their core, <strong>decorators are functions that accept another function as an argument and return a new function (called a wrapper)</strong>. They’re used to <em>extend or modify</em> the behavior of an existing function — without actually changing its core logic.</p><h3>A Bluetooth Speaker Analogy 🎵</h3><p>Imagine you’re holding your favorite thing in the world — your phone. (Honestly, I think my phone knows me better than most people.)</p><p>Now, you want to dance to a song from your ultimate banger playlist. But your phone’s built-in speaker just doesn’t have the power.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asQ24WC8xJPBgAxLZJbIGg.png" /></figure><p>You have two options:</p><ol><li><strong>Take your phone to a technician</strong> and ask them to open it up and install a tiny but powerful speaker.</li><li><strong>Connect it to a Bluetooth speaker</strong> — easy, non-invasive, and instantly loud.</li></ol><p>What do you pick? Obviously option 2.</p><p>That’s exactly what a decorator does. You don’t touch the original phone (or function), but you extend its capability (make it louder, better) by wrapping it with something external.</p><h3>Why Use Decorators?</h3><p>Decorators are incredibly useful when:</p><ul><li>You want to add some functionality temporarily without modifying the actual function.</li><li>You want to apply the same logic to multiple functions (e.g., timing, logging) without repeating code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*huVzD4OmV8tNCo0z2l-O1w.png" /></figure><p>Here are some real-world use cases:</p><ul><li><strong>Performance Monitoring</strong>: Measure how long each function takes.</li><li><strong>Logging</strong>: Automatically log inputs, outputs, and errors.</li><li><strong>Caching</strong>: Save results of expensive function calls to avoid repeating them.</li><li><strong>Attribute Management</strong>: Dynamically add or update attributes of functions.</li></ul><p><strong>A Quick Example (Without Decorators)</strong></p><p><strong>multiply.py</strong></p><pre>from add import Add<br>class Multiply:<br>    def print_stuff(self):<br>        print(&quot;Heyy! this is line 4 of multiply.py. Just checking if this is used&quot;)<br><br>    def multiply_2_variables(self, x,y):<br>        z = x*y<br>        return z<br><br>if __name__ == &quot;__main__&quot;:<br>    multiply_obj = Multiply()<br>    add_obj = Add()<br><br>    x = 4<br>    y = 5<br>    z = multiply_obj.multiply_2_variables(x,y)<br>    print(f&quot;Multiplication: {z}&quot;)<br>    c = add_obj.add_2_variables(x,y)<br>    print(f&quot;Addition: {c}&quot;)<br><br>    print(&quot;This is line 19 of multiply.py. Multiplication finished&quot;)</pre><pre>class Add:<br><br>    def print_stuff(self):<br>        print(&quot;Heyyy! this is line 2 of add.py. Just checking if this is executed&quot;)<br><br>    def add_2_variables(self, a,b):<br>        c = a +b<br>        return c<br><br>if __name__ == &quot;__main__&quot;:<br>    add_obj = Add<br>    print(f&quot;\n add_obj: {add_obj}&quot;)<br>    print(f&quot;type_add_obj: {type(add_obj)}&quot;)<br><br>    a = 4<br>    b = 3<br>    c = add_obj.add_2_variables(a,b)<br>    print(f&quot;sum is: {c}&quot;)<br><br>    print(&quot;This is line 12 of add.py. Adding finished&quot;)</pre><p>given above is simple function to multiply 2 given variables</p><p>Now we want to calculate time.</p><ol><li><strong>Brute Force:</strong> Either we can define start_time and end_time at the start and end of each function, and find total time it took from it.</li></ol><pre>from time import time<br><br>def do_something():<br>  <br>  start_time = time.time()<br><br>..... <br><br><br>  end_time = time.time()<br>  print(f&quot;total time taken by do_something function is: {(end_time - start_time).4f} seconds&quot;)<br>  return something</pre><p>Problems with this approach:</p><ul><li>We would have to go and modify each function, which will be costly</li><li>We don’t want to see time logs of each and every function, so it would add additional print logs, which will take up extra IO time.</li></ul><p>2. <strong>Decorators, a better solution</strong>: That is when decorator comes to our rescue. Here’s how we can define a reusable time_it decorator:</p><pre>import time<br><br>from functools import wraps<br><br>def time_it(func):<br>    &quot;&quot;&quot;<br>    A decorator to measure the execution time of a function.<br>    &quot;&quot;&quot;<br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        start_time = time.perf_counter()  # Use perf_counter for precise timing<br>        result = func(*args, **kwargs)<br>        end_time = time.perf_counter()<br>        total_time = end_time - start_time<br>        print(f&quot;Function &#39;{func.__name__}&#39; took {total_time:} seconds to execute.&quot;)<br>        return result<br>    return wrapper</pre><p>Let’s break it down:</p><ul><li><strong>time_it</strong> is the main decorator function.</li><li><strong>wrapper</strong> is a nested function inside it that adds extra behavior (timing, in this case).</li><li><strong>@wraps(func)</strong> preserves the metadata (like the original function name) of the wrapped function.</li></ul><h3>Using the Decorator</h3><p>To apply this to any function, just add @time_it above it:</p><pre>@time_it<br>    def multiply_2_variables(self, x,y):<br>        time.sleep(4)<br>        z = x*y<br>        return z</pre><p>Now the multiply_2_variables method will automatically print the time it takes to run—<strong>without modifying the original logic!</strong></p><h4>Final Code (Putting It All Together)</h4><pre>import time<br><br>from functools import wraps<br><br>def time_it(func):<br>    &quot;&quot;&quot;<br>    A decorator to measure the execution time of a function.<br>    &quot;&quot;&quot;<br>    @wraps(func)<br>    def wrapper(*args, **kwargs):<br>        start_time = time.perf_counter()  # Use perf_counter for precise timing<br>        result = func(*args, **kwargs)<br>        end_time = time.perf_counter()<br>        total_time = end_time - start_time<br>        print(f&quot;Function &#39;{func.__name__}&#39; took {total_time:.4f} seconds to execute.&quot;)<br>        return result<br>    return wrapper<br><br>from add import Add<br>class Multiply:<br>    def print_stuff(self):<br>        print(&quot;Heyy! this is line 4 of multiply.py. Just checking if this is used&quot;)<br><br>    @time_it<br>    def multiply_2_variables(self, x,y):<br>        time.sleep(4)<br>        z = x*y<br>        return z<br><br>if __name__ == &quot;__main__&quot;:<br>    multiply_obj = Multiply()<br>    add_obj = Add()<br><br>    x = 4<br>    y = 5<br>    z = multiply_obj.multiply_2_variables(x,y)<br>    print(f&quot;Multiplication: {z}&quot;)<br>    c = add_obj.add_2_variables(x,y)<br>    print(f&quot;Addition: {c}&quot;)<br><br>    print(&quot;This is line 19 of multiply.py. Multiplication finished&quot;)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*zeQlsC_VPeSYW63xU_P7lQ.png" /><figcaption>Final Output</figcaption></figure><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*gh-lFG8xinnAZIbjO0iH9w.jpeg" /><figcaption>image source: Yarn GIFs</figcaption></figure><p>Decorators are an elegant and powerful feature in Python that allow you to <strong>enhance or modify the behavior of functions without changing their source code</strong>. Whether you’re timing performance, logging activity, or adding conditional behavior, decorators help keep your code clean, reusable, and efficient.</p><p>And just like using a Bluetooth speaker — decorators give you <strong>amplified functionality without opening up the core system</strong>. 🎧</p><p>So next time you want to monitor, extend, or tweak your Python function — just wrap it in a decorator and jam on! 💃🕺</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fd211465f2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making silly mistakes ( and learning from them) - Part 2 : How I messed up class initialization]]></title>
            <link>https://medium.com/@modimuskan397/making-silly-mistakes-and-learning-from-them-part-2-how-i-messed-up-class-initialization-c939a7fc6b48?source=rss-76b587ab08b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c939a7fc6b48</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Muskan Modi]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 11:49:12 GMT</pubDate>
            <atom:updated>2025-08-04T11:49:12.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making silly mistakes ( and learning from them) - Part 2 : How I messed up class initialization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNWxL4wZeBuPv6y22NX-lw.png" /></figure><p>No matter how many books we read, how many tutorials we complete, or how many classes we attend, nothing compares to the real-world experience of working on an actual coding project. It’s humbling. Suddenly, you’re hit with errors you’ve never seen before, and you find yourself wondering: <em>What is going on here?</em></p><p>You end up spending a good chunk of time debugging — thankfully, tools like ChatGPT make that process a little easier — but even then, the errors persist. And the worst part? When it turns out to be something silly — like a missed indentation or a variable declared inside a loop getting overwritten ,and you’re left thinking: <em>Why couldn’t I figure this out earlier?</em></p><p>So, I’ve decided to start this series where I’ll share some common errors I made (and still make) as I started learning Object-Oriented Programming (OOP), along with explanations of what’s happening in the background that causes these issues.</p><p>When you’re new to OOP, you might often encounter an error like::</p><pre>TypeError: Add.add_2_variables() missing 1 required positional argument: &#39;b&#39;</pre><p>This one can be particularly frustrating. You might wonder — <em>Did I forget the </em><em>self parameter? Did I pass the wrong number of arguments? Or is there something else going on?</em></p><p>Let’s break it down step by step with an example.</p><p><strong>Add.py</strong></p><pre>class Add:<br><br>    def print_stuff(self):<br>        print(&quot;Heyyy! this is line 2 of add.py. Just checking if this is executed&quot;)<br><br>    def add_2_variables(self, a,b):<br>        c = a +b<br>        return c<br><br>if __name__ == &quot;__main__&quot;:<br>    add_obj = Add<br>    print(f&quot;\n add_obj: {add_obj}&quot;)<br>    print(f&quot;type_add_obj: {type(add_obj)}&quot;)<br><br>    a = 4<br>    b = 3<br>    c = add_obj.add_2_variables(a,b)<br>    print(f&quot;sum is: {c}&quot;)<br><br>    print(&quot;This is line 12 of add.py. Adding finished&quot;)</pre><h4>Key Concepts:</h4><p><strong><em>Class:</em></strong> Here add.py is a Python script used to add 2 numbers. Add is a class, which is a basically a blueprint of things it contains.</p><p><strong><em>Methods:</em></strong> functions print_stuff and add_2_variables are the methods of this class</p><p><strong><em>Object:</em></strong> An object is an instance of a class. It is the real-world version of a class. We initialize an object of a class in order to perform operations from methods of a class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pMTvJ0zJ_qzgA5S1fzcng.png" /><figcaption>Human</figcaption></figure><p>We can understand this with an example of a human body. We all know a human body contains 2 set of eyes, nose, 2 ears, 10 fingers, 10 toes, arms and so on. Let us call it a class Human body. It is a blueprint of how a human should look. Eyes, nose, ears, arms, legs, fingers, are all methods of this class.</p><p>Now you — person reading this is an object of that class. And by that we mean that you are a real world version of a class human, who follows the blueprints of a class but do have some unique features which seperates you from other humans.</p><p><strong><em>self:</em></strong> The self parameter refers to the <strong>current object</strong>. It’s used to access variables and methods <strong>inside the class</strong>.</p><p>💡<em>Can you use any other keyword instead of self?</em></p><blockquote>Definitely. selfjust a standard keyword we use to reference the current object, like we have for <strong>pd</strong> to import pandas, <strong>np </strong>to import numpy and so on. Go on, try it. Try to use your name instead of self and see if you get any errors.</blockquote><h3>What Happens If You Forget self?</h3><p>Let’s see this version of the class:</p><p>So what would happen if you forget the self parameter?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*sBSlPQKIa24k6hcPQC9LzQ.png" /></figure><p>I am using Pycharm IDE. The first parameter is highlighted as purple color, which signifies the self keyword. We saw above that we do not need to explicitly name it ‘self’ but we can give any name, it is just a pointer which refers to the current object. So, since we have not specified ‘self’ it will assume that ‘a’ is the self parameter. Naturally, we can see here it is highlighted as a purple color wherever a is mentioned.</p><p>As we run the code we will get this error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUpPhdCJqcMmJjS0mInXCg.png" /><figcaption>Type Error</figcaption></figure><pre>TypeError: Add.add_2_variables() takes 2 positional arguments but 3 were given</pre><p><strong>What was happening in the background:</strong></p><p>The method is treated as an instance method, so Python automatically passes the instance (self) as the first argument. But since you forgot to define self, Python ends up interpreting your first argument (a) as the instance (self). Now it&#39;s expecting only one more argument (b) but gets two (4 and 3)—hence, the error.</p><h4>Another Subtle Mistake: Forgetting Parentheses</h4><p>Now here’s the mistake I made that puzzled me for a while.</p><pre>class Add:<br><br>    def print_stuff(self):<br>        print(&quot;Heyyy! this is line 2 of add.py. Just checking if this is executed&quot;)<br><br>    def add_2_variables( a,b):<br>        c = a +b<br>        return c<br><br>if __name__ == &quot;__main__&quot;:<br>    add_obj = Add<br>    print(f&quot;\n add_obj: {add_obj}&quot;)<br>    print(f&quot;type_add_obj: {type(add_obj)}&quot;)<br><br>    a = 4<br>    b = 3<br>    c = add_obj.add_2_variables(a,b)<br>    print(f&quot;sum is: {c}&quot;)<br><br>    print(&quot;This is line 12 of add.py. Adding finished&quot;)</pre><p>Stop. Pause for a moment and read it. Can you see it ?</p><p>the error i got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gq7qNLkIVptEuuld4405zw.png" /><figcaption>Type Error</figcaption></figure><pre>Traceback (most recent call last):<br>  File &quot;C:\Users\ASUS\Desktop\Muskan Projects\Image Processing OpenCV\add.py&quot;, line 17, in &lt;module&gt;<br>    c = add_obj.add_2_variables(a,b)<br>        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^<br>TypeError: Add.add_2_variables() missing 1 required positional argument: &#39;b&#39;</pre><p>I checked the function definition:</p><pre>    def add_2_variables(self, a,b):<br>        c = a +b<br>        return c</pre><p>everything was alright.</p><p>I checked function calls:</p><pre>c = add_obj.add_2_variables(a,b)</pre><p>Everything was alright again. What was the issue? After contemplating for a while I went ahead and read the code. And then it hit me like a pebble (because it was really small and silly but annoying mistake) (-_-*)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*23Ac04IjAOYOA6koGqW0QQ.png" /><figcaption>Literally hit me like a pebble</figcaption></figure><p>I had not instantiated the class. I wrote add_obj = Add instead of add_obj = Add().</p><pre>add_obj = Add</pre><p>I forgot to add the paranthesis required after the Class name. We know that this is a stupid error in the syntax while writing the code. But, why does it not throw a syntax error but throws a Type Error while calling the function?</p><p>What is happening in the background:</p><h3>🧩 Why no SyntaxError?</h3><p>A <strong>SyntaxError</strong> only occurs when Python <strong>cannot understand the code at all</strong>, like:</p><pre>if True print(&quot;hello&quot;)  # ← this is invalid Python syntax</pre><p>But:</p><pre>add_obj = Add</pre><p>is perfectly valid syntax. You’re just assigning the <strong>class itself</strong> to add_obj, not an instance. So the syntax is fine — no error.</p><p>When you call:</p><p>add_obj.add_2_variables(4, 3)</p><p>It’s equivalent to:</p><p>Add.add_2_variables(4, 3)</p><p>Now look at the method definition:</p><p>def add_2_variables(self, a, b)</p><p>It expects:</p><ul><li>self (which should be the instance),</li><li>a</li><li>b</li></ul><p>But you’re only passing:</p><ul><li>4 → taken as self</li><li>3 → taken as a</li></ul><p>🔻 b is missing → hence the TypeError:</p><h3>✅ Correct Usage</h3><p>You must instantiate the class:</p><pre>add_obj = Add()  # ✅ Now add_obj is an instance<br>result = add_obj.add_2_variables(4, 3)</pre><h3>Conclusion</h3><p>Errors like these may seem trivial in hindsight, but when you’re new to programming or shifting to a new paradigm like OOP, they can be incredibly frustrating. That’s exactly why it’s important to <strong>pause, read your code slowly</strong>, and understand what’s happening behind the scenes.</p><p>This journey has taught me that coding isn’t just about writing correct syntax — it’s about <strong>learning how the language thinks</strong>, how it interprets your instructions, and how small oversights can lead to big confusion.</p><p>I hope this blog helps you avoid some of the mistakes I made. Stay tuned for the next post in this series, where we’ll explore more real-world bugs and the logic behind them. Happy debugging! Until then,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fHaLNQ0Q46-CSuiTKDwXMg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c939a7fc6b48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Python Import That Broke My Code (And Taught Me a Lesson)]]></title>
            <link>https://medium.com/@modimuskan397/the-python-import-that-broke-my-code-and-taught-me-a-lesson-3a5bea380ee9?source=rss-76b587ab08b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a5bea380ee9</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Muskan Modi]]></dc:creator>
            <pubDate>Fri, 01 Aug 2025 11:29:01 GMT</pubDate>
            <atom:updated>2025-08-04T07:03:38.488Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making silly mistakes — Part 1: The Python Import That Broke My Code (And Taught Me a Lesson)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2gUlF-zq9uobBfoEWbddKQ.png" /></figure><p>We all <em>know</em> why writing clean and structured code is important:</p><ul><li>✅ Easier to understand</li><li>✅ Meets industry standards</li><li>✅ Avoids hours of debugging</li></ul><p>Yeah, yeah, yeah, Muskan, we know…</p><p>But let’s be real — sometimes we get lazy, right?</p><blockquote>“I’m just writing this code to test something. It’s not going to production, so why bother perfecting it?”</blockquote><p>…That’s what I thought.<br> …And did.<br> …And <em>constantly</em> keep doing</p><p>Until recently — when something really strange happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ees4D-QQGIY-ovw6DhXbGg.png" /></figure><h3>The Setup: A Lazy Script</h3><p>I had written a simple Python script to calculate angles from .txt files. And like a <em>very</em> Python-savvy person (note the sarcasm), I wrote everything at the <strong>top level</strong>:</p><ul><li>Just for loops</li><li>Print logs</li><li>A calculate_angle function</li></ul><p>No if __name__ == &quot;__main__&quot;<br> No classes, no real structure.<br> <strong>Wild, right?</strong></p><p>Then came the moment: I needed the calculate_angle function in another script. Naturally, I didn’t want to rewrite it, so I did:</p><pre>from calculate_angles_from_predicted_labels import calculate_angle</pre><p>And then I ran my present code, let’s just call it present.py. I did not even use calculate_angle in my present.py, and Pycharm just grays the unused variables and imports like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*E-OWGpiQe0E6AkLJXfwDIg.png" /></figure><p>Let’s call the new script present.py.</p><p>And even though I didn’t <em>use</em> calculate_angle in present.py, something odd happened:</p><blockquote><em>The </em>entire<em> </em><em>calculate_angles_from_predicted_labels.py script ran.<br> Logs printed, print statements flew by.<br> Only after all that did </em><em>present.py start running.</em></blockquote><p>I sat there like:<br> <strong>“Wait… what sorcery is this?”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BG3X31tFNe5rEN3TYObNdA.png" /></figure><h3>The Why: Top-Level Code Gets Executed on Import</h3><p>So I did a little digging. And here’s the deal:</p><blockquote><strong><em>When you import a Python script, everything at the top level gets executed — </em></strong><em><br> not just the function you imported.</em></blockquote><p>Unless your code is properly encapsulated inside:</p><ul><li>Functions</li><li>Classes</li><li>And the oh-so-important if __name__ == &quot;__main__&quot; block</li></ul><p>…it will all run at import time. This is why Python libraries and training scripts follow a clean structure — not just to look neat, but to <strong>prevent exactly this kind of behavior.</strong></p><p>Let’s see this in action with a quick demo.</p><p>Let us try it. We will write 2 scripts and perform import and see how it pans out.</p><p>So we have 2 scripts, add.py and multiply.py</p><h4><strong>add.py</strong></h4><pre>print(&quot;Hiii!!! This is line 1 of add.py&quot;)<br><br>def add_2_variables(a,b):<br>    c = a +b<br>    return c<br><br>a = 4<br>b = 3<br>c = add_2_variables(a,b)<br>print(f&quot;sum is: {c}&quot;)<br><br>print(&quot;This is line 12 of add.py. Adding finished&quot;)</pre><h4>mutliply.py</h4><pre>from add import add_2_variables<br><br>print(&quot;This is line 3 of multiply.py&quot;)<br><br>def multiply_2_variables(x,y):<br>    z = x*y<br>    return z<br><br>x = 4<br>y = 5<br>z = multiply_2_variables(x,y)<br>print(f&quot;Multiplication: {z}&quot;)<br><br>print(&quot;This is line 14 of multiply.py. Multiplication finished&quot;)</pre><p>We have written clear print statements to check when and what is executed. We have imported add_2_variables function in our multiply.py, although we have not used it.Now let’s run multiply.py.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*oL7JUfM4PPm8Xoq3ccEkzg.png" /></figure><p>Even though we never actually <em>used</em> add_2_variables, the entire add.py script runs before multiply.py.</p><p><strong>Not ideal.</strong></p><h4>The Right Way</h4><p>Now we will follow proper format in order to use this code. Let us update both of our python scripts:</p><h4>updated add.py</h4><pre>def print_stuff():<br>    print(&quot;Heyyy! this is line 2 of add.py. Just checking if this is executed&quot;)<br><br>def add_2_variables(a,b):<br>    c = a +b<br>    return c<br><br>if __name__ == &quot;__main__&quot;:<br><br>    a = 4<br>    b = 3<br>    c = add_2_variables(a,b)<br>    print(f&quot;sum is: {c}&quot;)<br><br>    print(&quot;This is line 12 of add.py. Adding finished&quot;)</pre><h4>updated multiply.py</h4><pre>from add import add_2_variables<br><br>def print_stuff():<br>    print(&quot;Heyy! this is line 4 of multiply.py. Just checking if this is used&quot;)<br><br>def multiply_2_variables(x,y):<br>    z = x*y<br>    return z<br><br>if __name__ == &quot;__main__&quot;:<br><br>    x = 4<br>    y = 5<br>    z = multiply_2_variables(x,y)<br>    print(f&quot;Multiplication: {z}&quot;)<br>    c = add_2_variables(x,y)<br>    print(f&quot;Addition: {c}&quot;)<br><br>    print(&quot;This is line 19 of multiply.py. Multiplication finished&quot;)</pre><p>Now when we run multiply.py</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*TGq7asML4dRrwK-JoElkaw.png" /></figure><p>only the code we <em>intended</em> to run is executed. No unnecessary prints from add.py</p><h3>Conclusion: Structure Saves Sanity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OenYfezA0rcZvmEvn1BCQ.png" /></figure><p>This little mishap taught me a simple but powerful lesson:</p><blockquote><strong><em>Never underestimate the importance of structure — even in your quick tests or throwaway scripts.</em></strong></blockquote><p>Why structure is important:</p><ul><li>Avoid side effects when importing from other modules</li><li>Make debugging easier by isolating functionality</li><li>Write testable code — unit tests love well-structured modules</li><li>And most importantly — save time. No need to increase the time complexity of your code juse because we were too lazy to give time to add proper structure, right?</li></ul><p>The Python interpreter doesn’t care if your code is for testing or production — it just executes what you give it. So whether you’re building an AI pipeline, a CLI tool, or just playing with .txt files on a Sunday night, <strong>structure your scripts well</strong>:</p><ul><li>Use if __name__ == &quot;__main__&quot;</li><li>Encapsulate logic in functions</li><li>Keep your modules clean and reusable</li></ul><p>You’ll thank yourself later.<br> And so will your terminal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a5bea380ee9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Write Cleaner, Efficient Code — Part 1: Understanding Generators]]></title>
            <link>https://medium.com/@modimuskan397/how-to-write-cleaner-efficient-code-part-1-understanding-generators-0f23d2c52f5f?source=rss-76b587ab08b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f23d2c52f5f</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[advancedpythonprogramming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-development]]></category>
            <category><![CDATA[efficient-coding]]></category>
            <dc:creator><![CDATA[Muskan Modi]]></dc:creator>
            <pubDate>Tue, 13 May 2025 13:41:16 GMT</pubDate>
            <atom:updated>2025-05-13T13:41:16.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Write Cleaner, Efficient Code — Part 1: Understanding Generators</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpXk86zjm3V3pGK7JLKQ5w.png" /></figure><p>During one of my early code reviews as a Python developer, a senior shared a piece of advice that stayed with me:<br> <strong>“Good code isn’t just code that works — it’s code that’s efficient, well-structured, and easy for others to understand.”</strong></p><p>Interestingly, I had encountered a similar idea while learning content writing in college:<br> <strong>“A good piece of content isn’t about using fancy words — it’s about delivering your message clearly and engaging the reader.”</strong><br> It’s fascinating how, across different fields, the core principle of <em>clarity and simplicity</em> holds true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRU4-qqQVvoLLJFRTvL2rA.png" /></figure><p>When working with large codebases, writing clean and understandable code becomes essential — not just for functionality, but for maintainability, collaboration, and scalability. In this post, we’ll explore two powerful Python features — <strong>decorators</strong> and <strong>generators</strong> — that can help you write cleaner, more modular, and memory-efficient code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*qzhowdyhZuVw3cfV" /><figcaption>Image Source: <a href="https://www.nytimes.com/2007/06/13/dining/13rata.html">https://www.nytimes.com/2007/06/13/dining/13rata.html</a></figcaption></figure><p>Remember the animated movie <strong>Ratatouille</strong>? Our favorite rat-chef works in a famous 5-star restaurant where customers stream in, ordering a variety of dishes off the menu.</p><p>To run this kitchen, Ratatouille has two options:</p><ol><li><strong>Pre-cook every item</strong> on the menu and store it in large freezers. When an order comes, he just heats and serves.</li><li><strong>Prepare dishes fresh</strong>, on-demand, as customers order, with all ingredients and tools ready.</li></ol><p>Now let’s break this down.</p><h3>The Problem with Option 1</h3><p>This approach may work for <strong>10 customers a day</strong>, but what if the restaurant serves <strong>100 or 1000</strong>?</p><ul><li>Preparing all dishes in advance takes a <strong>lot of time</strong></li><li>You’ll need <strong>huge refrigerators</strong> for storage.</li><li>There’s risk of <strong>wastage</strong> on a slow day and <strong>shortage</strong> during festivals or rush hours.</li></ul><p>… and, let’s get this straight,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SkXGWoPgIhtxnLFB.png" /><figcaption>Image Source: <a href="https://www.eater.com/22702839/disney-anton-ego-ratatouille-restaurant-criticism">https://www.eater.com/22702839/disney-anton-ego-ratatouille-restaurant-criticism</a></figcaption></figure><p>this guy would get a heart attack.</p><h3>Option 2: Cook On Demand</h3><p>This makes much more sense — both for health and <strong>resource efficiency</strong>. Prepare food <strong>only when required</strong>, based on the customer’s request.</p><p>This is <em>exactly</em> what a <strong>Python generator</strong> does.</p><h4>Generators in Python</h4><p>Generators are special functions in Python that return an <strong>iterator</strong> — but instead of returning all values at once, they yield them one by one, <strong>on demand</strong>.</p><p>They use the yield keyword instead of return. This makes the function <strong>pause</strong> its state and <strong>resume</strong> from where it left off.</p><p>Syntax:</p><pre>def generator_function(n):<br>    i = 0<br>    while i &lt; n:<br>        yield i<br>        i += 1</pre><p>Instead of preparing and storing all values upfront (like lists), it <strong>yields</strong> one value at a time, <strong>only when asked</strong>, saving memory and time.</p><h4>Generators v/s For Loop</h4><blockquote>But Muskan, can’t we just do the same thing using a for loop?</blockquote><p>Absolutely! Most of us begin with for loops — they’re intuitive and work well in many cases. But let’s dig deeper into <strong>when and why</strong> you might want to use a <strong>generator instead</strong>.</p><h4>For Loop (Eager Evaluation)</h4><p>A for loop is used to iterate over a <strong>predefined set of values</strong> like a list, tuple, or string. When you run the loop, <strong>all elements are loaded into memory</strong> before iteration begins.</p><pre>nums = [1, 2, 3, 4, 5]<br>for num in nums:<br>    print(num)</pre><p>We can use a for loop when the data is small and can fit comfortable in a memory.</p><h4>Generator (Lazy Evaluation)</h4><p>A generator, on the other hand, <strong>yields</strong> values one at a time, <strong>only when requested</strong>. It doesn’t store the entire sequence — which means <strong>no memory is used for values not yet generated</strong>.</p><pre>def generate_nums():<br>    for i in range(1, 6):<br>        yield i<br><br>for num in generate_nums():<br>    print(num)</pre><p>and if we want to check what the generator function returns, we can check by simply printing it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkoUynuaHRGc7gni8UgB-g.png" /><figcaption>a generator object is returned by the generator function</figcaption></figure><p>We can use a generator when the data is large, we want lazy evaluation and we want to save memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*vdK-5F7ihDT9EnH9lwrs7A.png" /><figcaption>Key differences between a for loop and a generator</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f23d2c52f5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding REST APIs: Concepts, Functionality, and Applications]]></title>
            <link>https://medium.com/@modimuskan397/understanding-rest-apis-concepts-functionality-and-applications-580851f62aef?source=rss-76b587ab08b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/580851f62aef</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python-web-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Muskan Modi]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 06:01:06 GMT</pubDate>
            <atom:updated>2024-11-27T06:01:06.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ExfKMwXWpWMhQTMeUNgj-Q.jpeg" /></figure><p>In today’s digital world, <strong>APIs (Application Programming Interfaces)</strong> are the backbone of modern web development, allowing different software applications to communicate with each other. Whether you’re building a web application, mobile app, or integrating third-party services, understanding how to create and work with APIs is essential.</p><p>In this blog, we’ll dive into the basics of APIs, explore the different HTTP methods (GET, POST, PUT, DELETE), and learn how to design, create, and test an API. By the end of this guide, you’ll have a solid understanding of how APIs work, and you’ll be able to build your own APIs that interact with databases and external services. Let’s get started!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjCnFv5RkCllREEcQZ9sag.jpeg" /></figure><h4><strong>What is an API ?</strong></h4><p>An API ( Application Programming Interface) acts as a middleman that allows Software Applications to interact with each other. For example, you want to Log In to your Medium account. While Logging In, you get options, whether you want to enter Login and Password, or you want to Login through Gmail or Facebook.</p><p>Suppose you opt for Gmail, you receive an option to select the mail id, and you are logged in. What happens in the background is, Medium has made a request to access information from your Gmail account. There is an API that collects your information from your Gmail account and sends it to Medium, with the help of which you are authenticated, and are allowed to Log In to your account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhIeWBjTdY-g6f1jL72kEQ.png" /><figcaption>Image Source: <a href="https://www.ovhcloud.com/en/learn/what-is-rest-api/">https://www.ovhcloud.com/en/learn/what-is-rest-api/</a></figcaption></figure><h4>What is a REST API ?</h4><p>For two Software Applications to Interact with each other, there should be a certain set of rules that should be defined, in order for them to exchange information. An API defines certain set of rules, like a contract, that will define how they will interact.</p><p>Hence, if Software Applications are 2 businessmen having a business deal, API will act as the middleman who will be responsible for rules and interaction that will make this business deal successful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NA6bfM3XHPY2FBxxjoHniw.png" /></figure><p>REST (Representational State Transfer Application Programming Interface) is an architectural design that defines how you should build an API.</p><h4>Important Elements of REST API</h4><ol><li><strong>Client</strong>: Software Application on User’s side that requests a specific piece of Information</li><li><strong>Server</strong>: Sever that offers an API to connect with it’s data</li><li><strong>Resource</strong>: The specific piece of information that is requested by the user</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cjGAevnut9YuDmprV1Qmw.png" /><figcaption>Image Source: <a href="https://phpenthusiast.com/blog/what-is-rest-api">phpenthusiast</a></figcaption></figure><h4>Important HTTP Methods in an REST API</h4><p>The HTTP Methods in an API are similar to the CRUD Operations (Create, Read, Update, Delete)</p><ol><li><strong>GET</strong>: Retrieve a resource/ Get Information from a resource ( Similar to Read)</li><li><strong>POST</strong>: Create a new Resource ( Create)</li><li><strong>PUT</strong>: Update an existing Resource (Update)</li><li><strong>PATCH</strong>: Partially Update a Resource</li><li><strong>DELETE</strong>: Delete a Resource / Information</li></ol><h4>How to make a REST API using Flask ?</h4><ol><li><strong>Install flask.</strong></li></ol><pre>pip install flask</pre><p>Make sure you have flask installed in your local environment</p><p><strong>2. Start by creating a basic Flask application</strong></p><pre>from flask import Flask<br><br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def home():<br>    return &quot;Welcome to Flask!&quot;<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p><strong>3. Run the file. Visit your localhost address to check the output.</strong></p><pre>python app.py</pre><p>If you are using Pycharm, it would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvP7flzKFmDWxnc3wY9orQ.png" /></figure><p><strong>What are endpoints ?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vToP51SAajeeO6rjZIK5Uw.jpeg" /><figcaption>Image Source: <a href="https://www.wallarm.com/">wallarm.com</a></figcaption></figure><p><strong>Endpoints</strong> are specific <strong>URLs</strong> or <strong>URIs</strong> ( Uniform Resource Allocator) in an API that represent a particular resource. For example, when you enter a specifc URL, /home takes you to home page, /contact enters the contact information of that website, and so on.</p><p>Here we will make a simple Library Management System by performing basic CRUD operations</p><p>Let us start by defining basic structure of our data</p><pre>from flask import Flask, request, jsonify<br><br>app = Flask(__name__)<br><br># Sample data<br>books = [<br>    {&quot;id&quot;: 1, &quot;title&quot;: &quot;The Great Gatsby&quot;, &quot;author&quot;: &quot;F. Scott Fitzgerald&quot;},<br>    {&quot;id&quot;: 2, &quot;title&quot;: &quot;1984&quot;, &quot;author&quot;: &quot;George Orwell&quot;},<br>]</pre><p>Defining routes and endpoints</p><p><strong>GET</strong> — This will be our <strong>READ</strong> operation to display all the books in our current list</p><pre># Get all books<br>@app.route(&#39;/books&#39;, methods=[&#39;GET&#39;])<br>def get_books():<br>    return jsonify(books)</pre><p>We will also define a function where we will be able to retrieve books by their respective id</p><pre># Get a single book by ID<br>@app.route(&#39;/books/&lt;int:book_id&gt;&#39;, methods=[&#39;GET&#39;])<br>def get_book(book_id):<br>    book = next((book for book in books if book[&quot;id&quot;] == book_id), None)<br>    return jsonify(book) if book else (&quot;Book not found&quot;, 404)</pre><p><strong>POST</strong> — This will be the <strong>WRITE</strong> operation, where we will add a new book to our list.</p><pre># Add a new book<br>@app.route(&#39;/add&#39;, methods=[&#39;POST&#39;])<br>def add_book():<br>    new_book = request.get_json()<br>    books.append(new_book)<br>    return jsonify(new_book), 201</pre><p><strong>PUT</strong> — This will be our <strong>UPDATE</strong> operation where we will update details of a particular book belonging to a particular id</p><pre># Update a book by ID<br>@app.route(&#39;/update/&lt;int:book_id&gt;&#39;, methods=[&#39;PUT&#39;])<br>def update_book(book_id):<br>    book = next((book for book in books if book[&quot;id&quot;] == book_id), None)<br>    if book:<br>        data = request.get_json()<br>        book.update(data)<br>        return jsonify(book)<br>    return (&quot;Book not found&quot;, 404)</pre><p><strong>DELETE</strong> — This will be the <strong>DELETE</strong> operation where we will delete the details of a particular book belonging to a particular id</p><pre># Delete a book by ID<br>@app.route(&#39;/delete/&lt;int:book_id&gt;&#39;, methods=[&#39;DELETE&#39;])<br>def delete_book(book_id):<br>    global books<br>    books = [book for book in books if book[&quot;id&quot;] != book_id]<br>    return (&quot;&quot;, 204)</pre><h4>Complete Code :-</h4><pre>from flask import Flask, request, jsonify<br><br>app = Flask(__name__)<br><br># Sample data<br>books = [<br>    {&quot;id&quot;: 1, &quot;title&quot;: &quot;The Great Gatsby&quot;, &quot;author&quot;: &quot;F. Scott Fitzgerald&quot;},<br>    {&quot;id&quot;: 2, &quot;title&quot;: &quot;1984&quot;, &quot;author&quot;: &quot;George Orwell&quot;},<br>]<br><br># Get all books<br>@app.route(&#39;/books&#39;, methods=[&#39;GET&#39;])<br>def get_books():<br>    return jsonify(books)<br><br># Get a single book by ID<br>@app.route(&#39;/books/&lt;int:book_id&gt;&#39;, methods=[&#39;GET&#39;])<br>def get_book(book_id):<br>    book = next((book for book in books if book[&quot;id&quot;] == book_id), None)<br>    return jsonify(book) if book else (&quot;Book not found&quot;, 404)<br><br># Add a new book<br>@app.route(&#39;/add&#39;, methods=[&#39;POST&#39;])<br>def add_book():<br>    new_book = request.get_json()<br>    books.append(new_book)<br>    return jsonify(new_book), 201<br><br># Update a book by ID<br>@app.route(&#39;/update/&lt;int:book_id&gt;&#39;, methods=[&#39;PUT&#39;])<br>def update_book(book_id):<br>    book = next((book for book in books if book[&quot;id&quot;] == book_id), None)<br>    if book:<br>        data = request.get_json()<br>        book.update(data)<br>        return jsonify(book)<br>    return (&quot;Book not found&quot;, 404)<br><br># Delete a book by ID<br>@app.route(&#39;/delete/&lt;int:book_id&gt;&#39;, methods=[&#39;DELETE&#39;])<br>def delete_book(book_id):<br>    global books<br>    books = [book for book in books if book[&quot;id&quot;] != book_id]<br>    return (&quot;&quot;, 204)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><h4>Testing the API</h4><p>Now we have successfuly made the API and learned how to use HTTP Methods. Now we will learn how to test this API. Here we are going to use cURL to test the API.</p><p>Installation</p><pre>sudo apt install curl</pre><p>Start the API</p><pre>python library.py</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*JFV6wd3saFzZN7hEz4Z7GA.png" /></figure><p>The API will run on <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000</a> . To check it on your brower, you can just copy this link and paste it on your browser to check. Initially, you will get <em>404 NOT FOUND</em> error. Do not panic. It is because we have not defind anything for ‘/’ endpoint.</p><ol><li><strong>Testing the GET requests</strong></li></ol><p>a. <strong>To get all the books in the list</strong>:-</p><p>Remember we used the endpoint ‘/books’ with the function to retrieve all the books in the list? We will use the same endpoint with our link to get the response.</p><pre>curl -X GET http://127.0.0.1:5000/books</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*4CACrFcqe2kD4ypN61bRPQ.png" /><figcaption>Response</figcaption></figure><p>You can copy and paste this link on your browser to check the GET requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*vYJobJIya5YaiI4kAtXbsw.png" /></figure><p>It is going to look something like this.</p><p>b. <strong>Getting books by ID</strong></p><pre> curl -X GET http://127.0.0.1:5000/books/1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*VoRz1wW-xTdCsypm9Mn9Cw.png" /><figcaption>Git Bash</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*yWAElkSNedeaVBHSozEuDg.png" /><figcaption>Browser View</figcaption></figure><p>2. <strong>Testing POST and PUT Requests.</strong></p><p>While we can test GET and POST requests directly via browser, for POST and PUT requests, it gets a little tricky. For accessing books via id, we could simply put the id of the book in the address bar, but we cannot put our input in our POST request.</p><p>Let us try it. We will visit the endpoint ‘/add’ to check</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*JBdgecA7PdB0THufaAM3LA.png" /></figure><p>It throws the 405: Method not allowed error. It is because GET requests are used to read data, and browsers can handle it by default. But in POST requests, method requires a body, like in JSON or XML format. The address bar of the browser is not equipped to handle this. This is why we use tools like cURL or POSTMAN to test the APIs.</p><p>a. <strong>Add a new book to the list</strong></p><pre>curl -X POST http://127.0.0.1:5000/add -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;author&quot;: &quot;Arundhati Roy&quot;, &quot;id&quot;: 3, &quot;title&quot;: &quot;The God of Small Things&quot;}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a7oqbuChG4vPoGB8i-hY9w.png" /></figure><p>b. <strong>Update details of a book in the list</strong></p><pre>curl -X PUT http://127.0.0.1:5000/update/3 -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;author&quot;: &quot;Arundhati Roy&quot;, &quot;title&quot;: &quot;The Ministry of Utmost Happiness&quot;}&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AmRp1wWvG5Iy9YsOvSDO-w.png" /></figure><p>3. <strong>Delete</strong></p><pre>curl -X DELETE http://127.0.0.1:5000/delete/3</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*a7cdZrNcYPbu4UdgyGphAw.png" /></figure><p>Now, we will check the books list again</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*l7EU0HetmWH514_l1v4phQ.png" /></figure><p>As we can see now there are only 2 books in the list.</p><h4>Conclusion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*G9DNmQXWWP-WXrPMx-tsTg.gif" /></figure><p>Today, we explored the fundamentals of APIs, including the various HTTP methods like GET, POST, PUT, and DELETE, and how they interact with your data. We also discussed how to create a simple API and test it using tools like cURL , enabling you to build and manage your own APIs effectively. The possibilities are endless — whether you’re building a web app, automating tasks, or working on more complex projects.</p><p>So go ahead, create your own API, connect it to a database, and start retrieving and managing data in ways that suit your project needs.</p><p>In the next blog, we will learn how to make RESTful APIs using flask_restful, a library that simplifies the creation of REST APIs.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=580851f62aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RGB vs. RYB: The Science of Color in Digital Technology]]></title>
            <link>https://medium.com/@modimuskan397/rgb-vs-ryb-the-science-of-color-in-digital-technology-a4ed4f4f8504?source=rss-76b587ab08b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4ed4f4f8504</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[digital-image-processing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Muskan Modi]]></dc:creator>
            <pubDate>Tue, 27 Aug 2024 09:00:16 GMT</pubDate>
            <atom:updated>2024-08-27T09:01:57.673Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5876vL93ewRNXI7XARHCUg.png" /></figure><p>From middle school art classes to painting lessons, most of us grew up learning that red, yellow, and blue are the primary colors. We were taught that by mixing these three colors in various combinations, we could create every other color in the spectrum. It made sense, and it was fun to experiment with during art class, blending red and yellow to make orange or mixing blue and yellow to get green.</p><p>Fast forward a few years, and I found myself diving into the fascinating world of computer vision. This was where things got a little confusing. Suddenly, the color wheel I knew was turned on its head. In computer vision, the RGB model reigns supreme, declaring that red, green, and blue are the primary colors. Wait, what? Green as a primary color? But wasn’t green made by mixing yellow and blue? How could green possibly be a primary color?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4CZdjqq3XZ0l7q-iL0yTQ.jpeg" /></figure><p>If you’ve ever been confused by this, you’re not alone! Let’s take a closer look at the <strong>RGB and RYB</strong> models to understand the difference between them and why both are correct in their own way.</p><h4><strong>RYB Model: The Artistic Primary Colors</strong></h4><p>Red, Yellow and Blue are the Primary colors in artistic color theory. This is the first thing we learn, especially if you have taken any kind of art class. This is because the RYB model in painting uses the <strong>subtractive model</strong>. It is used in pigments, dyes while color mixing. In traditional art and painting, the color we perceive is because the pigment reflects the light of certain wavelength that our eye catches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*rxYYIVqAYuNndYdZ.png" /><figcaption>Image Source:<a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FColor_wheel&amp;psig=AOvVaw3HXFt1LEIKmEJvodkQcyFG&amp;ust=1724834017363000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCOCT2szhlIgDFQAAAAAdAAAAABAE"> Wikipedia</a></figcaption></figure><p>When we mix 2 pigments, the wavelength our eye catches are those which are reflected by both the pigments, and the rest is absorbed. Hence, it is called a subtractive model- because it works by subtracting the wavelengths of the 2 colored pigments from white.</p><p>The subtractive model isn’t suitable for digital screens, which rely on light emission rather than absorption.</p><h4><strong>RGB: The Digital Primary Colors</strong></h4><p>RGB — Red Green and Blue are considered the primary colors in Image Processing.</p><p><strong>Human Perception:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_S2vfXOgi3o22nzN5WqZQ.png" /></figure><p><strong>Trichromatic Vision:</strong> Humans have three types of color-sensitive cells in their eyes, called cones. Each type of cone is sensitive to a different range of wavelengths corresponding to red, green, and blue light.</p><p>Our eyes contain three types of photoreceptor cells called cones, each sensitive to different ranges of light wavelengths. These cones respond to light corresponding to red, green, and blue regions of the visible spectrum.</p><ul><li><strong>Red cones</strong> are most sensitive to long wavelengths of light, around 564–580 nanometers.</li><li><strong>Green cones</strong> respond best to medium wavelengths, around 534–545 nanometers.</li><li><strong>Blue cones</strong> are sensitive to shorter wavelengths, around 420–440 nanometers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*FhOcS967eppP3kUM" /><figcaption>Image Source: <a href="https://www.aao.org/eye-health/anatomy/cones">American Academy of Opthamology</a></figcaption></figure><p><strong>Color Mixing:</strong> Our brains combine the signals from these three types of cones to perceive a wide range of colors. By using red, green, and blue as the primary colors, we can create almost any other color through additive color mixing.</p><p>In RGB model, the colors are created by combining the light of these colors. When all the 3 colors are combined at full intensity, white light is produced. When none are present, the result is black. The RGB model has become a standard in digital imaging because it aligns with both how humans perceive color and how electronic devices generate color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9mKGWH90DfJl__cORNjxw.png" /><figcaption>Early Models of Television</figcaption></figure><p>The RGB model was adopted early on in the development of color television and computer monitors. It proved to be effective, and as technology evolved, the RGB model remained a standard.</p><p>Let us perform some experiments to see the role of Red, Green, Blue in Image Processing:</p><pre>import cv2<br>import numpy as np<br><br># Load an image in color (default)<br>image = cv2.imread(&#39;C:\\Users\\admin\\Downloads\\duck-1893080_640.jpg&#39;)<br><br># Display the image in an OpenCV window<br>cv2.imshow(&#39;Original Image&#39;, image)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*99tRbLawKuzMlB7-F7othQ.png" /><figcaption>Original Loaded Image</figcaption></figure><p>Now we will split this image into Red, Green and Blue channels, respectively.</p><pre>b, g, r = cv2.split(image)<br><br># Create an empty array with the same shape as the original image, but with all zeros<br>zeros = np.zeros_like(b)<br><br># Merge the channels with the empty channels to create colored images<br># Blue channel image<br>blue_image = cv2.merge([b, zeros, zeros])<br># Green channel image<br>green_image = cv2.merge([zeros, g, zeros])<br># Red channel image<br>red_image = cv2.merge([zeros, zeros, r])<br><br># Display the images<br>cv2.imshow(&#39;Blue Channel&#39;, blue_image)<br>cv2.imshow(&#39;Green Channel&#39;, green_image)<br>cv2.imshow(&#39;Red Channel&#39;, red_image)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*_QZ6D4k30FT_X2lofoLBcw.png" /><figcaption>Red Channel Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*2IVDUDXKdEp3IrefYcpZ3g.png" /><figcaption>Green Channel Image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*Y_5P6-offtiTp_SlAqdVLQ.png" /><figcaption>Blue Channel Image</figcaption></figure><p>Now we want to see how all these three channel can make a colored image. So, we are going to merge the values of these 3 channels to see if we can get back our colored image.</p><pre># Merge the channels back into a color image<br>merged_image = cv2.merge([b, g, r])<br>cv2.imshow(&#39;Merged Image&#39;, merged_image)<br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*v7v6q3YlK3qAZ82d7aFptw.png" /><figcaption>Merged Image</figcaption></figure><p>Let us try and Isolate a specific color by <strong>creating a Color Mask</strong>.</p><pre># Convert the image from BGR to HSV<br>hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)<br><br># Define the range for yellow color in HSV<br>lower_yellow = np.array([20, 100, 100])<br>upper_yellow = np.array([30, 255, 255])<br><br># Create a mask that includes only the yellow parts of the image<br>mask = cv2.inRange(hsv_image, lower_yellow, upper_yellow)<br><br># Use the mask to extract the yellow parts of the image<br>yellow_only = cv2.bitwise_and(image, image, mask=mask)<br><br># Display the original and the yellow-only images<br>cv2.imshow(&#39;Original Image&#39;, image)<br>cv2.imshow(&#39;Yellow Only&#39;, yellow_only)<br><br>cv2.waitKey(0)<br>cv2.destroyAllWindows()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*v9GFSsoefPHaKPenSRedLA.png" /><figcaption>Yellow Isolated Image</figcaption></figure><p>Here we have tried and isolated the yellow color. You can perform the similar operations with any color that you like. You would just have to provide proper lower and upper hsv range of the color you want to isolate.</p><h3>Conclusion</h3><p>Understanding the difference between traditional color models like RYB and digital color models like RGB is crucial in bridging the gap between art and technology. While traditional paintings rely on the Red-Yellow-Blue model, digital image processing uses the Red-Green-Blue model to efficiently represent and manipulate colors in a digital environment.</p><p>By exploring the RGB model, we can break down images into their constituent color channels, giving us the power to analyze, modify, and enhance images in ways that align with the capabilities of digital displays. Whether you’re isolating a particular color or merging channels to create a new visual effect, mastering these techniques opens up endless possibilities in image processing.</p><p>In today’s digital age, this knowledge is not only valuable for artists and designers but also for developers and engineers who seek to harness the full potential of digital imagery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4ed4f4f8504" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to parse JSON File and show Output JSON using Flask]]></title>
            <link>https://medium.com/@modimuskan397/how-to-parse-json-file-and-show-output-json-using-flask-c0b415f3f0a0?source=rss-76b587ab08b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0b415f3f0a0</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[jinja-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Muskan Modi]]></dc:creator>
            <pubDate>Mon, 22 Apr 2024 09:28:42 GMT</pubDate>
            <atom:updated>2024-04-22T09:28:42.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GMoaNeYMorL_q9wv7w9xPw.jpeg" /></figure><p>Hey there, welcome aboard! Ever wondered how to make your JSON data shine on the web? Welcome to our comprehensive guide on parsing JSON files and elegantly displaying their contents using Flask.</p><p><strong>JSON (JavaScript Object Notation)</strong> is a popular data interchange format, and Flask is a lightweight web framework for Python. In this tutorial, we’ll walk you through the process of uploading a JSON file, parsing its data, and presenting it in a user-friendly format on a web page.</p><p><strong>Input :</strong> Uploaded JSON file as the Input File<br><strong>Output:</strong> Values from the JSON file in the form of Table pair.</p><p>Firstly, we will start by parsing our JSON File. Here is a code to parse the JSON File:</p><pre>with open(input_file, encoding=&quot;utf-8&quot;) as json_file:<br>    parsed_json = json.load(json_file)</pre><p>Next, we will start accessing the Values of the JSON File using for loops. A JSON is essentially a nested dictionary with key and value pairs, which you can easily access using loops. You can write your own python code to access values from JSON by studying its structure, and iterating through the parsed JSON data.</p><p>Here is a code snippet of my code for your understanding:</p><pre>def extract_data(json_data):<br>    extracted_data = {}<br>    for employee in json_data[&#39;employees&#39;]:<br>        extracted_data[employee[&#39;id&#39;]] = {<br>            &#39;name&#39;: employee[&#39;name&#39;],<br>            &#39;position&#39;: employee[&#39;position&#39;],<br>            &#39;salary&#39;: employee[&#39;salary&#39;]<br>        }<br>    return extracted_data</pre><p>Once you are done with writing a working code to extract desired value from your JSON, make sure you convert it into a function for better usability.</p><p>Now that we have completed basics steps of reading our JSON file and learning how to access values from it, we will start with developing our Flask App.</p><p>To get started with Flask, you first need to install it in your environment.</p><pre>pip install Flask</pre><p>Once the installation is complete, you can verify that Flask is installed by typing</p><pre>flask --version</pre><p>We start by importing Flask</p><pre>from flask import Flask, render_template<br>import json<br><br>app = Flask(__name__)</pre><p>We will now add our function to this code.</p><pre>@app.route(&#39;/&#39;)<br>def display_data():<br>    return render_template(&#39;index.html&#39;, employees=employees_dict)<br><br>__name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>Now, we have to write the html code Index.html which will be displayed on the web page. We keep Index.html inside templates folder, which is on the same level as the main.py, where our rest of the python code is written. Here is the code for Index.html:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*1to24wlsRCrHgv8vgwZT-g.png" /></figure><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Employee Data&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Employee Data&lt;/h1&gt;<br>    &lt;table border=&quot;1&quot;&gt;<br>        &lt;thead&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;ID&lt;/th&gt;<br>                &lt;th&gt;Name&lt;/th&gt;<br>                &lt;th&gt;Position&lt;/th&gt;<br>                &lt;th&gt;Salary&lt;/th&gt;<br>            &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>            {% for id, employee in employees.items() %}<br>            &lt;tr&gt;<br>                &lt;td&gt;{{ id }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.name }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.position }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.salary }}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            {% endfor %}<br>        &lt;/tbody&gt;<br>    &lt;/table&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><ul><li>We start with the standard HTML structure.</li><li>Inside the &lt;body&gt; tag, we have a heading that says &quot;Employee Data.&quot;</li><li>We use a table to organize our employee data.</li><li>Within the table, we have table headers (&lt;th&gt;) for ID, Name, Position, and Salary.</li><li>We use a Jinja for loop to iterate over each employee in the employees dictionary.</li><li>For each employee, we display their ID, name, position, and salary within table cells</li></ul><pre> {% for id, employee in employees.items() %}<br>            &lt;tr&gt;<br>                &lt;td&gt;{{ id }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.name }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.position }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.salary }}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            {% endfor %}</pre><p>This part of the HTML code is a for loop, which is a Jinja template. A Jinja template is used in Flask to render dynamic HTML content.</p><p>Here, employees is the dictionary that we got from python function from parsing the JSON file. We are iterating over our dictionary and are displaying the values in the form of a table.</p><p>Here is the complete code:</p><p>JSON Document:</p><pre>{<br>    &quot;employees&quot;: [<br>      {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;John Doe&quot;,<br>        &quot;position&quot;: &quot;Software Engineer&quot;,<br>        &quot;salary&quot;: 70000<br>      },<br>      {<br>        &quot;id&quot;: 2,<br>        &quot;name&quot;: &quot;Jane Smith&quot;,<br>        &quot;position&quot;: &quot;Data Scientist&quot;,<br>        &quot;salary&quot;: 80000<br>      },<br>      {<br>        &quot;id&quot;: 3,<br>        &quot;name&quot;: &quot;Michael Johnson&quot;,<br>        &quot;position&quot;: &quot;Product Manager&quot;,<br>        &quot;salary&quot;: 90000<br>      }<br>    ]<br>  }</pre><p>Main.py :</p><pre>from flask import Flask, render_template<br>import json<br><br>app = Flask(__name__)<br><br># Load the JSON data<br>input_file= &quot;json_for_blog.json&quot;<br>with open(input_file, encoding=&quot;utf-8&quot;) as json_file:<br>    parsed_json = json.load(json_file)<br><br># Function to extract values into a dictionary<br>def extract_data(json_data):<br>    extracted_data = {}<br>    for employee in json_data[&#39;employees&#39;]:<br>        extracted_data[employee[&#39;id&#39;]] = {<br>            &#39;name&#39;: employee[&#39;name&#39;],<br>            &#39;position&#39;: employee[&#39;position&#39;],<br>            &#39;salary&#39;: employee[&#39;salary&#39;]<br>        }<br>    return extracted_data<br><br># Extract the data into a dictionary<br>employees_dict = extract_data(parsed_json)<br><br># Route to display data<br>@app.route(&#39;/&#39;)<br>def display_data():<br>    return render_template(&#39;index.html&#39;, employees=employees_dict)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>Index.html</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Employee Data&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;Employee Data&lt;/h1&gt;<br>    &lt;table border=&quot;1&quot;&gt;<br>        &lt;thead&gt;<br>            &lt;tr&gt;<br>                &lt;th&gt;ID&lt;/th&gt;<br>                &lt;th&gt;Name&lt;/th&gt;<br>                &lt;th&gt;Position&lt;/th&gt;<br>                &lt;th&gt;Salary&lt;/th&gt;<br>            &lt;/tr&gt;<br>        &lt;/thead&gt;<br>        &lt;tbody&gt;<br>            {% for id, employee in employees.items() %}<br>            &lt;tr&gt;<br>                &lt;td&gt;{{ id }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.name }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.position }}&lt;/td&gt;<br>                &lt;td&gt;{{ employee.salary }}&lt;/td&gt;<br>            &lt;/tr&gt;<br>            {% endfor %}<br>        &lt;/tbody&gt;<br>    &lt;/table&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LdfHLpDpyj50oP_yMCk-oQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0b415f3f0a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>