<?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 Everus Lainus on Medium]]></title>
        <description><![CDATA[Stories by Everus Lainus on Medium]]></description>
        <link>https://medium.com/@EverusLainus?source=rss-32d7c7458778------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*doH-1fu9yEl5lYy_F6uYYQ.jpeg</url>
            <title>Stories by Everus Lainus on Medium</title>
            <link>https://medium.com/@EverusLainus?source=rss-32d7c7458778------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 06:36:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@EverusLainus/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[HARLEY DAVIDSON- website clone.]]></title>
            <link>https://medium.com/@EverusLainus/harley-davidson-website-clone-ed9193a8ff26?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed9193a8ff26</guid>
            <category><![CDATA[clone-websites]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[collaborative-project]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 05:45:06 GMT</pubDate>
            <atom:updated>2026-04-29T05:45:06.485Z</atom:updated>
            <content:encoded><![CDATA[<h4>A collaborative project of cloning a Harley Davidson website.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSzs2zu58gdTYbXnSKGQqA.png" /></figure><p>The Project is to make a clone of Harley Davidson website using this design <a href="https://www.behance.net/gallery/166210441/Harley-Davidson-E-Commerce-Redesign?tracking_source=search_projects_appreciations%7Ce+commerce+website+">https://www.behance.net/gallery/166210441/Harley-Davidson-E-Commerce-Redesign?tracking_source=search_projects_appreciations%7Ce+commerce+website+</a></p><p>This is collaborative Project done over a span of 5 days by a team for 4 member that includes me.</p><p>For the front end we used HTML, CSS, JavaScript and React. For database management and Authentication we use <a href="https://console.firebase.google.com/">Firebase</a>.</p><h3>Features</h3><ul><li><strong>Sign-up and sigin user</strong>: Leverages several technologies, including React Router, Firebase Authentication, and Axios. It enables user registration via Google sign-in or a form submission, storing user data in a Firebase Realtime Database. The form submission includes client-side validation for a strong password. Styling is handled using a CSS file, and the interface is designed to be user-friendly, guiding users through the signup process with clear feedback and navigation.</li><li><strong>Add to cart functionality</strong>: dynamic cart page using React, Chakra UI, and Firebase. The code snippet leverages React hooks (useState and useEffect) to manage state and side effects. Chakra UI is utilized for UI components like Box, Button, and Flex, providing a responsive and visually appealing layout. Axios is employed for making HTTP requests to Firebase, where cart data is stored. The cart&#39;s functionality includes fetching user data from Firebase, calculating the total cost, and handling item quantity updates and removals, demonstrating an efficient and interactive e-commerce experience.</li><li><strong>Pay online Functionality: </strong>User-friendly payment form built using <strong>React</strong>, <strong>React Router</strong>, <strong>React Icons</strong>, and <strong>CSS</strong> for styling. The form leverages React’s useState hook for managing form data and validation states, and useNavigate from <strong>React Router</strong> for navigation. The form handles real-time input validation, such as card number formatting and type detection (Visa, Mastercard, Amex), ensuring data is accurately captured. The styling is enhanced with icons from <strong>React Icons</strong> to provide a visual representation of card types. This integration demonstrates a practical use of React in creating a responsive and accessible web form for payment processing.</li></ul><p><strong>Reference</strong></p><ul><li><a href="https://github.com/RahulGeorge96/Array-Archers_042/tree/develop">https://github.com/RahulGeorge96/Array-Archers_042/tree/develop</a></li><li><a href="https://harley-davidson-six.vercel.app/">https://harley-davidson-six.vercel.app/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed9193a8ff26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lamdify function from sympy library]]></title>
            <link>https://medium.com/@EverusLainus/lamdify-function-from-sympy-library-31eef919f670?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/31eef919f670</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[lamdify]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 05:42:21 GMT</pubDate>
            <atom:updated>2026-04-29T05:42:21.648Z</atom:updated>
            <content:encoded><![CDATA[<h4>explaining lamdify in depths.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4UcoEFZHhGliuwPt" /><figcaption>Photo by <a href="https://unsplash.com/@bramnaus?utm_source=medium&amp;utm_medium=referral">Bram Naus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>official doc:</p><p><a href="https://docs.sympy.org/latest/modules/utilities/lambdify.html">Lambdify - SymPy 1.13.3 documentation</a></p><p>sympy.utilities.lambdify.lambdify(<em>args</em>, <em>expr</em>, <em>modules=None</em>, <em>printer=None</em>, <em>use_imps=True</em>, <em>dummify=False</em>, <em>cse=False</em>, <em>docstring_limit=1000</em>)</p><p>takes parameters:</p><p><strong>args:</strong></p><p>A variable or a list of variables whose nesting represents the nesting of the arguments that will be passed to the function.</p><pre>f = lambdify(x, x + 1)<br>f(1)= 2</pre><p><strong>expr</strong> : Expr</p><p><em>An expression, list of expressions, or matrix to be evaluated.</em></p><p>To understand about lambdify, we need to know more about exec function.</p><pre>exec(object, globals=None, locals=None)</pre><p><strong>object</strong> (Required):</p><p>A string or code object that represents the Python code to be executed.</p><p><strong>globals</strong> (Optional):</p><p>A dictionary that will be used as the global namespace for the execution of the code. It defines the global variables that the code will have access to.</p><p><strong>locals</strong> (Optional):</p><p>A dictionary that will be used as the local namespace for the execution of the code. It defines the local variables for the execution context.</p><h3>Default Behavior:</h3><ul><li>If globals and locals are not provided, the current global and local namespaces are used.</li><li>If globals is provided but locals is not, the locals will default to the value of globals.</li><li>If both the <strong>custom global</strong> and <strong>custom local</strong> dictionaries in the exec function contain the same variable name, the variable from the <strong>local dictionary</strong> will take precedence over the one in the <strong>global dictionary</strong>.</li></ul><pre># Define some global and local variables<br>x = 10<br><br># Define the code to be executed<br>code = &quot;&quot;&quot;<br>result = x + 5<br>&quot;&quot;&quot;<br><br># Provide custom globals and locals dictionaries<br>custom_globals = {&quot;x&quot;: 20}  # x in globals is 20<br>custom_locals = {&quot;x&quot;: 30}   # x in locals is 30<br><br># Execute code with custom globals and locals<br>exec(code, custom_globals, custom_locals)<br><br># Print the result (this will use x from custom_locals)<br>print(custom_locals[&quot;result&quot;])  # Output: 35</pre><pre>exec(object)</pre><h3>How exec Works:</h3><ol><li>The string passed to exec is parsed and executed as Python code.</li><li>The executed code can modify variables, define functions, or perform any other actions as if it were written directly in the code.</li></ol><pre>x = 10<br>code = &quot;&quot;&quot;<br>result = x + 5<br>print(result)<br>&quot;&quot;&quot;<br>exec(code)  # This will execute the code inside the string</pre><h3>How Does exec Relate to lambdify?</h3><p>In SymPy’s lambdify, the exec function is used internally to convert SymPy expressions into executable Python code. When you use lambdify, SymPy generates the Python code as a string and uses exec to execute that code.</p><h3>Example of lambdify Using exec:</h3><pre>from sympy import symbols, sin, lambdify<br>import numpy as np<br># Define the symbolic variable<br>x = symbols(&#39;x&#39;)<br>expr = sin(x)<br># Lambdify expression<br>f = lambdify(x, expr, modules=&quot;numpy&quot;)<br># Print the function generated by lambdify<br>print(f(1))  # Output: 0.8414709848078965 (which is numpy.sin(1))</pre><h3>What Happens Behind the Scenes:</h3><ul><li>The expression sin(x) is converted into Python code (e.g., np.sin(x) if the numpy module is specified).</li><li>lambdify uses exec to execute the code and generate the Python function f.</li><li>When f(1) is called, it runs np.sin(1) to evaluate the result.</li></ul><pre>from sympy import symbols, exp, cse, lambdify<br><br>x = symbols(&quot;x&quot;)<br>expr = exp(x) + 2 * exp(x)<br><br># Apply CSE<br>cse_result = cse(expr)<br>print(&quot;CSE Result:&quot;, cse_result)<br><br># Convert to a function<br>f = lambdify(x, expr)<br>print(&quot;f(2) =&quot;, f(2))</pre><p>cse is applyed before calling lamdify , so csc will be an empty argument.</p><ul><li>The <strong>CSE extraction happens before </strong><strong>lambdify() is applied</strong>.</li></ul><h4>debugging doprint:</h4><pre>def doprint(self, funcname, args, expr, *, cses=()):<br>    &quot;&quot;&quot;<br>    Returns the function definition code as a string.<br>    &quot;&quot;&quot;<br>    from sympy.core.symbol import Dummy<br><br>    print(&quot;\n=== STARTING doprint ===&quot;)<br>    print(f&quot;Function Name: {funcname}&quot;)<br>    print(f&quot;Arguments: {args}&quot;)<br>    print(f&quot;Expression: {expr}&quot;)<br>    print(f&quot;Common Subexpressions (CSEs): {cses}\n&quot;)<br><br>    funcbody = []<br><br>    if not iterable(args):<br>        args = [args]<br><br>    if cses:<br>        subvars, subexprs = zip(*cses)<br>        exprs = [expr] + list(subexprs)<br>        argstrs, exprs = self._preprocess(args, exprs)<br>        expr, subexprs = exprs[0], exprs[1:]<br>        cses = zip(subvars, subexprs)<br>        print(f&quot;Processed CSEs: {list(cses)}&quot;)<br>    else:<br>        argstrs, expr = self._preprocess(args, expr)<br><br>    print(f&quot;Processed Arguments: {argstrs}&quot;)<br>    print(f&quot;Processed Expression: {expr}\n&quot;)<br><br>    # Generate argument unpacking and final argument list<br>    funcargs = []<br>    unpackings = []<br><br>    for argstr in argstrs:<br>        if iterable(argstr):<br>            dummy_var = self._argrepr(Dummy())<br>            funcargs.append(dummy_var)<br>            unpackings.extend(self._print_unpacking(argstr, dummy_var))<br>            print(f&quot;Unpacking Argument {argstr} -&gt; {dummy_var}&quot;)<br>        else:<br>            funcargs.append(argstr)<br><br>    funcsig = &#39;def {}({}):&#39;.format(funcname, &#39;, &#39;.join(funcargs))<br>    print(f&quot;\nGenerated Function Signature: {funcsig}\n&quot;)<br><br>    # Wrap input arguments before unpacking<br>    funcbody.extend(self._print_funcargwrapping(funcargs))<br><br>    funcbody.extend(unpackings)<br><br>    # Debugging CSE assignments<br>    for s, e in cses:<br>        if e is None:<br>            funcbody.append(&#39;del {}&#39;.format(self._exprrepr(s)))<br>            print(f&quot;Deleting Variable: {s}&quot;)<br>        else:<br>            assignment = &#39;{} = {}&#39;.format(self._exprrepr(s), self._exprrepr(e))<br>            funcbody.append(assignment)<br>            print(f&quot;Assigning: {assignment}&quot;)<br><br>    str_expr = _recursive_to_string(self._exprrepr, expr)<br><br>    if &#39;\n&#39; in str_expr:<br>        str_expr = &#39;({})&#39;.format(str_expr)<br>    <br>    return_statement = &#39;return {}&#39;.format(str_expr)<br>    funcbody.append(return_statement)<br>    print(f&quot;\nGenerated Return Statement: {return_statement}\n&quot;)<br><br>    funclines = [funcsig]<br>    funclines.extend([&#39;    &#39; + line for line in funcbody])<br><br>    final_function = &#39;\n&#39;.join(funclines) + &#39;\n&#39;<br>    print(&quot;\n=== FINAL GENERATED FUNCTION ===&quot;)<br>    print(final_function)<br><br>    return final_function</pre><pre>from sympy.printing.pycode import MpmathPrinter<br>from sympy import *<br>from sympy.abc import x<br>import mpmath<br><br>K=Symbol(&quot;K&quot;)<br>z=Symbol(&quot;z&quot;)<br>G=K*(z+1)*(z+1/3)/z/(z+1/2)/(z-1)<br><br>#printer = MpmathPrinter(settings={&#39;fully_qualified_modules&#39;: False, &#39;strict&#39;: False})<br>#print(nsolve((1+G,abs(z)-1),(K,z),(1,1j), printer=printer))<br><br>printer = MpmathPrinter(settings={&#39;fully_qualified_modules&#39;: False, &#39;strict&#39;: False})<br>print(nsolve((1+G,abs(z)-1),(K,z),(1,1j)))</pre><p>gives error:</p><pre>sympy.printing.codeprinter.PrintMethodNotImplementedError: Unsupported by &lt;class &#39;sympy.printing.pycode.MpmathPrinter&#39;&gt;: &lt;class &#39;sympy.core.function.Derivative&#39;&gt;<br>Printer has no method: _print_Derivative_re<br>Set the printer option &#39;strict&#39; to False in order to generate partially printed code.</pre><p>whereas</p><pre>from sympy.printing.pycode import MpmathPrinter<br>from sympy import *<br>from sympy.abc import x<br>import mpmath<br><br>K=Symbol(&quot;K&quot;)<br>z=Symbol(&quot;z&quot;)<br>G=K*(z+1)*(z+1/3)/z/(z+1/2)/(z-1)<br><br>printer = MpmathPrinter(settings={&#39;fully_qualified_modules&#39;: False, &#39;strict&#39;: False})<br>print(nsolve((1+G,abs(z)-1),(K,z),(1,1j), printer=printer))<br><br>#printer = MpmathPrinter(settings={&#39;fully_qualified_modules&#39;: False, &#39;strict&#39;: False})<br>#print(nsolve((1+G,abs(z)-1),(K,z),(1,1j)))</pre><p>gives error:</p><pre> ImmutableDenseMatrix([[(z + mpf((0, 6004799503160661, -54, 53)))*(z + 1)/(z*(z - 1)*(z + mpf((0, 1, -1, 1)))), K*(z + mpf((0, 6004799503160661, -54, 53)))/(z*(z - 1)*(z + mpf((0, 1, -1, 1)))) - K*(z + mpf((0, 6004799503160661, -54, 53)))*(z + 1)/(z*(z - 1)*(z + mpf((0, 1, -1, 1)))**2) + K*(z + 1)/(z*(z - 1)*(z + mpf((0, 1, -1, 1)))) - K*(z + mpf((0, 6004799503160661, -54, 53)))*(z + 1)/(z*(z - 1)**2*(z + mpf((0, 1, -1, 1)))) - K*(z + mpf((0, 6004799503160661, -54, 53)))*(z + 1)/(z**2*(z - 1)*(z + mpf((0, 1, -1, 1))))], [0, (re(z)*Derivative(re(z), z) + im(z)*Derivative(im(z), z))*sign(z)/z]]))<br>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            ^^^^^^^^^^<br>NameError: name &#39;Derivative&#39; is not defined</pre><p>suggession:</p><h3>3️⃣ The Suggested Alternative</h3><blockquote><em>“I could see value in overriding </em><em>lambdify entirely in </em><em>nsolve. Then the user could pass, e.g., </em><em>lambdify=lambda *args, **kwargs: lambdify(*args, printer=MyPrinter, **kwargs).&quot;</em></blockquote><p>This suggests <strong>a workaround</strong>:</p><p>Instead of modifying nsolve, let users <strong>override </strong><strong>lambdify</strong> by passing their own version:</p><pre>nsolve(my_expr, my_var, lambdify=lambda *args, **kwargs: lambdify(*args, printer=MyPrinter, **kwargs))</pre><p><strong>What happens here?</strong></p><ul><li>The user <strong>wraps</strong> lambdify inside another lambda function.</li><li>This ensures that printer=MyPrinter is <strong>always</strong> passed, without modifying nsolve.</li></ul><p><strong>More to Come.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31eef919f670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging and Deploying a Node.js Backend Server Using Render]]></title>
            <link>https://medium.com/@EverusLainus/debugging-and-deploying-a-node-js-backend-server-using-render-b295039f4d52?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/b295039f4d52</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[render]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[programming-tips]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 13:28:21 GMT</pubDate>
            <atom:updated>2025-04-23T13:28:21.259Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Step-by-Step Guide.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-mP-YRLFZI3d6xTx" /><figcaption>Photo by <a href="https://unsplash.com/@dose?utm_source=medium&amp;utm_medium=referral">Dose Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Deploying Your Backend with Render</h3><h3>Step 1: Sign Up &amp; Log In</h3><p>Visit <a href="https://render.com/">Render</a>.<br> If you haven’t already, sign up and log in to your account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MG_4Y6G4NNhDvy7UBouSRA.png" /></figure><h3>Step 2: Create a New Web Service</h3><ol><li>Click on the <strong>“New”</strong> button at the top-right corner.</li><li>Select <strong>“Web Service”</strong> to deploy your backend server.</li></ol><h3>Step 3: Connect Your Git Repository</h3><ul><li>Push your backend source code to a Git repository.</li><li>Copy the repository URL.</li><li>Choose either: <strong>Git Provider</strong> (GitHub, GitLab, Bitbucket), or <strong>Public Git Repository</strong> (used in this guide; ensure the repo is public).</li><li>Click <strong>“Connect”</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJdZO7o5q6SzN_RzmRuNpQ.png" /></figure><h3>Step 4: Configure Your Service</h3><ul><li>Fill in the required details (e.g., Name, Environment, Build Command, Start Command).</li><li>Choose the <strong>Free</strong> plan.</li><li>Click <strong>“Deploy Web Service”</strong>.</li></ul><h3>Step 5: Monitor Deployment</h3><ul><li>Go to the <strong>“Events”</strong> tab to view real-time deployment logs.</li><li>Once deployed successfully, you’ll see:<br> ✅ Your service is live 🎉</li></ul><h3>To edit details:</h3><p>Add your .env variables under the <strong>&quot;Environment&quot;</strong> tab in the left sidebar. To update previously entered settings, use the <strong>“Settings”</strong> tab.</p><h3>Debugging Common Errors</h3><h3>Error 1: Localhost Connection Refused</h3><p><strong>Error Message:</strong></p><pre>==&gt; Your service is live 🎉<br>message : MongooseServerSelectionError: connect ECONNREFUSED ::1:27017, connect ECONNREFUSED 127.0.0.1:27017</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPqS0d4X5i5fW9SHH3c_5w.png" /></figure><p><strong>Cause:</strong><br> Your backend is deployed on Render, but it’s trying to connect to MongoDB on localhost, which only works locally.</p><p><strong>Fix:</strong><br> Switch to a cloud-hosted database like <a href="https://www.mongodb.com/products/platform/atlas-database">MongoDB Atlas</a>.<br> Update your .env file with the <strong>cloud URI</strong> (e.g., mongodb+srv://...).</p><h3>Error 2: IP Not Whitelisted in Atlas</h3><p><strong>Error Message:</strong></p><pre>==&gt; Your service is live 🎉<br>message : MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you&#39;re trying to access the database from an IP that isn&#39;t whitelisted. Make sure your current IP address is on your Atlas cluster&#39;s IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOmP1iMTnpnxYz4PsA1NYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e70Ym4PEHTiYn9wZF9unxg.png" /></figure><p><strong>Cause:</strong><br> Your IP address is not whitelisted in MongoDB Atlas.</p><p><strong>Fix:</strong></p><ol><li>Log in to <a href="https://www.mongodb.com/cloud/atlas">MongoDB Atlas</a>.</li><li>Navigate to <strong>“Network Access”</strong> in the left sidebar.</li><li>Add your current IP address or allow access from all IPs (0.0.0.0/0) for development.</li></ol><p><em>Note: Atlas currently does not support IPv6 addresses in the whitelist.</em></p><h3>Final Notes</h3><ul><li>You can always revisit your Render service settings for changes or updates.</li><li>For security, avoid committing .env files to GitHub — use .gitignore.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b295039f4d52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use the YouTube API to Embed the Latest Video via Channel ID?]]></title>
            <link>https://medium.com/@EverusLainus/how-to-use-the-youtube-api-to-embed-the-latest-video-via-channel-id-1f41e04556fb?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f41e04556fb</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[youtube-api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[html5]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 12:51:52 GMT</pubDate>
            <atom:updated>2025-03-05T12:51:52.472Z</atom:updated>
            <content:encoded><![CDATA[<p>concise explanation of how to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Utpz4SpvAfF2Hdk" /><figcaption>Photo by <a href="https://unsplash.com/@collabstr?utm_source=medium&amp;utm_medium=referral">Collabstr</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>For example lets use this channel:</p><p><a href="https://www.youtube.com/@Dearlybethany">Dearly Bethany</a></p><p>To find the channel Id right click to find an option “<em>view page source</em>” — we can find this option in firefox, chrome and brave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSGhVvDz4KR3465dO3EVYg.png" /></figure><p>You get a raw code that the browser uses to render the webpage which looks as shown in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BlsjSzEGbGXLgOQCWQJatQ.png" /></figure><p>If the browser is Chrome or brave we get a option <strong>line wrap </strong>check it. Search for channel Id and copy its value. Every channel Id is a string of characters starting with “UC”. All the videos of the channel is listed in a playlist which has a playlist Id. The playlist Id for uploads is always the channel_id with “UU” subbed for “UC”.</p><blockquote>For more details read :</blockquote><blockquote><a href="https://youtube-data-api.readthedocs.io/en/latest/youtube_api.html">https://youtube-dataapi.readthedocs.io/en/latest/youtube_api.html</a></blockquote><p>In our example:</p><p>Channel Id : UC5Tmo6TCGnc9FioXnzzPJ5A</p><p>Playlist Id : UU5Tmo6TCGnc9FioXnzzPJ5A</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZXk9TLw9tmNFjStLUVvrfg.png" /></figure><p>For testing, we will create a basic HTML file.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;Embedding Latest Video&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;iframe<br>      src=&quot;https://www.youtube.com/embed?1istType=playlist&amp;list=UC5Tmo6TCGnc9FioXnzzPJ5A&quot;<br>    /&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The program uses the channel ID to retrieve the latest video and then embeds it into the web page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtKr9FpKNIexbRh4LhzBJw.png" /><figcaption>latest video as on 5 Mar 2025</figcaption></figure><pre>    &lt;iframe<br>      src=&quot;https://www.youtube.com/embed?1istType=playlist&amp;list=UU5Tmo6TCGnc9FioXnzzPJ5A&amp;index=2&quot;<br>    &gt;<br>    &lt;/iframe&gt;</pre><p>The aforementioned code yields the second most recent video upload. In a generalized context, an index of ‘k’ will retrieve the kth most recent video upload.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f41e04556fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A User Level Application to block packets that arrive at port 8080?]]></title>
            <link>https://medium.com/@EverusLainus/a-user-level-application-to-block-packets-that-arrive-at-port-8080-ca10da80b68c?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca10da80b68c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[packet-filtering-firewall]]></category>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[netfilter]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Sat, 09 Nov 2024 13:49:33 GMT</pubDate>
            <atom:updated>2024-11-09T13:49:33.315Z</atom:updated>
            <content:encoded><![CDATA[<h4>We will discuss its possibility in linux and macOS.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mJx1eCXi0JCTDYeG" /><figcaption>Photo by <a href="https://unsplash.com/@comparefibre?utm_source=medium&amp;utm_medium=referral">Compare Fibre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Linux</h3><p><strong>Netfilter</strong> is a powerful framework within the Linux kernel that allows you to inspect, modify, and filter network packets. It’s a crucial tool for implementing network security policies, network address translation (NAT), and other network-related functions.</p><p><strong>Key Components:</strong></p><p><strong>Hooks:</strong></p><p>Specific points in the packet processing pipeline where you can intervene. Common hooks include:</p><ul><li><strong>PREROUTING:</strong> Before routing decisions are made.</li><li><strong>INPUT:</strong> Before packets are delivered to local processes.</li><li><strong>FORWARD:</strong> Before packets are forwarded to another interface.</li><li><strong>OUTPUT:</strong> Before packets are sent out a local interface.</li><li><strong>POSTROUTING:</strong> After routing decisions are made.</li></ul><p><strong>Chains:</strong></p><p>A sequence of rules associated with a specific hook. Rules are evaluated in order until a match is found. Possible actions:</p><ul><li><strong>ACCEPT:</strong> Allow the packet.</li><li><strong>DROP:</strong> Discard the packet.</li><li><strong>REJECT:</strong> Send an error message to the sender.</li><li><strong>QUEUE:</strong> Pass the packet to user-space for further processing.</li></ul><p><strong>Tables:</strong></p><p>Collections of chains organized by purpose. Common tables include:</p><ul><li><strong>mangle:</strong> Modifies packet headers (e.g., QoS, TTL).</li><li><strong>nat:</strong> Performs NAT (e.g., changing source/destination IP/port).</li><li><strong>filter:</strong> Filters packets based on various criteria.</li><li><strong>raw:</strong> Used for connection tracking and stateful inspection.</li><li><strong>security:</strong> Enforces security policies.</li></ul><p><strong>Packet Flow:</strong></p><ol><li><strong>Packet Arrival:</strong> A packet arrives at a network interface.</li><li><strong>Hook Trigger:</strong> The appropriate hook is triggered.</li><li><strong>Table Selection:</strong> The packet is assigned to a specific table based on its characteristics and the desired action.</li><li><strong>Chain Execution:</strong> The packet traverses the chains within the selected table, with rules being evaluated in order.</li><li><strong>Action Execution:</strong> If a rule matches, the specified action is taken.</li><li><strong>Next Hook/Table:</strong> The packet may be passed to the next hook or table, depending on the action and the packet’s destination.</li></ol><p><strong>Example:</strong></p><p>To block incoming SSH traffic from a specific IP address:</p><ol><li><strong>Table:</strong> filter</li><li><strong>Chain:</strong> INPUT</li><li><strong>Rule:</strong></li></ol><pre>iptables -A INPUT -p tcp --dport 22 -s 192.168.1.100 -j DROP</pre><p>This rule will match any TCP packets destined for port 22 from the IP address 192.168.1.100 and drop them.</p><p>Using these hooks, developers can create custom rules to inspect, modify, or block packets at various stages. By writing code in user space or using tools like <strong>iptables</strong> or <strong>nftables</strong>, you can manage packet flow without needing kernel modifications.</p><h3>Kernel Code analysis of NF Hooks</h3><pre>//linux/blob/master/include/uapi/linux/netfilter.h<br><br>enum nf_inet_hooks {<br> NF_INET_PRE_ROUTING,<br> NF_INET_LOCAL_IN,<br> NF_INET_FORWARD,<br> NF_INET_LOCAL_OUT,<br> NF_INET_POST_ROUTING,<br> NF_INET_NUMHOOKS,<br> NF_INET_INGRESS = NF_INET_NUMHOOKS,<br>};</pre><p>To understand the code flow of these netfilter hooks in the kernel, let’s take a simple example of the <em>NF_INET_PRE_ROUTING</em> hook.</p><p>When an IPv4 packet is received, its handler function <em>ip_rcv</em> from net/ipv4/input.cis triggered as follows:</p><pre>/*<br> * IP receive entry point<br> */<br>int ip_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)<br>{<br> struct net *net = dev_net(dev);<br><br> skb = ip_rcv_core(skb, net);<br> if (skb == NULL)<br>  return NET_RX_DROP;<br><br> return NF_HOOK(NFPROTO_IPV4, NF_INET_PRE_ROUTING, net, NULL, skb, dev, NULL, ip_rcv_finish);<br>}</pre><p>In this handler function, you can see the hook is passed to the funciton <strong><em>NF_HOOK</em></strong> from `<em>include/linux/netfilter.h</em>`. Now this triggers hook functions attached to <strong><em>NF_INET_PRE_ROUTING</em></strong> and once they all are returned then <strong><em>ip_rcv_finish</em></strong> would be called, which is again an argument to the <strong><em>NF_HOOK</em></strong> callback.</p><pre>static inline int NF_HOOK(uint8_t pf, unsigned int hook, struct net *net, struct sock *sk, struct sk_buff *skb, struct net_device *in, struct net_device *out, int (*okfn)(struct net *, struct sock *, struct sk_buff *))<br>{<br>    int ret = nf_hook(pf, hook, net, sk, skb, in, out, okfn);<br>    if (ret == 1) {<br>        ret = okfn(net, sk, skb);<br>    }<br>    return ret;<br>}</pre><h3>macOS</h3><p>PF (Packet Filter) is a powerful firewall system that is included in macOS. It allows you to create detailed rules to control incoming and outgoing network traffic on your Mac. This can be useful for security, privacy, and network management purposes.</p><p>While macOS includes a built-in firewall that can be easily configured through System Preferences, PF offers more advanced customization options. By using the command-line tool `pfctl`, you can create complex rules to filter traffic based on various criteria, such as IP addresses, ports, protocols, and more.</p><p><strong>Key features of PF in macOS:</strong></p><p>- <strong>Packet filtering</strong>: You can define rules to allow or block specific types of traffic.<br>- <strong>Network Address Translation (NAT)</strong>: You can mask your IP address to hide your identity on the internet.<br>- <strong>Stateful inspection</strong>:PF can track the state of network connections to prevent unauthorized access.<br>- <strong>Performance optimization</strong>: PF is designed to be efficient and have minimal impact on system performance.</p><p>While ‘<strong>pf’</strong> isn’t as flexible for user-level applications as `<strong>iptables</strong>`, you can still write user-space firewall applications on macOS by:</p><p><strong>Using `libpcap` to Capture and Not Forward the Packet</strong></p><p>While you can’t prevent the kernel from processing the packet directly using `<strong>libpcap</strong>`, you can use `<strong>libpcap</strong>` to capture and log packets.</p><pre>/* Program to capture and log incomming packet details */<br>#include &lt;pcap.h&gt;<br>#include &lt;libnet.h&gt;<br>#include &lt;stdio.h&gt;<br>#include &lt;stdlib.h&gt;<br>#include &lt;string.h&gt;<br>#include &lt;arpa/inet.h&gt;<br><br><br>void packet_handler(u_char *user_data, const struct pcap_pkthdr *pkthdr, const u_char *packet) {<br>    struct libnet_ipv4_hdr *ip;<br>    struct libnet_tcp_hdr *tcp;<br><br><br>    ip = (struct libnet_ipv4_hdr *)(packet + 14);<br><br>    if (ip-&gt;ip_p == IPPROTO_TCP) {<br>        tcp = (struct libnet_tcp_hdr *)(packet + 14 + (ip-&gt;ip_hl * 4));<br>        <br><br>        printf(&quot;Captured TCP packet:\n&quot;);<br>        printf(&quot;Source IP: %s\n&quot;, inet_ntoa(ip-&gt;ip_src));<br>        printf(&quot;Destination IP: %s\n&quot;, inet_ntoa(ip-&gt;ip_dst));<br>        printf(&quot;Source port: %d\n&quot;, ntohs(tcp-&gt;th_sport));<br>        printf(&quot;Destination port: %d\n&quot;, ntohs(tcp-&gt;th_dport));<br>        printf(&quot;------------------------------------------------\n&quot;);<br><br>        // Check if the destination port is 8080<br>        if (ntohs(tcp-&gt;th_dport) == 8080) {             <br>            printf(&quot;Dropping packet arriving at port 8080\n&quot;);<br>            return;  // Simulate dropping the packet by simply returning<br>        }<br>    }<br>}<br><br>int main(int argc, char *argv[]) {<br>    char *dev;<br>    char errbuf[PCAP_ERRBUF_SIZE];<br>    pcap_t *handle;<br>    struct bpf_program fp;<br>    char filter_exp[] = &quot;tcp&quot;; // Filter expression for capturing only TCP packets<br>    bpf_u_int32 net;<br><br>    if (argc != 2) {<br>        fprintf(stderr, &quot;Usage: %s &lt;interface&gt;\n&quot;, argv[0]);<br>        return 1;<br>    }<br>    dev = argv[1];<br><br>  <br>    handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);<br>    if (handle == NULL) {<br>        fprintf(stderr, &quot;Couldn&#39;t open device %s: %s\n&quot;, dev, errbuf);<br>        return 2;<br>    }<br><br>    if (pcap_compile(handle, &amp;fp, filter_exp, 0, net) == -1) {<br>        fprintf(stderr, &quot;Couldn&#39;t parse filter %s: %s\n&quot;, filter_exp, pcap_geterr(handle));<br>        return 2;<br>    }<br>    if (pcap_setfilter(handle, &amp;fp) == -1) {<br>        fprintf(stderr, &quot;Couldn&#39;t install filter %s: %s\n&quot;, filter_exp, pcap_geterr(handle));<br>        return 2;<br>    }<br><br>   <br>    pcap_loop(handle, 0, packet_handler, NULL);<br><br>    pcap_freecode(&amp;fp);<br>    pcap_close(handle);<br><br>    return 0;<br>}</pre><p><strong>Using `libnet` to Inject Packets</strong></p><p>If you want to craft and inject your own packets, or modify the contents of packets as they pass through, you can use `libnet` to do that.</p><h3><strong>In summary:</strong></h3><ul><li><strong>iptables</strong>: You can dynamically modify rules at user-level and create user-space applications to interact with the firewall (e.g., build a firewall using `libpcap` and dynamically change `iptables` rules).<br>- <strong>pf</strong>: It is primarily a kernel-level tool on macOS, and while you can configure it, it’s not as flexible for real-time rule changes from user-space applications. You would typically edit the `pf.conf` configuration file and reload it using `pfctl`.</li></ul><p><strong>Reference</strong></p><ul><li><a href="https://blogs.oracle.com/linux/post/introduction-to-netfilter">https://blogs.oracle.com/linux/post/introduction-to-netfilter</a></li><li><a href="https://www.youtube.com/watch?v=vKbjhU--Lok">https://www.youtube.com/watch?v=vKbjhU--Lok</a></li><li><a href="https://www.youtube.com/watch?v=2axv4JeSNPE">https://www.youtube.com/watch?v=2axv4JeSNPE</a></li><li><a href="https://thermalcircle.de/doku.php?id=blog:linux:nftables_packet_flow_netfilter_hooks_detail">https://thermalcircle.de/doku.php?id=blog:linux:nftables_packet_flow_netfilter_hooks_detail</a></li><li><a href="https://organicprogrammer.com/2022/05/04/how-to-write-a-netfilter-firewall-part1/">https://organicprogrammer.com/2022/05/04/how-to-write-a-netfilter-firewall-part1/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca10da80b68c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens After a Packet Arrives?]]></title>
            <link>https://medium.com/@EverusLainus/what-happens-after-a-packet-arrives-c9d1dc17199f?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9d1dc17199f</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[osi-model]]></category>
            <category><![CDATA[computer-networking]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[network-interface-card]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 09:56:48 GMT</pubDate>
            <atom:updated>2024-10-25T09:56:48.488Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Detailed Examination of the e1000’s Packet Processing Pipeline.</h4><p>The e1000 is a popular Ethernet network interface controller (NIC) manufactured by Intel. It’s widely used in various devices due to its reliability, performance, and compatibility. However, it’s not the only available NIC on the market. There are some other common network interfaces like Broadcom BCM5708, Intel Wi-Fi 6E, e.t.c.<br>e1000 is a Intel 82540-based Ethernet controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W5QBTEJ-2tusp8Vz" /><figcaption>Photo by <a href="https://unsplash.com/@comparefibre?utm_source=medium&amp;utm_medium=referral">Compare Fibre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><ol><li><strong>Driver Initialization and MAC Address Setup</strong><br>- When the e1000 driver is loaded (typically in the probe function like <strong>e1000_probe()</strong> located in <em>drivers/net/ethernet/intel/e1000/e1000_main.c</em> ), it performs initialization tasks.<br>- The driver reads the MAC address from the NIC’s <strong>EEPROM</strong> (as is typical for the e1000 NIC) using a function like <strong>e1000_read_mac_addr()</strong> from <em>drivers/net/ethernet/intel/e1000/e1000_hw.c</em>, which retrieves the configured MAC address from the NIC’s EEPROM.</li></ol><pre> /**<br> * e1000_read_mac_addr - read the adapters MAC from eeprom<br> * @hw: Struct containing variables accessed by shared code<br> *<br> * Reads the adapter&#39;s MAC address from the EEPROM and inverts the LSB for the<br> * second function of dual function devices<br> */<br>s32 e1000_read_mac_addr(struct e1000_hw *hw)<br>{<br> u16 offset;<br> u16 eeprom_data, i;<br><br> for (i = 0; i &lt; NODE_ADDRESS_SIZE; i += 2) {<br>  offset = i &gt;&gt; 1;<br>  if (e1000_read_eeprom(hw, offset, 1, &amp;eeprom_data) &lt; 0) {<br>   e_dbg(&quot;EEPROM Read Error\n&quot;);<br>   return -E1000_ERR_EEPROM;<br>  }<br>  hw-&gt;perm_mac_addr[i] = (u8)(eeprom_data &amp; 0x00FF);<br>  hw-&gt;perm_mac_addr[i + 1] = (u8)(eeprom_data &gt;&gt; 8);<br> }<br><br> switch (hw-&gt;mac_type) {<br> default:<br>  break;<br> case e1000_82546:<br> case e1000_82546_rev_3:<br>  if (er32(STATUS) &amp; E1000_STATUS_FUNC_1)<br>   hw-&gt;perm_mac_addr[5] ^= 0x01;<br>  break;<br> }<br><br> for (i = 0; i &lt; NODE_ADDRESS_SIZE; i++)<br>  hw-&gt;mac_addr[i] = hw-&gt;perm_mac_addr[i];<br> return E1000_SUCCESS;<br>}</pre><p>Once the MAC address is read, it is stored in the <strong>net_device</strong> structure’s <strong>dev-&gt;dev_addr</strong> field from<em> /include/linux/netdevice.h</em>, which holds the MAC address for the interface.<br>The MAC address is then programmed into the NIC hardware’s Receive Address (RA) registers. This is done using function <strong>e1000_rar_set().</strong> This function writes the MAC address to specific registers:<br> <strong>E1000_RAH</strong> (Receive Address High) and structure’s dev-&gt;dev_addr field(Receive Address Low) are hardware registers that store the NIC’s MAC address in two parts (high and low). The MAC address is split and written into these registers.</p><pre>/**<br> * e1000_rar_set - Puts an ethernet address into a receive address register.<br> * @hw: Struct containing variables accessed by shared code<br> * @addr: Address to put into receive address register<br> * @index: Receive address register to write<br> */<br>void e1000_rar_set(struct e1000_hw *hw, u8 *addr, u32 index)<br>{<br> u32 rar_low, rar_high;<br><br> /* HW expects these in little endian so we reverse the byte order<br>  * from network order (big endian) to little endian<br>  */<br> rar_low = ((u32)addr[0] | ((u32)addr[1] &lt;&lt; 8) |<br>     ((u32)addr[2] &lt;&lt; 16) | ((u32)addr[3] &lt;&lt; 24));<br> rar_high = ((u32)addr[4] | ((u32)addr[5] &lt;&lt; 8));<br><br> /* Disable Rx and flush all Rx frames before enabling RSS to avoid Rx<br>  * unit hang.<br>  *<br>  * Description:<br>  * If there are any Rx frames queued up or otherwise present in the HW<br>  * before RSS is enabled, and then we enable RSS, the HW Rx unit will<br>  * hang.  To work around this issue, we have to disable receives and<br>  * flush out all Rx frames before we enable RSS. To do so, we modify we<br>  * redirect all Rx traffic to manageability and then reset the HW.<br>  * This flushes away Rx frames, and (since the redirections to<br>  * manageability persists across resets) keeps new ones from coming in<br>  * while we work.  Then, we clear the Address Valid AV bit for all MAC<br>  * addresses and undo the re-direction to manageability.<br>  * Now, frames are coming in again, but the MAC won&#39;t accept them, so<br>  * far so good.  We now proceed to initialize RSS (if necessary) and<br>  * configure the Rx unit.  Last, we re-enable the AV bits and continue<br>  * on our merry way.<br>  */<br> switch (hw-&gt;mac_type) {<br> default:<br>  /* Indicate to hardware the Address is Valid. */<br>  rar_high |= E1000_RAH_AV;<br>  break;<br> }<br><br> E1000_WRITE_REG_ARRAY(hw, RA, (index &lt;&lt; 1), rar_low);<br> E1000_WRITE_FLUSH();<br> E1000_WRITE_REG_ARRAY(hw, RA, ((index &lt;&lt; 1) + 1), rar_high);<br> E1000_WRITE_FLUSH();<br>}</pre><p><strong>2. Multicast Table Configuration</strong><br> — For multicast filtering, the driver configure the NIC’s multicast hash filter table. This is done by writing to the <strong>Multicast Table Array</strong> (MTA) registers.<br> — The MTA registers maintain a hash-based table that allows the NIC to efficiently filter multicast addresses. If the incoming packet’s multicast address matches any address in this hash table, the packet is accepted.<br> — The driver uses specific functions to compute the hash for multicast addresses and update the MTA registers.</p><p><strong>3. Receive Packet Filtering by Hardware</strong><br> Once the driver has completed initialization and the MAC address is configured in the NIC’s registers, the e1000 hardware is responsible for filtering incoming packets:<br> <br><strong>Unicast Filtering</strong>: <br> The NIC compares the destination MAC address of each incoming packet with the configured MAC address in the RA registers (RAH and RAL). If the MAC address in the packet matches the one stored in the RA registers, the packet is accepted and passed to the driver for further processing. If there is no match, the packet is dropped (unless it’s a broadcast or multicast packet).<br> <br><strong>Multicast Filtering</strong>: <br> The NIC compares the multicast MAC address of the incoming packet with the entries in the multicast hash filter (which has been configured via the MTA registers). If there is a match in the multicast table, the packet is accepted.<br> <br><strong>Broadcast Packets</strong>: <br> Packets with a broadcast MAC address (FF:FF:FF:FF:FF:FF) are automatically accepted by the NIC, as they are intended for all devices on the network.</p><p><strong>4. Interrupt and Packet Handling</strong><br> <br>Once a packet passes through the filtering stage, e1000 Ethernet network interface controller (NIC), sends an <strong>interrupt signal</strong> to the CPU.<br>The interrupt controller, which is the hardware component responsible for managing interrupts, invokes the corresponding interrupt handler function. In this case, the <strong>e1000_intr()</strong> function is the handler for the e1000 network interface. This function reads packets from the receive ring buffer and passes them up the network stack.</p><ul><li><strong>e1000_intr(int irq, void *data)</strong> from <em>e1000_main.c</em> is called. Once the function has completed these tasks, it returns an <em>irqreturn_t</em> value to the interrupt controller. This value indicates whether the interrupt has been handled successfully or whether further processing is required.</li><li>The receive queue is then processed by a separate task or thread, which calls the <strong>netif_receive_skb()</strong> function to handle the packet</li></ul><pre>/**<br> * netif_receive_skb - process receive buffer from network<br> * @skb: buffer to process<br> *<br> * netif_receive_skb() is the main receive data processing function.<br> * It always succeeds. The buffer may be dropped during processing<br> * for congestion control or by the protocol layers.<br> *<br> * This function may only be called from softirq context and interrupts<br> * should be enabled.<br> *<br> * Return values (usually ignored):<br> * NET_RX_SUCCESS: no congestion<br> * NET_RX_DROP: packet was dropped<br> */<br>int netif_receive_skb(struct sk_buff *skb)<br>{<br> int ret;<br><br> trace_netif_receive_skb_entry(skb);<br><br> ret = netif_receive_skb_internal(skb);<br> trace_netif_receive_skb_exit(ret);<br><br> return ret;<br>}</pre><p>-<strong> netif_receive_skb()</strong> is the entry point for handling incoming network packets, regardless of the protocol.<br>- For IPv4 packets, <strong>netif_receive_skb()</strong> calls <strong>ip_rcv()</strong> to perform the specific processing required for IPv4 packets. The <strong>ip_rcv()</strong> is responsible for handling the IP-specific tasks, such as decapsulation, routing, and passing the packet to the transport layer.</p><pre>/*<br> * IP receive entry point<br> */<br>int ip_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt,<br>    struct net_device *orig_dev)<br>{<br> struct net *net = dev_net(dev);<br><br> skb = ip_rcv_core(skb, net);<br> if (skb == NULL)<br>  return NET_RX_DROP;<br><br> return NF_HOOK(NFPROTO_IPV4, NF_INET_PRE_ROUTING,<br>         net, NULL, skb, dev, NULL,<br>         ip_rcv_finish);<br>}</pre><p>The <strong>ip_rcv()</strong> function, after determining that the packet is a TCP packet, calls the <strong>tcp_v4_rcv()</strong> function from <em>/net/ipv4/tcp_ipv4.c</em> to handle TCP-specific processing.</p><p>The <strong>tcp_v4_rcv()</strong> function uses <strong>__inet_lookup_skb()</strong> from <em>/net/inet_hashtables.h</em> to search for an existing TCP connection associated with the incoming packet’s source and destination addresses and port numbers.</p><pre>static inline struct sock *__inet_lookup_skb(struct inet_hashinfo *hashinfo,<br>          struct sk_buff *skb,<br>          int doff,<br>          const __be16 sport,<br>          const __be16 dport,<br>          const int sdif,<br>          bool *refcounted)<br>{<br> struct net *net = dev_net(skb_dst(skb)-&gt;dev);<br> const struct iphdr *iph = ip_hdr(skb);<br> struct sock *sk;<br><br> sk = inet_steal_sock(net, skb, doff, iph-&gt;saddr, sport, iph-&gt;daddr, dport,<br>        refcounted, inet_ehashfn);<br> if (IS_ERR(sk))<br>  return NULL;<br> if (sk)<br>  return sk;<br><br> return __inet_lookup(net, hashinfo, skb,<br>        doff, iph-&gt;saddr, sport,<br>        iph-&gt;daddr, dport, inet_iif(skb), sdif,<br>        refcounted);<br>}</pre><p><strong>__inet_lookup_skb()</strong> returns the socket or creates a new one: If a matching connection is found, the function returns the associated socket. If no connection exists, a new socket is created and initialized.</p><p><strong>tcp_v4_rcv()</strong> calls <strong>sock_queue_rcv_skb()</strong>: The tcp_v4_rcv() function passes the socket and the <em>skb</em> object to the <strong>sock_queue_rcv_skb()</strong> function.</p><pre>static inline int sock_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)<br>{<br> return sock_queue_rcv_skb_reason(sk, skb, NULL);<br>}</pre><p>The <strong>sock_queue_rcv_skb()</strong> from <em>/net/sock.h</em> function queues the <em>skb</em> object into the socket’s receive queue. This queue is used to store incoming packets until they can be processed by the application.</p><p>If the application calls the <strong>read()</strong> system call on the accepted socket, the kernel checks the socket buffer associated with the accepted socket for any incoming data. If data is found, the kernel copies the data from the socket buffer to the specified user-space buffer. The kernel returns the number of bytes read to the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9d1dc17199f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement Stack using Queue]]></title>
            <link>https://medium.com/@EverusLainus/implement-stack-using-queue-36f8cadc30f5?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/36f8cadc30f5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Fri, 06 Sep 2024 01:31:53 GMT</pubDate>
            <atom:updated>2024-09-06T01:31:53.631Z</atom:updated>
            <content:encoded><![CDATA[<h4>Naive to Optimised approaches to implement Stack using Queue.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o-LJNgITcPveQ-4G" /><figcaption>Photo by <a href="https://unsplash.com/@kimberlyfarmer?utm_source=medium&amp;utm_medium=referral">Kimberly Farmer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Problem Statement:</strong></h3><p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, pop and peek).</p><p>Implement the MyStack class:</p><ul><li>void push(int x) Pushes element x to the top of the stack.</li><li>int pop() Removes the element on the top of the stack and returns it.</li><li>int top() Returns the element on the top of the stack.</li></ul><p><a href="https://leetcode.com/problems/implement-stack-using-queues/">Implement Stack using Queues</a></p><h3><strong>Approach:</strong></h3><p>In the push() method, we can have two queues — queue1 and queue2. To push an element to stack, we add it to the empty queue2 .Then remove all the elements of queue1 and add it to queue2. Swap the two queues. This way the elements in the queue1 are arranged in an order such that the adding and removing elements from queue1 acts as adding and removing elements from stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*qMSnMr-5LJsqaJD-782IFw.jpeg" /></figure><pre>If the element to push to stack in order are [1, 2, 3, 4, 5]<br><br>- add 1 to q2: so q2 = [1]<br>- swap q1 and q2: so q2 = [1] and q1=[]<br><br>- add 2 to q2:q2 = [2]<br>- add elts of q1 to q2.<br>- swap q1 and q2: so q1=[2, 1]<br><br>- add 3 to q2:q2 = [3]<br>- add elts of q1 to q2.<br>- swap q1 and q2: so q1=[3, 2, 1]<br><br>- add 4 to q2:q2 = [4]<br>- add elts of q1 to q2.<br>- swap q1 and q2: so q1=[4, 3, 2, 1]<br><br>- add 5 to q2:q2 = [5]<br>- add elts of q1 to q2.<br>- swap q1 and q2: so q1=[5, 4, 3, 2, 1]</pre><p>Time complexity of Push() operation is O(n), of pop() and peek() is O(1). Space Complexity is O(n).</p><pre>  Queue&lt;Integer&gt; queue1 = new LinkedList&lt;&gt;();<br>  Queue&lt;Integer&gt; queue2 = new LinkedList&lt;&gt;();<br>  <br>  Queue&lt;Integer&gt; temp = new LinkedList&lt;&gt;();<br>  <br>  public void push(int data){<br><br>    queue2.add(data);<br>    while(!queue1.isEmpty()){<br>        queue2.add(queue1.remove());<br>    }<br><br>    temp = queue1;<br>    queue1=queue2;<br>    queue2 = temp;<br>  }<br>  <br>  public void pop(){   <br>    queue1.remove();<br>  }<br>  <br>  public int top(){    <br>    return queue1.peek();<br>  }</pre><p>In the above approach we use two queues, we can use a single approach to simulate the same process. Find the size of the queue, add the new element to the queue, remove all the element in the queue till the size previously calculated and add it to that queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*g9fzFNqdmCelIenWy4kIXA.jpeg" /></figure><p>Time complexity of Push() operation is O(n) and pop() and peek() is O(1). Space Complexity is O(n).</p><pre>  Queue&lt;Integer&gt; queue = new LinkedList&lt;&gt;();<br>  <br>  public void push(int data){<br>    int n = queue.size();<br><br>    queue.add(data);<br><br>    for(int i=0; i&lt;n; i++){<br>      queue.add(queue1.remove);<br>    }<br>  }<br>  <br>  public void pop(){<br>    queue.remove();<br>  }<br>  <br>  public int top(){   <br>    return queue.peek();<br>  }</pre><p>For any queries and suggestions please leave a reply.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36f8cadc30f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find the Student that will Replace the Chalk]]></title>
            <link>https://medium.com/@EverusLainus/find-the-student-that-will-replace-the-chalk-531b349cf0f5?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/531b349cf0f5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[leetcode-easy]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 01:31:23 GMT</pubDate>
            <atom:updated>2024-09-04T01:31:23.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discussing a LeetCode Easy problem.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dEEyNhMlrdrWPZ4b" /><figcaption>Photo by <a href="https://unsplash.com/@miloslopusina?utm_source=medium&amp;utm_medium=referral">Milos Lopusina</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Problem Statement:</strong></h3><p>There are n students in a class numbered from 0 to n - 1. The teacher will give each student a problem starting with the student number 0, then the student number 1, and so on until the teacher reaches the student number n - 1. After that, the teacher will restart the process, starting with the student number 0 again.</p><p>You are given a <strong>0-indexed</strong> integer array chalk and an integer k. There are initially k pieces of chalk. When the student number i is given a problem to solve, they will use chalk[i] pieces of chalk to solve that problem. However, if the current number of chalk pieces is <strong>strictly less</strong> than chalk[i], then the student number i will be asked to <strong>replace</strong> the chalk.</p><p>Return <em>the </em><strong><em>index</em></strong><em> of the student that will </em><strong><em>replace</em></strong><em> the chalk pieces</em>.</p><p><a href="https://leetcode.com/problems/find-the-student-that-will-replace-the-chalk/">Find the Student that Will Replace the Chalk</a></p><h4><strong>Approach:</strong></h4><p>My first intuition is to simulate the natural way of find the answer by going through each index and decrementing values from k.</p><pre><br>    public int chalkReplacer(int[] chalk, int k) {<br>        int n = chalk.length;<br>        int cur = k;<br>        int res = -1;<br>        int i=0;<br>        while(chalk[i%n] &lt;= k){<br>          //  System.out.println((i%n) +&quot; &quot;+k);         <br>            k -= chalk[i%n];<br>            i++;  <br>        }<br>        return (i%n);<br>    }</pre><p>One worst cast of this approach would be if k is 1 and all the values in chalk array is one. In this case the while loop runs O(k) times. Time complexity is O(k) and space complexity is O(1).</p><p>Note that the result depends upon the final iteration through the array where the value is greater than remaining value of k. In each iteration through the array once, we reduce sum of elements of array times of k. So we could figure out the value of k at the final iteration through array as k %(sum of elements of array). Using this idea:</p><pre>    public int chalkReplacer(int[] chalk, int k) {<br>        int n = chalk.length;<br>        long totalChalk = 0;<br>        for(int x : chalk){<br>            totalChalk += x;<br>        }<br>        totalChalk = (int ) k% totalChalk;<br><br>        int res = -1;<br>        <br>        for(int i=0; i&lt;n; i++){<br>            //System.out.println(i+&quot; &quot;+k);<br>            if(chalk[i] &gt; totalChalk){<br>                res = i;<br>                break;<br><br>            }<br>            totalChalk -= chalk[i];            <br>        }<br>        return res;<br>    }</pre><p>Time complexity of this approach is O(n) and Space complexity is O(1).</p><p>For suggessions and comments, please leave a reply.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=531b349cf0f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a User-Specific Cart Page in React]]></title>
            <link>https://medium.com/@EverusLainus/building-a-user-specific-cart-page-in-react-8cf9d8bad205?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cf9d8bad205</guid>
            <category><![CDATA[e-commerce-website]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 18:17:09 GMT</pubDate>
            <atom:updated>2024-09-01T18:23:32.746Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating a Dynamic Shopping Experience with Firebase and Chakra UI</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SumEWFQx6Vtg8vVn" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=medium&amp;utm_medium=referral">Campaign Creators</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In today’s e-commerce landscape, delivering a seamless and dynamic shopping experience is essential. This article will walk you through the creation of a user-specific cart page using React, Firebase, and Chakra UI. The provided code snippet demonstrates how to fetch user-specific cart data from Firebase, display it in a visually appealing layout, and allow users to adjust item quantities or remove items. Let’s break down the core features of the code and understand how it works.</p><h3>Core Features of the User-Specific Cart Page</h3><ol><li><strong>Fetching User Data from Local Storage</strong>: The component begins by retrieving the currently logged-in user’s ID from the browser’s local storage. This user ID is crucial for fetching the corresponding cart data from Firebase.</li></ol><pre>useEffect(() =&gt; {<br>  const storedUser = JSON.parse(localStorage.getItem(&quot;currloginuser&quot;));<br>  if (storedUser &amp;&amp; storedUser[0]) {<br>    setUserId(storedUser[0][0]);<br>  }<br>}, []);</pre><pre>// endponts<br><br>- user<br>    - userId1<br>        - emailId<br>        - userName<br>        - cart<br>            - cart-item-1<br>            - cart-item-2<br>.....</pre><p>2. <strong>Retrieving Cart Items from Firebase</strong>: Once the user ID is obtained, the component makes an API call to Firebase to fetch the user’s cart items. The retrieved data is stored in the cartItems state.</p><pre>useEffect(() =&gt; {<br>  if (!userId) return;<br><br>  const firebaseUrl = `https://name.firebasedatabase.app/user/${userId}/cart.json`;<br><br>  axios<br>    .get(firebaseUrl)<br>    .then((response) =&gt; {<br>      console.log(&quot;Retrieved data from Firebase:&quot;, response.data);<br>      setCartItems(response.data || []);<br>    })<br>    .catch((error) =&gt; {<br>      console.error(&quot;Error fetching data from Firebase:&quot;, error);<br>    });<br>}, [userId]);</pre><p>3. <strong>Calculating the Total Cost</strong>: The total cost of the cart is computed whenever the cartItems state changes. This calculation multiplies the price of each item by its quantity and sums up the results.</p><pre>useEffect(() =&gt; {<br>  const totalSum = cartItems.reduce(<br>    (sum, item) =&gt; sum + item.price * item.quantity,<br>    0<br>  );<br>  setTotal(totalSum);<br>}, [cartItems]);</pre><p>4. <strong>Updating Item Quantities</strong>: The handleQuantityChange function allows users to increase or decrease the quantity of a specific item in their cart. The updated cart data is then sent back to Firebase to keep the backend in sync.</p><pre>const handleQuantityChange = (index, change) =&gt; {<br>  const updatedItems = [...cartItems];<br>  updatedItems[index].quantity = Math.max(<br>    1,<br>    updatedItems[index].quantity + change<br>  );<br>  setCartItems(updatedItems);<br><br>  if (userId) {<br>    axios<br>      .patch(<br>        `https://name.firebasedatabase.app/user/${userId}.json`,<br>        { cart: updatedItems }<br>      )<br>      .then((response) =&gt; {<br>        console.log(&quot;Cart updated in Firebase:&quot;, response.data);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&quot;Error updating cart in Firebase:&quot;, error);<br>      });<br>  }<br>};</pre><p>5. <strong>Removing Items from the Cart</strong>: Users can also remove items from their cart using the handleRemoveFromCart function. Similar to quantity updates, this function modifies the local state and sends the updated cart data to Firebase.</p><pre>const handleRemoveFromCart = (index) =&gt; {<br>  const updatedItems = [...cartItems];<br>  updatedItems.splice(index, 1);<br>  setCartItems(updatedItems);<br><br>  if (userId) {<br>    axios<br>      .patch(<br>        `https://name.firebasedatabase.app/user/${userId}.json`,<br>        { cart: updatedItems }<br>      )<br>      .then((response) =&gt; {<br>        console.log(&quot;Cart updated in Firebase:&quot;, response.data);<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&quot;Error updating cart in Firebase:&quot;, error);<br>      });<br>  }<br>};</pre><p><strong>6. Displaying the Cart</strong>: The component renders the cart items dynamically using Chakra UI components, providing a clean and responsive design. Each cart item displays its image, name, price, and quantity, along with buttons to adjust the quantity or remove the item.</p><pre>return (<br>  &lt;Box w=&quot;100%&quot; className=&quot;backgroundchange&quot;&gt;<br>    &lt;Box<br>      padding=&quot;0px 30px&quot;<br>      backgroundColor=&quot;#303030&quot;<br>      maxWidth=&quot;1360px&quot;<br>      margin=&quot;0 auto&quot;<br>      borderRadius=&quot;md&quot;<br>    &gt;<br>      &lt;Heading mb={6} color=&quot;white&quot; textAlign=&quot;center&quot;&gt;<br>        Your Cart<br>      &lt;/Heading&gt;<br>      {cartItems != null &amp;&amp; cartItems.length &gt; 0 ? (<br>        &lt;Flex direction={{ base: &quot;column&quot;, lg: &quot;row&quot; }} gap=&quot;10px&quot;&gt;<br>          {/* Cart Items and Checkout Card Rendering */}<br>        &lt;/Flex&gt;<br>      ) : (<br>        &lt;Text color=&quot;white&quot; textAlign=&quot;center&quot;&gt;<br>          Your cart is empty<br>        &lt;/Text&gt;<br>      )}<br>    &lt;/Box&gt;<br>  &lt;/Box&gt;<br>);</pre><h3>Conclusion</h3><p>By combining React’s state management with Firebase’s real-time database and the aesthetic appeal of Chakra UI, this code creates a robust and user-friendly cart page. The dynamic fetching and updating of user-specific data ensure a personalized shopping experience that enhances user engagement. This approach not only demonstrates how to manage user data effectively but also highlights the importance of creating a responsive and interactive user interface in modern web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cf9d8bad205" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI Chatbot]]></title>
            <link>https://medium.com/@EverusLainus/building-an-ai-chatbot-57035fcf1cb4?source=rss-32d7c7458778------2</link>
            <guid isPermaLink="false">https://medium.com/p/57035fcf1cb4</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-libraries]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[google-gemini-api]]></category>
            <category><![CDATA[chatbot-development]]></category>
            <dc:creator><![CDATA[Everus Lainus]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 10:30:26 GMT</pubDate>
            <atom:updated>2025-11-10T09:28:43.388Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using React, Vite and the Gemini API</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BApVKDVKn4_2bQN7" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To create a react + vite application named chatBot.</p><pre>npm create vite@latest chatBot - - template react</pre><p>Navigate to <em>App.jsx</em>. Remove the contents such that it looks like</p><pre>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;chatbot&lt;/h1&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>run $npm run dev</pre><p>You would see something like this in Live server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B2UP1S2xEQxBI4Fx6cBY6w.png" /></figure><p>We use @chatscope/chat-ui-kit-react library to develop out chat box. The Chat UI Kit from chatscope is an open source UI toolkit for developing web chat applications. Read about its usage from:</p><p><a href="https://www.npmjs.com/package/@chatscope/chat-ui-kit-react">https://www.npmjs.com/package/@chatscope/chat-ui-kit-react</a></p><p>Install it using:</p><pre>npm i @chatscope/chat-ui-kit-react</pre><p>Create a file named “Chatbot.jsx” with a component called Chatbot.</p><p>Copy the usage code from @chatscope/chat-ui-kit-react doc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUPXoQGQ75bDiru_DLWCDw.png" /></figure><p>Import CharBot and Chatbot component to the Application:</p><pre>import { ChatBot } from &quot;./Chatbot&quot;;<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;chatbot&lt;/h1&gt;<br>      &lt;ChatBot /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>UI would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMmjRRCYEaeuQX93fEkfxg.png" /></figure><p>We create a array of message add render then in ChatContainer using map method:</p><pre>import &quot;@chatscope/chat-ui-kit-styles/dist/default/styles.min.css&quot;;<br>import {<br>  MainContainer,<br>  ChatContainer,<br>  MessageList,<br>  Message,<br>  MessageInput,<br>} from &quot;@chatscope/chat-ui-kit-react&quot;;<br><br>export const ChatBot = () =&gt; {<br>  const chatHistory = [<br>    &quot;hi&quot;,<br>    &quot;hi&quot;,<br>    &quot;how are you&quot;,<br>    &quot;i am fine, thanks. How you doing&quot;,<br>    &quot;im doing great.&quot;,<br>  ];<br>  return (<br>    &lt;div style={{ position: &quot;relative&quot;, height: &quot;500px&quot; }}&gt;<br>      &lt;MainContainer&gt;<br>        &lt;ChatContainer&gt;<br>          &lt;MessageList&gt;<br>            {chatHistory.map((elt, i) =&gt; (<br>              &lt;Message<br>                key={i}<br>                model={{<br>                  message: elt,<br>                  sentTime: &quot;just now&quot;,<br>                  sender: &quot;Joe&quot;,<br>                }}<br>              /&gt;<br>            ))}<br>          &lt;/MessageList&gt;<br>          &lt;MessageInput placeholder=&quot;Type message here&quot; /&gt;<br>        &lt;/ChatContainer&gt;<br>      &lt;/MainContainer&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>UI would look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwGX0K--GMOCW10zlhyzPQ.png" /></figure><p>Model also takes a property “direction” which has two values “outgoing” and “incoming”, to decide if the messages are aligned to right side of container or left side of container.</p><p>Because we have to place messages right side and left side alternatively. To distinguish between if it is the message that comes from AI or user. We use objects with two fields — one containing message and another details of who sends it.</p><p>Use onChange property in MessageInput element to get the input from the user and handle is using “handleUserInput” and store in is “userInput”.</p><p>Use onSend property to handle send event.</p><p>We can use a state to keep tract of chat history (say chatHistory). Now we have done with the basic setup for the chat box. We have to integrate AI.</p><p>To use Google’s AI. Read the doc <a href="https://ai.google.dev/gemini-api/docs">https://ai.google.dev/gemini-api/docs</a>. Click on getting started and choose Node.js, since we are using React.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRRjLL-XA5Q39bmyxJasEw.png" /></figure><p>Instal @google/generative-ai:</p><pre>npm install @google/generative-ai<br></pre><p><a href="https://ai.google.dev/gemini-api/docs/api-key">Using Gemini API keys | Google AI for Developers</a></p><p>On the about page, click on <strong>get an API key.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uliv2I4B3b1VzqD5uZiVnA.png" /></figure><p>Then click of <strong>create API key.</strong></p><p>Store the API key in .env file and add the file to .gitignore.</p><pre>//.env file<br>export VITE_API_KEY = &lt;YOUR_API_KEY&gt;</pre><p>Here’s is documentation on how to use it:</p><p><a href="https://ai.google.dev/gemini-api/docs/quickstart?lang=node">Gemini API quickstart | Google for Developers</a></p><p>Import and intitialise GeoogleDenrat use</p><pre>import { GoogleGenerativeAI } from &quot;@google/generative-ai&quot;;<br><br>// Access your API key as an environment variable (see &quot;Set up your API key&quot; above)<br>const genAI = new GoogleGenerativeAI(process.env.API_KEY);<br><br>const model = genAI.getGenerativeModel({ model: &quot;gemini-1.5-flash&quot;});</pre><p>To use it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FGt6Wh2bo_q4M_qRpStTQ.png" /></figure><pre>  const sendMessage = async (messageText) =&gt; {<br>    if (messageText.trim() === &quot;&quot;) return;<br><br>    try {<br>      const prompt = messageText;<br>      const result = await model.generateContent(prompt);<br>      const response = result.response;<br>      const text = response.text();<br>      setChatHistory((prev) =&gt; [<br>        ...prev,<br>        { type: &quot;user&quot;, message: messageText },<br>        { type: &quot;bot&quot;, message: text },<br>      ]);<br>      setUserInput(&quot;&quot;);<br>      setIsLoading(true);<br>      console.log(text);<br>    } catch (e) {<br>      console.log(&quot;Error occurred while fetching&quot;, e);<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  };</pre><p>Now our UI would look like with, and if we send a message AI would reply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hmB4kdlRSEuHI2IwFGw0w.png" /></figure><p>The final code:</p><pre>import &quot;@chatscope/chat-ui-kit-styles/dist/default/styles.min.css&quot;;<br>import {<br>  MainContainer,<br>  ChatContainer,<br>  MessageList,<br>  Message,<br>  MessageInput,<br>} from &quot;@chatscope/chat-ui-kit-react&quot;;<br>import { useState } from &quot;react&quot;;<br>import { GoogleGenerativeAI } from &quot;@google/generative-ai&quot;;<br><br>export const ChatBot = () =&gt; {<br>  const [userInput, setUserInput] = useState(&quot;&quot;);<br>  const [chatHistory, setChatHistory] = useState([]);<br><br>  const handleUserInput = (value) =&gt; {<br>    console.log(value);<br>    setUserInput(value);<br>  };<br>  const genAI = new GoogleGenerativeAI(import.meta.env.VITE_API_KEY);<br>  const model = genAI.getGenerativeModel({ model: &quot;gemini-1.5-flash&quot; });<br><br>  const sendMessage = async (messageText) =&gt; {<br>    if (messageText.trim() === &quot;&quot;) return;<br><br>    try {<br>      const prompt = messageText;<br>      const result = await model.generateContent(prompt);<br>      const response = result.response;<br>      const text = response.text();<br>      setChatHistory((prev) =&gt; [<br>        ...prev,<br>        { type: &quot;user&quot;, message: messageText },<br>        { type: &quot;bot&quot;, message: text },<br>      ]);<br>      setUserInput(&quot;&quot;);<br>      console.log(text);<br>    } catch (e) {<br>      console.log(&quot;Error occurred while fetching&quot;, e);<br>    }<br>  };<br><br>  return (<br>    &lt;div style={{ position: &quot;relative&quot;, height: &quot;500px&quot; }}&gt;<br>      &lt;MainContainer&gt;<br>        &lt;ChatContainer&gt;<br>          &lt;MessageList&gt;<br>            {chatHistory.map((elt, i) =&gt; (<br>              &lt;Message<br>                key={i}<br>                model={{<br>                  message: elt.message,<br>                  sender: elt.type,<br>                  sentTime: &quot;just now&quot;,<br><br>                  direction: elt.type === &quot;user&quot; ? &quot;outgoing&quot; : &quot;incoming&quot;,<br>                }}<br>              /&gt;<br>            ))}<br>          &lt;/MessageList&gt;<br>          &lt;MessageInput<br>            placeholder=&quot;Type message here&quot;<br>            value={userInput}<br>            onChange={(value) =&gt; handleUserInput(value)}<br>            onSend={sendMessage}<br>          /&gt;<br>        &lt;/ChatContainer&gt;<br>      &lt;/MainContainer&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>For any suggestion or comments please leave a reply.</p><p>Like my work? <a href="http://buymeacoffee.com/everuslainus">Support it with a coffee</a>☕️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57035fcf1cb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>