<?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"><channel><title><![CDATA[Akladyous]]></title><description><![CDATA[Akladyous]]></description><link>https://boula.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 10 Nov 2026 01:26:14 GMT</lastBuildDate><atom:link href="https://boula.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Batching in React]]></title><description><![CDATA[software engineering]]></description><link>https://boula.hashnode.dev/batching-in-react</link><guid isPermaLink="true">https://boula.hashnode.dev/batching-in-react</guid><category><![CDATA[React]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Sat, 24 Jun 2023 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728757189269/a72a5886-7349-4267-9350-0dc67a8b3075.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>React is known for its efficient rendering process, and one of the key techniques it utilizes is batching. Batching refers to the process of combining multiple updates into a single update, minimizing the number of times the real DOM needs to be updated. In this article, we will explore how batching works under the hood in React and its impact on performance. We will also provide examples to demonstrate the concept.</p>
<h3 id="heading-understanding-batching">Understanding Batching</h3>
<p>When React renders a component, it doesn’t immediately apply every change to the real DOM. Instead, it batches the updates together and performs them all at once, resulting in better performance and a smoother user experience. React achieves batching through a technique called “transaction,” which groups related operations and executes them as a single unit of work.</p>
<blockquote>
<p>Example: Updating State with Batching:</p>
</blockquote>
<p>Let’s consider an example where a component updates its state multiple times in quick succession. Without batching, React would update the real DOM for each state change separately, even if the actual value changed only once. This approach would be inefficient.</p>
<p>However, due to batching, React combines these updates into a single transaction. As a result, the real DOM is updated only once after all the state changes have been processed. This reduces unnecessary DOM updates and improves performance.</p>
<p>To demonstrate this, let’s modify the example code to log the current transaction state:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Example</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

    <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(
            <span class="hljs-string">"before "</span>,
            React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner.currentDispatcher,
        );
        setCount(count + <span class="hljs-number">1</span>);
        setCount(count + <span class="hljs-number">1</span>);
        setCount(count + <span class="hljs-number">1</span>);

        <span class="hljs-built_in">console</span>.log(
            <span class="hljs-string">"after "</span>,
            React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner.currentDispatcher,
        );
    };

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}
</code></pre>
<p>In this modified example, we log the current transaction state before and after the state updates. By observing the logs, we can see that React batches the updates together into a single transaction.</p>
<p>Common Pitfall: Event Handlers and Batching: React’s batching behavior can sometimes lead to confusion, especially when dealing with event handlers. Consider an example where a component updates its state and logs the count immediately after the state update. Due to batching, the logged count will always be one less than the actual value at that moment.</p>
<p>This happens because React schedules a batch of updates to the real DOM, deferring the actual application of changes. Therefore, when the log statement is executed, the state update might not have been processed yet.</p>
<h4 id="heading-fiber-architecture-and-incremental-updates">Fiber Architecture and Incremental Updates</h4>
<p>React Fiber, introduced in React 16, is a re-implemented rendering engine that offers enhanced efficiency and flexibility. It introduces incremental updates to the virtual DOM, enabling the browser to handle user input and other events without blocking the UI.</p>
<p>With React Fiber, updates are broken down into smaller chunks, allowing for prioritization and interleaving of different tasks. This approach enhances responsiveness and ensures that the user interface remains interactive even during intense rendering processes.</p>
<h4 id="heading-conclusion">Conclusion</h4>
<p>Batching is a fundamental mechanism in React that optimizes UI updates for improved performance. By combining multiple updates into a single transaction, React minimizes the number of DOM manipulations and delivers a smoother user experience. Understanding batching and its impact on event handling and performance is crucial for developing efficient React applications.</p>
<p>In this article, we discussed the concept of batching in React, its implementation through transactions, and its benefits in terms of performance. We provided examples to illustrate how batching works and explained the significance of React Fiber’s incremental updates. By leveraging batching effectively, developers can build highly performant and responsive React applications.</p>
<p><em>Thank you for reading! ❤️</em></p>
]]></content:encoded></item><item><title><![CDATA[React Fiber]]></title><description><![CDATA[React Fiber is a game-changing addition to react, designed to boost performance by optimizing the rendering process]]></description><link>https://boula.hashnode.dev/react-fiber</link><guid isPermaLink="true">https://boula.hashnode.dev/react-fiber</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[React]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Thu, 12 Jan 2023 17:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1766354831403/f9d24af7-8147-4e81-b4a6-080a17906f07.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-an-overview-of-fiber-trees-and-reconciliation">An Overview of Fiber Trees and Reconciliation</h2>
<h2 id="heading-unlocking-the-power-of-web-scraping-for-data-collection-and-analysis">Unlocking the Power of Web Scraping for Data Collection and Analysis</h2>
<p>React Fiber is a revolutionary feature in the React library that aims to significantly enhance the performance and rendering efficiency of React applications. At the heart of Fiber lies the reconciliation process, a powerful mechanism that efficiently updates the user interface based on changes in application state. In this blog, we will delve into the concept of Fiber trees and explore how the reconciliation process works.</p>
<h2 id="heading-reconciliation-stack">Reconciliation Stack</h2>
<p>Before the release of React 16, React employed a stack-based reconciliation algorithm known as the "stack reconciler" to compare the old and new virtual trees and update the DOM accordingly. While suitable for simpler scenarios, the stack reconciler faced challenges as applications grew in complexity.</p>
<p>The synchronous nature of the stack reconciler caused updates to block the main thread, leading to janky and unresponsive user interfaces, especially with large virtual trees or slower devices. Additionally, changes to the virtual tree were delayed until the reconciler completed its work, affecting overall performance and responsiveness.</p>
<h2 id="heading-the-fiber-reconciler">The Fiber Reconciler</h2>
<p>To address these challenges and improve React's performance, React 16 introduced the Fiber reconciler, a complete rewrite of the previous stack-based algorithm with several significant benefits.</p>
<h2 id="heading-how-react-fiber-works">How React Fiber Works</h2>
<p>When a React application undergoes an update triggered by user interactions or events, the reconciliation process is initiated. Its goal is to efficiently determine the parts of the user interface that require updating and apply these changes to the real DOM.</p>
<h2 id="heading-fiber-trees-current-and-work-in-progress"><em>Fiber Trees - Current and Work in Progress</em></h2>
<p>The reconciliation process involves two sets of virtual DOM trees: the "current" tree and the "work in progress" tree, also known as the Fiber tree. The "current" tree represents the existing state of the virtual DOM, while the "work in progress" tree is a replica that incorporates the updates to be performed.</p>
<h2 id="heading-render-phase">Render Phase</h2>
<p>The reconciliation process begins with the render phase, where React traverses the component tree and creates fiber nodes, special data structures representing different portions of the virtual DOM.</p>
<p>During the render phase, React compares the fiber nodes in the "current" and "work in progress" trees to identify parts of the virtual DOM requiring updates. Leveraging a work loop, React breaks rendering work into smaller units that can be interrupted and resumed, prioritizing important updates to maintain a responsive user interface.</p>
<h2 id="heading-commit-phase">Commit Phase</h2>
<p>After completing the render phase and applying the necessary updates to the "work in progress" tree, React enters the commit phase. Here, React takes the updates from the "work in progress" tree and applies them to the real DOM, making the changes visible to users.</p>
<p>React optimizes the performance by batching updates during the commit phase, reducing unnecessary reflows and repaints for a smoother user experience.</p>
<h2 id="heading-a-new-horizon-for-concurrency-and-batching">A New Horizon for Concurrency and Batching</h2>
<p>React Fiber, the new reconciliation architecture introduced in React 16, not only improves rendering efficiency but also unlocks powerful features for concurrency and batching. This allows React to break free from the limitations of synchronous updates and enables the library to handle complex user interactions more intelligently.</p>
<p>| Concurrency and Batching</p>
<p>In traditional synchronous rendering, React updates the entire component tree before reflecting changes in the real DOM. This approach can lead to unnecessary processing, causing performance bottlenecks and affecting user experience. React Fiber introduces the concept of concurrency, which enables asynchronous rendering and prioritization of tasks.</p>
<p>With concurrency, React can pause, resume, or abort rendering work as needed, and even divide the rendering process into smaller, more manageable chunks. This fine-grained control empowers React to prioritize essential updates and respond faster to user interactions, making the user interface feel more responsive and fluid</p>
<h2 id="heading-new-functionality-in-react-fiber">New Functionality in React Fiber</h2>
<p>To leverage the benefits of concurrency and batching, React introduces several new functionalities:</p>
<pre><code class="lang-js">useDeferredValue;
</code></pre>
<p>The useDeferredValue hook allows developers to defer the processing of non-essential updates, optimizing performance by prioritizing high-priority work. For example, in a search input, we may want to defer the rendering of search results until the user pauses typing. This way, React can focus on more critical tasks like handling user input, ensuring a smoother experience.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useDeferredValue } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> Search = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [query, setQuery] = useState(<span class="hljs-string">""</span>);

    <span class="hljs-comment">// Defer the processing of non-essential updates</span>
    <span class="hljs-keyword">const</span> deferredQuery = useDeferredValue(query);

    <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
        setQuery(e.target.value);
    };

    <span class="hljs-comment">// Rest of the component logic</span>
};
</code></pre>
<pre><code class="lang-js">useTransition;
</code></pre>
<p>The useTransition hook allows developers to create smoother transitions during rendering updates. It helps to manage complex interactions by defining specific points in the rendering process where React should wait for a transition to complete before displaying the changes.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useTransition, useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> ExpensiveComponent = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> [isPending, startTransition] = useTransition();

    <span class="hljs-comment">// Simulate a time-consuming rendering process</span>
    useEffect(<span class="hljs-function">() =&gt;</span> {
        startTransition(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-comment">// Code to render the expensive component</span>
        });
    }, []);

    <span class="hljs-keyword">if</span> (isPending) {
        <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
    }

    <span class="hljs-comment">// Return the fully rendered component</span>
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Expensive Component Content<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
};
</code></pre>
<h2 id="heading-suspense-component">Suspense Component</h2>
<p>The Suspense component is a powerful tool that allows developers to handle loading states and fallback UIs in an elegant and straightforward manner. It is especially useful when dealing with asynchronous data fetching or code-splitting.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Suspense } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Suspense</span> <span class="hljs-attr">fallback</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}&gt;
            {/* Asynchronously load and render the lazy component */}
            <span class="hljs-tag">&lt;<span class="hljs-name">LazyComponent</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Suspense</span>&gt;</span></span>
    );
};
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>React Fiber's reconciliation process, powered by the concept of Fiber trees, plays a pivotal role in driving React's remarkable performance. By intelligently managing virtual DOM updates and efficiently applying them to the real DOM, React ensures that user interfaces remain snappy and responsive, making React a popular and powerful choice for building modern web applications. The introduction of React Fiber marks a significant milestone in React's evolution, paving the way for even more efficient and responsive applications.</p>
<p>Thanks for reading ❤️</p>
]]></content:encoded></item><item><title><![CDATA[Web scraping News Articles using NewsAPI]]></title><description><![CDATA[Web Scraping is a technique employed to gather large amounts of data from websites whereby the data is extracted and stored into a structured format. such…]]></description><link>https://boula.hashnode.dev/web-scraping-news-articles-using-newsapi</link><guid isPermaLink="true">https://boula.hashnode.dev/web-scraping-news-articles-using-newsapi</guid><category><![CDATA[Python]]></category><category><![CDATA[web scraping]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Tue, 12 Oct 2021 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728748476242/9a00aeb6-b96b-412b-9b04-7189ed6b4633.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Web Scraping is a technique employed to gather large amounts of data from websites whereby the data is extracted and stored into a structured format. such technique is widely used for a range of purposes, including market analysis, machine learning, news tracking and financial data aggregation. The ability of web scraping is an important skill for any data scientist to have in their set.</p>
<p>There are many different approaches for getting data from the web such as writing a custom crawler from scratch, or by using one of the many existing libraries that make it absolutely easy to create a web scraping tool in Python.</p>
<p>In this Python tutorial we will go through a simple example of how to scrap a website to gather news articles and create simple applications using NEWSAPI library.</p>
<p>Most of the libraries for gathering information are Python standard, with the exception of the Pandas and NewsApi libraries accessible via installation and free registration on the official websites.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Get API key</p>
<p>Firstly, get the API key by registering on the News API web page. Be sure to register as an individual. This will grant the free usage of the API. Click Here and fill out the form. The API key should be in your inbox shorty.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">import</span> json
</code></pre>
<p>API Key Note that in order to interact with the API, it is mandatory to provide the API key.</p>
<p>There are two ways to do that:</p>
<ol>
<li><p><strong>Using API key in the request URL</strong>: Include the API key as a query parameter in the URL when making requests.</p>
<pre><code class="lang-python"> https://newsapi.org/v2/everything?q=bitcoin&amp;apiKey=YOUR_API_KEY
</code></pre>
</li>
<li><p><strong>Using the NewsApiClient library</strong>: Initialize the client with your API key (requires installing the <code>newsapi-python</code> package).</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> newsapi <span class="hljs-keyword">import</span> NewsApiClient
 newsapi = NewsApiClient(api_key=<span class="hljs-string">'YOUR_API_KEY'</span>)
</code></pre>
</li>
</ol>
<h2 id="heading-headers">Headers</h2>
<p>we create a dictionary to store our API key, we include it in the header of the “requests”</p>
<pre><code class="lang-python"><span class="hljs-comment"># Create a variable to hold the API key</span>
headers = {<span class="hljs-string">'Authorization'</span>: <span class="hljs-string">'cd23a40b7a0d44cb99af86eeb31869eb'</span>
</code></pre>
<h2 id="heading-api-endpoint">API Endpoint</h2>
<p>News API has 2 main endpoints:</p>
<ul>
<li><p><strong>Everything</strong> /v2/everything – search every article published by over 75,000 different sources large and small in the last 3 years. This endpoint is ideal for news analysis and article discovery.</p>
</li>
<li><p><strong>Top headlines</strong> /v2/top-headlines – returns breaking news headlines for countries, categories, and singular publishers. This is perfect for use with news tickers or anywhere you want to display live up-to-date news headlines.</p>
</li>
</ul>
<pre><code class="lang-python"><span class="hljs-comment"># create 2 variables to hold the API endpoints.</span>
everything = <span class="hljs-string">"https://newsapi.org/v2/everything?"</span>
top_headlines = <span class="hljs-string">"https://newsapi.org/v2/top-headlines?"</span>
</code></pre>
<h2 id="heading-api-keywords">API Keywords</h2>
<p>Keywords or a phrase to search for.</p>
<p>the parameter ‘q’ stands for the keyword search value. The news articles matching the keyword search are returned as a response</p>
<pre><code class="lang-python"><span class="hljs-comment"># in our tutorial we look for news related to Apple</span>
symbols = <span class="hljs-string">"apple"</span>
</code></pre>
<h2 id="heading-api-sources">API Sources</h2>
<p>A comma-seperated string of identifiers for the news sources or blogs you want headlines from.</p>
<pre><code class="lang-python">sources = [<span class="hljs-string">'abc-news'</span>, <span class="hljs-string">'business-insider'</span>, <span class="hljs-string">'financial-post'</span>, <span class="hljs-string">'google-news'</span>,
          <span class="hljs-string">'reuters'</span>,<span class="hljs-string">'nbc-news'</span>, <span class="hljs-string">'techcrunch'</span>, <span class="hljs-string">'the-wall-street-journal'</span>]
</code></pre>
<h2 id="heading-api-sortby">API sortBy</h2>
<p>The ‘sortBy’ parameter contains the option that applies to the returned articles. Based on this value, the articles are sorted in the response</p>
<p>Possible options: [relevancy, popularity, publishedAt].</p>
<pre><code class="lang-python">sorby = <span class="hljs-string">"popularity"</span>
</code></pre>
<h2 id="heading-payloads">Payloads</h2>
<p>Next step is to create different payloads that need to be sent to the API. The payload is nothing more than some information that needs to be sent to the API. The payload can include information such as news category, country, language, etc.</p>
<pre><code class="lang-python">params= {
       <span class="hljs-string">'q'</span>: keywords,
       <span class="hljs-string">'apiKey'</span>: api_key,
       <span class="hljs-string">'sortBy'</span>: sorby,
       <span class="hljs-string">'language'</span>: <span class="hljs-string">'en'</span>,
       <span class="hljs-string">'page'</span>: <span class="hljs-number">1</span>
      }
</code></pre>
<h2 id="heading-requests-api">Requests API</h2>
<p>Make the request using the get() method of the requests library.</p>
<p>Make the request using the get() method of the requests library. we’re going to pass ony 2 parameters, first the ‘url’ parameter, specify the NewsAPI endpoint, and lastly pass the payloads dictionary to the ‘params’ parameter.</p>
<pre><code class="lang-python">response = requests.get(url=top_headlines, headers=headers, params=params)
</code></pre>
<p>The structure of the “requests” remains the same throughout, we can update the parameters “url” and “params” parameter in order to gather diffrent type of news.</p>
<h2 id="heading-response">Response</h2>
<p>Create a viariable to hold the the “response” in dictionary format</p>
<pre><code class="lang-python">output = response.json()
</code></pre>
<p>Print out the response on the console by accessing the method “json”, since it already data formated by NewsAPI library.</p>
<pre><code class="lang-python">print(json.dumps(output, indent=<span class="hljs-number">4</span>))
{
    <span class="hljs-string">"status"</span>: <span class="hljs-string">"ok"</span>,
    <span class="hljs-string">"totalResults"</span>: <span class="hljs-number">10</span>,
    <span class="hljs-string">"articles"</span>: [
        {
            <span class="hljs-string">"source"</span>: {
                <span class="hljs-string">"id"</span>: null,
                <span class="hljs-string">"name"</span>: <span class="hljs-string">"Rappler"</span>
            },
            <span class="hljs-string">"author"</span>: <span class="hljs-string">"Rappler.com"</span>,
            <span class="hljs-string">"title"</span>: <span class="hljs-string">"Jollibee introduces new sweet chili chicken - Rappler"</span>,
            <span class="hljs-string">"description"</span>: <span class="hljs-string">"Jollibee's fried chicken is coated in a sweet-spicy chili glaze"</span>,
            <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://www.rappler.com/life-and-style/food-drinks/jollibee-sweet-chili-chicken"</span>,
            <span class="hljs-string">"urlToImage"</span>: <span class="hljs-string">"https://assets2.rappler.com/2021/06/1-1623468746894.jpg"</span>,
            <span class="hljs-string">"publishedAt"</span>: <span class="hljs-string">"2021-06-12T03:39:00Z"</span>,
            <span class="hljs-string">"content"</span>: <span class="hljs-string">"Jollibee's new limited edition item can be ordered for dine-in, take-out, drive-thru, or delivery via the Jollibee Delivery app, website, hotline number, GrabFood, and foodpanda. Rappler.com"</span>
        },
        {
            <span class="hljs-string">"source"</span>: {
                <span class="hljs-string">"id"</span>: null,
                <span class="hljs-string">"name"</span>: <span class="hljs-string">"Rappler"</span>
            },
            <span class="hljs-string">"author"</span>: <span class="hljs-string">"Reuters"</span>,
            <span class="hljs-string">"title"</span>: <span class="hljs-string">"Hong Kong democracy activist Agnes Chow released from prison - Rappler"</span>,
            <span class="hljs-string">"description"</span>: <span class="hljs-string">"(1st UPDATE) Agnes Chow serves nearly seven months in prison for her role in an unauthorized assembly during Hong Kong's 2019 anti-government protests"</span>,
            <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://www.rappler.com/world/asia-pacific/hong-kong-democracy-activist-agnes-chow-released"</span>,
            <span class="hljs-string">"urlToImage"</span>: <span class="hljs-string">"https://assets2.rappler.com/2021/06/Agnes-Chow-Wikimedia-June-12-2021-1623465814534.jpeg"</span>,
            <span class="hljs-string">"publishedAt"</span>: <span class="hljs-string">"2021-06-12T02:45:00Z"</span>,
            <span class="hljs-string">"content"</span>: <span class="hljs-string">"Hong Kong pro-democracy activist Agnes Chow was released from prison on Saturday, June 12, after serving nearly seven months for her role in an unauthorized assembly during anti-government protests i\u2026 [+18 chars]"</span>
        },
</code></pre>
<h2 id="heading-save-resonse-to-csv">Save Resonse to CSV</h2>
<p>In order to create a dataframe with the result obtained, we must access the dictionary values using the “articles” key</p>
<pre><code class="lang-python">print(output.keys())
dict_keys([<span class="hljs-string">'status'</span>, <span class="hljs-string">'totalResults'</span>, <span class="hljs-string">'articles'</span>])
</code></pre>
<p>Create a variable to hold the articles information.</p>
<pre><code class="lang-python">articles = output[<span class="hljs-string">'articles'</span>]
</code></pre>
<p>Using “pandas” we create a dataframe using the method “DataFrame” passing parameter “data” with the articles variable</p>
<pre><code class="lang-python">df = pd.DataFrame(articles)
df.head(<span class="hljs-number">3</span>)
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1766354297200/4d42fbd3-642d-458f-8599-af26878631a0.png" alt class="image--center mx-auto" /></p>
<p>You can find my Jupyter Notebook for this on my Github.</p>
<p>Thanks for reading and happy web scraping everyone! ❤️</p>
]]></content:encoded></item><item><title><![CDATA[Rails Action Mailer Configuration]]></title><description><![CDATA[How does Action Mailer work?]]></description><link>https://boula.hashnode.dev/rails-action-mailer-configuration</link><guid isPermaLink="true">https://boula.hashnode.dev/rails-action-mailer-configuration</guid><category><![CDATA[Action Mailer]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[Rails]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Mon, 21 Jun 2021 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743615644/1eb253f2-47f1-4bb3-9a8a-4ee579da237b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h4 id="heading-action-mailer-overview"><em>Action Mailer overview</em></h4>
<p>Rails has a wonderful built-in mailing system called Action Mailer, which allows us to send email from our application as long as we have a <strong>mailer model</strong>. Mailers are actually a lot like controllers: they have their own <code>app/mailers</code> directory, and each mailer has its own associated view as well. Each mailer also inherits from <code>ActionMailer::Base</code>, and just like controllers, can be generated really easily.</p>
<p>This tutorial explains how to configure Ruby on Rails in the development environment toward sending emails via Ruby on Rails Action Mailer integrated with the most popular email providers Gmail &amp; SendGrid.</p>
<p>Let’s take it step by step, first we need to do a bit of configuration, we are going to send emails from the developement enviroment.</p>
<h4 id="heading-actionmailer-gmail-confiruation">ActionMailer Gmail Confiruation</h4>
<p>In order to use Action Mail with Gmail, the best solution that does not violate your other security such as 2-step certification is using <a target="_blank" href="https://support.google.com/accounts/answer/185833">App Password</a></p>
<ul>
<li>Open your <a target="_blank" href="https://myaccount.google.com/security">Account Security Settings</a></li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743611502/a347147b-081c-44d7-9a53-80e8671e7db8.png" alt /></p>
<ul>
<li>Navigate to App Password</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743612727/fd9ee542-2ea8-43eb-aef3-f9e0c4148fdf.png" alt /></p>
<ul>
<li>On the App Password page, select “Mail” app, and “Other” device, now we provide the name of ruby on Rail application. Then click “Generate”.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743614067/8041a7a1-0192-470c-a282-be6abd8af0b5.png" alt /></p>
<ul>
<li>Copy your App password from the yellow Box.</li>
</ul>
<h4 id="heading-actionmailer-rails-confiruation">ActionMailer Rails Confiruation</h4>
<p>Ruby doesn’t require any additional gems to be installed, as it’s just a simple smtp setting, we just need to configure the setup by adding the following code into our file <em>development.rb</em> so that the Action Mailer and mailcatcher will be setup properly.</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="023038ae4684d598685649981b0e00e0"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/023038ae4684d598685649981b0e00e0" class="embed-card">https://gist.github.com/023038ae4684d598685649981b0e00e0</a></div><p> </p>
<p>for mote informaition refer to <a target="_blank" href="https://guides.rubyonrails.org/action_mailer_basics.html#action-mailer-configuration-for-gmail">Action Mail Confiruation for Gmail</a>.</p>
<p>To start, we’ll use Rails to generate a mailer:</p>
<h4 id="heading-creating-a-mailer">Creating a Mailer</h4>
<p>So the first thing we need to do is to create a new Mailer. To do this we can use the Rails generator:</p>
<p>rails generate mailer UserMailer welcome_message<br />create app/mailers/user_mailer.rb<br />invoke erb<br />create app/views/user_mailer<br />create app/views/user_mailer/welcome_message.text.erb<br />create app/views/user_mailer/welcome_message.html.erb</p>
<p>Running this command in the terminal generates a few different files for us. We now have an <code>app/mailers</code> directory, with an <code>user_mailer.rb</code> and <code>application_mailer.rb</code> file.</p>
<p>class ApplicationMailer &lt; ActionMailer::Base<br />default from: "from@example.com"<br />layout "mailer"<br />end</p>
<p>The<code>application_mailer.rb</code> is the base class that all other mailers are going to inhert from, we notice it inherts from ActionMailer::Base and the first thing it does it cause the default method <em>default from: "</em><a target="_blank" href="mailto:from@example.com"><em>from@example.com</em></a><em>"</em> and passes some options, these option will be applied to all of our email by default because it's defined up here in the base class. The from option is the email address you want to use as the sender of the email.</p>
<p>class UserMailer &lt; ApplicationMailer<br />def welcome_message<br />@greeting = "Hi"<br />mail to: "to@example.org", subject: 'Account registration'<br />end<br />end</p>
<p>It also generated this <em>UserMailer</em>, notice that the user_mailer.rb inherts from the ApplicationMailer.</p>
<p>Now this mailer classes works similarlly to rails controllers, they inherts from the common base class, in this case “ApplicationMailer”. Thet also has a method inside of him, notice that this method correspond to the name we gave in the command line “welcome_message” , and those methods are similiar to controller actions, but instead of generating an HTML response, “mailer” method generate an “email”.</p>
<p>So this welcome_message is goning to generate the email we want. we also see that step down method includes this “@greeting” instance variable, an instance variables define inside of <em>welcome_message</em> method are accessabile in <em>view templates</em> just like we would expect with the controller action.</p>
<p>And the last line of these mailer methods must call this <em>mail</em> method to accualty create a mail message a return it. now you notice we can also pass option to this method, in this case we have the option <em>to:</em>, this the person we want to send the email to.</p>
<p>To create that email, the <em>mail</em> method is goning to render some email template, now the generator went ahead and created 2 email templates for us to render that new message. and those templates are over in:</p>
<p>App<br />|- Views<br />|- user_mail<br />|- welcome_message.html.erb<br />|- welcome_message.text.erb</p>
<p>notice that the name of the file includes the name of the mailer method, <em>welcome_message.html.erb</em> that generates an HTML email and <em>welcome_message.text.erb</em> that generates a plain text email.</p>
<p>If we take look at the HTML template, what we see it looks just like any other view template.</p>
<p>It’s a good practice to send both plain text and HTML email and let the email client decide which one to display, and the action mailer does all the heavy lifting for us because we have 2 views templates with the same name but different content types ebedded in their file names, both templates will get rendered and sent out in one multi-part email.</p>
<p>Let’s go ahead and setup a user login with our <em>welcome_message</em> method, so our <em>users_controller.rb</em> looks like:</p>
<p>def create<br />@user = User.new(signup_params)<br />if @user.save!<br />session[:user_id] = @user.id<br />UserMailer.with(user: current_user).welcome_msg.deliver_now<br />render json: @user, status: :created<br />end<br />end</p>
<p>It would be handy to change our template so that it generates an email content we want.</p>
<h1 id="heading-welcome-to-wwwexamplecomhttpwwwexamplecom-lt-username-gt">Welcome to [www.example.com,](http://www.example.com,) &lt;%= @user.name %&gt;</h1>
<p>You have successfully signed up to www.example.com</p>
<p>Your email address is : &lt;%= @user.email%&gt;</p>
<p>Your user name is : &lt;%= @user.user\_name%&gt;</p>
<p>Thanks for joining and have a great day!</p>
<p>Conclusion</p>
<p>It doesn’t really matter if you are building a consumer or business application, you’re going to need to send emails to your users as some point.</p>
<p>Thank you for reading! ❤️</p>
]]></content:encoded></item><item><title><![CDATA[React Controlled vs. Uncontrolled Components]]></title><description><![CDATA[React Form Handling, Explore Controlled Components for efficient data manipulation in React]]></description><link>https://boula.hashnode.dev/react-controlled-vs-uncontrolled-components</link><guid isPermaLink="true">https://boula.hashnode.dev/react-controlled-vs-uncontrolled-components</guid><category><![CDATA[controlled and uncontrolled components]]></category><category><![CDATA[React]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Sun, 13 Jun 2021 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743617705/38633da2-ab11-4877-ad8d-0db728ab4a90.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-react-makes-it-easy-to-manipulate-data-using-forms">React makes it easy to manipulate data using forms.</h3>
<p>One of the most common patterns you’ll see in React when dealing with <em>forms</em> is that we need to make React aware of changes to the form inputs when the user types. This means that the component containing those input elements typically needs to keep track of the text in the input elements using state.</p>
<p>React supports two types of components: <strong>controlled components</strong> and <strong>uncontrolled components</strong>. Let’s uncover the main differences between controlled and uncontrolled components.</p>
<h4 id="heading-controlled-component">Controlled Component</h4>
<p>Unlike the uncontrolled component, the input form element in the controlled component is handled by the component rather than the DOM. It takes its current value through props. The changes are notified through useState Hook. Let’s consider an example to understand it in a better way.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ControlledComponent</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">""</span>);
    <span class="hljs-keyword">const</span> [age, setAge] = useState();
    <span class="hljs-keyword">const</span> [hairColor, setHairColor] = useState(<span class="hljs-string">""</span>);
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"name"</span>&gt;</span>
                Name
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                    <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span>
                    <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
                    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Name"</span>
                    <span class="hljs-attr">value</span>=<span class="hljs-string">{name}</span>
                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setName(e.target.value)}
                /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"age"</span>&gt;</span>
                Age
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                    <span class="hljs-attr">name</span>=<span class="hljs-string">"age"</span>
                    <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span>
                    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Age"</span>
                    <span class="hljs-attr">value</span>=<span class="hljs-string">{age}</span>
                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setAge(Number(e.target.value))}
                /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"haircolor"</span>&gt;</span>
                Hair Color
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                    <span class="hljs-attr">name</span>=<span class="hljs-string">"haircolor"</span>
                    <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
                    <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Hair Color"</span>
                    <span class="hljs-attr">value</span>=<span class="hljs-string">{hairColor}</span>
                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setHairColor(e.target.value)}
                /&gt;
            <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
    );
}
</code></pre>
<p>​</p>
<p>The input field is Controlled because React sets its value from the state .</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> /&gt;</span>
</code></pre>
<p>Whenever we type into the input field, the onChange handler updates the state with the input’s value accessed from the event object. The value state variable is the source of truth. When we need to access the value entered by the user into the input field, we have to read the value from the state variable. The Controlled components can help access the value of any input field.</p>
<h4 id="heading-uncontrolled-component">Uncontrolled component</h4>
<p>Similar to the traditional HTML form inputs, the uncontrolled component can be written using a ref to get form values from the DOM. Thus there is no need to write an event handler for every state update and the HTML elements maintain their own state that will be updated when the input value changes.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { createRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UncontrolledComponent</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> nameInput = createRef();
    <span class="hljs-keyword">const</span> ageInput = createRef();
    <span class="hljs-keyword">const</span> hairColorInput = createRef();
    <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
        e.preventDefault();
        <span class="hljs-built_in">console</span>.log(nameInput.current.value);
        <span class="hljs-built_in">console</span>.log(ageInput.current.value);
        <span class="hljs-built_in">console</span>.log(hairColorInput.current.value);
    };
    <span class="hljs-keyword">return</span> (
        &lt;div&gt;
            &lt;form onSubmit={handleSubmit}&gt;
                &lt;label htmlFor=<span class="hljs-string">"name"</span>&gt;
                    Name
                    &lt;input name=<span class="hljs-string">"name"</span> <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> placeholder=<span class="hljs-string">"Name"</span> ref={nameInput} /&gt;
                &lt;/label&gt;
                &lt;label htmlFor=<span class="hljs-string">"age"</span>&gt;
                    Age
                    &lt;input name=<span class="hljs-string">"age"</span> <span class="hljs-keyword">type</span>=<span class="hljs-string">"number"</span> placeholder=<span class="hljs-string">"Age"</span> ref={ageInput} /&gt;
                &lt;/label&gt;
                &lt;label htmlFor=<span class="hljs-string">"haircolor"</span>&gt;
                    Hair Color
                    &lt;input name=<span class="hljs-string">"haircolor"</span> <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span> placeholder=<span class="hljs-string">"Hair Color"</span> ref={hairColorInput} /&gt;
                &lt;/label&gt;
                &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;Submit&lt;/button&gt;
            &lt;/form&gt;
        &lt;/div&gt;
    );
}
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Both the controlled and uncontrolled form fields have their merit. Evaluate your specific situation and pick the approach — what works for you is good enough.</p>
<p>As always, thanks for reading!</p>
]]></content:encoded></item><item><title><![CDATA[Demystifying the Confusion Matrix]]></title><description><![CDATA[Understand the significance of a confusion matrix and its role in assessing classification model performance]]></description><link>https://boula.hashnode.dev/demystifying-the-confusion-matrix</link><guid isPermaLink="true">https://boula.hashnode.dev/demystifying-the-confusion-matrix</guid><category><![CDATA[Machine Learning Classificasion]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Sun, 13 Jun 2021 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743589830/878a468c-01f6-445a-8c54-62acc2f8b760.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>What is Confusion Matrix</strong></p>
<p>A confusion matrix is a table that is often used to describe the performance of a classification model, the result obtained from the confusion matrix is obtained by comparing the result of the test dataset for which the true values known. depending on the type of classification model the number of classes may vary but the concept is very simple even the correlated terminology can create confusion.</p>
<p>A confusion matrix is useful in the supervised learning category of machine learning using a labelled data set. As shown below, it is represented by a table. This is a sample confusion matrix for a binary classifier (i.e. 0-Negative or 1-Positive)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743583282/bb0c9bf8-1893-4d06-8f19-9a9c590ea872.png" alt /></p>
<h3 id="heading-understanding-the-confusion-matrix">Understanding the Confusion Matrix</h3>
<h4 id="heading-true-positive-tp">True Positive (TP)</h4>
<p>The predicted value matches the actual value<br />The actual value was positive and the model predicted a positive value</p>
<h4 id="heading-true-negative-tn">True Negative (TN)</h4>
<p>The predicted value matches the actual value<br />The actual value was negative and the model predicted a negative value</p>
<h4 id="heading-false-positive-fp-type-1-error">False Positive (FP) — Type 1 error</h4>
<p>The predicted value was falsely predicted<br />The actual value was negative but the model predicted a positive value<br />Also known as the Type 1 error</p>
<h4 id="heading-false-negative-fn-type-2-error">False Negative (FN) — Type 2 error</h4>
<p>The predicted value was falsely predicted<br />The actual value was positive but the model predicted a negative value<br />Also known as the Type 2 error</p>
<h4 id="heading-classification-metrics">Classification Metrics</h4>
<p>There are multiple accuracy metrics that can be generated from the confusion matrix.</p>
<h4 id="heading-accuracy">Accuracy</h4>
<p>Accuracy (ACC) is calculated as the number of all correct predictions divided by the total number of the dataset. The best accuracy is 1.0, whereas the worst is 0.0. It can also be calculated by 1 — ERR.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743584373/71707c52-c095-4a54-a072-fd261b8a721f.gif" alt /></p>
<h4 id="heading-precision">Precision</h4>
<p>Precision is the number of True Positives divided by the number of True Positives and False Positives. Put another way, it is the number of positive predictions divided by the total number of positive class values predicted. It is also called the Positive Predictive Value (PPV)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743585747/bb71e4ea-1e7b-4399-8a78-e2062662c0a1.gif" alt /></p>
<h4 id="heading-recall">Recall</h4>
<p>Precision is the ratio of true positives to the total of the true positives and false positives. Precision looks to see how much junk positives got thrown in the mix. If there are no bad positives (those FPs), then the model had 100% precision. The more FPs that get into the mix, the uglier that precision is going to look.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743587162/9ba4b291-c197-45a4-8ad6-4e1ec3f2896d.gif" alt /></p>
<h4 id="heading-f1-score">F1 Score</h4>
<p>F1 Score is the weighted average of Precision and Recall. Therefore, this score takes both false positives and false negatives into account. Intuitively it is not as easy to understand as accuracy, but F1 is usually more useful than accuracy, especially if you have an uneven class distribution. Accuracy works best if false positives and false negatives have similar cost. If the cost of false positives and false negatives are very different, it’s better to look at both Precision and Recall. In our case, F1 score is 0.701</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743588546/05eade5f-5d24-40b9-9bd5-5b3b9ca74c09.gif" alt /></p>
<p>Thanks for reading!</p>
]]></content:encoded></item><item><title><![CDATA[Sentiment Analysis using VADER]]></title><description><![CDATA[Understanding Sentiment Analysis in Natural Language Processing]]></description><link>https://boula.hashnode.dev/sentiment-analysis-using-vader</link><guid isPermaLink="true">https://boula.hashnode.dev/sentiment-analysis-using-vader</guid><category><![CDATA[natural language processing]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Sat, 12 Jun 2021 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728757511129/abcbf615-bf56-4888-9671-78531b2dceed.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sentiment Analysis is a supervised Machine Learning technique used to determine if a chunk of text is positive, negative or neutral. In text analytics, natural language processing (NLP) and machine learning (ML) techniques are combined to assign sentiment scores to topics, categories or entities within a phrase.</p>
<p>Sentiment analysis is a powerful tool that businesses can leverage to better understand the overall opinions of their customer, gain insights and make data-driven decisions.</p>
<p>In this tutorial we will classify text articles using VADER on a dataset from CrowdFlower.</p>
<h4 id="heading-import-libraries">Import Libraries</h4>
<p>import pandas as pd<br />import nltk<br />from nltk.corpus import stopwords<br />from nltk.probability import FreqDist<br />from nltk.tokenize import sent_tokenize, RegexpTokenizer<br />from nltk.sentiment.vader import SentimentIntensityAnalyzer<br />nltk.download('stopwords')<br />nltk.download('vader_lexicon')<br />nltk.download('punkt')</p>
<h4 id="heading-data-collection">Data Collection</h4>
<p>For the sake of this tutorial we’re going to use a simple dataset from CrowdFlower via data.world (IMDB Sentiment Sampled). For more info visit the link:</p>
<blockquote>
<p><a target="_blank" href="https://data.world/robbertb/imdb-sentiment-sampled">https://data.world/robbertb/imdb-sentiment-sampled</a></p>
</blockquote>
<p>df = pd.read_csv('imdb_sentiment.csv')<br />df.head()</p>
<p>review<br />0Protocol is an implausible movie whose only sa...<br />1I just watched The Dresser this evening, havin...<br />2Besides being boring, the scenes were oppressi...<br />3I'm not sure why the producers needed to trade...<br />4Honestly - this short film sucks. the dummy us...</p>
<h4 id="heading-preprocessing">Preprocessing</h4>
<p>The NLTK module is a massive tool kit, aimed to help you with the entire Natural Language Processing (NLP) methodology. NLTK will aid you with everything from splitting sentences from paragraphs, splitting up words, recognizing the part of speech of those words.</p>
<p>In order to apply polarity score we need to prepare your data, we start by the converting our data to lowercase using the built-in function “lower”.</p>
<p>df['review'] = df['review'].apply(lambda txt: txt.lower())</p>
<p>Removing stop word using NLTK by downloading the english stopwords.</p>
<p>stop_words=stopwords.words('english')<br />df['review'] = df['review'].apply(lambda txt: ' '.join([word for word in txt.split() if word not in stop_words]))</p>
<p>Sentences Tokenization</p>
<p>df['review'] = df['review'].apply(lambda txt: sent_tokenize(txt))</p>
<p>Join the tokenized data into text.</p>
<p>df['review'] = df['review'].apply(lambda txt: ' '.join(txt))</p>
<h4 id="heading-vader">VADER</h4>
<p>VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media.</p>
<p>It is used for sentiment analysis of text which has both the polarities i.e. positive/negative. VADER is also used to quantify how much positive or negative emotion the text has and also the intensity of emotion.</p>
<h4 id="heading-polarity-classification">Polarity classification</h4>
<p>The VADER library returns 4 values such as:</p>
<ul>
<li><p><strong>pos</strong>: The probability of the sentiment to be <strong>positive</strong></p>
</li>
<li><p><strong>neu</strong>: The probability of the sentiment to be <strong>neutral</strong></p>
</li>
<li><p><strong>neg</strong>: The probability of the sentiment to be <strong>negative</strong></p>
</li>
<li><p><strong>compound</strong>: The normalized compound score which calculates the sum of all lexicon ratings and takes values from -1 to 1</p>
</li>
</ul>
<p>Notice that the <code>pos</code>, <code>neu</code> and <code>neg</code> probabilities add up to <strong>1</strong>. Also, the <code>compound</code> score is a very useful metric in case we want a single measure of sentiment. Typical threshold values are the following:</p>
<ul>
<li><p><strong>positive</strong>: compound <strong>score&gt;=0.05</strong></p>
</li>
<li><p><strong>neutral</strong>: compound score between <strong>-0.05 and 0.05</strong></p>
</li>
<li><p><strong>negative</strong>: compound <strong>score&lt;=-0.05</strong></p>
</li>
</ul>
<p>Instantiate a new object with NLTK SentimentIntensityAnalyzer</p>
<p>sid = SentimentIntensityAnalyzer()</p>
<p>Now we can create a new column to the original DataFrame to store the polarity_scores dictionary, the scores extracted will have the keys “neg”, “neu”, “pos”, “compound” derived from the composite score.</p>
<p>df['score'] = df['review'].apply(lambda txt: sid.polarity_scores(txt))</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743600452/41b3be20-08a6-4662-9ae6-2a30b0ee6183.png" alt /></p>
<p>df['negative'] = df['score'].apply(lambda txt: txt['neg'])</p>
<p>df['neutral'] = df['score'].apply(lambda txt: txt['neu'])</p>
<p>df['positive'] = df['score'].apply(lambda txt: txt['pos'])</p>
<p>df['compound'] = df['score'].apply(lambda txt: txt['compound'])</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743601863/d27a80f4-91b9-42ee-81c8-7e2fddfbdfae.png" alt /></p>
<p>We will follow by creating a function called “polarity_score” to calculate the accuracy test for each review in our dataframe. We can finally apply the function by creating a new column called “sentiment”.</p>
<p>The reviews in this column will be classified into positive, negative and neutral.</p>
<p>def polarity_score(compound):<br />if compound &gt; 0.05:<br />return "positive"<br />elif compound &lt; -0.5:<br />return "negative"<br />elif compound &gt;= -0.05 and compound &lt; 0.05:<br />return "neutral"</p>
<p>df['sentiment'] = df['compound'].apply(lambda val: polarity_score(val))<br />df.head()</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743603702/8ce69c66-e51a-4171-905c-f4914044ecf9.png" alt /></p>
<p>df['sentiment'].value_counts()</p>
<h4 id="heading-conclusion">Conclusion</h4>
<p>VADER classifies the sentiments very well. It is easy to use, the ready-made model which can be used across multiple domains, social-media texts.</p>
<p>Thanks for reading and happy web scraping everyone!</p>
<p>You can find my Jupyter Notebook for this on my <a target="_blank" href="https://github.com/akladyous/sentiment-analysis-using-vader">Github</a>.</p>
]]></content:encoded></item><item><title><![CDATA[exploring logistic regression for classification]]></title><description><![CDATA[Understand the fundamentals of logistic regression and its applications in classification problems]]></description><link>https://boula.hashnode.dev/exploring-logistic-regression-for-classification</link><guid isPermaLink="true">https://boula.hashnode.dev/exploring-logistic-regression-for-classification</guid><category><![CDATA[classifications]]></category><category><![CDATA[Machine Learning]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Sat, 12 Jun 2021 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1766354945150/c891e771-d3ca-4dfa-8f46-fdba3b326c86.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-exploring-logistic-regression-for-classification">Exploring Logistic Regression for Classification</h3>
<h2 id="heading-introduction">Introduction</h2>
<p>Logistic regression is a classification algorithm used to assign observations to a discrete set of classes. Unlike linear regression which outputs continuous number values, logistic regression transforms its output using the logistic sigmoid function to return a probability value which can then be mapped to two or more discrete classes.</p>
<p>Logistic regression is used to calculate the probability of a binary event occurring and to deal with issues of classification. For example, predicting if an incoming email is spam or not spam, or predicting if a credit card transaction is fraudulent or not fraudulent. In a medical context, logistic regression may be used to predict whether a tumor is benign or malignant. In marketing, it may be used to predict if a given user (or group of users) will buy a certain product or not. An online education company might use logistic regression to predict whether a student will complete their course on time or not.</p>
<h2 id="heading-what-are-the-different-types-of-logistic-regression">What are the different types of logistic regression?</h2>
<p>The three types of logistic regression are:</p>
<p>-- Binary logistic regression is the statistical technique used to predict the relationship between the dependent variable (Y) and the independent variable (X), where the dependent variable is binary in nature. For example, the output can be Success/Failure, 0/1 , True/False, or Yes/No. This is the type of logistic regression that we’ve been focusing on in this post.</p>
<p>-- Multinomial logistic regression is used when you have one categorical dependent variable with two or more unordered levels (i.e two or more discrete outcomes). It is very similar to logistic regression except that here you can have more than two possible outcomes. For example, let’s imagine that you want to predict what will be the most-used transportation type in the year 2030. The transport type will be the dependent variable, with possible</p>
<p>-- outputs of train, bus, tram, and bike (for example). Ordinal logistic regression is used when the dependent variable (Y) is ordered (i.e., ordinal). The dependent variable has a meaningful order and more than two categories or levels. Examples of such variables might be t-shirt size (XS/S/M/L/XL), answers on an opinion poll (Agree/Disagree/Neutral), or scores on a test (Poor/Average/Good).</p>
<h2 id="heading-advantages-of-logistic-regression">Advantages of logistic regression</h2>
<h2 id="heading-advantages">Advantages</h2>
<ul>
<li><p>Logistic regression is easier to implement, interpret, and very efficient to train.</p>
</li>
<li><p>It makes no assumptions about distributions of classes in feature space.</p>
</li>
<li><p>It can easily extend to multiple classes(multinomial regression) and a natural probabilistic view of class predictions.</p>
</li>
<li><p>Logistic regression works well for cases where the dataset is linearly separable.</p>
</li>
</ul>
<h2 id="heading-disadvantages">Disadvantages</h2>
<ul>
<li><p>Logistic regression fails to predict a continuous outcome.</p>
</li>
<li><p>If the number of observations is lesser than the number of features, Logistic Regression should not be used, otherwise it may lead to overfitting.</p>
</li>
<li><p>Logistic Regression requires average or no multicollinearity between independent variables.</p>
</li>
<li><p>Logistic regression may not be accurate if the sample size is too small.</p>
</li>
</ul>
<h2 id="heading-what-is-sigmoid-function">What is Sigmoid Function</h2>
<p>In order to map predicted values to probabilities, we use the sigmoid function. The function map any real input <strong><em>t</em></strong> and outputs a value between <strong><em>zero</em></strong> and <strong><em>one</em></strong>. For the logit, this is interpreted as taking input log-odds and having output probability. the logistic “sigmoid” function is defined as follow:</p>
<p>To understand how sigmoid function squashes the values within the range, let’s visualize the graph of the sigmoid function.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1766351135583/4b33f912-8cc9-40a1-bf4d-9e97641d0f68.png" alt class="image--center mx-auto" /></p>
<p>As you can see from the graph, the sigmoid function becomes asymptote to y=1 for positive values of x and becomes asymptote to y=0 for negative values of x.</p>
<h2 id="heading-regularization-in-logistic-regression">Regularization in Logistic Regression</h2>
<p>Regularization is extremely important in logistic regression modeling. Without regularization, the asymptotic nature of logistic regression would keep driving loss towards 0 in high dimensions.</p>
<p>Regularization is the most used technique to penalize complex models in machine learning, it is deployed for reducing overfitting (or, contracting generalization errors) by putting network weights small. It also enhances the performance of models for new inputs.</p>
<h2 id="heading-penalty-term">Penalty Term</h2>
<p>Through biasing data points towards specific values such as very small values to zero, regularization achieves this biasing by adding a tuning parameter to strengthen those data points:</p>
<ol>
<li><p>L1 regularization: It adds an L1 penalty that is equal to the absolute value of the magnitude of coefficient, or simply restricting the size of coefficients. For example, Lasso regression implements this method.</p>
</li>
<li><p>L2 Regularization: It adds an L2 penalty which is equal to the square of the magnitude of coefficients. For example, Ridge regression and SVM implement this method.</p>
</li>
<li><p>Elastic Net: When L1 and L2 regularization combine together, it becomes the elastic net method, it adds a hyperparameter.</p>
</li>
</ol>
<p>If both L1 and L2 regularization work well, you might be wondering why we need both. It turns out they have different but equally useful properties, from a practical standpoint, L1 tends to shrink coefficients to zero whereas L2 tends to shrink coefficients evenly.</p>
<p>L1 is therefore useful for feature selection, as we can drop any variables associated with coefficients that go to zero.</p>
<p>L2 on the other hand, is useful when you have collinear/codependent features.</p>
<p>(An example pair of codependent features is gender and ispregnant since, at the current level of medical technology, only females can be ispregnant.) Codependence tends to increase coefficient variance, making coefficients unreliable/unstable, which hurts model generality. L2 reduces the variance of these estimates, which counteracts the effect of codependencies.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this blog I presented the basic concept of logistic regression. I hope this blog was helpful and motivated you enough to get interested in the topic.</p>
<p><a target="_blank" href="https://akladyous.medium.com/logistic-regression-7885cebd3699">For a Deeper Dive, Check the Original Post 🔗</a></p>
<p>Thank you for reading! ❤️</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Scopes in Rails]]></title><description><![CDATA[software-engineering]]></description><link>https://boula.hashnode.dev/understanding-scopes-in-rails</link><guid isPermaLink="true">https://boula.hashnode.dev/understanding-scopes-in-rails</guid><category><![CDATA[Active Model]]></category><category><![CDATA[Ruby on Rails]]></category><category><![CDATA[Rails]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Wed, 09 Jun 2021 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728743597808/c6f72d8f-d049-4b92-b26e-4dd8159af957.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Understanding Rails Scopes and Class Methods for Efficient Database Queries<em>?</em></p>
<p><em>ope in Rails?</em></p>
<p>Scopes in Rails are special methods to run SQL queries that you can build in any rails model. A scope will always return an ActiveRecord::Relation object, even if the conditional evaluates to <code>false</code> , whereas a class method, will return <code>nil</code>. we frequently run similar queries in our rails console to query our database and also understand the structure of the result we are receiving before going further with the development of our applications.</p>
<p><em>Why use Scopes? &amp; why is it useful</em></p>
<p>A use case for scopes is often for filtering by status, date, date ranges, ordering, groupings, and more. Compared to class methods, scope methods are incredibly fast and quite easy to return the desired result in fraction of time.</p>
<p>Scopes help you D.R.Y out your active record calls and also keep your codes organized. Scopes make it easy to find the records you need at a particular time.</p>
<p><em>Lets start with the basic, We’ll use a sample model named Book to illustrate what scopes allow you to do.</em></p>
<p>On your homepage, you only want to show published books of course. So in your action, you would use the following code to ensure that.</p>
<p>Class Book &lt; ActiveRecord::Base<br />scope :published, -&gt; { where(:published =&gt; true) }<br />end<br /># This retuns ActiveRecord::Relation object</p>
<p>Then in our controller or views, we can return the newly scoped objects.</p>
<p>class BooksController &lt; ApplicationContrpller<br /> def index<br />   @books = Book.published<br /> end<br />end</p>
<p><em>Taking arguments.</em></p>
<p>scopes can also receive parameters, let’s see how we can create a scope to get all books written by a specific author.</p>
<p>class Book &lt; ActiveRecord::Base<br /> scope :author_name, -&gt; (name) { where(:authorName =&gt; name) }<br />end</p>
<p><em>Using conditional with scopes.</em></p>
<p>The scope named available, in the code block is a typical example of how to use conditional with scopes.</p>
<p>class Book &lt; ActiveRecord::Base<br /> scope :available, -&gt; (bool) { where("available = ?", bool) if bool.present? }<br />end</p>
<p><em>Chaining</em></p>
<p>Scopes are extremely powerful due to their ability to be chained together. Think of them as a chain links</p>
<p>class BooksController &lt; ApplicationContrpller<br /> def index  </p>
<h1 id="heading-return-all-available-amp-published-books">return all available &amp; published books.</h1>
<p>   @books = Book.published.available<br /> end<br />end</p>
<p><strong>Summary</strong></p>
<p>It’s always a good idea to use scopes for selecting, sorting, joining or filtering data through your database, and then you can use class methods to chain those scopes, or even write more complex logic.</p>
<p>This is very important to note that the scope is intended to return an <a target="_blank" href="https://api.rubyonrails.org/classes/ActiveRecord/Relation.html">ActiveRecord::Relation</a> object which is composable with other scopes. In short scopes should be chainable.</p>
<p>Hope this article helped you understand the ActiveRecord <code>Scoping</code> method and its uses.</p>
<p>Thank you for reading! ❤️</p>
]]></content:encoded></item><item><title><![CDATA[Single Page Application (SPA) WorkFlow]]></title><description><![CDATA[software-engineering]]></description><link>https://boula.hashnode.dev/single-page-application-spa-workflow</link><guid isPermaLink="true">https://boula.hashnode.dev/single-page-application-spa-workflow</guid><category><![CDATA[Frontend Development]]></category><category><![CDATA[Single Page Application]]></category><category><![CDATA[Single Page Application (SPA)]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Sun, 21 Mar 2021 16:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1766355009176/73eb6431-d17d-4cfd-b310-5813dfbcc2ea.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let’s explain how we'd build the same todo application as a Single Page Application (SPA) using React.js, focusing on data and state management. Let's start with a high-level overview and then dive into the details.</p>
<p>First, let's visualize the structure of our React SPA todo app:</p>
<pre><code class="lang-mermaid">graph TD
    A[App Component] --&gt; B[TodoList Component]
    A --&gt; C[AddTodo Component]
    B --&gt; D[TodoItem Component]
    D --&gt; E[Edit Todo]
    D --&gt; F[Delete Todo]
    D --&gt; G[Toggle Complete]

    H[State Management] --&gt; A
    H --&gt; B
    H --&gt; C
    H --&gt; D
</code></pre>
<p>In this React SPA structure, we have a main App component that contains child components for different parts of our application. The key difference from the MPA version is that all of these components exist within a single page, and React manages the rendering and updating of these components based on user interactions and state changes.</p>
<p>Now, let's talk about data flow and state management in this React SPA:</p>
<ol>
<li><p><strong>State Management</strong>: In React, we typically keep the state at the highest necessary level and pass it down to child components as props. For a simple app, we might keep all state in the App component. For more complex apps, we might use a state management library like Redux or Recoil.</p>
</li>
<li><p><strong>Data Storage</strong>: Unlike the MPA where data was primarily stored on the server, in an SPA we keep a copy of the data in the client-side state. We still persist data to a server via API calls, but the immediate source of truth for the UI is the client-side state.</p>
</li>
<li><p><strong>CRUD Operations</strong>: These are typically handled by updating the client-side state and making asynchronous API calls to sync with the server.</p>
</li>
</ol>
<p>Let's walk through a typical workflow:</p>
<ol>
<li><p>Initial Load:</p>
<ul>
<li><p>React app loads and mounts the App component</p>
</li>
<li><p>App component fetches todos from the server (e.g., via a REST API)</p>
</li>
<li><p>State is updated with the fetched todos, causing a re-render</p>
</li>
</ul>
</li>
<li><p>Add Todo:</p>
<ul>
<li><p>User inputs new todo in AddTodo component</p>
</li>
<li><p>On submit, state is updated with new todo</p>
</li>
<li><p>An API call is made to add the todo on the server</p>
</li>
</ul>
</li>
<li><p>Edit Todo:</p>
<ul>
<li><p>User clicks edit on a TodoItem</p>
</li>
<li><p>TodoItem switches to edit mode (managed by local state)</p>
</li>
<li><p>On save, parent state is updated and an API call is made</p>
</li>
</ul>
</li>
<li><p>Delete Todo:</p>
<ul>
<li><p>User clicks delete on a TodoItem</p>
</li>
<li><p>Todo is removed from state, causing an immediate UI update</p>
</li>
<li><p>An API call is made to delete the todo on the server</p>
</li>
</ul>
</li>
<li><p>Toggle Complete:</p>
<ul>
<li><p>User clicks to toggle todo status</p>
</li>
<li><p>State is immediately updated, reflecting the change in the UI</p>
</li>
<li><p>An API call is made to update the status on the server</p>
</li>
</ul>
</li>
</ol>
<p>Now, let's look at a simplified code example for our main App component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> TodoList <span class="hljs-keyword">from</span> <span class="hljs-string">"./TodoList"</span>;
<span class="hljs-keyword">import</span> AddTodo <span class="hljs-keyword">from</span> <span class="hljs-string">"./AddTodo"</span>;
<span class="hljs-keyword">import</span> { fetchTodos, addTodo, updateTodo, deleteTodo } <span class="hljs-keyword">from</span> <span class="hljs-string">"./api"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> [todos, setTodos] = useState([]);

    useEffect(<span class="hljs-function">() =&gt;</span> {
        fetchTodos().then(setTodos);
    }, []);

    <span class="hljs-keyword">const</span> handleAddTodo = <span class="hljs-function">(<span class="hljs-params">title</span>) =&gt;</span> {
        <span class="hljs-keyword">const</span> newTodo = { <span class="hljs-attr">id</span>: <span class="hljs-built_in">Date</span>.now(), title, <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span> };
        setTodos([...todos, newTodo]);
        addTodo(newTodo);
    };

    <span class="hljs-keyword">const</span> handleToggle = <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
        setTodos(todos.map(<span class="hljs-function">(<span class="hljs-params">todo</span>) =&gt;</span> (todo.id === id ? { ...todo, <span class="hljs-attr">completed</span>: !todo.completed } : todo)));
        <span class="hljs-keyword">const</span> todoToUpdate = todos.find(<span class="hljs-function">(<span class="hljs-params">todo</span>) =&gt;</span> todo.id === id);
        updateTodo({ ...todoToUpdate, <span class="hljs-attr">completed</span>: !todoToUpdate.completed });
    };

    <span class="hljs-keyword">const</span> handleDelete = <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
        setTodos(todos.filter(<span class="hljs-function">(<span class="hljs-params">todo</span>) =&gt;</span> todo.id !== id));
        deleteTodo(id);
    };

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My Todos<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">AddTodo</span> <span class="hljs-attr">onAdd</span>=<span class="hljs-string">{handleAddTodo}</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">TodoList</span> <span class="hljs-attr">todos</span>=<span class="hljs-string">{todos}</span> <span class="hljs-attr">onToggle</span>=<span class="hljs-string">{handleToggle}</span> <span class="hljs-attr">onDelete</span>=<span class="hljs-string">{handleDelete}</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In this React example:</p>
<ol>
<li><p>We use the <code>useState</code> hook to manage our todos state.</p>
</li>
<li><p><code>useEffect</code> is used to fetch todos when the component mounts.</p>
</li>
<li><p>CRUD operations are handled by functions that update the state and make API calls.</p>
</li>
<li><p>The UI automatically updates when the state changes, thanks to React's reactivity.</p>
</li>
</ol>
<p>The key differences from the MPA approach are:</p>
<ol>
<li><p><strong>Single Page</strong>: Everything happens within a single page load. React handles updating the UI.</p>
</li>
<li><p><strong>Client-Side State</strong>: The immediate source of truth is the client-side state, not the server.</p>
</li>
<li><p><strong>Asynchronous Updates</strong>: API calls happen asynchronously, allowing for immediate UI updates.</p>
</li>
<li><p><strong>Component Structure</strong>: The UI is broken down into reusable components.</p>
</li>
</ol>
<p>This approach provides a more fluid user experience, as most interactions don't require a full page reload. However, it also means we need to carefully manage state and keep it in sync with the server.</p>
<p>Is this helpful in understanding the SPA approach? Would you like me to elaborate on any specific part of this workflow or dive deeper into how React manages updates?</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Coefficient of Variation]]></title><description><![CDATA[data-science]]></description><link>https://boula.hashnode.dev/understanding-coefficient-of-variation</link><guid isPermaLink="true">https://boula.hashnode.dev/understanding-coefficient-of-variation</guid><category><![CDATA[Statistical Analysis]]></category><category><![CDATA[statistical inference]]></category><category><![CDATA[Data Science]]></category><dc:creator><![CDATA[Boula Akladyous]]></dc:creator><pubDate>Thu, 28 Jan 2021 17:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1766355037905/f3dc02ed-387a-403f-9a70-5674705756bb.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the realm of data analysis, various statistical measures assist in unraveling the nature of datasets. Variability, denoting the extent to which data points in a dataset differ, holds a paramount role in data analysis. Measuring variability aids in comprehending the dispersion or clustering of data, facilitating informed decision-making, prediction, and pattern identification.</p>
<p>Several measures of variability exist, each with distinct strengths and weaknesses. Commonly used ones include:</p>
<ol>
<li><p><strong>Range:</strong> The simplest measure, calculated by subtracting the smallest from the largest value in the dataset.</p>
</li>
<li><p><strong>Interquartile Range (IQR):</strong> A more robust measure less sensitive to outliers, obtained by subtracting the first quartile from the third quartile.</p>
</li>
<li><p><strong>Variance:</strong> Indicates how much data deviates from the mean, calculated by summing squared differences between each data point and the mean.</p>
</li>
<li><p><strong>Standard Deviation:</strong> The square root of variance, a widely used measure conveying average deviation from the mean.</p>
</li>
</ol>
<p>Understanding variability is pivotal for making sense of data, enabling insights into dataset characteristics for more informed decision-making.</p>
<h2 id="heading-what-is-coefficient-of-variation-cv">What is Coefficient of Variation (CV)?</h2>
<p>Variability assessment is crucial in statistics, referring to the degree of dispersion or spread in a dataset. The Coefficient of Variation (CV) emerges as one such measure, representing the ratio of standard deviation to the mean. Often expressed as a percentage, CV facilitates comparing variation between different datasets. Widely applied in finance, biology, and engineering, CV aids in gauging risk or uncertainty within datasets.</p>
<p><strong>Key Points about Coefficient of Variation:</strong></p>
<ol>
<li><p><strong>Formula:</strong> CV = (Standard Deviation / Mean) x 100%. It gauges the relative variability of a dataset, expressed as a percentage.</p>
</li>
<li><p><strong>Comparative Analysis:</strong> Used to compare variability across datasets with different units, aiding decisions in various fields.</p>
</li>
<li><p><strong>Risk Assessment:</strong> Valuable in finance for evaluating investment risk. Higher CV suggests higher risk and volatility.</p>
</li>
<li><p><strong>Reliability Assessment:</strong> Applied to assess the reliability of measurement tools, such as blood glucose monitors.</p>
</li>
<li><p><strong>Interpretation:</strong> A lower CV signifies a more consistent dataset, while a higher CV implies greater variability. Interpretation context varies with the dataset and field of study.</p>
</li>
</ol>
<h2 id="heading-calculating-coefficient-of-variation">Calculating Coefficient of Variation</h2>
<p>In measuring variability, the Coefficient of Variation (CV) stands out as a versatile statistical tool widely employed in finance, biology, and engineering. As a relative measure, CV represents standard deviation as a percentage of the mean, offering a robust means to compare datasets with different units or means. Let's delve into how to calculate CV, providing insights into its interpretation and application.</p>
<ol>
<li><p><strong>Formula for Calculating CV:</strong></p>
<ul>
<li>CV = (Standard Deviation / Mean) x 100%</li>
</ul>
</li>
</ol>
<p>    <strong>Example:</strong> Consider daily stock returns over ten days: 1.2%, -0.5%, 0.8%, -1.1%, 2.3%, 0.9%, -2.0%, -0.7%, 1.5%, 0.3%. Mean return = 0.34%, Standard Deviation = 1.48%, CV = (1.48 / 0.34) x 100% = 435.29%.</p>
<ol start="2">
<li><p><strong>Interpretation of CV:</strong></p>
<ul>
<li><p>Low CV (&lt; 15%): Low variability.</p>
</li>
<li><p>Moderate CV (15% - 30%): Moderate variability.</p>
</li>
<li><p>High CV (&gt; 30%): High variability.</p>
</li>
</ul>
</li>
</ol>
<p>    Interpretation varies by field; e.g., in finance, CV &lt; 30% may be considered low.</p>
<ol start="3">
<li><p><strong>Application of CV:</strong></p>
<ul>
<li><p>Finance: Measures risk and volatility.</p>
</li>
<li><p>Biology: Gauges variability in biological traits.</p>
</li>
<li><p>Engineering: Assesses manufacturing process variability.</p>
</li>
<li><p>Medicine: Evaluates variability in medical test results.</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-4-interpreting-coefficient-of-variation">4. Interpreting Coefficient of Variation</h2>
<h3 id="heading-coefficient-of-variation">Coefficient of Variation</h3>
<p>The Coefficient of Variation (CV) serves as a dimensionless metric to measure the relative variability of data. Its interpretation is pivotal, offering insights into data consistency and reliability. Widely used in finance, engineering, and biology, understanding how to interpret CV is crucial for informed decision-making.</p>
<p><strong>Ways to Interpret CV:</strong></p>
<ol>
<li><p><strong>Low CV:</strong> Indicates tightly clustered data points around the mean, suggesting consistency and reliability. Useful in contexts like test score reliability.</p>
</li>
<li><p><strong>High CV:</strong> Signifies widely dispersed data points, indicating lower consistency and reliability. Relevant in scenarios such as salary distribution analysis.</p>
</li>
<li><p><strong>Comparing CVs:</strong> Facilitates insights into relative variability between datasets. Useful in identifying higher variability in one group over another.</p>
</li>
</ol>
<p>Interpreting CV is essential for understanding</p>
<p>Thank you for reading! ❤️</p>
]]></content:encoded></item></channel></rss>