<?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 NadeeshaMadusanka on Medium]]></title>
        <description><![CDATA[Stories by NadeeshaMadusanka on Medium]]></description>
        <link>https://medium.com/@nadeeshamadusanka44?source=rss-46e71cbcb1ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mK2Ynxbvpgw2zYRL3nuuQg.jpeg</url>
            <title>Stories by NadeeshaMadusanka on Medium</title>
            <link>https://medium.com/@nadeeshamadusanka44?source=rss-46e71cbcb1ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:12:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nadeeshamadusanka44/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[Honeypots: Inspired by Mr.Robot]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/honeypots-inspired-by-mr-robot-fa6e44ae723e?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa6e44ae723e</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[threat-detection]]></category>
            <category><![CDATA[honeypot]]></category>
            <category><![CDATA[network-security]]></category>
            <category><![CDATA[cyber-defense]]></category>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 13:17:36 GMT</pubDate>
            <atom:updated>2025-01-04T13:17:36.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IqFchaTfRCnE6pfg" /><figcaption>Adapted from <a href="https://www.strongdm.com/blog/what-is-a-honeypot">source</a></figcaption></figure><h3>1. Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*POETXpt83Z8fftk-" /></figure><p>While watching the 8th episode of<strong> <em>Mr. Robot </em></strong>season 01, I heard the term ‘<strong><em>honeypot’</em> </strong>for the first time. It caught my attention because the idea of setting up fake systems to trick hackers seemed really interesting. I wanted to know more, so I looked into it. What I found was something truly clever. It’s an effective tool that helps stop cybercriminals in their tracks.</p><p>Honeypots are not just fake systems; they act as traps to catch hackers and learn about their strategies. By pretending to be vulnerable, they distract attackers from real systems and give important information about cyber threats. But how exactly do they work, and why are they so useful? Let’s explore.</p><h3>2. What is a Honeypot?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*FiVdu6GFTiOU45Is" /><figcaption>Adapted from <a href="https://proxyscrape.com/blog/what-are-honeypots">source</a></figcaption></figure><p>Honeypot is a tool used in cybersecurity that acts as a decoy system, designed to look like a real network or service. The idea is to make it appear vulnerable so that hackers will be attracted to it, thinking they can exploit it for malicious purposes.</p><p>But, in reality, it’s a trap. While the hacker tries to breach this decoy system, security teams can gather valuable information about their methods, techniques, and tools. This helps cybersecurity experts stay one step ahead, understanding the tactics of attackers before they target actual systems.</p><p>In short, honeypots serve three main purposes:</p><ol><li><strong>Collect Intelligence: </strong>They gather details about how hackers operate, which can be used to improve defenses.</li><li><strong>Study Attackers:</strong> By monitoring their activities, security teams can learn how different types of cyberattacks work.</li><li><strong>Deflect Threats:</strong> They draw attention away from real systems, protecting valuable data and services from potential harm.</li></ol><p>By using honeypots, organizations can proactively defend against cyberattacks while also gathering insights that help strengthen overall security.</p><h3>3. How Do Honeypots Work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*VF9QOp_mgd6zmgLH" /><figcaption>Adapted from <a href="https://www.idstrong.com/sentinel/how-honeypot-protects-against-cyber-attacks/">source</a></figcaption></figure><p>Honeypots work by using three main steps and here’s how each of these steps functions:</p><ol><li><strong>Attraction:<br></strong>The first step is to simulate a vulnerable system. This could be anything from a fake website, an open port on a server, or a fake login page. The idea is to make it appear as though it holds valuable data or services that a hacker would want to exploit. These decoys are designed to look like legitimate targets, drawing hackers into attempting an attack.</li><li><strong>Monitoring:<br></strong>Once a hacker tries to break into the system, the honeypot’s job is to track their every move. The system is designed to record all the activities of the attacker. Such as IP addresses, the tools used, and the steps they take to try to exploit the system. This information is logged and carefully analyzed to understand the attacker’s behavior and techniques.</li><li><strong>Response:<br></strong>After the attack is captured, security experts use the data gathered from the honeypot to improve the real defenses of the organization. By understanding what methods attackers use to breach the system, they can make the real network more secure by patching vulnerabilities or strengthening security measures.</li></ol><h3>4. Types of Honeypots</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ny-7HOEhMCczbk_S" /><figcaption>Adapted from <a href="https://www.hackingarticles.in/comprehensive-guide-on-honeypots/">source</a></figcaption></figure><p>There are two main types of honeypots: <strong>Research Honeypots</strong> and <strong>Production Honeypots</strong>. Each serves a different purpose, but both are crucial in cybersecurity.</p><h4>4.1. Research Honeypots</h4><p>Research honeypots are designed to gather detailed information about attack methods and the behaviors of cybercriminals. Their primary goal is to learn as much as possible about how hackers operate and what tactics, techniques, and procedures (TTPs) they use. These honeypots are often deployed in environments where the main aim is to study attackers, understand the tools they use, and observe how they exploit systems.</p><blockquote><strong>Example:<br></strong>A research honeypot could simulate a vulnerable web application. By observing how attackers target this application, whether they use SQL injection, cross-site scripting, or other techniques. The cybersecurity team can gather valuable data on emerging attack trends.</blockquote><h4>4.2. Production Honeypots</h4><p>Production honeypots are used in live environments to protect real systems by diverting attackers away from valuable resources. Instead of acting as purely informational tools, production honeypots are more integrated with a network’s defenses. Their purpose is to confuse attackers into thinking they’ve compromised a real system, while in reality, they’re engaging with a decoy. These honeypots allow organizations to isolate and contain threats before they can affect critical systems.</p><blockquote><strong>Example:<br></strong>Consider an IoT (Internet of Things) honeypot. A company may set up a fake smart device that seems like a real part of its network. When attackers try to exploit the device, they are diverted from more critical IoT systems or servers. This keeps the actual devices safe and allows security teams to monitor the attacker’s actions in a controlled environment.</blockquote><p>Both types of honeypots provide crucial information, whether it’s for studying attackers or for protecting real systems, making them an essential part of modern cybersecurity strategies.</p><h3>5. Real-World Relevance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X7ndy2GmYm49pNfL" /><figcaption>Adapted from <a href="https://labs.leaseweb.com/real-time-honeypot-attack-map-ce2b48cf1cd5">source</a></figcaption></figure><p>Honeypots have become an integral part of modern cybersecurity strategies, especially as cyberattacks grow more sophisticated and frequent. Organizations across various industries use honeypots to detect, analyze, and mitigate threats before they can impact critical systems. Here’s why they’re so important:</p><h4>5.1. Financial Institutions</h4><p>Financial institutions are prime targets for cybercriminals, with attackers constantly looking for ways to steal sensitive customer data or execute fraud. Honeypots in this sector are used to simulate fake banking systems, payment processing platforms, or even ATM networks. By luring attackers into these decoy systems, security teams can monitor their tactics and protect real financial data from theft or compromise.</p><blockquote><strong>Example:</strong> A bank might deploy a honeypot to monitor attempts to breach their online payment portal. This helps them identify new attack patterns like phishing schemes or credential stuffing before they can affect actual customers.</blockquote><h4>5.2. Government Systems</h4><p>Government systems, from defense to public services, are often targeted by advanced persistent threats (APTs) or nation-state actors. Honeypots in government networks act as a first line of defense, detecting early signs of unauthorized access. These systems help security professionals track hacker movements and prevent potentially catastrophic breaches.</p><blockquote><strong>Example:</strong> A government agency might use a honeypot to simulate a fake internal network, where attackers might try to exploit vulnerabilities. Any interaction with the honeypot helps identify cyber threats aimed at stealing confidential information or disrupting critical infrastructure.</blockquote><h4>5.3. Healthcare Sector</h4><p>Healthcare institutions store sensitive personal and medical information, making them a major target for ransomware attacks and data theft. By setting up honeypots that mimic patient databases or health record management systems, these organizations can divert attackers, while continuously learning about attack techniques.</p><blockquote><strong>Example:</strong> A hospital might deploy a honeypot to simulate a hospital management system. If an attacker attempts to access patient data, the organization can isolate the threat and take immediate action to safeguard real medical records.</blockquote><h4>5.4. E-Commerce and Retail</h4><p>E-commerce and retail companies often face attacks targeting payment systems and customer data. By using honeypots to mimic fake shopping carts, payment gateways, or customer databases, these businesses can trap hackers looking to steal credit card information or manipulate transactions.</p><blockquote><strong>Example:</strong> An online retailer could set up a honeypot to look like a payment processing system. If cybercriminals attempt to exploit vulnerabilities, they are redirected to the honeypot, where their activity can be logged and studied.</blockquote><h4>5.5. Critical Infrastructure</h4><p>Critical infrastructure industries, like energy, utilities, and transportation, are at high risk from cyberattacks, which can have wide-reaching consequences. Honeypots can act as an early warning system by attracting attackers who try to infiltrate power grids, water supply systems, or transportation networks.</p><blockquote><strong>Example:</strong> A power plant could deploy a honeypot to simulate control systems. If an attacker tries to infiltrate the plant’s infrastructure, the honeypot diverts them while security teams analyze the threat.</blockquote><p>In these industries, honeypots are vital not only for protecting assets but also for improving the overall cybersecurity posture by gathering intelligence on emerging attack techniques and refining security protocols. By using honeypots, organizations can stay one step ahead of attackers and ensure they are better prepared to handle future threats.</p><h3>6. Conclusion: Why Honeypots Matter</h3><p>Honeypots are vital tools in cybersecurity, acting as both defensive shields and research instruments. By simulating vulnerable systems, they not only divert attackers but also provide insights into hacker tactics, strengthening real defenses.</p><p>As cyber threats grow more sophisticated, honeypots help organizations stay proactive and improve their security. They enable teams to understand evolving risks and adjust defenses accordingly.</p><p>In today’s rapidly changing cyber landscape, honeypots remind us that the best defense is often a clever offense, using decoys to stay one step ahead of attackers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa6e44ae723e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Mutex and Semaphores: Senate Bus Stop Simulation]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/understanding-mutex-and-semaphores-senate-bus-stop-simulation-18a61ae3c4d4?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/18a61ae3c4d4</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[parallel-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 10:31:39 GMT</pubDate>
            <atom:updated>2024-10-25T10:31:39.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b26M3PQZmEUi9SYY1oC5AQ.jpeg" /></figure><h3>Introduction</h3><p>Concurrent programming is a fundamental concept in modern software development, where multiple processes or threads execute simultaneously. However, this concurrent execution brings challenges like race conditions, deadlocks, and resource contention. Two primary tools to handle these challenges are mutex and semaphores.</p><h3>Theoretical Foundation</h3><h4>Understanding Process Synchronization</h4><p>In concurrent programming, multiple processes or threads may need to access shared resources. Without proper synchronization, this can lead to:</p><ul><li><strong>Race conditions: </strong>When multiple threads access shared data simultaneously</li><li><strong>Deadlocks: </strong>When threads are stuck waiting for each other</li><li><strong>Resource contention:</strong> When multiple threads compete for limited resources</li></ul><h4>Mutex (Mutual Exclusion)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*G3-2W1o_UGLZ8oJciLJQEA.jpeg" /><figcaption>Adapted from <a href="https://codegym.cc/groups/posts/220-whats-the-difference-between-a-mutex-a-monitor-and-a-semaphore">source</a></figcaption></figure><p>A mutex is a synchronization primitive that provides exclusive access to a shared resource. Think of it as a single key to a room:</p><ul><li>Only one thread can hold the mutex at a time</li><li>Other threads must wait until the mutex is released</li><li>Used for exclusive access to critical sections</li></ul><h4>Semaphores</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*JUigjY9YFuOReZSr8DnFMg.jpeg" /><figcaption>Adapted from <a href="https://codegym.cc/groups/posts/220-whats-the-difference-between-a-mutex-a-monitor-and-a-semaphore">source</a></figcaption></figure><p>A <strong>semaphore</strong> is a synchronization primitive that manages access to shared resources through a counter, representing available permits.</p><p><strong>Key Points:</strong></p><ul><li><strong>Resource Management:</strong> Can handle multiple resources.</li><li><strong>Permit System:</strong> Counter tracks available resources.</li></ul><p><strong>Operations:</strong></p><ol><li><strong>P (wait/acquire):</strong> Decreases the counter, indicating resource use.</li><li><strong>V (signal/release):</strong> Increases the counter, indicating resource availability.</li></ol><p><strong>Semaphore Types:</strong></p><ol><li><strong>Binary Semaphore:</strong> Counter is 0 or 1, like a mutex.</li><li><strong>Counting Semaphore:</strong> Counter ranges from 0 to n, used for managing multiple resources.</li></ol><h3>The Problem Statement: Senate Bus Problem</h3><p>The Senate Bus problem is a classic synchronization challenge from Wellesley College that demonstrates these concepts in action.</p><p>The scenario involves:</p><ul><li>Multiple riders arrive randomly at a bus stop.</li><li>Buses arrive periodically with a capacity of 50 riders.</li><li>When a bus arrives, up to 50 waiting riders can board.</li><li>No new riders can board once the bus starts loading.</li><li>Riders arriving after boarding starts must wait for the next bus.</li><li>Ensures orderly boarding and prevents overcrowding.</li></ul><h4>Synchronization Challenges</h4><ol><li><strong>Mutual Exclusion</strong>: Only one bus can load at a time</li><li><strong>Ordering</strong>: Riders must board in sequence</li><li><strong>Capacity Management</strong>: Maximum 50 riders per bus</li><li><strong>Arrival Management</strong>: New arrivals during boarding must wait</li></ol><h3>Implementation Deep Dive</h3><p><strong>Core Components and Their Theoretical Basis</strong></p><ol><li><strong>Synchronization Primitives</strong></li></ol><pre>public class BusStop {<br>    private static final int BUS_CAPACITY = 50;<br>    private Semaphore waitingRiders = new Semaphore(0);<br>    private Semaphore busMutex = new Semaphore(1);<br>    private Semaphore allAboard = new Semaphore(0);<br>    private int waitingRiderCount = 0;<br>}</pre><p><strong>Theory Behind the Implementation:</strong></p><ul><li><em>busMutex</em>: Ensures only one bus can load passengers at a time (mutual exclusion).</li><li><em>waitingRiders</em>: Controls the number of riders boarding, like a gate that opens when allowed (boarding control).</li><li><em>allAboard</em>: Ensures all riders that are eligible for the bus have boarded before the bus leaves (synchronization).</li></ul><p><strong>2. Critical Section Management</strong></p><p><strong>Theory:</strong></p><p>A critical section is a code segment where shared resources are accessed. It requires:</p><ul><li><strong>Mutual Exclusion</strong>: Only one thread can access the critical section at a time, ensuring no overlap.</li><li><strong>Progress</strong>: Threads should be able to move forward without unnecessary delays or waiting.</li><li><strong>Bounded Waiting</strong>: Each thread should eventually get a chance to enter the critical section, avoiding infinite waiting times.</li></ul><p>This prevents issues like race conditions and ensures orderly access to shared resources.</p><p><strong>Implementation:</strong></p><pre>public synchronized void riderArrives() throws InterruptedException {<br>    waitingRiderCount++;<br>    System.out.println(&quot;BusStop: Rider arrived. Waiting riders: &quot; + waitingRiderCount);<br>}</pre><p>The <em>synchronized </em>keyword ensures:</p><ul><li>Only one thread can execute this method at a time</li><li>Atomic update of <em>waitingRiderCount</em></li><li>Automatic mutex acquisition and release</li></ul><p><strong>3. Producer-Consumer Pattern</strong></p><p><strong>Theory:</strong></p><p>The Producer-Consumer pattern manages interactions between:</p><ul><li><strong>Producers</strong>: These are entities that generate or create resources. In our context, the bus represents the producer that creates boarding permits for riders.</li><li><strong>Consumers</strong>: These are entities that use or consume the resources created by producers. Here, riders act as consumers who use the boarding permits to board the bus.</li><li><strong>Buffer Overflow</strong>: This occurs when producers generate resources faster than consumers can process them.</li><li><strong>Buffer Underflow</strong>: This happens when consumers attempt to consume resources that are not yet available. Without proper synchronization, consumers might end up waiting indefinitely.</li><li><strong>Race Conditions</strong>: This occurs when multiple threads access shared data simultaneously without proper synchronization.</li></ul><p><strong>Implementation:</strong></p><p>Producer (Bus):</p><pre>// Producer (Bus)<br>public void busArrives() throws InterruptedException {<br>    busMutex.acquire();<br>    int boarding = Math.min(waitingRiderCount, BUS_CAPACITY);<br>    <br>    // Produce boarding permits<br>    for (int i = 0; i &lt; boarding; i++) {<br>        waitingRiders.release();<br>    }<br>}</pre><ul><li>When the bus arrives, it first acquires the busMutex to ensure that no other bus can load passengers at the same time.</li><li>It then calculates how many riders can board, which is the lesser of the number of waiting riders and the bus’s capacity.</li><li>For each rider that can board, it releases a permit from the <em>waitingRiders </em>semaphore, effectively signaling that a rider can board the bus.</li></ul><p>Consumer (Rider):</p><pre>// Consumer (Rider)<br>public void boardBus() throws InterruptedException {<br>    // Consume boarding permit<br>    waitingRiders.acquire();<br>    allAboard.release();<br>}</pre><ul><li>Each rider attempts to board the bus by acquiring a permit from the <em>waitingRiders</em> semaphore. This ensures that they only board if there is a permit available.</li><li>After successfully boarding, the rider releases a permit from the <em>allAboard </em>semaphore to signal that they are on the bus and ready for departure.</li></ul><p><strong>4. Barrier Synchronization</strong></p><p><strong>Theory:</strong></p><p>A barrier ensures that all threads in a group reach a certain point before any can proceed. This is useful for:</p><ul><li><strong>Coordinated Actions</strong>: In many scenarios, threads may need to perform a set of operations before moving on to the next phase. Barriers ensure that all threads complete their current tasks before any can continue.</li><li><strong>Phase Synchronization</strong>: Barriers are useful for synchronizing threads that are working on different phases of a computation. For example, in simulations or multi-step calculations, each phase may depend on the completion of the previous one.</li><li><strong>Batch Processing</strong>: In scenarios where multiple resources are processed in batches, barriers can ensure that all resources are ready before proceeding with batch processing. This is important for maintaining consistency and preventing race conditions.</li></ul><p><strong>Implementation:</strong></p><pre>public void busArrives() throws InterruptedException {<br>    // ... previous code ...<br>    <br>    // Barrier implementation<br>    for (int i = 0; i &lt; boarding; i++) {<br>        allAboard.acquire();<br>    }<br>    <br>    waitingRiderCount -= boarding;<br>}</pre><ul><li><strong>Waiting for All Riders</strong>: The loop <em>for (int i = 0; i &lt; boarding; i++)</em> iterates for each rider that is boarding the bus. For each iteration, the bus calls <em>allAboard.acquire()</em>. This call serves as a synchronization barrier, where each bus must wait until all designated riders have boarded before it can proceed to the next step (e.g., departing).</li><li><strong>Ensuring Completeness</strong>: By requiring all riders to signal they have boarded (through the <em>allAboard </em>semaphore), the bus ensures that it does not leave with missing riders. This not only maintains order but also enhances safety by preventing the bus from departing prematurely.</li><li><strong>Updating Waiting Count</strong>: After all riders have boarded, the bus updates the <em>waitingRiderCount </em>to reflect the number of riders who successfully boarded. This step is crucial to ensure that the system accurately tracks the number of riders waiting for the next bus.</li></ul><h3>Putting It All Together: The Complete System</h3><h4><strong>The Rider Class:</strong></h4><pre>public class Rider implements Runnable {<br>    private static int riderCount = 0;<br>    private int id;<br>    private BusStop busStop;<br><br>    public Rider(BusStop busStop) {<br>        this.busStop = busStop;<br>        this.id = ++riderCount;<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            busStop.riderArrives();  // Enter critical section<br>            busStop.boardBus();      // Consume boarding permit<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><p><strong>Key Components</strong>:</p><ul><li><em>static int riderCount</em>: This variable keeps track of the total number of riders created. It is static because it is shared among all instances of the <em>Rider </em>class.</li><li><em>int id</em>: Each rider is assigned a unique ID to distinguish between different riders.</li><li><em>BusStop busStop</em>: This field holds a reference to the shared <em>BusStop </em>object, allowing the rider to interact with the bus stop’s methods.</li></ul><p><strong>Method</strong>:</p><p><em>run()</em>: This method is called when the rider thread starts. It attempts to:</p><ul><li>Call <em>busStop.riderArrives()</em>: This method updates the count of waiting riders and may enter a critical section, ensuring thread safety when accessing shared resources.</li><li>Call <em>busStop.boardBus()</em>: This method allows the rider to board the bus by consuming a boarding permit. It handles the synchronization required to ensure that only a certain number of riders can board at once.</li></ul><p><strong>Error Handling</strong>:</p><ul><li>If the thread is interrupted during its operations, the exception is caught, and the thread’s interrupted status is set using <em>Thread.currentThread().interrupt()</em>. This ensures proper handling of thread interruptions.</li></ul><h4><strong>The Bus Class:</strong></h4><pre>public class Bus implements Runnable {<br>    private BusStop busStop;<br><br>    public Bus(BusStop busStop) {<br>        this.busStop = busStop;<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            busStop.busArrives();    // Produce boarding permits<br>            TimeUnit.SECONDS.sleep(2);<br>            busStop.busDeparts();    // Release resources<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><p><strong>Method</strong>:</p><p><em>run()</em>: This method is called when the bus thread starts. It attempts to:</p><ul><li>Call <em>busStop.busArrives()</em>: This method signals the arrival of the bus, producing boarding permits for the riders waiting at the bus stop.</li><li><em>TimeUnit.SECONDS.sleep(2)</em>: This line simulates a delay (in this case, 2 seconds) to represent the time it takes for riders to board the bus. This is a crucial step as it gives riders a chance to board before the bus departs.</li><li>Call <em>busStop.busDeparts()</em>: This method releases any resources and signals that the bus is now leaving.</li></ul><p><strong>Error Handling</strong>:</p><ul><li>Similar to the <em>Rider </em>class, if the bus thread is interrupted during its operations, the exception is caught, and the thread’s interrupted status is set.</li></ul><h4><strong>The BusStop Class:</strong></h4><p><a href="https://github.com/nadeeshaMadusanka99/bus_riders_synchronization/blob/master/src/BusStop.java">bus_riders_synchronization/src/BusStop.java at master · nadeeshaMadusanka99/bus_riders_synchronization</a></p><blockquote>Since the code is kinda long, I’m embedding the class file from my github repo. Go check that out</blockquote><p>The <em>BusStop </em>class serves as the central hub for managing riders and buses. It controls the synchronization between the arriving riders and the buses, ensuring that boarding occurs smoothly and without race conditions.</p><p><strong>Key Components</strong>:</p><ul><li>waitingRiders: Controls the number of riders waiting to board.</li><li>busMutex: Ensures mutual exclusion during bus loading.</li><li>allAboard: Implements a barrier, ensuring all riders have boarded before the bus departs.</li></ul><p><strong>Methods</strong>:</p><ul><li><em>riderArrives()</em>: Updates the count of waiting riders.</li><li><em>busArrives()</em>: Manages the arrival of a bus, releasing permits for boarding and ensuring all riders board before departure.</li><li><em>boardBus()</em>: Allows riders to board the bus by acquiring a permit.</li><li><em>busDeparts()</em>: Signals that the bus has left.</li></ul><h4><strong>The BusSimulation Class:</strong></h4><p><a href="https://github.com/nadeeshaMadusanka99/bus_riders_synchronization/blob/master/src/BusSimulation.java">bus_riders_synchronization/src/BusSimulation.java at master · nadeeshaMadusanka99/bus_riders_synchronization</a></p><blockquote>Since the code is kinda long, I’m embedding the class file from my GitHub repo. Go check that out</blockquote><p>The <em>BusSimulation </em>class orchestrates the entire simulation. It initializes the <em>BusStop </em>and creates threads for both riders and the bus.</p><p><strong>Key Components</strong>:</p><ul><li><strong>ExecutorService</strong>: Manages a pool of threads for simulating the arrival of multiple riders concurrently. This is a convenient way to handle multithreading.</li></ul><p><strong>Main Method</strong>:</p><ul><li>Creates a fixed thread pool based on the total number of riders.</li><li>Iteratively creates and starts <em>Rider </em>threads, each trying to arrive at the bus stop.</li><li>Creates and starts a single <em>Bus </em>thread to manage bus operations.</li><li>Calls <em>executor.shutdown()</em> to ensure the executor stops accepting new tasks after all riders are executed.</li></ul><h3>Conclusion</h3><p>Understanding the theoretical foundations of synchronization primitives helps in:</p><ol><li>Designing robust concurrent systems</li><li>Avoiding common pitfalls</li><li>Implementing efficient solutions</li><li>Debugging synchronization issues</li></ol><p>The Senate Bus problem demonstrates how these theoretical concepts translate into practical implementation, providing a concrete example of:</p><ul><li>Mutex usage for exclusive access</li><li>Semaphores for resource management</li><li>Barrier synchronization for coordinated actions</li><li>Producer-Consumer pattern implementation</li></ul><p>This combination of theory and practice provides a solid foundation for tackling real-world concurrent programming challenges.</p><h4>Reference:</h4><p>Problem based on <a href="https://greenteapress.com/semaphores/LittleBookOfSemaphores.pdf">“Little Book of Semaphores”</a> page 211.</p><h4>GitHub Repo:</h4><p><a href="https://github.com/nadeeshaMadusanka99/bus_riders_synchronization.git">GitHub - nadeeshaMadusanka99/bus_riders_synchronization</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18a61ae3c4d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Canny Edge Detection Explained: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/canny-edge-detection-explained-a-step-by-step-guide-f51dad94fa9b?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/f51dad94fa9b</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[canny-edge-detection]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Tue, 15 Oct 2024 03:45:00 GMT</pubDate>
            <atom:updated>2024-10-15T03:45:00.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gqt54nv8ukatmS2GoxgI3g.jpeg" /><figcaption>Results of the python script</figcaption></figure><p>Hello there! Recently, I had the opportunity to work on Canny Edge Detection as part of a university assignment and it was very interesting to explore how it works. Canny Edge Detection is a powerful technique used in image processing to identify the edges of objects within an image. This method is widely used in various applications, from computer vision to robotics.</p><p>In this article, we will break down the Canny edge detection algorithm into simple steps and provide code snippets to illustrate each part of the process.</p><h3>What is Canny Edge Detection?</h3><p>Canny edge detection was developed by John F. Canny in 1986. It aims to detect a wide range of edges in images while minimizing noise and false detections. The algorithm consists of several key steps that transform an input image into a binary image, highlighting the detected edges.</p><h3>Steps of Canny Edge Detection</h3><p>Here are the main steps involved in the Canny edge detection algorithm</p><ol><li><strong>Convert the Image to Grayscale:</strong> Transform the color image into a single-channel grayscale image.</li><li><strong>Apply Gaussian Blur</strong>: Reduce noise in the image using a Gaussian blur.</li><li><strong>Calculate Gradients</strong>: Determine where the intensity changes significantly using Sobel filters.</li><li><strong>Non-Maximum Suppression</strong>: Thin out the detected edges by keeping only local maxima in the gradient magnitude.</li><li><strong>Double Thresholding</strong>: Classify pixels as strong edges or weak edges based on their gradient values.</li><li><strong>Final Edge Selection</strong>: Perform edge tracking by hysteresis to finalize which weak edges should be retained based on their connectivity to strong edges.</li></ol><p>Now, let’s dive into each step in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vzarLiJihT2bk2ZqZoTNg.jpeg" /><figcaption>Input Image</figcaption></figure><h4>Step 1: Convert the Image to Grayscale</h4><p>The first step in the Canny edge detection process is converting the color image into a grayscale image. This transformation simplifies the data we need to process and focuses on intensity rather than color.</p><h4>Why Convert to Grayscale?</h4><ul><li><strong>Reduced Complexity: </strong>Color images contain multiple channels (typically three for RGB). By converting to grayscale, we reduce this to a single channel, simplifying calculations and speeding up processing.</li><li><strong>Focus on Intensity:</strong> Edges are primarily defined by changes in intensity rather than color. Grayscale images highlight these changes more clearly, making it easier for algorithms to detect edges.</li><li><strong>Noise Reduction:</strong> Working with a single channel can help minimize noise that may be present in individual color channels, leading to cleaner edge detection results.</li></ul><pre>def rgb_to_grayscale(rgb_image):<br>    r, g, b = rgb_image[:, :, 0], rgb_image[:, :, 1], rgb_image[:, :, 2]<br>    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b<br>    return gray.astype(np.uint8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtgRAM133IqNzQfa-RI5xA.png" /><figcaption>Output after converting to greyscale</figcaption></figure><h4>Step 2: Apply Gaussian Blur</h4><p>The first step in the Canny edge detection process is to reduce noise in the image using a Gaussian blur. This helps smooth out the image, making it easier to detect edges.</p><pre>def gaussian_blur(image, kernel_size=5, sigma=1):<br>    kernel = gaussian_kernel(kernel_size, sigma)<br>    blurred = conv2d(image, kernel)<br>    return blurredp</pre><p>Here I did not provide the kernel making function and conv2d function, I’m just giving you the steps that are need to be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oX-CnhIK5eEDFsCAN3RyyA.png" /><figcaption>Output after the gaussian blur</figcaption></figure><h4>Step 3: Calculate Gradients</h4><p>Next, we need to calculate the gradients of the image using Sobel filters. So that previous blurred image is sent to this function. This step helps us determine where the intensity changes significantly, indicating potential edges.</p><pre>def sobel_filters(img):<br>    # Sobel kernels<br>    Kx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float32)<br>    Ky = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], np.float32)<br><br>    # Convolve kernels with image<br>    Ix = conv2d(img, Kx)<br>    Iy = conv2d(img, Ky)<br><br>    # Calculate gradient magnitude and direction<br>    G = np.hypot(Ix, Iy)<br>    # Normalize gradient values to 0-255<br>    G = G / G.max() * 255<br>    theta = np.arctan2(Iy, Ix)<br>    return G, theta</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-GH1hMEZA4aX0AlL-JYRKQ.png" /><figcaption>Gradient output of the function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8whfVWa1Qceg0_wTuZhQDw.png" /><figcaption>Theta output of the function</figcaption></figure><h4>Step 4: Non-Maximum Suppression</h4><p>After calculating the gradients, we apply non-maximum suppression. This step thins out the detected edges by keeping only local maxima(points where the gradient value is higher than its neighboring points in the direction of the gradient) in the gradient magnitude .</p><pre>def non_max_suppression(img, theta):<br>    # Get image dimensions and angles in degrees<br>    M, N = img.shape<br>    output_img = np.zeros((M, N), dtype=np.int32)<br>    angle = theta * 180.0 / np.pi<br>    angle[angle &lt; 0] += 180<br><br>    # Perform non-maximum suppression<br>    for i in range(1, M - 1):<br>        for j in range(1, N - 1):<br>            try:<br>                q = 255<br>                r = 255<br><br>                # angle 0<br>                if (0 &lt;= angle[i, j] &lt; 22.5) or (157.5 &lt;= angle[i, j] &lt;= 180):<br>                    q = img[i, j + 1]  # Right pixel<br>                    r = img[i, j - 1]  # Left pixel<br>                # angle 45<br>                elif 22.5 &lt;= angle[i, j] &lt; 67.5:<br>                    q = img[i + 1, j - 1]  # Bottom-left pixel<br>                    r = img[i - 1, j + 1]  # Top-right pixel<br>                # angle 90<br>                elif 67.5 &lt;= angle[i, j] &lt; 112.5:<br>                    q = img[i + 1, j]  # Bottom pixel<br>                    r = img[i - 1, j]  # Top pixel<br>                # angle 135<br>                elif 112.5 &lt;= angle[i, j] &lt; 157.5:<br>                    q = img[i - 1, j - 1]  # Bottom-right pixel<br>                    r = img[i + 1, j + 1]  # Top-left pixel<br><br>                # Suppress non-maximum pixels<br>                if (img[i, j] &gt;= q) and (img[i, j] &gt;= r):<br>                    output_img[i, j] = img[i, j]<br>                else:<br>                    output_img[i, j] = 1<br><br>            except IndexError as e:<br>                pass<br><br>    return output_img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9mOZM_H7y7MUMeW0Zg8Kg.png" /><figcaption>Output after the suppression</figcaption></figure><h4>Step 5: Double Thresholding</h4><p>In this step, we apply double thresholding to classify pixels as strong edges or weak edges based on their gradient values.</p><pre>def dual_threshold(img, low_threshold_ratio=0.05, high_thhreshold_ratio=0.09):<br>    high_threshold = img.max() * high_thhreshold_ratio<br>    low_threshold = high_threshold * low_threshold_ratio<br><br>    M, N = img.shape<br>    result = np.zeros((M, N), dtype=np.int32)<br><br>    weak = np.int32(25)<br>    strong = np.int32(255)<br><br>    # Apply double thresholding<br>    strong_i, strong_j = np.where(img &gt;= high_threshold)<br>    zeros_i, zeros_j = np.where(img &lt; low_threshold)<br>    weak_i, weak_j = np.where((img &lt;= high_threshold) &amp; (img &gt;= low_threshold))<br><br>    # Set weak and strong edges in the image<br>    result[strong_i, strong_j] = strong<br>    result[weak_i, weak_j] = weak<br><br>    return result, weak, strong</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmjpTIPfwy69kaIGkdwovQ.png" /><figcaption>Threshold output of the function</figcaption></figure><h4>Step 6: Final Edge Selection</h4><p>Finally, we perform edge tracking by hysteresis to finalize which weak edges should be retained based on their connectivity to strong edges.</p><pre>def final_edge_selection(img, weak, strong):<br>    M, N = img.shape<br>    for i in range(1, M - 1):<br>        for j in range(1, N - 1):<br>            if img[i, j] == weak:<br>                try:<br>                    # Check if any of the 8-connected neighbors is a strong edge<br>                    if (<br>                        (img[i + 1, j - 1] == strong)<br>                        or (img[i + 1, j] == strong)<br>                        or (img[i + 1, j + 1] == strong)<br>                        or (img[i, j - 1] == strong)<br>                        or (img[i, j + 1] == strong)<br>                        or (img[i - 1, j - 1] == strong)<br>                        or (img[i - 1, j] == strong)<br>                        or (img[i - 1, j + 1] == strong)<br>                    ):<br>                        img[i, j] = strong<br>                    else:<br>                        img[i, j] = 0<br>                except IndexError as e:<br>                    pass<br>    return img</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGDV2UnCJxBrbyJr48ndsw.png" /><figcaption>Output of the final edge selection function:<strong> Final output</strong></figcaption></figure><h4>Putting It All Together</h4><p>Now that we have all the components defined for Canny edge detection, like this you can call all of them step by step.</p><pre>def canny_edge_detection(image):<br><br>    if len(image.shape) == 3:<br>        gray_image = rgb_to_grayscale(image)<br>    else:<br>        gray_image = image<br><br>    blurred = gaussian_blur(gray_image)<br><br>    gradients, theta = sobel_filters(blurred)<br><br>    suppressed = non_max_suppression(gradients, theta)<br><br>    thresholded, weak, strong = dual_threshold(suppressed)<br><br>    final_edges = final_edge_selection(thresholded, weak, strong)<br><br>    return final_edges</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gqt54nv8ukatmS2GoxgI3g.jpeg" /><figcaption>Results of the python script</figcaption></figure><h3>Conclusion</h3><p>Canny edge detection is a robust method for identifying edges in images. By following these steps you can effectively implement this algorithm in your own projects. This guide provides a comprehensive understanding of how Canny edge detection works and how you can implement it using Python code snippets. Whether you’re working on computer vision projects or just exploring image processing techniques for fun, this knowledge will serve you well!</p><p><strong>GitHub Repo:</strong> Here you can find the complete script of the canny edge detection <a href="https://github.com/nadeeshaMadusanka99/canny_edge_detector.git">https://github.com/nadeeshaMadusanka99/canny_edge_detector.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f51dad94fa9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Fit, Best Forecast: The Linear Regression Journey]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/best-fit-best-forecast-the-linear-regression-journey-492a36ee5d22?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/492a36ee5d22</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematical-modeling]]></category>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 09:52:41 GMT</pubDate>
            <atom:updated>2024-07-30T10:00:10.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/938/0*Tx_6_DaE7EqBlfbX" /><figcaption>Adapted from <a href="https://www.imsl.com/blog/what-is-regression-model">source</a></figcaption></figure><h3>1. Introduction</h3><p>Linear regression is a fundamental statistical technique used to model the relationship between a dependent variable and one or more independent variables. It assumes this relationship is linear, meaning it can be represented by a straight line on a graph.</p><p>In data analysis, linear regression is essential for several reasons:</p><h4>1.1. Simplicity and Interpretability:</h4><p>Linear regression provides a straightforward way to understand the relationship between variables, making it easy to explain trends and patterns in data.</p><h4>1.2. Predictive Power:</h4><p>Once established, a linear regression model can predict new, unseen data, which is valuable in many fields.</p><h4>1.3. Feature Importance:</h4><p>Linear regression helps identify which independent variables significantly impact the dependent variable, aiding in understanding complex systems.</p><p>To illustrate these concepts, we’ll use a practical example throughout this article, Predicting house prices based on their size. This example is intuitive and relatable, making it ideal for explaining linear regression to even beginners.</p><p>Imagine you’re a real estate agent trying to estimate the price of a house. You know that generally, larger houses tend to be more expensive. Linear regression can help quantify this relationship, allowing you to make more accurate price estimates based on a house’s square footage.</p><p>By the end of this article, you’ll understand how to use linear regression to model this relationship, make predictions, and evaluate the accuracy of your model.</p><h3>2. The Basics of Linear Regression</h3><h4>2.1. The Simple Equation:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*ZhhGEbs31WfM4Y0Vnn_kTA.png" /></figure><ul><li>y is the dependent variable (what we’re trying to predict)</li><li>x is the independent variable (what we’re using to make the prediction)</li><li>w is the slope of the line (how much y changes for each unit change in x)</li><li>b is the y-intercept (the value of y when x is zero)</li></ul><h4>2.2. In Our Context,</h4><p>For our house pricing example, we can translate this equation:</p><ul><li>Price is our dependent variable (y)</li><li>Size is our independent variable (x)</li><li>w represents the price increase per square foot</li><li>b represents the base price of a house (theoretically, the price of a house with zero square feet)</li></ul><p>So, our equation becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*xU25a6Isx6aIHOdEFG6KQA.png" /></figure><h4>2.3. Visualizing Raw Data</h4><p>Before we start building our model, it’s crucial to visualize our data. This helps us understand the relationship between house sizes and prices, and can reveal patterns or outliers in our dataset.</p><p>Here’s the Python code to import and visualize our sample data:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br><br># Load the dataset <br>data = pd.read_csv(&quot;house_pricing_dataset.csv&quot;)<br><br># Extract features (house_sizes) and target variable (house_prices) <br>house_sizes = data[&#39;Size&#39;].values <br>house_prices = data[&#39;Price&#39;].values  <br><br># Create a scatter plot<br>plt.figure(figsize=(8, 4))<br>plt.scatter(house_sizes, house_prices, alpha=0.5)<br>plt.xlabel(&quot;House Size (sq ft)&quot;)<br>plt.ylabel(&quot;Price (Rs)&quot;)<br>plt.title(&quot;House Prices vs Size&quot;)<br><br># Display the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*kQ0M5aDTtba-WYm_" /><figcaption><em>Figure 1</em></figcaption></figure><p>This code does the following:</p><ul><li>Imports necessary libraries, reads housing data from “<em>house_pricing_dataset.csv</em>” file, and extracts relevant columns for house sizes and prices.</li><li>We use Matplotlib to create a scatter plot of this data.</li></ul><p>When you run this code, you’ll see a scatter plot <em>Figure 1 </em>where each point represents a house, with its size on the x-axis and its price on the y-axis. This visualization should show a general upward trend, indicating that larger houses tend to be more expensive, but with some variation.</p><p>Understanding this raw data visualization is the first step in building an effective linear regression model. It helps us confirm that a linear model is appropriate and gives us a baseline understanding of the relationship we’re trying to model.</p><h3>3. The Mathematics Behind Linear Regression</h3><h4>3.1. The Vectorized Form:</h4><p>First, we used a simple equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*-C4Mc6iqMgrKZhn3OwHwOg.png" /></figure><p>This equation works well for a single feature (in our case, house size) but in real life house price not only depends only on house size, It has many dependencies. So, we need to generalize that equation to make it more flexible and powerful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*VPDDKsF797TMYxoZ0ihMzg.png" /></figure><p>but to move forward we’ll change the b to θ0 and w1,w2,…,wn to θ1, θ2,…, θn then the equation will be like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*ey7KeElL-Giyd5CoyxlLoQ.png" /></figure><p>This can be written much more concisely using a vectorized form as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*oc4TX7xgFW553zePMV5ZpA.png" /></figure><p>Here:</p><ul><li>ŷ (y-hat) represents our predicted value</li><li>hθ(x) is our hypothesis function</li><li>θ (theta) is a vector containing our parameters (w and b)</li><li>x is a vector of our input features, including a 1 for the bias term</li></ul><p>This form allows us to easily extend our model to multiple features if needed.</p><h4>3.2. Parameters θ: Slope and Intercept</h4><p>In our vectorized form, θ contains two values:</p><p>· θ1 (equivalent to w): The slope, indicating how much the price changes per unit change in house size.</p><p>· θ0 (equivalent to b): The y-intercept, representing the base price.</p><p>These parameters define our regression line and are what we need to optimize to create the best-fitting model.</p><h4>3.3. Cost Function: Mean Squared Error (MSE)</h4><p>The MSE is a way to measure how well our line fits the data. It’s calculated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*07YbV2eIsHVNfggLW5JAlg.png" /></figure><p>Here:</p><ul><li>n is the number of data points</li><li>y is the actual value</li><li>ŷ is our predicted value</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*0v0GgMVFrSvI4VxV" /><figcaption><em>Figure 2: Adapted from </em><a href="https://www.ml-science.com/mean-squared-error"><em>source</em></a></figcaption></figure><p>We use MSE because:</p><ul><li>It penalizes larger errors more heavily, which helps in finding a line that doesn’t have any extremely poor predictions.</li><li>It’s always positive, making it easier to interpret and optimize.</li><li>It’s differentiable, which is important for optimization algorithms.</li></ul><h4>3.4. The Normal Equation</h4><p>In linear regression, our goal is to find the best values for our parameters (, which includes w and b) that minimize the difference between our predictions and the actual data. The Normal Equation provides a direct mathematical solution to this problem.</p><p>The Normal Equation is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*xm2EduHeuIredK5wDm8wAw.png" /></figure><p>Here:</p><ul><li>θ is our parameter vector</li><li>X is our input data matrix (including a column of 1s for the bias term)</li><li>y is our target variable vector</li></ul><p>Here’s how we implement this in Python for our house pricing example:</p><pre>import numpy as np<br><br># Assuming we have our house_sizes and house_prices from earlier<br><br># Add x0 = 1 to each instance for the bias term<br>X_b = np.c_[np.ones((100, 1)), house_sizes]<br><br># Calculate theta using the Normal Equation<br>theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(house_prices)<br><br>print(&quot;Theta calculated using Normal Equation:&quot;, theta_best)</pre><pre>Theta calculated using Normal Equation: [[52150.96157547]<br> [97.70113386]]</pre><p>This code does the following:</p><ul><li>We add a column of 1s to our input data (<em>X_b</em>) to account for the bias term.</li><li>We use NumPy’s linear algebra functions to compute the inverse and dot products required by the Normal Equation.</li><li>The result, <em>theta_best</em>, gives us our optimal parameters.</li></ul><p>The Normal Equation approach is particularly useful for small to medium-sized datasets. It’s simple to implement and provides an exact solution. However, it’s worth noting that for very large datasets or when dealing with a high number of features, other methods might be more computationally efficient.</p><h4>3.5. Singular Value Decomposition (SVD) Approach</h4><p>Here we explore the Singular Value Decomposition (SVD) approach, which offers advantages in certain cases when compared to normal equation approaches.</p><p>Limitations of the Normal Equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*D3ffuLVbpiKsAYMnccv5XQ.png" /></figure><ul><li>Inverting the matrix (XTX) in the Normal Equation can become computationally expensive, especially for datasets with many features.</li></ul><p>SVD Approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*_oCPMu1fyB8CoeKC3VLhcw.png" /></figure><ul><li>SVD offers an alternative solution for linear regression by decomposing the design matrix (X) into three matrices: U, Σ, and V.</li><li>This decomposition allows us to calculate the <strong>pseudoinverse of X</strong>, which is a more efficient way to find the optimal parameters (θ) compared to directly inverting X in some cases.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*eaHoNHVDSqRr8L77vPp-LA.png" /></figure><p>Where Σ+ is the pseudoinverse of Σ, obtained by taking the reciprocal of non-zero diagonal elements and transposing the resulting matrix.</p><p>The solution to the linear regression problem using the pseudoinverse is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*z0Kmy_vL7TrZly0cSb7pHA.png" /></figure><ul><li>If we take XTX as (n+1)*(n+1) matrix, then the computational complexity of inverting a matrix is about O(n2.4) to O(n3).</li><li>The SVD approach is typically O(n2), which is generally more efficient.</li></ul><pre>import numpy as np<br><br># Assuming we have our house_sizes and house_prices from earlier<br><br># Add x0 = 1 to each instance for the bias term<br>X_b = np.c_[np.ones((100, 1)), house_sizes]<br><br># Perform SVD on X_b<br>U, S, Vt = np.linalg.svd(X_b, full_matrices=False)<br><br># Calculate the pseudoinverse using S<br>S_inv = np.diag(1 / S)  # Invert non-zero diagonal elements<br>X_plus = Vt.T.dot(S_inv).dot(U.T)  # Calculate pseudoinverse<br><br># Calculate theta using the pseudoinverse<br>theta_best = X_plus.dot(house_prices)<br><br>print(&quot;Theta calculated using SVD approach:&quot;, theta_best)</pre><pre>Theta calculated using SVD approach: [[52150.96157547]<br> [97.70113386]]</pre><p>This code does the following:</p><ul><li>The design matrix <em>X_b </em>is created by adding a column of ones to house_sizes to account for the bias term in the linear regression model.</li><li>Then <em>X_b </em>is decomposed into three matrices<em> U, S</em>, and<em> Vt</em> using SVD with <em>full_matrices=False</em>, which provides a compact representation of the decomposition.</li><li>The pseudoinverse <em>X_plus </em>of <em>X_b </em>is computed by inverting the non-zero diagonal elements of <em>S</em> and performing matrix multiplications with transpose of <em>Vt</em> and transpose of <em>U</em>.</li><li>The optimal parameters <em>theta_best </em>are then calculated using this pseudoinverse and the target variable <em>house_prices</em>, providing the best fit for the linear regression model.</li></ul><p>So, the SVD approach provides a robust solution that simplifies the computational process and improves performance, as demonstrated by the regression model derived from house sizes and prices.</p><h3>4. Implementing, Predicting, and Visualizing Linear Regression with Scikit-Learn</h3><p>Scikit-learn is a powerful, widely used machine learning library for Python. It provides a powerful and user-friendly way to implement linear regression.</p><h4>4.1 Creating and Fitting the Model</h4><p>We’ll use Scikit-Learn’s <em>LinearRegression</em> class to create and fit our model:</p><pre>from sklearn.linear_model import LinearRegression<br><br># Create the model<br>lin_reg = LinearRegression()<br><br># Fit the model to our data<br>lin_reg.fit(house_sizes, house_prices)<br><br># Print the model parameters<br>print(&quot;Intercept:&quot;, lin_reg.intercept_)<br>print(&quot;Coefficient:&quot;, lin_reg.coef_)</pre><pre>Intercept: [52150.96157547]<br>Coefficient: [[97.70113386]]</pre><p>This code creates a <em>LinearRegression</em> object and fits it to our data. The <em>fit </em>method calculates the optimal parameters (slope and intercept) for our model. We can then access these parameters using <em>lin_reg.intercept_</em> and <em>lin_reg.coef_.</em></p><h4>4.2 Visualizing the Results</h4><p>Visualization is crucial for understanding our model. We’ll create a scatter plot of our original data and overlay our regression line:</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br># Get the min and max of house sizes<br>x_min, x_max = house_sizes.min(), house_sizes.max()<br><br># Create a range of house sizes for the line<br>X_line = np.linspace(x_min, x_max, 100).reshape(-1, 1)<br><br># Predict prices for this range<br>Y_line = lin_reg.predict(X_line)<br><br>plt.figure(figsize=(8, 4))<br>plt.scatter(house_sizes, house_prices, color=&#39;blue&#39;, alpha=0.5, label=&#39;Data points&#39;)<br>plt.plot(X_line, Y_line, color=&#39;red&#39;, label=&#39;Regression Line&#39;)<br>plt.xlabel(&quot;House Size (sq ft)&quot;)<br>plt.ylabel(&quot;Price ($)&quot;)<br>plt.title(&quot;Linear Regression: House Prices vs Size&quot;)<br># plt.legend()<br><br># Save the plot as an image<br>plt.savefig(&#39;linear_regression.png&#39;)<br><br># Display the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*wRqHUFKiemYbCiHa" /><figcaption><em>Figure 3</em></figcaption></figure><p>This code creates a scatter plot of our original data (blue points) and adds our regression line (in red) as shown in <em>Figure 3</em>. The regression line extends from our smallest to our largest house size, showing the model’s predictions across this range. As earlier we use matplotlib to plot the data.</p><p>Interpreting the Results:</p><ul><li>The scatter plot shows our original data points, giving us a sense of the relationship between house size and price.</li><li>The red line is our regression line, representing our model’s predictions.</li><li>The slope of this line tells us how much the price increases for each additional square foot.</li></ul><h4>4.3 Making Predictions</h4><p>Once our model is fitted, we can use it to make predictions:</p><pre># Generate points for prediction<br>X_new = np.array([[1000], [2000]])<br><br># Make predictions<br>y_predict = lin_reg.predict(X_new)<br><br>print(&quot;Predicted prices for 1000 and 2000 sq ft houses:&quot;, y_predict)</pre><pre>Predicted prices for 1000 and 2000 sq ft houses: [[149852.09543985]<br> [247553.22930424]]</pre><p>Here, we’re predicting the prices for houses of 1000 and 2000 square feet.</p><p>The <em>predict </em>method applies our fitted model to these new data points. By combining these steps, implementing the model, visualizing the results and making predictions, we get a comprehensive view of our linear regression analysis. We can see how well our model fits the data and use it to make predictions for new house sizes.</p><p>This approach using Scikit-Learn is particularly powerful because it’s easy to use and can be quickly adapted to more complex scenarios, such as multiple linear regression with several features.</p><h4>4.4 Evaluating the Model’s Performance</h4><p>After implementing our linear regression model, it’s crucial to evaluate its performance. We’ll use two common metrics: R-squared (R²) and Mean Squared Error (MSE).</p><p><strong>4.4.1 Mean Squared Error (MSE)</strong></p><p>MSE measures the average squared difference between the estimated values and the actual value. It’s always non-negative, and lower MSE indicates better model performance. MSE is particularly useful because it penalizes larger errors more heavily.</p><p><strong>4.4.2 R-squared Value (Coefficient of Determination)</strong></p><p>R-squared measures the proportion of the variance in the dependent variable (house prices) that is predictable from the independent variable (house sizes). It ranges from 0 to 1</p><p>Here:</p><ul><li>1 indicates that the model explains all the variability of the response data around its mean.</li><li>0 indicates that the model explains none of the variability of the response data around its mean.</li></ul><p>Here’s how we calculate these metrics using Scikit-learn:</p><pre>from sklearn.metrics import mean_squared_error, r2_score<br><br># Make predictions on our original data<br>y_pred = lin_reg.predict(house_sizes)<br><br># Calculate MSE and R-squared<br>mse = mean_squared_error(house_prices, y_pred)<br>r2 = r2_score(house_prices, y_pred)<br><br>print(&quot;Mean squared error: &quot;, mse)<br>print(&quot;R-squared score: &quot;, r2)</pre><pre>Mean squared error:  80658456.39670533<br>R-squared score:  0.9764567983510799</pre><h4>Interpreting the Results:</h4><ol><li>Mean Squared Error (MSE):</li></ol><ul><li>The units of MSE are squared units of the output.</li><li>The square root of MSE (RMSE) can be used to get an idea of the average prediction error in the original units.</li><li>As shown in the screenshot that the noise in our data has a standard deviation of 10,000, the variance of the noise is 10,0002 = 100,000,000.</li><li>Our MSE value of 80,658,456.39670533 is in the same order of magnitude as the noise variance, suggesting that your model’s predictions are reasonably good considering the inherent noise in the data.</li></ul><p>2. R-squared Score:</p><ul><li>While a higher R-squared generally indicates a better fit, it’s important to consider it alongside other factors and not overly rely on it.</li><li>An R-squared score of 0.976 indicates that 97.65% of the variance in house prices can be explained by the house size.</li><li>This high R-squared value suggests that the model provides a very good fit for the data.</li></ul><p>These metrics help us understand how well our model is performing. A low MSE and a high R-squared generally indicate a good fit, but it’s important to consider these in the context of your specific problem and data.</p><h3>5. Limitations and Considerations</h3><h4>5.1. When Linear Regression Might Not Be Appropriate</h4><ul><li>If the relationship between variables is not linear, simple linear regression will fail to capture the true pattern.</li><li>When many variables influence the outcome, simple linear regression might be too simplistic.</li><li>For data with temporal dependencies, specialized time series models are often more appropriate.</li></ul><h4>5.2. Overfitting and Underfitting</h4><p><strong>Overfitting:</strong> Occurs when the model fits the training data too closely, including noise. Signs include:</p><ul><li>High accuracy on training data but poor performance on new data.</li><li>Unusually high R-squared values.</li></ul><p><strong>Underfitting:</strong> Happens when the model is too simple to capture the underlying pattern. Signs include:</p><ul><li>Poor performance on both training and new data</li><li>Unusually low R-squared values</li></ul><h3>6. Conclusion</h3><p>Encourage further exploration and practice:</p><ul><li>Try incorporating more variables to improve your model’s predictive power.</li><li>Learn about Ridge and Lasso regression to handle overfitting.</li><li>Apply linear regression to publicly available datasets to gain practical experience.</li><li>Use this as a stepping stone to learn about more complex algorithms like logistic regression, decision trees, or neural networks.</li><li>Practice using techniques like k-fold cross-validation to get more robust estimates of your model’s performance.</li><li>Continue to improve your data visualization skills.</li></ul><p>Remember, mastering linear regression provides a strong foundation for more advanced data science and machine learning techniques. It’s a valuable skill that opens doors to deeper understanding and more complex analyses in the field of predictive modeling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=492a36ee5d22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the hell is PKCE? : A Deep Dive]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/what-the-hell-is-pkce-a-deep-dive-9e8a7983d74f?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e8a7983d74f</guid>
            <category><![CDATA[pkce]]></category>
            <category><![CDATA[cyber]]></category>
            <category><![CDATA[digital-security]]></category>
            <category><![CDATA[oauth]]></category>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Fri, 24 May 2024 07:33:44 GMT</pubDate>
            <atom:updated>2024-05-25T06:54:16.922Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What the hell is PKCE? : A Deep Dive</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leHsO6Eb_S4QDFySf7uYpg.png" /><figcaption>Adapted from <a href="https://blog.techsoup.org/posts/protect-your-nonprofits-digital-security-hackernomics-101">source</a></figcaption></figure><p>In today’s interconnected world, applications often rely on external services like Facebook or Google for user authentication. This convenience comes with a crucial responsibility ensuring secure authorization. Here’s where OAuth 2.0 shines, a widely adopted framework that lets apps access your data without requiring your actual password.<br> <br> But OAuth 2.0, while robust, has a potential vulnerability — authorization codes. These short-lived codes, exchanged during the authorization process, could be intercepted by malicious actors. This is where <strong>PKCE (Proof Key for Code Exchange)</strong>, pronounced “pixy,” comes to the rescue.</p><h3><strong>Basic understanding OAuth 2.0:</strong></h3><p>Imagine you’re logging in to a new app using your Facebook account. Here’s the basic OAuth 2.0 flow:<br>The app redirects you to Facebook’s authorization server.</p><ol><li>You log in to Facebook, granting the app permission to access specific data (photos, profile information, etc.).</li><li>Facebook sends an <strong>authorization code</strong> back to the app.</li><li>The app uses this code to request an <strong>access token</strong> from Facebook. This token allows the app to access your authorized data securely.</li></ol><h3><strong>The Problem: Vulnerable Authorization Codes</strong></h3><p>While convenient, authorization codes are susceptible to interception. A malicious actor positioned between you and the authorization server (think “Man-in-the-Middle” attack) could steal the code and use it to impersonate you and access your data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*9tJdhuCTVeoL7fB60uU91Q.png" /><figcaption>Adapted from <a href="https://blog.postman.com/what-is-pkce/#:~:text=PKCE%2C%20which%20stands%20for%20%E2%80%9CProof,layer%20on%20top%20of%20it.">source</a></figcaption></figure><h3><strong>The Solution: Introducing PKCE</strong></h3><p>PKCE adds an extra layer of security to the OAuth 2.0 flow by introducing a secret handshake between the app and the authorization server. Here’s what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*6SW-LO4ocwNDu6A9BNXqKA.png" /><figcaption>Adapted from <a href="https://blog.postman.com/what-is-pkce/#:~:text=PKCE%2C%20which%20stands%20for%20%E2%80%9CProof,layer%20on%20top%20of%20it.">source</a></figcaption></figure><ul><li>The app generates a random string called a <strong>code verifier. </strong>This is a cryptographically generated random string and it has a minimum length of 43 characters and maximum length of 128 characters. This string is kept confidential on the app’s side.</li><li>The app creates a <strong>code challenge</strong> by applying a specific hashing function (like SHA-256) to the code verifier. This transformed version is safe to send over the internet.</li></ul><p><strong>1.</strong> This challenge is sent to the authorization server during the initial authorization request, along with a <strong>code challenge method</strong> indicating how the transformation was performed. And there are two code challenge methods:</p><ul><li><strong><em>Plain:</em> </strong>In this the code challenge is<strong> </strong>identical to the code verifier. No transformation is applied.</li><li><strong><em>S256:</em></strong><em> </em>This is the recommended method. It involves applying a strong cryptographic hash function (SHA-256) to the code verifier and then encoding the result using BASE64URL encoding. This ensures the challenge remains unpredictable even if intercepted by an attacker.</li></ul><p><strong>2. </strong>The app redirects you to the authorization server, along with the code challenge. You log in to the authorization server and grant permission to the app. The authorization server sends an authorization code back to the app (Here both Legitimate and Malicious apps can get this authorization code).</p><p><strong>3. </strong>Then app sends the authorization code<strong> </strong>along with the code verifier back to the authorization server (Here the malicious apps don’t have this code verifier, Only the legitimate app has it).</p><p><strong>4.</strong> Then the authorization server hashes the code verifier using SHA-256 (if it has a code challenge method<strong> </strong>of S256) and encodes the hashed value as a BASE64URL. The corresponding value is then compared to the code challenge. If they match, an<em> access token</em> is issued. Otherwise, an error message is returned.</p><h3><strong>Benefits of PKCE:</strong></h3><ul><li><strong>Enhanced Security:</strong> PKCE significantly reduces the risk of stolen authorization codes being used for malicious purposes.</li><li><strong>Public Client Protection:</strong> PKCE is particularly beneficial for public clients (like mobile or web apps) that cannot securely store secret keys. By eliminating the need for such secrets, PKCE improves overall security.</li><li><strong>Increased Trust:</strong> PKCE strengthens the trust model of OAuth 2.0 by ensuring a more secure exchange of authorization codes.</li></ul><h3><strong>In conclusion:</strong></h3><p>PKCE plays a vital role in fortifying the OAuth 2.0 framework, ensuring a safer and more reliable login experience for you and countless users across the web. By implementing PKCE, developers can significantly enhance the security of their applications and protect user data from unauthorized access.</p><h4>References:</h4><ul><li><a href="https://blog.postman.com/what-is-pkce/#:~:text=PKCE%2C%20which%20stands%20for%20%E2%80%9CProof,layer%20on%20top%20of%20it."><em>https://blog.postman.com/what-is-pkce/#:~:text=PKCE%2C%20which%20stands%20for%20%E2%80%9CProof,layer%20on%20top%20of%20it.</em></a></li><li><a href="https://cloudentity.com/developers/basics/oauth-extensions/authorization-code-with-pkce/"><em>https://cloudentity.com/developers/basics/oauth-extensions/authorization-code-with-pkce/</em></a></li><li><a href="https://curity.io/resources/learn/oauth-pkce/"><em>https://curity.io/resources/learn/oauth-pkce/</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e8a7983d74f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Made Easy: From Chaos to Clarity]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/git-made-easy-from-chaos-to-clarity-f3d478119ebe?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3d478119ebe</guid>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Sat, 04 May 2024 15:10:30 GMT</pubDate>
            <atom:updated>2024-05-04T15:10:30.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*K6yIjBBcwMhzv9lUHMpmcg.png" /></figure><p>In the ever-evolving world of project development, Git empowers you to keep track of all the modifications made to your project files. Means you can rewind the clock and revert to previous versions if needed. Git also allows you to branch out and experiment.</p><p>By creating branches, you can work on features in isolation without affecting the main project codebase. This is especially useful for collaboration, as you can seamlessly share your code with others, integrate changes effortlessly, and work together.</p><h3>Getting Started with Git</h3><p>To embark on your Git journey, head to,</p><p><a href="https://git-scm.com/downloads">Install</a></p><p>and download Git for your operating system.</p><ul><li>Windows Users: Enter the Git Bash Arena</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*JSqCMvkLihDnkzHUTObkUw.png" /><figcaption>Git bash</figcaption></figure><p>For Windows users, consider using Git Bash. It’s a terminal emulator pre-configured for Git commands, offering syntax highlighting and a more developer-friendly environment than the standard command prompt.</p><h3>Understanding the Git Workflow: A Four-Act Play</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*oS1_ytOyW5oEWJcCQ7bNcA.png" /><figcaption>Source — <a href="https://www.dezlearn.com/getting-started-with-git/"><em>https://www.dezlearn.com/getting-started-with-git/</em></a></figcaption></figure><ul><li><strong>Working Directory: </strong>This is your local project folder on your computer, where you actively develop and modify files.</li><li><strong>Staging Area: </strong>Think of this as a temporary waiting room. You use git add to stage specific changes you want to include in your next commit.</li><li><strong>Local Repository:</strong> This is the heart of Git. It stores the complete history of your project, with each commit acting as a snapshot of the project’s state at a specific point in time.</li><li><strong>Remote Repositories: </strong>While the local repository holds your project’s history, remote repositories like <em>GitHub, GitLab, or Bitbucket </em>provide a central location to store and share code with others. You can “push” your local commits to a remote repository and “pull” down changes made by others.</li></ul><h4>Some Essential Git Commands:</h4><p>Now that you understand the landscape, let’s explore some key commands:</p><p><strong><em>git add:</em></strong> This command acts like placing your modified files on stage for the next commit. You have two options for using git add:</p><pre>git add &lt;filename&gt;</pre><blockquote>Adds a specific file with the provided filename to the staging area. This allows you to selectively include only the changes you want in the next commit.</blockquote><pre>git add .</pre><blockquote>Stages all modified files present in your working directory. This is a convenient option when you want to include all changes at once.</blockquote><p><strong><em>git status:</em></strong> This command is your window into the current state of your Git repository. It provides valuable information like:</p><pre>git status</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*jGfDfx-cGDiEPzInPgf5kw.png" /></figure><ul><li><strong>Untracked Files:</strong> Lists any new files in your working directory that haven’t been added to Git yet.</li><li><strong>Staged Changes:</strong> Shows which files you’ve added using git add and are ready to be committed.</li><li><strong>Unstaged Changes:</strong> Highlights any modified files that exist in your working directory but haven’t been staged for the next commit using git add.</li></ul><p>Using git status frequently helps you stay organized and ensures you’re committing the intended changes.</p><p><strong><em>git commit : </em></strong>This command is the heart of creating a permanent record of your changes in Git. It takes all the staged files (added using git add) and captures them in a commit.</p><pre>git commit -m &quot;&lt;message&gt;&quot;</pre><p>The -m flag specifies the commit message, which is a crucial element for describing the changes you made.</p><p><strong><em>git push </em>:</strong> This command comes into play when you’re collaborating with others and using a remote repository service like GitHub. It pushes your local commits to the remote repository, making them accessible to your team members.</p><pre>git push origin &lt;branch_name&gt;</pre><p>However, git push is typically used after you’ve established a connection with the remote repository and configured your Git settings.</p><p><strong>Remember:</strong> The order of these commands is essential. You typically use <em>git add</em> to stage files, followed by <em>git commit</em> to create a commit with a descriptive message. Finally, <em>git push</em> is used for collaboration workflows involving remote repositories. And <em>git status</em> helps you verify the state of your Git repository throughout the process.</p><h3>Committing Best Practices: Small &amp; Clear</h3><p>Think of a commit as a small, specific change in your project’s history. Each commit should ideally address a single, atomic task with a descriptive message written in present tense (e.g., “Add login functionality” instead of “Added login functionality”). This makes it easier to track project evolution and collaborate effectively.</p><p>For more info about git best practices go :</p><p><a href="https://www.freecodecamp.org/news/git-best-practices-commits-and-code-reviews/">Git Best Practices - How to Write Meaningful Commits, Effective Pull Requests, and Code Reviews</a></p><h3>The .gitignore File: Your Secret Weapon</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*FWzN-hn-re9izlvTLxx5cQ.png" /><figcaption>.gitignore file</figcaption></figure><p>Not all files in your project deserve a starring role in Git’s history. For example, configuration files, temporary build artifacts, or operating system-specific files can clutter your Git history.</p><p>This is where the .gitignore file comes in. Create a file named .gitignore in your project’s root directory and list patterns of files you want Git to ignore when committing.</p><h3>Unstaging a File: Leaving the Staging Area</h3><p>Let’s say you added a file to the staging area but decided it’s not quite ready for the spotlight. Use</p><pre>git rm - cached &lt;filename&gt;</pre><p>to remove that specific file from the staging area without affecting the working directory.</p><h3>Some More Useful Commands: Peeking Under the Hood</h3><pre>git checkout &lt;branch_name&gt;:</pre><p>allows you to switch to a different branch in your local repository. This is crucial for working on different features or tasks in isolation.</p><pre>git rm -rf &lt;filename&gt;:</pre><p>This permanently deletes a file from both the working directory and the staging area (use with caution!).</p><pre>git show HEAD~</pre><p>shows the details of the commit that came before the current one (useful for reviewing past changes).</p><pre>git log</pre><p>this command provides a detailed history of your commits.</p><pre>git reflog</pre><p>shows a history of all your HEAD (current commit pointer) movements.</p><h3>Git Merge vs. Git Rebase: Merging Your Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*-yaqCVuCqKIgfCahXTruiw.png" /><figcaption>Source — <a href="https://unstop.com/blog/git-rebase"><em>https://unstop.com/blog/git-rebase</em></a></figcaption></figure><p>These merge and rebase commands are used to integrate changes from different branches into your main codebase. Here’s a quick overview I’m not going to go into more details on this section:</p><pre>git merge &lt;branch_name&gt;</pre><p>Creates a new commit that merges changes from another branch into the current branch. This can sometimes lead to merge conflicts, which need to be resolved manually.</p><pre>git rebase &lt;branch_name&gt;</pre><p>Rewrites history to make it appear as if the changes from another branch were made on top of the current branch. This can be a more advanced technique and requires careful handling.</p><p>You can get an idea about how these two works from the graphical image above.</p><h3>Git Cheat Sheet: Your Quick Reference</h3><p>Keep this handy for easy reference,</p><p>You can access to a git cheat sheet from here.</p><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//education.github.com/git-cheat-sheet-education.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/58585761cded8c233f1568e936719f27/href">https://medium.com/media/58585761cded8c233f1568e936719f27/href</a></iframe><h3>References</h3><ul><li><a href="https://www.freecodecamp.org/news/git-best-practices-commits-and-code-reviews/"><em>https://www.freecodecamp.org/news/git-best-practices-commits-and-code-reviews/</em></a></li><li><a href="https://www.dezlearn.com/getting-started-with-git/"><em>https://www.dezlearn.com/getting-started-with-git/</em></a></li><li><a href="https://unstop.com/blog/git-rebase"><em>https://unstop.com/blog/git-rebase</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3d478119ebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Web: A Deep Dive]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/behind-the-web-a-deep-dive-1d96787e44de?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d96787e44de</guid>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 15:52:41 GMT</pubDate>
            <atom:updated>2024-04-05T15:52:41.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*5pV3HucFdjWxsdBGkr0fMw.png" /></figure><p>The internet has revolutionized the way we access and share information. It’s become an indispensable part of our lives, transforming how we work, learn, communicate, and entertain ourselves. Imagine a world without instant access to knowledge, the ability to connect with people across the globe, or the convenience of online shopping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*l2M0ieJS-4ciC4AAGO2lUg.png" /><figcaption>source — <a href="https://www.scaler.com/topics/difference-between-internet-and-www/"><em>https://www.scaler.com/topics/difference-between-internet-and-www/</em></a></figcaption></figure><p>The web, built upon the vast infrastructure of the internet, provides all this and more. It acts as a user-friendly interface, utilizing specific technologies to translate complex data into the web pages we see on our screens. By harnessing the power of the internet, the web empowers us to explore a vast digital landscape, enriching our lives in countless ways.</p><h3><strong>The basic flow of a Webpage:</strong></h3><p>Here’s a simplified breakdown of how a webpage comes to life, When you type a web address (URL) in your browser like “<em>https://google.com/”,</em> your computer first contacts a Domain Name System (DNS) server.</p><h4><strong>Domain Name System (DNS):</strong></h4><p>Imagine you have a giant phonebook for every city in the world. But instead of names and phone numbers, This contains website addresses (like <a href="https://google.com/)">https://google.com/)</a> and corresponding IP addresses (like 142.250.184.196). This is essentially what the DNS does for the internet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*zMm3JAR8fC2HVQ38AoL8PQ.png" /><figcaption>source — <a href="https://performanceconnectivity.com/dns/"><em>https://performanceconnectivity.com/dns/</em></a></figcaption></figure><ul><li><strong>User-Friendly to Machine-Readable: </strong>Humans remember names easily, but computers work with numbers. DNS acts as a translator, converting the easy-to-remember domain names we type into the numerical IP addresses that web servers understand.</li><li><strong>A Distributed Network:</strong> Unlike a physical phonebook, DNS isn’t stored in a single location. It’s a distributed network of servers spread worldwide. When you request a website, your computer queries a local DNS server, which then contacts other servers if it doesn’t have the IP address readily available. This distributed system ensures redundancy and efficiency.</li><li><strong>Caching for Speed:</strong> To improve performance, DNS servers often cache frequently accessed addresses. This means subsequent visits to the same website might be resolved quicker because the IP address is already stored locally.</li><li><strong>Dynamic Updates:</strong> When a website changes servers, the DNS record needs to be updated. This process isn’t instantaneous, but it usually happens within a few hours, ensuring users are eventually directed to the correct location.</li></ul><p>In essence, DNS is the invisible magic behind the scenes, allowing us to navigate the web using familiar names instead of cryptic numbers. It’s a fundamental building block of the internet, ensuring a smooth and user-friendly experience for everyone.</p><h4><strong>Connecting with the Server:</strong></h4><p>With the IP address in hand, your computer establishes a connection with the web server where the website’s files reside.</p><h4><strong>The Server Responds:</strong></h4><p>The web server locates the requested files (HTML, CSS, JavaScript) and sends them back to your computer.</p><h4><strong>The Browser:</strong></h4><p>Your web browser receives the data, interprets the code, and renders it into a visually appealing webpage displayed on your screen.</p><h3><strong>The Building Blocks of a Webpage:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*udU_q2RaYIPyr5Nf-PDTFg.png" /><figcaption>source — <a href="https://www.linkedin.com/pulse/fundamental-elements-web-development-html-css-anass-essadikine-byn7e/"><em>https://www.linkedin.com/pulse/fundamental-elements-web-development-html-css-anass-essadikine-byn7e/</em></a></figcaption></figure><h4><strong>HTML (Hypertext Markup Language):</strong></h4><p>This is the foundation of a webpage, acting like a blueprint that defines the structure and content. It tells the browser where to place text, images, and links. Imagine it as the skeleton of a house.</p><p><em>Example</em>:</p><pre>&lt;p&gt;This is a paragraph of text.&lt;/p&gt;</pre><p>defines a paragraph, like that.</p><h4><strong>CSS (Cascading Style Sheets):</strong></h4><p>CSS adds style and presentation to the webpage, similar to paint and decorations for a house. It controls the layout, fonts, colors, and overall visual appeal.</p><p><em>Example</em>:</p><pre>body {background-color: #f0f0f0;}</pre><p>defines a light gray background color for the entire page.</p><h4><strong>JavaScript:</strong></h4><p>Imagine a webpage as a static picture, it’s informative, but lacking engagement. JavaScript gives a dose of interactivity and dynamism, transforming webpages into dynamic experiences.</p><p>It allows for animations, user input forms, and real-time updates, like the “search suggestions” as you type on Google.</p><p>Example:</p><pre>&lt;body&gt;<br>  &lt;button onclick=&quot;showAlert()&quot;&gt;Click Me!&lt;/button&gt;<br>  &lt;script&gt;<br>    function showAlert() {<br>    alert(&quot;This is an alert message from JavaScript!&quot;);<br>    }<br>  &lt;/script&gt;<br>&lt;/body&gt;</pre><p>A simple script can display an alert message when a button is clicked. (Inside &lt;script&gt; tag is the javascript code)</p><h3><strong>IPv4 &amp; IPv6:</strong></h3><p>Every device connected to the internet needs a unique address, similar to a house address. These addresses are assigned using a protocol called <strong>Internet Protocol (IP).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*UTOHdzPTumWhmdbKAvY-WQ.png" /><figcaption>source — <a href="https://bluecatnetworks.com/blog/ipv4-vs-ipv6-whats-the-difference/"><em>https://bluecatnetworks.com/blog/ipv4-vs-ipv6-whats-the-difference/</em></a></figcaption></figure><h4><strong>IPv4:</strong></h4><p>The original addressing system, but it’s running out of available addresses due to the ever-growing number of internet users and devices.</p><p><em>Example: 192.168.1.1 (typical home network router address)</em></p><h4><strong>IPv6:</strong></h4><p>The next-generation addressing scheme with a much larger pool of addresses to accommodate future growth.</p><p><em>Example: 2001:db8:85a3:08d0:0000:8a2e:0370:7334</em></p><h3><strong>HTTP &amp; HTTPS: Secure Communication Channels:</strong></h3><p>The smooth flow of information between your web browser and servers relies on communication protocols. Here’s a breakdown of HTTP and HTTPS, the essential protocols that govern this exchange:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*47TCrxpbskhz_iVWuaTmcA.png" /><figcaption>source — <a href="https://www.edhotels.com/http-vs-https-the-difference-and-everything-you-need-to-know/"><em>https://www.edhotels.com/http-vs-https-the-difference-and-everything-you-need-to-know/</em></a></figcaption></figure><h4><strong>HTTP (Hypertext Transfer Protocol):</strong></h4><p>Imagine a conversation between your computer and a web server. HTTP acts as the common language they use to understand each other. It defines the rules for how requests are made, how data is formatted, and how responses are sent.</p><p>The core functionality of HTTP lies in delivering web content. However, it has a critical limitation: it transmits data in plain text. This means anyone intercepting the communication between your computer and the server could potentially read the information being exchanged. This is suitable for webpages displaying non-sensitive data like news articles or public information, HTTP is sufficient.</p><h4><strong>HTTPS (Hypertext Transfer Protocol Secure):</strong></h4><p>HTTPS is the secure version of HTTP. It addresses the security concerns of plain text communication by encrypting the data exchange between your browser and the server. This encryption scrambles the data into an unreadable format, making it impossible for anyone eavesdropping on the communication to decrypt the information.</p><p>Think of HTTPS as a secure tunnel between your computer and the server. Encryption acts like a lock on this tunnel, ensuring only authorized parties (your browser and the server) can access the data. This is crucial when transmitting sensitive information like credit card details, login credentials, or personal data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*GsNX39I7WA84bwjjHbigSA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*jpCrbLgAOUh3KvJClZwS_g.png" /></figure><p>By using HTTPS, websites demonstrate their commitment to user security. The <strong>padlock symbol</strong> displayed in the address bar of your browser when using HTTPS indicates a secure connection, fostering trust and confidence when entering sensitive information online.</p><h3><strong>Keeping Up with the Crowd: How Servers Scale for High Traffic</strong></h3><p>A website with a huge traffic can overwhelm a single server, leading to slow loading times or even crashes. To ensure a smooth user experience even during peak hours, websites employ various scaling techniques:</p><h4><strong>1. Load Balancing:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*KW5jBBzl1l2Z9Fs8PtRvKw.png" /><figcaption>source — <a href="https://www.cloud4u.com/blog/what-is-a-load-balancer-and-its-types/"><em>https://www.cloud4u.com/blog/what-is-a-load-balancer-and-its-types/</em></a></figcaption></figure><p>This technique distributes incoming traffic across multiple servers, preventing any single server from becoming overloaded. This ensures efficient processing of requests and faster response times for users.</p><h4><strong>There are different load balancing strategies:</strong></h4><ul><li><strong>Round Robin:</strong> Requests are distributed evenly among available servers.</li><li><strong>Weighted Round Robin:</strong> Servers with more processing power can handle a larger share of the traffic.</li><li><strong>Least Connections:</strong> Requests are directed to the server with the fewest current connections, ensuring a balanced workload.</li></ul><h4><strong>2. Cloud Computing: Elastic Resources on Demand</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*o11yPqZ0D118g7sZbTVfug.png" /><figcaption>source - <a href="https://www.geeksforgeeks.org/automated-scaling-listener-in-cloud-computing/"><em>https://www.geeksforgeeks.org/automated-scaling-listener-in-cloud-computing/</em></a></figcaption></figure><p>Unlike a physical server with fixed resources, cloud platforms offer a more scalable solution. Websites can leverage cloud services to dynamically adjust their server capacity based on real-time traffic demands.</p><p>Cloud computing provides the flexibility, during low traffic times, resources can be scaled down, optimizing cost-efficiency.</p><p>Popular cloud platforms like Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform offer a range of services, including scalable server instances, storage options, and databases.</p><h4><strong>3. Content Delivery Networks (CDNs): Bringing Content Closer</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*7g0KXwne1r3sVh-_6sLTGQ.png" /><figcaption>source — <a href="http://www.aalphanetsolution.com/blog/what-is-cdn/"><em>http://www.aalphanetsolution.com/blog/what-is-cdn/</em></a></figcaption></figure><p>A CDN acts like a network of geographically distributed servers that store cached copies of website content (static files like images, JavaScript, CSS). When a user requests a webpage, the CDN server closest to their location can deliver the content faster, reducing latency and improving user experience.</p><p>Imagine having local branches of the restaurant in different cities to serve food quickly. A CDN works in a similar way, delivering website content from the closest server, especially beneficial for users located far from the main website server.</p><h4><strong>4. Caching Strategies: Keeping Things Speedy</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*2cgoYRIPpoC4-wfd4SFhLQ.png" /><figcaption>source — <a href="https://www.keycdn.com/support/cache-definition-explanation"><em>https://www.keycdn.com/support/cache-definition-explanation</em></a></figcaption></figure><p>Caching involves storing frequently accessed data on the server for quicker retrieval. This reduces the load on the main server and improves website performance.</p><p>Your web browser might cache frequently accessed website files, so subsequent visits load faster. Similarly, servers can cache frequently requested data, minimizing the need to constantly retrieve the same information.</p><p>By employing a combination of these scaling techniques, websites can ensure they can handle huge traffic, deliver content efficiently, and provide a positive user experience even during peak usage periods.</p><h3><strong>Websites vs. Web Applications:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*b6yrh26b7ugcTlvUDp5koA.png" /><figcaption>source — <a href="https://mdevelopers.com/blog/website-vs-web-application-what%27s-the-difference"><em>https://mdevelopers.com/blog/website-vs-web-application-what%27s-the-difference</em></a></figcaption></figure><p><strong>Website:</strong> A collection of interconnected web pages that reside on a single domain name. It’s like the entire book filled with various chapters (web pages) related to a specific topic.</p><p><strong>Web Application (Web App):</strong> A software program accessible through a web browser that delivers functionality and interaction beyond static content. Think of online banking or social media platforms. Web apps leverage web technologies but offer features like user accounts, data storage, and real-time updates, similar to a traditional desktop application accessed through a web interface.</p><h4><strong>In Conclusion:</strong></h4><p>The web is a powerful tool that connects us, informs us, and entertains us. By understanding how it works, we can become more responsible users and creators. <strong>What will you build?</strong> The web is a vast canvas waiting for your unique contribution. So, unleash your creativity and make your mark on the digital world!</p><h4>Reference:</h4><ul><li><a href="https://performanceconnectivity.com/dns/"><em>https://performanceconnectivity.com/dns/</em></a></li><li><a href="https://bluecatnetworks.com/blog/ipv4-vs-ipv6-whats-the-difference/"><em>https://bluecatnetworks.com/blog/ipv4-vs-ipv6-whats-the-difference/</em></a></li><li><a href="https://www.edhotels.com/http-vs-https-the-difference-and-everything-you-need-to-know/"><em>https://www.edhotels.com/http-vs-https-the-difference-and-everything-you-need-to-know/</em></a></li><li><a href="https://www.cloud4u.com/blog/what-is-a-load-balancer-and-its-types/"><em>https://www.cloud4u.com/blog/what-is-a-load-balancer-and-its-types/</em></a></li><li><a href="https://www.geeksforgeeks.org/automated-scaling-listener-in-cloud-computing/"><em>https://www.geeksforgeeks.org/automated-scaling-listener-in-cloud-computing/</em></a></li><li><a href="http://www.aalphanetsolution.com/blog/what-is-cdn/"><em>http://www.aalphanetsolution.com/blog/what-is-cdn/</em></a></li><li><a href="https://www.keycdn.com/support/cache-definition-explanation"><em>https://www.keycdn.com/support/cache-definition-explanation</em></a></li><li><a href="https://mdevelopers.com/blog/website-vs-web-application-what%27s-the-difference"><em>https://mdevelopers.com/blog/website-vs-web-application-what%27s-the-difference</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d96787e44de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Login Screen: How Servers Store Your Passwords]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/beyond-the-login-screen-how-servers-store-your-passwords-7cdb58b22836?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cdb58b22836</guid>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 06:38:22 GMT</pubDate>
            <atom:updated>2024-04-01T04:10:39.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grqfLjCagAIrd_LJSyfhSw.jpeg" /><figcaption>Source — <a href="https://hullabaloo.co.uk/blog/">https://hullabaloo.co.uk/blog/</a></figcaption></figure><p>In today’s digital world, our passwords are the keys to our online, digital lives. But how do servers actually store these passwords behind the scenes? Unfortunately, not all methods are created equal. A data breach can expose your credentials if they’re not secured properly, putting your accounts at risk. Let’s delve into the world of password storage and explore the best practices to keep your information safe.</p><h3><strong>1. Plain Text: Hacker’s dream</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*pk5AAvVugUBiUu0y9LmXHQ.png" /><figcaption>source — <a href="https://jscrambler.com/blog/how-to-store-passwords-safely">https://jscrambler.com/blog/how-to-store-passwords-safely</a></figcaption></figure><p>Imagine storing your house key under the doormat! That’s essentially what plain text password storage is like. Passwords are saved exactly as entered, making them a hacker’s dream. If a cybercriminal breaches the server, they can easily access and steal all user passwords. This was a common practice in the early days of the internet, but thankfully, it’s rarely used anymore due to its glaring security risks.</p><h3><strong>2. Encryption: A double-edged sword</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*6lDcwIVDMNjQ__nvOp1ITw.png" /><figcaption>source — <a href="https://www.pandasecurity.com/en/mediacenter/what-is-encryption/"><em>https://www.pandasecurity.com/en/mediacenter/what-is-encryption/</em></a></figcaption></figure><p>Encryption scrambles data using a secret key, making it unreadable without decryption. This might seem like a foolproof solution, but it has a flaw. Servers need to store the encryption key alongside the encrypted passwords. If a hacker gains access to both the encrypted passwords and the key, they can decrypt them all, revealing the original passwords.</p><p>A famous example of this vulnerability was the Adobe data breach in 2013, where hackers obtained encrypted passwords along with the decryption key, compromising millions of accounts.</p><h3><strong>3. Hashing: A One-Way Street to Security</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*sOccHn944QbPw7t2VUGclg.png" /><figcaption>source — <a href="https://signmycode.com/resources/best-hashing-algorithms"><em>https://signmycode.com/resources/best-hashing-algorithms</em></a></figcaption></figure><p>Imagine a password as a long string of letters, numbers, and symbols. A hashing function acts like a special machine that takes this input and creates a unique fixed-size output, the hash. This function works like a one-way street — it’s easy to create a hash from a password, but extremely difficult (practically impossible) to recreate the original password from the hash alone.</p><h4>Why is Hashing Secure?</h4><ul><li><strong>One-way nature:</strong> As mentioned earlier, the one-way property is crucial. Even the most powerful computers today cannot efficiently reverse a hash function to get the original password.</li><li><strong>Uniqueness:</strong> Ideally, each unique password should result in a unique hash. This ensures that even if two users have the same password (which is a bad practice!), their hashed passwords won’t be identical.</li></ul><h4>Hash Collisions:</h4><p>It’s important to note that collisions can occur. A collision happens when two different passwords generate the same hash. However, good hashing functions are designed to minimize the chances of collisions. In real-world scenarios, with proper password length and complexity, the risk of collisions is negligible.</p><h4>Types of Hashing Functions:</h4><p>There are various hashing algorithms available, each with its own strengths and weaknesses. Common choices include:</p><ul><li><strong>MD5 (Message Digest 5):</strong> An older algorithm, no longer considered secure due to its vulnerability to collisions.</li><li><strong>SHA-256 (Secure Hash Algorithm 256):</strong> A widely used and secure hashing algorithm that generates 256-bit hashes.</li><li><strong>bcrypt:</strong> A slower but more secure hashing algorithm designed to resist brute-force attacks. It incorporates a salting mechanism (explained later) within the hashing process.</li></ul><h3><strong>4. Salting: Why it matters?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*1dOv-b9ylUmZ6rTXqIC44g.png" /><figcaption>source — <a href="https://cheapsslweb.com/blog/why-password-salt-and-hash-make-for-better-security"><em>https://cheapsslweb.com/blog/why-password-salt-and-hash-make-for-better-security</em></a></figcaption></figure><p>Salting is a technique to increase the security in password storing. It works like this:</p><ul><li><strong>The Salt Generation:</strong> Before the password gets hashed, a random string of characters, called a salt, is generated. This salt is unique for each user.</li><li><strong>Appending the Salt:</strong> The chosen password is then appended (attached) to the salt, creating a combined string.</li><li><strong>Hashing the Combo:</strong> This combined string of password and salt is then fed into the hashing function. The resulting hash is a unique value specific to that user and their password, even if the original password itself is common.</li></ul><h4><strong>Why does salting defeat rainbow tables?</strong></h4><p>Rainbow tables are pre-computed hashes for a vast number of common passwords and their variations. However, salting completely disrupts this approach. Since a unique salt is added to each password before hashing, the resulting hash won’t be found in a pre-computed rainbow table. Hackers would need to create a new rainbow table for every single combination of salt and password, which becomes a computationally impractical task.</p><h4><strong>Salt Length and Security:</strong></h4><p>The strength of salting relies on the randomness and length of the salt. A longer and more unpredictable salt provides better protection. Modern systems typically use salts with a length of at least 32 characters, making it extremely difficult for attackers to pre-compute rainbow tables that account for all possible salt variations.</p><h3>5.<strong>Slowing Down the Attack: The Power of Strong Hashing Algorithms</strong></h3><p>There are different hashing algorithms, some faster than others. While speed can be beneficial for server performance, it can also be a double-edged sword. Faster algorithms can be cracked more easily with brute-force attacks, which systematically try every possible password combination.</p><p>Algorithms like SHA-256 are faster but more vulnerable. bcrypt, on the other hand, is a slower hashing algorithm designed to be resistant to brute-force attacks. It takes significantly longer to compute the hash, making it much harder for attackers to crack passwords this way.</p><p>Think of it like adding a complex lock to your door, it takes more time and effort to break in.</p><h3>6. <strong>The Ideal Solution: Avoiding Storing Passwords Altogether (OAuth — Open Authorization)</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*hJGblJLFxLeNhowSYZamuw.png" /><figcaption><strong><em>OAuth Actors</em></strong><em> souce-</em><a href="https://developer.okta.com/blog/2017/06/21/what-the-heck-is-oauth"><em>https://developer.okta.com/blog/2017/06/21/what-the-heck-is-oauth</em></a></figcaption></figure><p>OAuth acts as a bridge between your existing accounts and the websites you want to access. Instead of creating and storing passwords on every website, you can leverage your login credentials from a trusted service like Google, Facebook, or Apple to access other platforms.</p><h4><strong>Benefits of OAuth:</strong></h4><ul><li><strong>Enhanced Security:</strong> OAutheliminates the risk of password breaches on individual websites. Since the website doesn’t store your password, it’s not vulnerable if a hacker gains access to their database.</li><li><strong>Convenience:</strong> No more remembering multiple passwords! Oauth allows you to log in with a single click using your existing credentials.</li></ul><h4><strong>How </strong>OAuth<strong>Works:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*b6zeqWjUmyAJAVC0utFwJA.png" /><figcaption><strong>OAuth Architectural style</strong> source — <a href="https://www.tutorialspoint.com/oauth2.0/oauth2_concepts.htm"><em>https://www.tutorialspoint.com/oauth2.0/</em></a></figcaption></figure><ul><li><strong>Initiating Login:</strong> You visit a website that supports Oauth and choose to log in using a trusted service like Google.</li><li><strong>Redirection:</strong> You’re redirected to the login page of your chosen service (e.g : Google).</li><li><strong>Authorization:</strong> You enter your credentials and authorize the website to access specific information from your account (e.g: name, email).</li><li><strong>Access Granted:</strong> Once authorized, the trusted service sends a secure token back to the website.</li><li><strong>Website Login:</strong> The website verifies the token and grants you access to their platform.</li></ul><h4><strong>Considerations for OAuth:</strong></h4><ul><li><strong>Privacy Concerns:</strong> While convenient, Oauth involves sharing some information with the trusted service you’re using to log in. It’s important to understand what data is being shared and trust the privacy practices of the service provider.</li><li><strong>Vendor Lock-In:</strong> Reliance on a single trusted service introduces a potential point of failure. Ongoing development of decentralized identity solutions is aiming to mitigate this concern.</li></ul><p>Overall, OAuth offers a secure and convenient alternative to traditional password-based logins. As technology evolves and privacy concerns are addressed, Oauth might become the norm, leaving the era of password vulnerabilities behind.</p><h3>Making Your Passwords Stronger</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*1Owtq3DhCQO5v0N74-tvVg.png" /><figcaption>source -<a href="https://stock.adobe.com/"><em>https://stock.adobe.com/</em></a></figcaption></figure><ul><li><strong>Length is Key:</strong> Aim for at least 12+ characters with a mix of upper/lowercase, numbers, and symbols.</li><li><strong>Outsmart Hackers:</strong> Avoid obvious substitutions and spread characters throughout.</li><li><strong>Memorable Strength:</strong> Craft passphrases using first letters of words + symbols (e.g: <em>LoveSpicyNoodlesEveryNight#!</em><strong> </strong>for more security -<em>L0veSp1cyn00dle5EveryN1ght#!</em><strong> </strong>or<strong> </strong><em>L5NeN#!</em>)</li><li><strong>Security First:</strong> Never share passwords and try to enable 2FA(Two factor authentication) whenever possible.</li></ul><p>As technology evolves, so too will password security methods. Stay informed about emerging trends like password less logins and embrace new security measures as they become available. After all, a strong password is the first line of defense in protecting your digital identity.</p><p><strong>Good luck!</strong></p><h4><strong>References:</strong></h4><ul><li><a href="https://www.pandasecurity.com/en/mediacenter/what-is-encryption/"><em>https://www.pandasecurity.com/en/mediacenter/what-is-encryption/</em></a></li><li><a href="https://signmycode.com/resources/best-hashing-algorithms"><em>https://signmycode.com/resources/best-hashing-algorithms</em></a></li><li><a href="https://cheapsslweb.com/blog/why-password-salt-and-hash-make-for-better-security"><em>https://cheapsslweb.com/blog/why-password-salt-and-hash-make-for-better-security</em></a></li><li><a href="https://developer.okta.com/blog/2017/06/21/what-the-heck-is-oauth"><em>https://developer.okta.com/blog/2017/06/21/what-the-heck-is-oauth</em></a></li><li><a href="https://www.tutorialspoint.com/oauth2.0/oauth2_concepts.htm"><em>https://www.tutorialspoint.com/oauth2.0/</em></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cdb58b22836" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Cryptography: Protecting Your Data in the Digital Age]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/the-power-of-cryptography-protecting-your-data-in-the-digital-age-c15d195cf1f3?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/c15d195cf1f3</guid>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 13:10:24 GMT</pubDate>
            <atom:updated>2024-03-22T13:27:48.806Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A graphical image with laptop with a lock coming out of it to show the security of a computer" src="https://cdn-images-1.medium.com/max/975/1*TyUVSO8NgmWpcZSk5xCyrA.png" /><figcaption><em>Image source: </em><a href="https://www.iot-now.com/"><em>iot-now.com</em></a></figcaption></figure><p>In my fifth semester I had a module called “Computer Security” and those concepts were so interesting that leads me to write this article, Here I’m talking like a single drop from the ocean of Computer/Cyber security. So, let me begin.</p><p>Cryptography, the art of securing information, is the basis of modern cybersecurity. It empowers us to safeguard sensitive data, ensuring confidentiality and integrity even in the face of potential breaches. So, this article dives into the fascinating world of cryptography, exploring its core concepts, applications, and some advanced technical aspects I hope you might find it interest.</p><h3><strong>A Historical Perspective:</strong></h3><p>Cryptography owns a rich history going back to ancient civilizations. Early ciphers (<em>*Cipher is an algorithm for performing encryption or decryption</em>) like Caesar’s shift cipher, employed simple techniques to conceal messages.</p><figure><img alt="Image to show how the ceaser’s cipher works" src="https://cdn-images-1.medium.com/max/975/1*e5VfNLcq1jPFbO6hprD45Q.png" /><figcaption><strong><em>Ceaser’s Cipher — Caesar’s cipher encrypts messages by shifting letters based on a secret key</em></strong> <em>Image source: </em><a href="https://en.wikipedia.org/wiki/Caesar_cipher"><em>wikipedia</em></a></figcaption></figure><p>As communication evolved, so did cryptographic methods. The invention of public-key cryptography in the 20th century revolutionized the field, enabling secure communication even without prior key exchange.</p><p>The heart of cryptography holds on two main approaches:</p><ul><li><strong>Symmetric Encryption:</strong> This method utilizes a <strong>single secret key </strong>for both encryption and decryption. It’s efficient for encrypting large amounts of data and is often used for securing files, emails, and disk drives. Common symmetric algorithms include AES (Advanced Encryption Standard), a widely used block cipher with robust security.</li></ul><figure><img alt="Image about private key encryption" src="https://cdn-images-1.medium.com/max/975/1*mpjm-c5NL96gmuddRQfkXA.png" /><figcaption>Image source: <a href="https://cheapsslsecurity.com/"><em>cheapsslsecurity.com</em></a></figcaption></figure><ul><li><strong>Asymmetric Encryption:</strong> This approach leverages a <strong>key pair,</strong> a <strong>public key</strong> (widely distributed) and a <strong>private key</strong> (kept secret). Data encrypted with the public key can only be decrypted using the corresponding private key. This is ideal for secure communication and digital signatures, where a public key can be freely shared for encryption, but only the authorized recipient with the private key can decrypt the message.</li></ul><figure><img alt="Image about public key encryption" src="https://cdn-images-1.medium.com/max/975/1*lzH4QNt9hq2vbTKaE3b_cA.png" /><figcaption>Image source:<a href="https://cheapsslsecurity.com/"> <em>cheapsslsecurity.com</em></a></figcaption></figure><h3><strong>Public Key Infrastructure (PKI):</strong></h3><p>PKI plays a vital role in asymmetric encryption by establishing trust and managing digital certificates. Imagine you’re sending a secret message to a friend, but you’re worried someone might intercept it. Asymmetric encryption lets you conceal the message with that friend’s public key (like a widely known lock) that anyone can use. However, only your friend has the private key (like a secret key) to unlock it. But how do you know the public key you’re using belongs to your friend?</p><p>This is where Public Key Infrastructure (PKI) steps in. PKI acts as a trusted third party, when you visit a secure website (HTTPS), the website has a digital certificate issued by a trusted Certificate authority (CA). This certificate contains the website’s public key and a digital signature from the CA confirming for its authenticity. Your browser checks this signature and its own trust store (containing reputable CAs) to confirm it’s genuine. This creates a chain of trust, ensuring you’re sending your message to the real website and not an imposter. PKI forms the foundation for secure communication across the internet, making HTTPS websites the norm for protecting your online interactions.</p><h3><strong>Hashing Functions: Secure the integrity</strong></h3><p>Imagine you have a document and want to ensure it hasn’t been changed during sending process. Hashing functions act like digital fingerprints for data. They take any input, like your document, and create a <strong>unique fixed-size code</strong> <strong>(hash)</strong> based on its content. This code is like a summary of the information.</p><p>And any tiny change to the document will completely change the hash. And also hashing functions are one-way functions. You can easily create a hash from data, but it’s practically impossible to recreate the original data from just the hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*IEJZr-aFSePXYYJymU9tlw.png" /><figcaption><strong><em>You can see the difference is only the letter “s” at the end and the hash value is totally different. </em></strong><em>Image source: </em><a href="https://codesigningstore.com/">codesigningstore.com</a></figcaption></figure><p>So, how does this ensure data integrity? Before sending a file, you can calculate its hash and send it along with the file. The recipient can then calculate the hash of the received file. If both hashes match, you know the data hasn’t been tampered with because even a slight change would have resulted in different hashes.</p><h3><strong>Security Analysis and Best Practices:</strong></h3><ul><li><strong>No Flawless Systems:</strong> No cryptographic system is perfect. Security researchers continuously analyze algorithms and protocols to identify weaknesses. These weaknesses can be exploited by attackers through various means.</li><li><strong>The Importance of Scrutiny:</strong> Security analysis helps identify these vulnerabilities before attackers do. Cryptographic algorithms undergo rigorous testing and cryptanalysis (the art of breaking ciphers) to ensure their strength.</li><li><strong>Choosing Wisely: </strong>Not all cryptographic libraries are created equal. It’s essential to use well-vetted and secure libraries that have undergone thorough security audits and are actively maintained by developers.</li></ul><figure><img alt="Just a graphical image it does not give any theory" src="https://cdn-images-1.medium.com/max/975/1*ynDLtNCu9ajrcQ5XZVK2lw.png" /><figcaption>Image source: <a href="https://blog.1password.com/"><em>blog.1password.com</em></a></figcaption></figure><h3><strong>Cryptography in Action: Real-World Applications:</strong></h3><ul><li><strong>Surfing Securely</strong>: Ever notice the padlock symbol next to a website address? That signifies a secure connection using HTTPS. Behind the scenes, cryptography plays a vital role. Websites and your browser use TLS/SSL protocols, which rely on public-key cryptography and digital certificates.</li><li><strong>Email Confidence:</strong> When you send a digitally signed email, it’s like adding a tamper-proof wax seal. This signature, powered by asymmetric encryption, ensures authentication and integrity.</li><li><strong>Data at Rest:</strong> Disk encryption utilizes cryptography to transform your data into an unreadable format. Even if someone gains access to your device, they can’t access your sensitive information without the decryption key. Similarly, cloud storage providers often encrypt your data at rest, adding an another layer of security.</li><li><strong>Secure messaging apps:</strong> Encrypting your messages to ensure only the intended recipient can read them.</li><li><strong>Virtual Private Networks (VPNs):</strong> Tunneling your internet traffic through an encrypted connection for added privacy.</li><li><strong>Password storage:</strong> Securely storing your passwords as encrypted hashes, making them much harder to crack in case of a data breach.</li></ul><p>So, cryptography empowers us to navigate the digital age with confidence. By understanding its core concepts, applications, and exciting advancements, we can become active participants in building a more secure digital world. From securing our online interactions to safeguarding sensitive information, cryptography acts as our silent guardian in the digital realm. So, let’s embrace these powerful tools and work together to create a future where trust and security are more important.</p><h4><strong>References:</strong></h4><p>· <a href="https://en.wikipedia.org/wiki/Caesar_cipher">https://en.wikipedia.org/wiki/Caesar_cipher</a></p><p>· <a href="https://cheapsslsecurity.com/p/what-is-public-key-and-private-key-cryptography-and-how-does-it-work/">https://cheapsslsecurity.com/p/what-is-public-key-and-private-key-cryptography-and-how-does-it-work/</a></p><p>· <a href="https://codesigningstore.com/what-is-the-most-secure-hashing-algorithm">https://codesigningstore.com/what-is-the-most-secure-hashing-algorithm</a></p><p>· <a href="https://blog.1password.com/what-is-public-key-cryptography/">https://blog.1password.com/what-is-public-key-cryptography/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c15d195cf1f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharge React Forms : Building Elegant Forms with Formik and Yup]]></title>
            <link>https://medium.com/@nadeeshamadusanka44/supercharge-react-forms-building-elegant-forms-with-formik-and-yup-87ec7f2ea2f5?source=rss-46e71cbcb1ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/87ec7f2ea2f5</guid>
            <dc:creator><![CDATA[NadeeshaMadusanka]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 14:55:42 GMT</pubDate>
            <atom:updated>2024-03-09T14:55:42.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>Supercharge React Forms : Building Elegant Forms with <em>Formik </em>and Yup</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38BmfJjazuKObT9zsxMy2w.png" /></figure><p>During my internship, I had to work with a react-native application and, I’ve spent hours wrestling with the complexities of form handling. From managing form state to implementing robust validation, building user-friendly forms often felt like a complex task.</p><p>But there’s a light at the end of the tunnel. <em>Formik</em> and <em>Yup</em> joined to the chat, two powerful libraries that have transformed my approach to building React forms. These tools work in beautiful harmony, streamlining form development and validation.</p><p>Let’s dive deeper into the specific challenges I faced, and how <em>Formik</em> and <em>Yup</em> helped me overcome them:</p><p><strong>State Management:</strong> Handling individual component states for each form field quickly became a tangled mess. <em>Formik </em>eliminates this pain by managing the entire form state centrally, making it easier to track changes and keep the code organized.</p><p><strong>Validation Woes:</strong> Implementing custom validation logic for various form fields can be time-consuming and error-prone. <em>Yup </em>offers a declarative approach to validation, allowing you to define clear and concise validation rules using schemas.</p><p><strong>Error Handling Headaches:</strong> <em>Formik</em> seamlessly integrates with <em>Yup</em>, enabling you to easily display validation errors next to the corresponding form fields, improving the user experience.</p><p>So because of these common pain points, <em>Formik </em>and <em>Yup </em>have become my go-to tools for building React forms. In this article, we’ll explore their functionalities in detail, showing you how to build elegant and robust forms that are a joy to create and use.</p><h3><strong>Building Elegant Forms with Formik and Yup</strong></h3><p>Imagine building a form without the usual hassles of managing state, validation, and error handling. That’s the magic of Formik and Yup working together! Let’s break down their functionalities and see how they simplify form development in React.</p><h4><strong>Formik: Your Form Management Hero</strong></h4><ul><li><strong>State Management Made Easy:</strong> Forget juggling individual states for each form field. <em>Formik </em>takes care of the entire form state centrally. You define the initial values for your form fields, and Formik keeps track of changes to those values as users interact with the form.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*PB38ScwNF5ip3CfBHkUrPQ.png" /><figcaption>Formik function</figcaption></figure><p>In this example, I used <em>initialValues</em> used to set initial form values. <em>useFormik</em> takes these values and manages the state as the user interacts with the form using <em>formik.getFieldProps.</em></p><ul><li><strong>Built-in Validation:</strong> While <em>Formik </em>provides basic validation capabilities, it shines when paired with <em>Yup </em>for more robust validation.</li></ul><h4><strong>Formik and Yup:</strong></h4><p>· <strong>Yup: The Validation Powerhouse:</strong> <em>Yup </em>is a separate library that offers a powerful and declarative way to define validation rules for your form fields. You create <em>Yup </em>schemas that specify the validation criteria for each field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*_yD-9pnsMV093D2MEw8IZw.png" /><figcaption>Yup schema</figcaption></figure><p>This schema defines validation rules for <strong>name</strong> and <strong>email</strong> fields. required ensures a value is present, and email validates the email format.</p><h4><strong>Integrating Yup with Formik:</strong></h4><p><strong>Seamless Validation Integration:</strong> Simply pass your <em>Yup </em>schema to the <em>validationSchema</em> prop of <em>useFormik</em>. <em>Formik </em>automatically validates the form data against the schema whenever there’s a change or on submission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Y7KpQEh1etpiCGcjqiCJ_A.png" /><figcaption>Formik with Yup</figcaption></figure><h4><strong>Displaying Validation Errors:</strong></h4><p>· <strong>User-Friendly Error Messages:</strong> When validation fails, <em>Yup </em>provides detailed error messages. <em>Formik </em>integrates with these messages, allowing you to easily display them next to the corresponding form fields, providing clear feedback to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*N4Kw2qjBmMgnOJK_AhKMvQ.png" /><figcaption>return statement of the Formik with Yup</figcaption></figure><p>This code checks if a field has been touched (meaning the user interacted with it) and if there’s an error for that field. If so, it displays the error message next to the field using a CSS class named “error” for styling .<br> <br> <em>Formik </em>and <em>Yup </em>empower you to build user-friendly, robust, and elegant forms in React. Here I just showed you a very basic examples you can create more complex forms with these two, So ditch the tedious state management and validation struggles, and experience the joy of a streamlined form development process. <strong>Give <em>Formik </em>and <em>Yup </em>a try!</strong> You’ll be glad you did.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87ec7f2ea2f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>