<?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 Rishabh IO on Medium]]></title>
        <description><![CDATA[Stories by Rishabh IO on Medium]]></description>
        <link>https://medium.com/@rishabh.io?source=rss-97388397e268------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-dJmKiAxp0T8Otw8srpx1A.jpeg</url>
            <title>Stories by Rishabh IO on Medium</title>
            <link>https://medium.com/@rishabh.io?source=rss-97388397e268------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:34:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishabh.io/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[Using Alembic for Postgres DB Migrations]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@rishabh.io/using-alembic-for-postgres-db-migrations-e5377cbb8c88?source=rss-97388397e268------2"><img src="https://cdn-images-1.medium.com/max/1024/1*PcQVX_PjVI5QGfqV-k2O-g.png" width="1024"></a></p><p class="medium-feed-snippet">My stories are also available for free using the friend link</p><p class="medium-feed-link"><a href="https://medium.com/@rishabh.io/using-alembic-for-postgres-db-migrations-e5377cbb8c88?source=rss-97388397e268------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@rishabh.io/using-alembic-for-postgres-db-migrations-e5377cbb8c88?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5377cbb8c88</guid>
            <category><![CDATA[alembic]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[rdbms]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 11:16:13 GMT</pubDate>
            <atom:updated>2024-12-06T11:18:31.192Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to Nail Senior Python Engineer Interviews]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@rishabh.io/how-to-fail-senior-python-engineer-interviews-db1accc4cf54?source=rss-97388397e268------2"><img src="https://cdn-images-1.medium.com/max/1900/1*Zhh8mRuN0YQpB4czTYyPeQ.png" width="1900"></a></p><p class="medium-feed-snippet">So you&#x2019;ve been doing Python for a few years and now you&#x2019;re ready to go on your next adventure and the only thing standing between you and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@rishabh.io/how-to-fail-senior-python-engineer-interviews-db1accc4cf54?source=rss-97388397e268------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@rishabh.io/how-to-fail-senior-python-engineer-interviews-db1accc4cf54?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/db1accc4cf54</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 15:21:59 GMT</pubDate>
            <atom:updated>2024-12-02T06:12:49.450Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Erlang: A Great Choice for Building Distributed Systems]]></title>
            <link>https://medium.com/@rishabh.io/erlang-a-great-choice-for-building-distributed-systems-86dd11f16ed4?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/86dd11f16ed4</guid>
            <category><![CDATA[memory-efficiency]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[erlang]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Fri, 20 Sep 2024 12:11:40 GMT</pubDate>
            <atom:updated>2024-09-20T12:11:40.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_1zZ1wVQE-v2yiKBPbImQ.png" /></figure><p>Erlang, a <strong>concurrent</strong>, <strong>functional</strong> programming language originally developed by Ericsson, is known for its ability to handle <strong>large-scale</strong>, <strong>distributed</strong>, and <strong>fault-tolerant</strong> systems with ease. What sets Erlang apart is its lightweight process model, which makes it ideal for systems that require the handling of thousands or even millions of concurrent activities, like a chat application. In this article, let’s explore more about <strong>Erlang</strong> with reference to a chat application.</p><h4>Why Erlang for Distributed Systems?</h4><p>Erlang was designed from the ground up to build systems that need <strong>high availability</strong>, <strong>fault tolerance</strong>, and <strong>real-time</strong> performance. Here are the key reasons <strong>Erlang</strong> excels in distributed systems:</p><p>1. <strong>Lightweight Processes</strong>: Erlang’s concurrency model is based on extremely lightweight processes (much lighter than OS-level threads). This makes it possible to run millions of processes simultaneously, which is ideal for handling user connections in systems like chat applications.<br>2. <strong>Fault Tolerance</strong>: Erlang embraces failure with its “<em>let it crash</em>” philosophy. It provides built-in support for supervising and restarting processes when they fail.<br>3. <strong>Distributed by Design</strong>: Erlang has built-in primitives for distributed communication, allowing processes to communicate across different nodes in a distributed network as easily as if they were on the same machine.<br>4. <strong>Hot Code Upgrades</strong>: In production systems, downtime is costly. Erlang allows you to update running systems without stopping them, making it perfect for applications that need to be available 24/7.</p><h4>Erlang’s Lightweight Process Model: A Game Changer</h4><p>In a system like a chat application, each user typically <strong>gets their own process</strong>. If you were to build this in a language with heavyweight threads, memory overhead would quickly become prohibitive as the number of users grows. Erlang, however, can spawn hundreds of thousands (or even millions) of processes with minimal memory overhead.</p><p>Let’s look at an example of how Erlang handles processes efficiently.</p><h4>Example: A Chat System Using Erlang Processes</h4><p>Here, we’ll show how a simple chat system can be designed using lightweight Erlang processes.</p><h4>Step 1: Creating Processes for Each User</h4><p>In Erlang, every user can be represented by a separate process. Here’s a small snippet to demonstrate how lightweight processes are created:</p><blockquote>Note: Highlighting may be wrong as medium doesn’t support erlang</blockquote><pre><br>-module(chat).<br>-export([start/0, create_user/1, send_message/2]).<br><br>% Entry point to start the chat system<br>start() -&gt;<br>    io:format(&quot;Chat system started~n&quot;).<br><br>% Function to create a user process<br>create_user(UserName) -&gt;<br>    spawn(fun() -&gt; user_loop(UserName) end).<br><br>% Function to handle user actions in a loop<br>user_loop(UserName) -&gt;<br>    receive<br>        {send_message, Message} -&gt;<br>            io:format(&quot;~p received message: ~p~n&quot;, [UserName, Message]),<br>            user_loop(UserName);<br>        {quit} -&gt;<br>            io:format(&quot;User ~p quitting~n&quot;, [UserName])<br>    end.<br><br>% Function to send a message to a user<br>send_message(UserPid, Message) -&gt;<br>    UserPid ! {send_message, Message}.</pre><h4>Here’s what happens:</h4><p>- <strong>create_user/1</strong>: creates a new process for each user using <strong>spawn/1</strong>, which creates an extremely lightweight Erlang process. The memory overhead for each process is tiny compared to traditional OS-level threads.<br>- The process enters a loop (<strong>user_loop/1</strong>) where it waits for messages. This process could handle actions like sending messages or quitting.</p><h4>Step 2: Running the System</h4><p>You can start the chat system and simulate message passing between users like this:</p><pre>% Start the chat system<br>chat:start().<br>% Create two user processes<br>User1 = chat:create_user(&quot;Alice&quot;).<br>User2 = chat:create_user(&quot;Bob&quot;).<br>% Send a message from Alice to Bob<br>chat:send_message(User2, &quot;Hello Bob!&quot;).<br></pre><p>This would output:</p><pre>Alice received message: &quot;Hello Bob!&quot;</pre><h4>Step 3: Minimal Memory Usage</h4><p>Erlang’s processes are extremely efficient. On average, an Erlang process takes about <a href="https://www.erlang.org/doc/system/memory.html"><strong><em>300 bytes of memory</em></strong></a><strong><em>.</em></strong> Compare that with an OS-level thread that can consume megabytes of memory, and it becomes clear why Erlang is an excellent choice for high-concurrency applications. For a chat application with millions of users, this level of efficiency is crucial.</p><h4>Key Erlang Components for Building Distributed Systems</h4><p>Erlang provides several components and features that make it perfect for building scalable, distributed systems.</p><h4>1. <a href="https://www.erlang.org/doc/system/design_principles.html#supervision-trees">Supervision Trees</a></h4><p>Erlang uses a “<em>let it crash</em>” philosophy, where processes are expected to fail, but the system remains resilient. <a href="https://www.erlang.org/doc/system/design_principles.html#supervision-trees">Supervision trees</a> are a core concept where supervisors monitor worker processes and restart them if necessary.</p><p>Here’s an example of a simple supervisor:</p><pre>-module(chat_supervisor).<br>-behaviour(supervisor).<br>-export([start_link/0, init/1]).<br>start_link() -&gt;<br> supervisor:start_link({local, chat_supervisor}, chat_supervisor, []).<br>init([]) -&gt;<br> Children = [<br> {chat_worker, {chat, start_link, []}, permanent, 5000, worker, [chat]}<br> ],<br> {ok, {{one_for_one, 5, 10}, Children}}.</pre><p>In this example, the supervisor will monitor the chat worker, and if the worker crashes, it will be restarted automatically. This approach keeps the system running smoothly even in the face of failures.</p><h4>2.<a href="https://www.erlang.org/doc/system/readme.html"> OTP (Open Telecom Platform)</a></h4><p>Erlang’s <a href="https://www.erlang.org/doc/system/readme.html">OTP framework</a> provides libraries and design patterns for building robust systems. OTP includes everything from process supervision to messaging and distributed communication. OTP simplifies building large-scale systems, especially for fault tolerance and scalability.</p><h4>3. <a href="https://www.erlang.org/doc/system/conc_prog.html#distributed-programming">Distributed Erlang</a></h4><p>Erlang provides built-in support for <a href="https://www.erlang.org/doc/system/conc_prog.html#distributed-programming">distributed computing</a>. You can easily connect multiple nodes (machines) and communicate between them as if they were on the same machine:</p><pre>% Start a distributed node<br>net_adm:ping(&#39;node_name@host&#39;).</pre><p>With this, Erlang allows you to build distributed systems that can span across multiple physical machines, making it easier to handle load balancing and fault tolerance.</p><h4>4. Hot Code Swapping</h4><p>Erlang’s hot code swapping allows you to update running systems without downtime. This is especially useful for distributed systems that need to run continuously. You can load new code into a running system without restarting it:</p><pre>code:load_file(chat).</pre><h4>Conclusion</h4><p>Erlang’s lightweight processes, fault tolerance through supervision trees, distributed communication, and hot code swapping make it a powerful tool for building distributed systems. With its ability to spawn millions of processes with minimal memory overhead, Erlang is a fantastic choice for applications like chat systems, where scalability and resilience are paramount.</p><p>The lightweight process model, combined with features like built-in distribution and fault tolerance, enables developers to build systems that are both scalable and robust, making Erlang one of the best languages for large-scale, concurrent, and distributed applications.</p><p>Resources:</p><p>Erlang: <a href="https://www.erlang.org/">https://www.erlang.org/</a></p><p>OTP: <a href="https://www.erlang.org/doc/system/design_principles.html">https://www.erlang.org/doc/system/design_principles.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86dd11f16ed4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Rusty WebSocket Server]]></title>
            <link>https://medium.com/@rishabh.io/building-a-rusty-websocket-server-4f3ba4b6b19c?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f3ba4b6b19c</guid>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[sockets]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 19:28:49 GMT</pubDate>
            <atom:updated>2024-12-02T06:11:04.824Z</atom:updated>
            <content:encoded><![CDATA[<p>Using Rust to build a fast web socket server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stpFJ2sKte6iAxa9dofGzg.png" /><figcaption>Building web sockets in Rust</figcaption></figure><h3># Introduction</h3><p>In this article, we’ll learn how to build a web socket server in Rust. Rust has been around for while and is now getting acceptance across many popular organizations where speed and safety play a crucial role. Rust has been known for its performance and memory safety. Better known as a systems language, Rust is now paving its way to more diverse applications like Blockchains, WebApps, Games etc. So there’s never been a better time to get your hands rusty with Rust code. Let’s dive in.</p><h3># Create a new Rust Project</h3><p>We use cargo, viz Rust’s package manager to initialize a new project. You can execute the following command in your working directory.</p><pre>cargo new web-sockets </pre><blockquote>Note: If you’re only interested in the code, you can jump to the end of the article.</blockquote><h3># Navigate to Project’s root</h3><p>Once the project has been created, we can navigate to the project’s root directory by using the following command:</p><pre>cd web-sockets</pre><h3># Add the dependencies</h3><p>Open the file cargo.toml ( it’s created automatically when we initialize a project ) and add the following dependencies under the [dependencies] section:</p><pre><br><br>[dependencies]<br>tokio = { version = &quot;1&quot;, features = [&quot;full&quot;] }<br>tokio-tungstenite = &quot;0.15&quot;<br>futures = &quot;0.3&quot;<br>log = &quot;0.4&quot;<br>env_logger = &quot;0.9&quot;</pre><p>we’ll talk about the role of each and every dependency as we write code.</p><h3># Write the Code</h3><p>Next let’s write the code step by step and also understand what each line of code is meant for:</p><h4>## Imports</h4><p>Imports in Rust are like any other programming language except for the syntax. In Rust, we use the use keyword to include functionality from other modules and packages.</p><pre>use tokio::net::{TcpListener, TcpStream};<br>use tokio_tungstenite::{accept_async, tungstenite::protocol::Message};<br>use futures::{StreamExt, SinkExt};<br>use std::env;<br>use std::net::SocketAddr;<br>use log::{info, error};</pre><ol><li>Tokio: Tokio is an asynchronous runtime for Rust. It provides the essential tools to write asynchronous programs.</li><li>Tokio-tungstenite: Tokio-tungstenite is a library that provides WebSocket support for Tokio. It allows us to create WebSocket clients and servers that integrate seamlessly with the Tokio async runtime.</li><li>Futures: Futures is a library that provides abstractions for asynchronous programming.</li><li>Log: log provides a standard interface for logging in Rust.</li><li>Std::env: std::env module provides functions and types for interacting with the execution environment of Rust. We’ll be using it to read the command line args.</li><li>Std::net: The std::net::SocketAddr module provides types and functions for handling network addresses, both IPv4 and IPv6. A SocketAddr is a combination of an IP address and a port number.</li></ol><h4>## Code</h4><p>First I’ll be writing the code for the main function and then will explain the code line by line.</p><blockquote>Reminder: If you’re only interested in the code, you can jump to the end of the article.</blockquote><pre>#[tokio::main]<br>async fn main() {<br>    // Initialize the logger<br>    env_logger::init();<br><br>    // Get the address to bind to<br>    let addr = env::args().nth(1).unwrap_or_else(|| &quot;127.0.0.1:8080&quot;.to_string());<br>    let addr: SocketAddr = addr.parse().expect(&quot;Invalid address&quot;);<br><br>    // Create the TCP listener<br>    let listener = TcpListener::bind(&amp;addr).await.expect(&quot;Failed to bind&quot;);<br><br>    info!(&quot;Listening on: {}&quot;, addr);<br><br>    while let Ok((stream, _)) = listener.accept().await {<br>        // Spawn a new task for each connection<br>        tokio::spawn(handle_connection(stream));<br>    }<br>}</pre><h4>## Detailed explanation of each line:</h4><pre>#[tokio::main]</pre><ul><li>This macro indicates that the main function will be the entry point for a Tokio runtime. It sets up the Tokio runtime, allowing you to use asynchronous features within this function.</li></ul><pre>async fn main() {</pre><ul><li>Declares the main function as asynchronous, allowing the use of await for asynchronous operations inside the function.</li></ul><pre>    // Initialize the logger<br>    env_logger::init();</pre><ul><li>Initializes the logger using the env_logger crate.</li></ul><pre>    // Get the address to bind to<br>    let addr = env::args().nth(1).unwrap_or_else(|| &quot;127.0.0.1:8080&quot;.to_string());</pre><ul><li>Retrieves the first command-line argument (expected to be the address to bind to). If no argument is provided, it defaults to 127.0.0.1:8080</li></ul><pre>    let addr: SocketAddr = addr.parse().expect(&quot;Invalid address&quot;);</pre><ul><li>Parses the address string into a SocketAddr type. If the string is not a valid address, it will panic with the message <strong>Invalid address</strong></li></ul><pre>    // Create the TCP listener<br>    let listener = TcpListener::bind(&amp;addr).await.expect(&quot;Failed to bind&quot;);</pre><ul><li>Binds a TCP listener to the specified address. The await keyword pauses the function until the binding operation completes. If it fails, the program will panic with the message <strong>Failed to bind</strong>.</li></ul><pre>    info!(&quot;Listening on: {}&quot;, addr);</pre><ul><li>Logs an informational message indicating that the server is listening on the specified address.</li></ul><pre>    while let Ok((stream, _)) = listener.accept().await {</pre><ul><li>Continuously accepts incoming TCP connections. The await keyword pauses the loop until a new connection is received. If a connection is successfully accepted, it returns a tuple with the stream and the remote address, which is unpacked into stream and _ (the latter being ignored).</li></ul><pre>        // Spawn a new task for each connection<br>        // Note that we&#39;ll be writing the handle_connection function in <br>        // next section. <br>        tokio::spawn(handle_connection(stream));</pre><ul><li>For each accepted connection, spawns a new asynchronous task to handle the connection using the handle_connection function. This allows the server to handle multiple connections concurrently.</li></ul><h4>## handle_connection Function</h4><p>First let’s look at the complete function and then we’ll break it to understand it.</p><pre>async fn handle_connection(stream: TcpStream) {<br>    // Accept the WebSocket connection<br>    let ws_stream = match accept_async(stream).await {<br>        Ok(ws) =&gt; ws,<br>        Err(e) =&gt; {<br>            error!(&quot;Error during the websocket handshake: {}&quot;, e);<br>            return;<br>        }<br>    };<br><br>    // Split the WebSocket stream into a sender and receiver<br>    let (mut sender, mut receiver) = ws_stream.split();<br><br>    // Handle incoming messages<br>    while let Some(msg) = receiver.next().await {<br>        match msg {<br>            Ok(Message::Text(text)) =&gt; {<br>                // Reverse the received string and send it back<br>                let reversed = text.chars().rev().collect::&lt;String&gt;();<br>                if let Err(e) = sender.send(Message::Text(reversed)).await {<br>                    error!(&quot;Error sending message: {}&quot;, e);<br>                }<br>            }<br>            Ok(Message::Close(_)) =&gt; break,<br>            Ok(_) =&gt; (),<br>            Err(e) =&gt; {<br>                error!(&quot;Error processing message: {}&quot;, e);<br>                break;<br>            }<br>        }<br>    }<br>}</pre><p>Given that this is slightly longer function, let’s try to split it into multiple blocks instead of lines to keep things simpler.</p><h4>## Block-1 Accepting the WebSocket connection</h4><pre>async fn handle_connection(stream: TcpStream) {<br>    // Accept the WebSocket connection<br>    let ws_stream = match accept_async(stream).await {<br>        Ok(ws) =&gt; ws,<br>        Err(e) =&gt; {<br>            error!(&quot;Error during the websocket handshake: {}&quot;, e);<br>            return;<br>        }<br>    };</pre><ul><li>This block attempts to accept a WebSocket connection from the provided TCP stream using accept_async.</li><li>If successful, the WebSocket stream (ws_stream) is returned. If there’s an error during the handshake, it logs an error message and exits the function early.</li></ul><h4>## Block-2 Splitting the WebSocket Stream</h4><pre>    // Split the WebSocket stream into a sender and receiver<br>    let (mut sender, mut receiver) = ws_stream.split();</pre><ul><li>This block splits the WebSocket stream into a sender (sender) and a receiver (receiver).</li><li>The sender is used to send messages back to the client, while the receiver is used to receive messages from the client.</li></ul><h4>## Block-3 Handle incoming messages</h4><pre>    // Handle incoming messages<br>    while let Some(msg) = receiver.next().await {<br>        match msg {<br>            Ok(Message::Text(text)) =&gt; {<br>                // Reverse the received string and send it back<br>                let reversed = text.chars().rev().collect::&lt;String&gt;();<br>                if let Err(e) = sender.send(Message::Text(reversed)).await {<br>                    error!(&quot;Error sending message: {}&quot;, e);<br>                }<br>            }<br>            Ok(Message::Close(_)) =&gt; break,<br>            Ok(_) =&gt; (),<br>            Err(e) =&gt; {<br>                error!(&quot;Error processing message: {}&quot;, e);<br>                break;<br>            }<br>        }<br>    }<br>}</pre><ul><li>This block continuously processes incoming messages from the receiver in a loop.</li><li><strong>while let Some(msg) = receiver.next().await:</strong> Waits for the next message to arrive asynchronously.</li><li><strong>match msg:</strong> Matches on the type of message received.</li><li><strong>Ok(Message::Text(text)):</strong> If the message is a text message, it reverses the text and sends it back to the client using the sender.</li><li><strong>Ok(Message::Close(_)):</strong> If a close message is received, it breaks the loop and ends the connection.</li><li><strong>Ok(_):</strong> Ignores other types of messages (e.g., binary messages).</li><li><strong>Err(e):</strong> If there’s an error processing the message, it logs the error and breaks the loop.</li></ul><p>Now let’s combine all of the code we’ve written above in a file called src/main.rs, note that this file is created when you run cargo new so you don’t have to create it again, just overwrite the already created file.</p><p>src/main.rs</p><pre>use tokio::net::{TcpListener, TcpStream};<br>use tokio_tungstenite::{accept_async, tungstenite::protocol::Message};<br>use futures::{StreamExt, SinkExt};<br>use std::env;<br>use std::net::SocketAddr;<br>use log::{info, error};<br><br>#[tokio::main]<br>async fn main() {<br>    // Initialize the logger<br>    env_logger::init();<br><br>    // Get the address to bind to<br>    let addr = env::args().nth(1).unwrap_or_else(|| &quot;127.0.0.1:8080&quot;.to_string());<br>    let addr: SocketAddr = addr.parse().expect(&quot;Invalid address&quot;);<br><br>    // Create the TCP listener<br>    let listener = TcpListener::bind(&amp;addr).await.expect(&quot;Failed to bind&quot;);<br><br>    info!(&quot;Listening on: {}&quot;, addr);<br><br>    while let Ok((stream, _)) = listener.accept().await {<br>        // Spawn a new task for each connection<br>        tokio::spawn(handle_connection(stream));<br>    }<br>}<br><br>async fn handle_connection(stream: TcpStream) {<br>    // Accept the WebSocket connection<br>    let ws_stream = match accept_async(stream).await {<br>        Ok(ws) =&gt; ws,<br>        Err(e) =&gt; {<br>            error!(&quot;Error during the websocket handshake: {}&quot;, e);<br>            return;<br>        }<br>    };<br><br>    // Split the WebSocket stream into a sender and receiver<br>    let (mut sender, mut receiver) = ws_stream.split();<br><br>    // Handle incoming messages<br>    while let Some(msg) = receiver.next().await {<br>        match msg {<br>            Ok(Message::Text(text)) =&gt; {<br>                // Reverse the received string and send it back<br>                let reversed = text.chars().rev().collect::&lt;String&gt;();<br>                if let Err(e) = sender.send(Message::Text(reversed)).await {<br>                    error!(&quot;Error sending message: {}&quot;, e);<br>                }<br>            }<br>            Ok(Message::Close(_)) =&gt; break,<br>            Ok(_) =&gt; (),<br>            Err(e) =&gt; {<br>                error!(&quot;Error processing message: {}&quot;, e);<br>                break;<br>            }<br>        }<br>    }<br>}</pre><p>Now we can check the code for errors with the following command:</p><pre>cargo check</pre><p>If there are any errors, this command will display them.</p><p>If everything’s okay, we can go to the next step and run our web socket server with the following command:</p><pre>cargo run</pre><p>Now we can connect to the web socket server at the addr viz 127.0.0.1:8080 and start sending messages. It’ll simply return the same message in the reversed format.</p><h3>## Summary</h3><p>In this article, we learnt how to build a web socket server using the Rust programming language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f3ba4b6b19c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Human Intelligence is Limited but Human Imagination is Infinite]]></title>
            <link>https://medium.com/@rishabh.io/human-intelligence-is-limited-but-human-imagination-is-infinite-ac01bd2e5248?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac01bd2e5248</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[human-mind]]></category>
            <category><![CDATA[imagination]]></category>
            <category><![CDATA[ai-replacing-human]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 00:28:40 GMT</pubDate>
            <atom:updated>2024-01-06T00:28:40.279Z</atom:updated>
            <content:encoded><![CDATA[<p>Why AI is not yet close to replacing human intelligence.</p><p>Irrespective of what part of the world you’re present right now, if the thought of AI replacing you is consuming a lot of your time then it’s better that you get back to work because AI is not yet close to taking the role human play in taking the universe ahead.</p><p>How humans evolved to where they are today is definitely beyond the scope of this article but we definitely understand how AI works. So if I were to explain it to a 6 years old, I would simply say that think of AI as your lazy classmate who doesn’t want to invest time in imagination and so he goes over to observe what 30 other classmates are doing and finally he comes back with that learning and draw something out of what he learnt.</p><p>Did he complete the job at hand? The answer is YES, but did he think on his own. Unfortunately not!</p><p>Based on my current understanding of the mathematics and algorithms driving AI, there’s absolutely no doubt about AI’s capabilities in replacing a lot of repetitive tasks but that phenomenon is not new.</p><p>I remember reading about Spinning jenny a long time back ( during school days ) and how it led to a lot of people losing their jobs. Similarly whenever there’s a new technological revolution, jobs are lost but let’s not forget that this has been the trend ever since the birth of humanity. The jobs which fascinated my father’s generation never fascinated mine and the jobs which are quite fascinating to my generation ( say #FAANG ) may not be very lucrative to the upcoming generation.</p><p>But when it comes to AI taking away all the jobs, I think we’re still at a very early stage to make bold statements about that. I don’t want to completely ignore the possibility of an algorithm which evolves genetically by learning from the environment but then if we shift our focus to how far we’ve come in our understanding of human brain and how it works, there are still a lot of mysteries to be unsolved.</p><p>AI’s going to be a great assistant but how close are we to building an AI which can imagine and evolve based on the environmental factors is something before which we’ve more to explore about the neural networks forming the basis of our own minds.</p><p>Human beings have an inherent desire to learn and grow and that’s the reason we’ve seen that the learners quite often outgrow their own mentors. Remember your mathematics teacher from school? If they’re still teaching elementary mathematics then there’s a higher possibility you know more mathematics than them but let’s not forget that it’s got nothing to do with your training but more to do with your desire to keep learning. On the contrary there are going to be people younger than you knowing mathematics way better than you because of their own desire to learn.</p><p>How close are we to programming these human qualities in AI is something we need to reflect upon but my OPINION on this is that there’s a lot more to be explored about human brain and where we get our infinite imagination from. How we went form bullock carts to space crafts is what makes humans different than AI.</p><p>Can humans pass on these humanly qualities in the form of algorithms to AI, well if the answer is yes then I guess we’ll no longer be humans, we’ll rather be the creators.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac01bd2e5248" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Google Big Query Data Warehouse]]></title>
            <link>https://medium.com/@rishabh.io/getting-started-with-google-big-query-data-warehouse-dbfb98c9f51c?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbfb98c9f51c</guid>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 06:01:38 GMT</pubDate>
            <atom:updated>2023-09-29T06:01:38.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5kbkdEU7zgADp1s30Jxo1w.png" /><figcaption>Google Big Query Data Warehouse</figcaption></figure><p>One day you got bored of writing the Python ( insert your language here ) APIs and decided to talk to your manager about it. You’re the kind of person who’s always up to explore something new and challenging.</p><p>Your manager not only understood your concerns but also talked about a client having a lot of data coming from different sources like databases, social media campaigns, websites etc and how they want to build a data warehouse to store all of it for analytical processing.</p><p>Given the client’s infra is on GCP, so as a proactive step, your manager asked you to experiment with Google’s Big Query and that’s when you found this article on “well again” Google :)</p><p>Alright! Below is a comprehensive, step-by-step guide to getting started with inserting data into Google BigQuery, starting from setting up a Google Cloud Project.</p><h3>Step 1: Create a Google Cloud Project</h3><ol><li>Go to the <a href="https://console.cloud.google.com/">Google Cloud Console</a>.</li><li>If you haven’t already, sign in with your Google Account.</li><li>Click the “Select a project” dropdown, then “New Project”, and follow the prompts to create a new project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QherRjqQbdDpLUeF8EAe-g.png" /><figcaption>Start with a new Google Project</figcaption></figure><blockquote>Note: You can sign up for Google’s free tier which offers $300 for experimentation ( in case your manager didn’t provide you with the credentials :) )</blockquote><h3>Step 2: Enable BigQuery API</h3><ol><li>Navigate to your newly created project in the Cloud Console.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwbyDMI3ZGIcTjO7g485jg.png" /><figcaption>Navigate to your Project</figcaption></figure><p>2. Go to the “Navigation Menu” (three horizontal lines in the upper left corner).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBTQzUWUsPGN4KDMNeEY7w.png" /><figcaption>Go to “APIs &amp; Services”</figcaption></figure><p>3. Navigate to “APIs &amp; Services” &gt; “Dashboard”.</p><p>4. Click “+ ENABLE APIS AND SERVICES”.</p><p>5. Search for “BigQuery API” and enable it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0rNtPS-hTVBTBJ-vnEKDw.png" /><figcaption>Enable the “Big Query” API</figcaption></figure><h3>Step 3: Create a Dataset and Table in BigQuery</h3><ol><li>Go to the Navigation Menu &gt; BigQuery.</li><li>In the left sidebar, next to your project’s name. You’ll see 3 vertical dots, click on them and you’ll see the option to create a new dataset</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSGgpkWYOfM4CjzDUy_9FQ.png" /><figcaption>Create a new DataSet</figcaption></figure><p>3. Click Create Dataset.</p><p>4. Give your dataset a name and leave the other settings as default ( or edit as per your requirements ), then click Create Dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyXQmV4b8H5XVghIWFq24w.png" /></figure><p>5. Go to the Dataset you just created, click Create Table.</p><p>6. Give a name to your table.</p><p>7. Define your table schemaby adding field names and their types, reflecting the data you wish to insert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-raA0Z3h61wFAmrUll7kZQ.png" /><figcaption>Add fields as per your requirements</figcaption></figure><p>8. Click Create Table once done.</p><h3>Step 4: Create a Service Account</h3><ol><li>Go to the Navigation Menu &gt; IAM &amp; Admin &gt; Service Accounts.</li><li>Click Create Service Account.</li><li>Give your service account a name and description, then click Create.</li><li>Grant the service account BigQuery permissions by assigning the following roles: Big Query User, Big Query Data Editor</li><li>Click + CREATE KEY, select JSON, and click CREATE. The key file will be downloaded to your computer. Keep it secure and confidential.</li></ol><blockquote>Note: Screenshots are skipped assuming that by now you’ve become familiar with the interface. In case you face any trouble free free ot reach out to us on our Discord ( Link Given at the end of the Article )</blockquote><h3>Step 5: Set Up Your Local Environment</h3><ol><li>Navigate to the directory where you want to run your experiment</li></ol><pre>cd path_to_your_working_directory</pre><p>2. Create a Virtual Environment ( to keep our project’s dependencies isolated from others )</p><pre>python -m venv venv </pre><p>3. Install the Google Cloud BigQuery Library:</p><pre>pip install google-cloud-bigquery</pre><p>4. Set an environment variable pointing to the downloaded service account key file:</p><pre>export GOOGLE_APPLICATION_CREDENTIALS=&quot;/path/to/your/service/account/key.json&quot;</pre><h3>Step 6: Write Python Code to Insert Data</h3><ol><li>Create a Python script, say insert_data.py, in your favorite editor e.g. VSCode or PyCharm.</li><li>Write the following Python code:</li></ol><pre>from google.cloud import bigquery<br><br>client = bigquery.Client()<br>table_id = &quot;your-project-id.your_dataset_id.your_table_id&quot;<br><br>table = client.get_table(table_id)<br><br>rows_to_insert = [<br>    {&quot;column1&quot;: &quot;value1&quot;, &quot;column2&quot;: &quot;value2&quot;, &quot;column3&quot;: &quot;value3&quot;},<br>]<br><br>errors = client.insert_rows_json(table, rows_to_insert)<br>if errors == []:<br>    print(&quot;New rows have been added.&quot;)<br>else:<br>    print(&quot;Errors occurred:&quot;, errors)</pre><p>Replace your-project-id, your_dataset_id, your_table_id, and rows_to_insert with your actual project ID, dataset ID, table ID, and the data you want to insert, respectively.</p><p>3. Execute the Python script.</p><pre>python insert_data.py </pre><p>4. Observe the output, it should be:</p><pre>New rows have been added.</pre><p>In case you face any issue on this step, it could be because of one of the following reasons:</p><ol><li>Your Service Account is not setup properly ( check the roles / permissions once again ).</li><li>Your data is not in the right format.</li></ol><h3>Step 7: Verify Data from the GCP Console</h3><p>Go back to the Google Console &gt; big Query to verify that the data is added. Go to BigQuery &gt; Your Project &gt; Your DataSet &gt; YourTable and Click on Preview.</p><p>You should be able to see the Data you just inserted. Congratulations! You’ve successfully started your exploration of the Google Big Query. Keep going and don’t step.</p><h3>Step-8 Before you Leave</h3><p>If you’ve followed all the steps till here and successfully got your data inside the table, it’s important that you now stop / deactivate all the resource you created above otherwise it may exhaust your credits.</p><h3>Conclusion</h3><p>After following this detailed guide, you should have a Google Cloud project set up with a BigQuery table and should be able to insert data into this table using a Python script. Keep exploring and experimenting with different functionalities that Google Cloud and BigQuery offer to optimize your workflow as needed.</p><h3>7. “Fuel 100 Million Dreams” Our Mission.</h3><p>In today’s fast pacing world, it’s important to keep unlearning what’s not needed and keep refreshing your skills based on the winds of technology. We push our limits to bring content to keep you up to date with just the skills you need. Our goal as a community is to touch and impact 100 Mlives and fuel 100 M dreams, but it all starts at one. Would you be that one? Join hands and <strong><em>together we can do it better</em></strong>.</p><ol><li><a href="https://youtube.com/@fourofourever">Subscribe</a> to our <a href="https://youtube.com/@fourofourever">Youtube Channel fourofour</a> for amazing tech videos.</li></ol><p>2. Join our <a href="https://discord.gg/4MzMg7ea">Discord Server</a></p><p>3. Join our <a href="https://chat.whatsapp.com/JWIQtCP1rnY8AjXSs2sbkl">Whatsapp Group</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbfb98c9f51c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying and Serving a React App with Docker and Nginx]]></title>
            <link>https://medium.com/@rishabh.io/deploying-and-serving-a-react-app-with-docker-and-nginx-85eda5cbbcb4?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/85eda5cbbcb4</guid>
            <category><![CDATA[production]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 06:02:26 GMT</pubDate>
            <atom:updated>2023-09-28T06:02:26.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DY3tprCen_m9lrnlk76M_A.png" /><figcaption>React App with Docker and Nginx</figcaption></figure><p>So you’re a React DEV who not only does his job well but also goes out of the way to write clean <strong>test cases</strong> and follow <strong>all the best practices</strong>.</p><p>And this time as well, you’ve completed all your work locally and your project is working fine, but this time your manager has thrown a new challenge in your court. You don’t just have to push the code to the project’s repository but instead you’ve to build a docker image for your project using Nginxas web server so the project can run as a container on your local and in production.</p><p>Now you’re a React PRO but hardly ever came face to face with things like Nginx and Docker. What should you do? There are 2 options:</p><ol><li>Fight with your manager and ask him to give it to somebody else.</li><li>Follow this article till the end and get the shit done.</li></ol><p>Being the never-give-up programmer you’re, you opt for option number #2 and as the saying goes, with difficult choices come adventures.</p><h3># Pre-requisites</h3><p>You’ve the following setup:</p><ol><li><strong>A dummy React Project</strong> created with create-react-app ( or any tool of your choice )</li><li>Docker installed on your System</li></ol><p>Note: After installing Docker, you can confirm with the command docker -v</p><h3>1. Navigate to your React Project:</h3><p>Navigate to your project directory where your React app is located.</p><pre>cd /path-to-your-react-app</pre><h3>2. Create a Dockerfile</h3><p>Create a Dockerfile in your project directory and add the following content to it:</p><pre># Stage 1: Build the React Application<br>FROM node:18 as build<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>RUN npm run build<br><br># Stage 2: Setup the Nginx Server to serve the React Application<br>FROM nginx:1.25.0-alpine as production<br>COPY --from=build /app/build /usr/share/nginx/html<br>COPY nginx.conf /etc/nginx/conf.d/default.conf<br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><h3>3. Create an Nginx Configuration File</h3><p>Create a file named nginx.conf in your project directory and add the following content to it:</p><pre>server {<br>  listen 80;<br>  location / {<br>    root   /usr/share/nginx/html;<br>    index  index.html index.htm;<br>    try_files $uri $uri/ /index.html =404;<br>  }<br>}</pre><h3>4. Build the Docker Image</h3><p>Now, build your Docker image from your project directory:</p><pre>docker build -t my-react-app .</pre><p>Replace my-react-app with the name you prefer for your Docker image.</p><h3>5. Run the Docker Container</h3><p>Run a container using the image you just built:</p><pre>docker run -p 8080:80 --name my-react-app-container my-react-app</pre><p>Replace my-react-app-container with the name you prefer for your Docker container.</p><h4>5.1 Point of Confusion</h4><p>Even smart programmers often get confused on which port is the host port and which one is the docker port in above command. So it’s a good idea to understand the syntax clearly.</p><pre>docker run -p [LOCAL_MACHINE_PORT]:[DOCKER_CONTAINER_PORT] --name [CONTAINER_NAME] [IMAGE_NAME]</pre><p>So in the example:</p><ul><li>[LOCAL_MACHINE_PORT] is 8080</li><li>[DOCKER_CONTAINER_PORT] is 80</li><li>[CONTAINER_NAME] is my-react-app-container</li><li>[IMAGE_NAME] is my-react-app</li></ul><blockquote>This means that the application inside the Docker container, which is running on port 80, will be accessible on your local machine at port 8080.</blockquote><h3>6. Access the Application</h3><p>Now, open your web browser and navigate to http://localhost:8080 to access your React app served by Nginx inside a Docker container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvbTSuuX3T1Cj50HpKy7yw.png" /><figcaption>Your View will be different based on your Project</figcaption></figure><h3>7. Stop the Docker Container</h3><p>When you’re done, you can stop the Docker container by running:</p><pre>docker stop my-react-app-container</pre><h3>8. Remove the Docker Container</h3><p>If you want to remove the Docker container, use the following command:</p><pre>docker rm my-react-app-container</pre><h3>9. Summary</h3><p>With these steps, you should be able to containerize your React application using Docker and serve it with Nginx. This setup is very common and provides you with a scalable and manageable deployment solution.</p><h3># “Fuel 100 Million Dreams” Our Mission.</h3><p>In today’s fast pacing world, it’s important to keep unlearning what’s not needed and keep refreshing your skills based on the winds of technology. We push our limits to bring content to keep you up to date with just the skills you need. Our goal as a community is to touch and impact 100 Mlives and fuel 100 M dreams, but it all start at one. Would you be that one? Join hands and <strong><em>together we can do it better</em></strong>.</p><ol><li><a href="https://youtube.com/@fourofourever">Subscribe</a> to our <a href="https://youtube.com/@fourofourever">Youtube Channel fourofour</a> for amazing techotent.</li></ol><p>2. Join our <a href="https://discord.gg/4MzMg7ea">Discord Server</a></p><p>3. Join our <a href="https://chat.whatsapp.com/JWIQtCP1rnY8AjXSs2sbkl">Whatsapp Group</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85eda5cbbcb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Aliens learn GraphQL with Python Flask and Graphene]]></title>
            <link>https://medium.com/four-o-four/how-aliens-learn-graphql-with-python-flask-and-graphene-310bda97c824?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/310bda97c824</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[flask-framework]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 06:58:08 GMT</pubDate>
            <atom:updated>2023-09-27T06:58:08.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KFMfYG1XGZ6IRdgvlV4Sg.png" /><figcaption>Learn GraphQL with Python and Flask</figcaption></figure><p>So you’ve been hearing this term called “GraphQL” again and again and you wanted to play around with it but were not able to spare any time so far. Relax and let your mind immerse in this short and simple treat to your curious neurons as we delve into the world of GraphQL with Python and Flask.</p><p>To get started with GraphQL using Python, you can use a Python library called Graphene, which is a Python library for building GraphQL APIs in Python easily.</p><p>So here’s a step-by-step “<em>no-text only code</em>” guide to creating a basic GraphQL API using Flask, which is a micro web framework written in Python, and Graphene.</p><h3>1. Setup Your Project</h3><p>Create a new directory for your project and navigate into it:</p><pre>mkdir flask-graphql-demo<br>cd flask-graphql-demo</pre><p>Create a virtual environment and activate it:</p><pre>python -m venv venv<br># Windows:<br>.\venv\Scripts\activate<br># Linux/MacOS:<br>source venv/bin/activate</pre><h3>2. Install Dependencies</h3><pre>pip install Flask Flask-GraphQL graphene</pre><h3>3. Create a Basic Flask App with GraphQL</h3><ol><li>Create a new Python file, let’s say app.py</li><li>Open it in your preferred text editor.</li><li>Here’s a basic example that demonstrates how to create a GraphQL API with a single query:</li></ol><pre>from flask import Flask<br>from flask_graphql import GraphQLView<br>import graphene<br><br>class Query(graphene.ObjectType):<br>    hello = graphene.String(description=&#39;A typical hello world&#39;)<br>    <br>    def resolve_hello(self, info):<br>        return &#39;Hello, World!&#39;<br><br>schema = graphene.Schema(query=Query)<br><br>app = Flask(__name__)<br>app.add_url_rule(&#39;/graphql&#39;, view_func=GraphQLView.as_view(&#39;graphql&#39;, schema=schema, graphiql=True))<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run()</pre><h4>In this example:</h4><ul><li>We define a single query hello that returns a string.</li><li>The resolve_hello method is the resolver that returns the actual data for the hello query.</li><li>We create a Flask app and add a URL rule for /graphql where our GraphQL API will be accessible.</li><li>We enable GraphiQL, a graphical interactive in-browser GraphQL IDE, allowing you to test your GraphQL queries.</li></ul><h3>4. Run Your App</h3><p>Navigate to your project directory in the terminal, and run:</p><pre>python app.py</pre><p>This will start your Flask app. You can open your browser and go to http://127.0.0.1:5000/graphql to interact with your GraphQL API using GraphiQL.</p><p>Type the following query in the GraphiQL editor:</p><pre>{<br>  hello<br>}</pre><p>And run it. You should see the response:</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;hello&quot;: &quot;Hello, World!&quot;<br>  }<br>}</pre><h3>5. Next Steps</h3><p>Now that you have set up a basic GraphQL API with a single query, you can start expanding it by defining more complex types, queries, mutations, and resolvers as per your application needs. You can refer to the <a href="https://docs.graphene-python.org/en/latest/">Graphene Documentation</a> for more advanced features and examples.</p><h3>6. Summary</h3><p>This guide provides a basic introduction to creating a GraphQL API using Flask and Graphene in Python, and you can build upon this foundation to create more complex and feature-rich GraphQL APIs as needed.</p><h3>7. “Fuel 100 Million Dreams” Our Mission.</h3><p>In today’s fast pacing world, it’s important to keep unlearning what’s not needed and keep refreshing your skills based on the winds of technology. We push our limits to bring content to keep you up to date with just the skills you need. Our goal as a community is to touch and impact 100 Mlives and fuel 100 M dreams, but it all start at one. Would you be that one? Join hands and <strong><em>together we can do it better</em></strong>.</p><ol><li><a href="https://youtube.com/@fourofourever">Subscribe</a> to our <a href="https://youtube.com/@fourofourever">Youtube Channel fourofour</a> for amazing techotent.</li></ol><p>2. Join our <a href="https://discord.gg/4MzMg7ea">Discord Server</a></p><p>3. Join our <a href="https://chat.whatsapp.com/JWIQtCP1rnY8AjXSs2sbkl">Whatsapp Group</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=310bda97c824" width="1" height="1" alt=""><hr><p><a href="https://medium.com/four-o-four/how-aliens-learn-graphql-with-python-flask-and-graphene-310bda97c824">How Aliens learn GraphQL with Python Flask and Graphene</a> was originally published in <a href="https://medium.com/four-o-four">FourOFour</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Rust: An Introduction and Deep Dive]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/four-o-four/mastering-rust-an-introduction-and-deep-dive-2f1056a16c8f?source=rss-97388397e268------2"><img src="https://cdn-images-1.medium.com/max/1074/1*RC8jSGQmt42-NhGyyMpQnw.png" width="1074"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://medium.com/four-o-four/mastering-rust-an-introduction-and-deep-dive-2f1056a16c8f?source=rss-97388397e268------2">Continue reading on FourOFour »</a></p></div>]]></description>
            <link>https://medium.com/four-o-four/mastering-rust-an-introduction-and-deep-dive-2f1056a16c8f?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f1056a16c8f</guid>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[blockchain-technology]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 11:33:15 GMT</pubDate>
            <atom:updated>2023-09-13T11:33:15.329Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[5 Python Mistakes Even Experienced Developers Make!]]></title>
            <link>https://medium.com/@rishabh.io/5-python-mistakes-even-experienced-developers-make-3741f74c1a81?source=rss-97388397e268------2</link>
            <guid isPermaLink="false">https://medium.com/p/3741f74c1a81</guid>
            <category><![CDATA[list-comprehension]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[shallow-copy]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rishabh IO]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 01:10:17 GMT</pubDate>
            <atom:updated>2024-05-07T03:58:13.760Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTQE4A0sNntZU6w2PWgLuA.png" /><figcaption>Mistakes in Python may also cause Pain :)</figcaption></figure><h3>1. Not Understanding Interning in Python</h3><p><a href="https://youtu.be/fNVEfubXZPg"><strong>Interning</strong></a><strong> is a memory optimization technique</strong> where a single instance of an immutable object is reused across multiple references, if they have the same value. This is particularly common with small integers and certain strings in Python.</p><p>In Python, small integers are interned automatically. This range usually includes integers from -5 to 256, although this is implementation-specific and may vary.</p><h4># Positive Example</h4><pre>a = 5<br>b = 5<br>print(a is b)  # True, because both &#39;a&#39; and &#39;b&#39; refer to the same memory location</pre><h4># Negative Example</h4><pre>a = 257<br>b = 257<br>print(a is b)  # False, because integers outside the range -5 to 256 are not interned</pre><p>Understanding the concept of interning is essential for efficient memory usage and to avoid potential confusion. Not all integers and strings are interned, and it’s tied to specific conditions, such as the value of the integer or the content and construction of the string. Being aware of these nuances helps in writing effective and performant code.</p><h3>2. Shallow Copy vs Deep Copy</h3><h4># Shallow Copy</h4><p>A <a href="https://youtu.be/fNVEfubXZPg">shallow copy</a> creates a new object that is a copy of the original object with a new reference. However, the elements inside the object (e.g., the elements of a list within a list) still refer to the same memory location as the original object.</p><p>A shallow copy can be created using methods like the copy module’s copy() function or the object’s copy() method (if available).</p><pre>import copy<br><br>original_list = [[1, 2], [3, 4]]<br>shallow_copied_list = copy.copy(original_list)<br><br>shallow_copied_list[0][0] = &#39;X&#39;<br>print(original_list)          # [[&#39;X&#39;, 2], [3, 4]]<br>print(shallow_copied_list)    # [[&#39;X&#39;, 2], [3, 4]]</pre><p>As you can see, changing the inner list in the shallow copy also changes the original list, as they both point to the same inner objects.</p><h4># Example with a Flat List</h4><pre>original_flat_list = [1, 2, 3]<br>shallow_copied_flat_list = original_flat_list.copy()<br><br>shallow_copied_flat_list[0] = &#39;X&#39;<br>print(original_flat_list)           # [1, 2, 3]<br>print(shallow_copied_flat_list)     # [&#39;X&#39;, 2, 3]</pre><p>In the case of a one-dimensional, flat list, the shallow copy behaves like a deep copy, as there are no nested references to share.</p><h4># Deep Copy</h4><p>A <a href="https://youtu.be/fNVEfubXZPg"><strong>deep copy</strong></a> creates a new object and recursively adds copies of the objects found in the original. This means that a deep copy duplicates everything, including the objects inside the original object.</p><p>A deep copy can be created using the copy module’s deepcopy() function.</p><pre>import copy<br><br>original_list = [[1, 2], [3, 4]]<br>deep_copied_list = copy.deepcopy(original_list)<br><br>deep_copied_list[0][0] = &#39;X&#39;<br>print(original_list)         # [[1, 2], [3, 4]]<br>print(deep_copied_list)      # [[&#39;X&#39;, 2], [3, 4]]</pre><p>Changing the deep copy doesn’t affect the original, as they are completely independent of each other.</p><h3>3. Evaluation of Function’s Default Parameters Only Once</h3><p>In Python, default parameters are evaluated when the function is defined, not each time the function is called. This can lead to unexpected behavior, especially when mutable objects like lists or dictionaries are used as default values.</p><h4># Using Immutable Default Values</h4><p>When using immutable objects like integers, strings, or tuples as default values, this behavior is usually not an issue.</p><pre>def my_function(a=42):<br>    print(a)<br><br>my_function()        # 42<br>my_function(100)     # 100</pre><p>Since integers are immutable, there’s no unexpected behavior in this case.</p><h4># Using Mutable Default Values</h4><p>Problems can arise when using mutable objects like lists or dictionaries as default values.</p><pre>def add_to_list(value, my_list=[]):<br>    my_list.append(value)<br>    return my_list<br><br>first_call = add_to_list(1)    # [1]<br>second_call = add_to_list(2)   # [1, 2]<br><br>print(first_call)    # [1, 2]<br>print(second_call)   # [1, 2]</pre><p>Here, both first_call and second_call point to the same list object, as the default list was created only once when the function was defined. Subsequent calls to the function use the same list, leading to unexpected behavior.</p><h4># Best Practice: Using None as Default Value</h4><p>To avoid this pitfall, it’s common to use None as the default value and create the mutable object inside the function if needed.</p><pre>def add_to_list(value, my_list=None):<br>    if my_list is None:<br>        my_list = []<br>    my_list.append(value)<br>    return my_list<br><br>first_call = add_to_list(1)    # [1]<br>second_call = add_to_list(2)   # [2]<br><br>print(first_call)    # [1]<br>print(second_call)   # [2]</pre><p>By using None and creating the list inside the function, each call gets its own independent list, avoiding the unexpected behavior.</p><h3>4. Using Loops Instead of Using Map Function</h3><p>Using loops to transform data instead of the map function makes code more verbose and less expressive. The map function applies a given function to all items in an input list, producing a new iterable.</p><pre># Using a loop<br>numbers = [1, 2, 3, 4]<br>squares = []<br>for n in numbers:<br>    squares.append(n**2)<br>print(squares)  # Outputs [1, 4, 9, 16]<br><br># Using map<br>squares_with_map = map(lambda x: x**2, numbers)<br>print(list(squares_with_map))  # Outputs [1, 4, 9, 16]</pre><h3>5. Comparison: == vs is</h3><p>The <a href="https://youtu.be/MyvsYPxkx6o">== operator</a> checks if two variables are equal in value, while the <a href="https://youtu.be/MyvsYPxkx6o">is operator</a> checks if two variables refer to the same object in memory. Let’s break down these concepts:</p><h4># Using the == Operator</h4><p>The == operator compares the values of two variables and returns True if they are equal.</p><pre>x = [1, 2, 3]<br>y = [1, 2, 3]<br><br>print(x == y)  # True<br>print(x is y)  # False</pre><p>Here, x and y contain the same values, so x == y is True. However, they are not the same object in memory, so x is y is False.</p><h4># Using the is Operator</h4><p>The is operator compares the memory locations of two variables and returns True if they refer to the same object.</p><pre>a = [4, 5, 6]<br>b = a<br><br>print(a == b)  # True<br>print(a is b)  # True</pre><h4># Pitfall with String and Integer Interning</h4><p>The is operator can sometimes behave unexpectedly with strings and small integers due to a performance optimization feature called interning.</p><pre>c = 255<br>d = 255<br><br>print(c == d)  # True<br>print(c is d)  # True<br><br>e = 256<br>f = 256<br><br>print(e == f)  # True<br>print(e is f)  # False</pre><p>Small integers (from -5 to 256) are interned in Python, so they refer to the same object in memory. This leads to c is d being True. However, integers outside this range don’t necessarily behave this way, as seen with e is f.</p><h3># Summary</h3><p>In this article we learnt about 5 common mistakes Even seasoned Python developers can occasionally make, leading to code behaving unexpectedly. This article delves into five pivotal concepts and the potential pitfalls. Recognizing and understanding these areas can enhance code robustness and help prevent subtle, perplexing errors.</p><h3>Next Steps</h3><p><em>Venv in Python</em>: <a href="https://youtu.be/6e1Mjnb8uRA">https://youtu.be/6e1Mjnb8uRA</a></p><p><em>Python IDEs:</em> <a href="https://youtu.be/EfNe4xWDj_A">https://youtu.be/EfNe4xWDj_A</a></p><p><em>Subscribe </em><a href="https://www.youtube.com/@fourofourever"><em>fourofour</em></a><em> on </em><a href="https://www.youtube.com/@fourofourever"><em>Youtube</em></a><em> to stay upto date on new and informative content on </em><a href="https://www.youtube.com/@fourofourever"><em>Python</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3741f74c1a81" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>