<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Nikhil Akki's Blog | Co-Founder at Antmind.ai]]></title><description><![CDATA[Nikhil Akki's is India's leading Back-end and Cloud Engineer &amp; Solution Architect. He was experience building production grade applications on Cloud for Fortune 500 companies.]]></description><link>https://nikhilakki.in</link><generator>RSS for Node</generator><lastBuildDate>Sun, 12 Apr 2026 19:55:47 GMT</lastBuildDate><atom:link href="https://nikhilakki.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Django Signals: The Silent Heroes of Your Web App 🦸‍♂️]]></title><description><![CDATA[Have you ever wished your Django models could chat with each other like teenagers on social media? Well, they can! Django signals are like that friend who always knows the latest gossip and makes sure everyone stays in the loop. Let me share my journ...]]></description><link>https://nikhilakki.in/django-signals-the-silent-heroes-of-your-web-app</link><guid isPermaLink="true">https://nikhilakki.in/django-signals-the-silent-heroes-of-your-web-app</guid><category><![CDATA[Django]]></category><category><![CDATA[Python]]></category><category><![CDATA[signals]]></category><category><![CDATA[Backend Development]]></category><category><![CDATA[Tech Tutorial]]></category><category><![CDATA[CodeExamples]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 11 Jan 2025 06:12:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736045868680/708e6f8d-3810-4fca-92d6-d91f3168456a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever wished your Django models could chat with each other like teenagers on social media? Well, they can! Django signals are like that friend who always knows the latest gossip and makes sure everyone stays in the loop. Let me share my journey of discovering these magical messengers.</p>
<p>I still remember the day I discovered Django signals. I was building a social media app where users needed profile pictures automatically created upon registration. My initial solution? A tangled mess of function calls scattered throughout the codebase like Christmas lights in January. Then, signals entered my life.</p>
<h3 id="heading-the-aha-moment">The "Aha!" Moment</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db.models.signals <span class="hljs-keyword">import</span> post_save
<span class="hljs-keyword">from</span> django.dispatch <span class="hljs-keyword">import</span> receiver
<span class="hljs-keyword">from</span> django.contrib.auth.models <span class="hljs-keyword">import</span> User
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Profile

<span class="hljs-meta">@receiver(post_save, sender=User)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_user_profile</span>(<span class="hljs-params">sender, instance, created, **kwargs</span>):</span>
    <span class="hljs-keyword">if</span> created:
        Profile.objects.create(user=instance)
</code></pre>
<p>This little piece of code changed everything. It was like hiring a personal assistant who whispers "Hey, a new user just signed up, let me handle that profile creation for you." No more manual intervention needed!</p>
<h3 id="heading-the-signal-family">The Signal Family</h3>
<p>Think of Django signals like different types of notifications on your phone:</p>
<ol>
<li><p><strong>pre_save</strong>: The friend who tells you "Hey, you're about to post that embarrassing photo!"</p>
<pre><code class="lang-python"><span class="hljs-meta"> @receiver(pre_save, sender=Article)</span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">clean_up_title</span>(<span class="hljs-params">sender, instance, **kwargs</span>):</span>
     instance.title = instance.title.strip().title()
</code></pre>
</li>
<li><p><strong>post_save</strong>: The friend who announces "It's official!" after you update your relationship status</p>
<pre><code class="lang-python"><span class="hljs-meta"> @receiver(post_save, sender=Post)</span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">notify_followers</span>(<span class="hljs-params">sender, instance, created, **kwargs</span>):</span>
     <span class="hljs-keyword">if</span> created:
         instance.author.followers.notify(<span class="hljs-string">f"New post: <span class="hljs-subst">{instance.title}</span>"</span>)
</code></pre>
</li>
<li><p><strong>pre_delete</strong>: The cautious friend asking "Are you sure you want to delete those vacation photos?"</p>
</li>
<li><p><strong>post_delete</strong>: The cleanup crew after the party</p>
</li>
</ol>
<h3 id="heading-the-plot-twist-when-signals-get-too-chatty">The Plot Twist: When Signals Get Too Chatty</h3>
<p>But here's the thing - like that friend who updates their status every five minutes, signals can sometimes be too eager to help. I learned this the hard way when my app's performance started resembling a snail in a marathon.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Don't do this! 🙈</span>
<span class="hljs-meta">@receiver(post_save, sender=User)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">do_everything</span>(<span class="hljs-params">sender, instance, **kwargs</span>):</span>
    instance.send_welcome_email()
    instance.create_default_lists()
    instance.analyze_profile()
    instance.recommend_friends()
    <span class="hljs-comment"># ... and the kitchen sink</span>
</code></pre>
<h3 id="heading-the-art-of-signal-wisdom">The Art of Signal Wisdom</h3>
<p>After some face-palm moments, I developed my "Signal Sanity Checklist":</p>
<ol>
<li><p><strong>Is this signal really necessary?</strong> Like deciding whether to text your ex, think twice.</p>
<pre><code class="lang-python"> <span class="hljs-comment"># Instead of a signal, sometimes a simple model method is better</span>
 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-params">models.Model</span>):</span>
     <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">save</span>(<span class="hljs-params">self, *args, **kwargs</span>):</span>
         <span class="hljs-keyword">if</span> self._state.adding:
             self.set_default_preferences()
         super().save(*args, **kwargs)
</code></pre>
</li>
<li><p><strong>Keep it light</strong> - Signals should be more like Twitter and less like a dissertation.</p>
</li>
<li><p><strong>Register responsibly</strong> - Put your signals in a dedicated <a target="_blank" href="http://signals.py"><code>signals.py</code></a> file:</p>
<pre><code class="lang-python"> <span class="hljs-comment"># apps.py</span>
 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyAppConfig</span>(<span class="hljs-params">AppConfig</span>):</span>
     name = <span class="hljs-string">'myapp'</span>

     <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">ready</span>(<span class="hljs-params">self</span>):</span>
         <span class="hljs-keyword">import</span> myapp.signals  <span class="hljs-comment"># Stay organized!</span>
</code></pre>
</li>
</ol>
<h3 id="heading-the-happy-ending">The Happy Ending</h3>
<p>Once you understand signals, they're like having a well-trained orchestra in your Django app. Each instrument (model) knows exactly when to play its part, creating beautiful music (functionality) without the conductor (you) having to micromanage every note.</p>
<h3 id="heading-pro-tips-from-the-trenches">Pro Tips From the Trenches</h3>
<ol>
<li><p><strong>Debug with style:</strong></p>
<pre><code class="lang-python"><span class="hljs-meta"> @receiver(post_save, sender=User)</span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">log_user_changes</span>(<span class="hljs-params">sender, instance, **kwargs</span>):</span>
     logger.info(<span class="hljs-string">f"🔍 User <span class="hljs-subst">{instance.username}</span> updated"</span>)
     <span class="hljs-comment"># Because logs should spark joy</span>
</code></pre>
</li>
<li><p><strong>Keep it async-friendly</strong> - Your signals should play nice with Django's async capabilities.</p>
</li>
<li><p><strong>Test your signals</strong> - They're part of your app's functionality, not just decorative tinsel.</p>
</li>
</ol>
<h3 id="heading-wrapping-up">Wrapping Up</h3>
<p>Django signals are like the background characters in a movie - you might not notice them when they're doing their job well, but the story wouldn't flow without them. They've saved me countless hours of writing boilerplate code and helped keep my applications maintainable and modular.</p>
<p>Remember, with great power comes great responsibility. Use signals wisely, and they'll be your app's silent heroes. Abuse them, and they'll become your app's hidden villains.</p>
<hr />
<p><em>What's your experience with Django signals? Have they saved your day or caused unexpected troubles? Share your stories in the comments below!</em></p>
<hr />
<p><strong>About the Author:</strong> A Django enthusiast who learned about signals the hard way so you don't have to. Currently building awesome web apps and occasionally writing about it.</p>
<p><strong>Image Attribution</strong></p>
<ol>
<li><p><a target="_blank" href="https://www.fullstackpython.com/img/logos/django.png">Django Logo</a></p>
</li>
<li><p><a target="_blank" href="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/1200px-Python-logo-notext.svg.png">Python Logo</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/www-concept-illustration_8426454.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=18587c10-e456-4bd5-a20f-e55c92563491">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/illustration-radio-antenna_2606095.htm#fromView=search&amp;page=1&amp;position=12&amp;uuid=a5617f89-7700-4cd4-9367-94effa14afd2">Image #2</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Bringing Your Ubuntu Desktop Back to Life: A Developer's Guide to System Restoration]]></title><description><![CDATA[As a developer who has spent countless hours customizing and occasionally breaking my Ubuntu installations, I've learned that knowing how to restore your system is as crucial as knowing how to code. Today, I want to share my experience with restoring...]]></description><link>https://nikhilakki.in/bringing-your-ubuntu-desktop-back-to-life-a-developers-guide-to-system-restoration</link><guid isPermaLink="true">https://nikhilakki.in/bringing-your-ubuntu-desktop-back-to-life-a-developers-guide-to-system-restoration</guid><category><![CDATA[gnome-desktop]]></category><category><![CDATA[gdm3]]></category><category><![CDATA[apt-pkg-manager]]></category><category><![CDATA[Ubuntu]]></category><category><![CDATA[Linux]]></category><category><![CDATA[debian]]></category><category><![CDATA[apt]]></category><category><![CDATA[package manager]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 04 Jan 2025 04:44:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735965778384/93ea4b04-b2c3-4dc1-86bd-b21847e83812.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a developer who has spent countless hours customizing and occasionally breaking my Ubuntu installations, I've learned that knowing how to restore your system is as crucial as knowing how to code. Today, I want to share my experience with restoring Ubuntu desktop installations, a skill that has saved me from numerous late-night system emergencies.</p>
<p>The moment when your carefully crafted development environment starts showing signs of trouble can be nerve-wracking. Maybe it's the desktop environment refusing to load, or perhaps some critical GNOME components have gone rogue after an interrupted update. Whatever the case, having a systematic approach to restoration can mean the difference between a quick fix and a complete re-installation.</p>
<p>Let's start with the basics. The first line of defense is typically reinstalling the Ubuntu-desktop package. Open your terminal (Ctrl+Alt+F3 if your desktop environment isn't loading) and run:</p>
<pre><code class="lang-bash">sudo apt update
sudo apt install --reinstall ubuntu-desktop
</code></pre>
<p>This command often resolves common desktop environment issues, but sometimes you need to dig deeper. In my experience, a more comprehensive approach is to reinstall the entire desktop task package using:</p>
<pre><code class="lang-bash">sudo apt install --reinstall ubuntu-desktop^
</code></pre>
<p>The caret symbol here is crucial – it tells apt to reinstall not just the base package, but all the recommended packages that come with a fresh Ubuntu desktop installation. This has saved my system more times than I can count, especially after overzealous package cleaning sessions.</p>
<p>For those situations where your system needs more than just a desktop environment fix, reinstalling the Ubuntu standard packages can help:</p>
<pre><code class="lang-bash">sudo apt install ubuntu-standard
</code></pre>
<p>This command ensures that all the essential system components are in place and properly configured. Think of it as giving your system a fresh foundation while keeping your personal files and configurations intact.</p>
<p>If you're dealing specifically with display manager issues or a misbehaving GNOME shell, this combination has proven particularly effective:</p>
<pre><code class="lang-bash">sudo apt install --reinstall gnome-shell gnome-session gdm3
</code></pre>
<p>After any of these operations, don't forget the most important step:</p>
<pre><code class="lang-bash">sudo reboot
</code></pre>
<p>One lesson I've learned the hard way is to always check your package sources before attempting any restoration. Make sure your <code>/etc/apt/sources.list</code> is properly configured and that you haven't accidentally disabled any essential repositories. This simple check can save hours of troubleshooting.</p>
<p>Here's a pro tip from my experience: before starting any restoration process, back up your current package list:</p>
<pre><code class="lang-bash">dpkg --get-selections &gt; ~/package_list.txt
</code></pre>
<p>This creates a snapshot of your installed packages, which can be invaluable if you need to reproduce your development environment on another machine or after a clean install.</p>
<p>Remember that while these steps can fix most issues, they won't repair corrupted user configurations in your home directory. If you're still experiencing issues after system restoration, you might need to reset your desktop environment configurations:</p>
<pre><code class="lang-bash">rm -rf ~/.config/gnome-* ~/.config/dconf
</code></pre>
<p>Be cautious with this command – it will reset all your GNOME settings to defaults, but sometimes a fresh start is exactly what you need.</p>
<p>The beauty of Linux systems like Ubuntu is that they're remarkably resilient. With the right knowledge and tools, most system issues can be resolved without resorting to a complete re-installation. Keep these commands handy, and you'll be prepared for whatever system challenges come your way.</p>
<p>Remember, maintaining a healthy system is an ongoing process. Regular updates, careful package management, and maintaining backups of critical configurations will help prevent the need for restoration in the first place. But when things do go wrong, knowing how to restore your system effectively is an invaluable skill in any developer's toolkit.</p>
<p><strong>Image Attributions</strong></p>
<ol>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/database-access-data-bank-opening-info-security-information-protection-secured-storage-hacker-cartoon-character-office-with-metal-safe_11669637.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=aa8a0ecc-ac5d-4d25-91f4-0f6c711f25c8">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/programming-concept-illustration_7118755.htm#fromView=search&amp;page=1&amp;position=6&amp;uuid=017e80db-7c00-4617-bc95-40a3bcd92539">Image #2</a></p>
</li>
<li><p><a target="_blank" href="https://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Ubuntu-logo-2022.svg/2560px-Ubuntu-logo-2022.svg.png">Ubuntu Logo</a></p>
</li>
<li><p><a target="_blank" href="https://upload.wikimedia.org/wikipedia/commons/0/04/Debian_logo.png">Debian Logo</a></p>
</li>
<li><p><a target="_blank" href="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/800px-Tux.svg.png">Linux Mascot</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Open Source Alternatives to AWS CodeGuru]]></title><description><![CDATA[Introduction
In today's fast-paced software development landscape, code quality and security are non-negotiable. While AWS CodeGuru offers impressive capabilities for automated code reviews and security analysis, its cost structure and AWS-centric na...]]></description><link>https://nikhilakki.in/open-source-alternatives-to-aws-codeguru</link><guid isPermaLink="true">https://nikhilakki.in/open-source-alternatives-to-aws-codeguru</guid><category><![CDATA[code-scan]]></category><category><![CDATA[static code analysis]]></category><category><![CDATA[Python]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Devops]]></category><category><![CDATA[ci-cd]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 28 Dec 2024 13:10:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1735390793077/8e012273-fae4-4a4b-9ee6-9a8541a02fea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In today's fast-paced software development landscape, code quality and security are non-negotiable. While AWS CodeGuru offers impressive capabilities for automated code reviews and security analysis, its cost structure and AWS-centric nature might not suit every organization's needs. Enter the world of open source alternatives – a rich ecosystem of tools that can match and sometimes exceed CodeGuru's capabilities. The beauty of these tools lies not just in their zero-dollar price tag, but in their community-driven nature, extensive customization options, and platform independence. Whether you're leading a startup trying to bootstrap its security practices or managing enterprise-level code quality at scale, these open source alternatives provide a robust foundation for maintaining high standards in your software development life-cycle. Let's dive into this carefully curated collection of tools that can help you achieve professional-grade code analysis without the premium price tag.</p>
<h2 id="heading-simpler-explanation">Simpler explanation</h2>
<p>Imagine you're building a huge LEGO castle. You want to make sure all the pieces fit perfectly and there are no weak spots where it might fall down. These tools are like having a super-smart friend who checks your castle while you build it. They look for missing pieces (bugs), weak spots (security issues), and even hidden treasures that shouldn't be there (secrets). Instead of paying for this friend's help, these tools are free and created by other LEGO builders who want to help everyone build better castles.</p>
<h2 id="heading-use-cases">Use Cases</h2>
<ul>
<li><p><strong>Continuous Integration Pipeline Security</strong></p>
<ul>
<li><p>Integrate tools like <strong>GitLeaks</strong> and <strong>Semgrep</strong> into your CI/CD pipeline to catch security issues and exposed secrets before code reaches production.</p>
</li>
<li><p>Perfect for organizations handling sensitive data and needing to comply with security standards.</p>
</li>
</ul>
</li>
<li><p><strong>Legacy Code Modernization</strong></p>
<ul>
<li><p>Use <strong>SonarQube</strong> and language-specific analyzers to identify technical debt and code smells in existing codebases.</p>
</li>
<li><p>Helps teams prioritize refactoring efforts and gradually improve code quality.</p>
</li>
</ul>
</li>
<li><p><strong>Developer Productivity Enhancement</strong></p>
<ul>
<li><p>Implement pre-commit hooks with tools like detect-secrets and language-specific linters.</p>
</li>
<li><p>Catches issues early in the development cycle, reducing review iterations and improving code quality from the start.</p>
</li>
</ul>
</li>
<li><p><strong>Compliance and Audit Requirements</strong></p>
<ul>
<li><p>Deploy a combination of security scanning tools to generate comprehensive reports for auditors.</p>
</li>
<li><p>Helps maintain compliance with standards like <strong>SOC2, ISO 27001, and HIPAA.</strong></p>
</li>
</ul>
</li>
<li><p><strong>Open Source Project Management</strong></p>
<ul>
<li><p>Use automated tools to maintain code quality standards across multiple contributors.</p>
</li>
<li><p>Ensures consistency and security in projects with diverse contributor bases.</p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-take-away">Take Away</h2>
<p>The open source ecosystem provides a robust alternative to AWS CodeGuru through a combination of specialized tools. While this approach requires more initial setup and integration work compared to CodeGuru's turnkey solution, it offers greater flexibility, customization, and platform independence. However, CodeGuru's machine learning-powered insights, seamless AWS integration, and managed service model make it compelling for organizations heavily invested in AWS. The ML capabilities, in particular, enable CodeGuru to provide contextual recommendations and identify resource leaks that traditional static analysis might miss. Additionally, for teams lacking dedicated security expertise or infrastructure resources, CodeGuru's zero-configuration approach and automatic updates could justify its cost through reduced operational overhead. The choice ultimately depends on your infrastructure strategy, in-house expertise, and whether the convenience of a managed service outweighs the flexibility and cost savings of open source alternatives. Remember, the goal isn't to choose based on price alone, but to select a solution that best aligns with your organization's capabilities and needs.</p>
<h2 id="heading-reference-links">Reference Links</h2>
<ul>
<li><p><a target="_blank" href="https://www.sonarqube.org/">SonarQube</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/PyCQA/bandit">Bandit</a></p>
</li>
<li><p><a target="_blank" href="https://semgrep.dev/">Semgrep</a></p>
</li>
<li><p><a target="_blank" href="https://owasp.org/www-project-dependency-check/">OWASP Dependency Check</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/zricethezav/gitleaks">GitLeaks</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/trufflesecurity/trufflehog">TruffleHog</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/Yelp/detect-secrets">detect-secrets</a></p>
</li>
<li><p><a target="_blank" href="https://eslint.org/">ESLint</a></p>
</li>
<li><p><a target="_blank" href="https://www.pylint.org/">Pylint</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/astral-sh/ruff">Ruff</a></p>
</li>
<li><p><a target="_blank" href="https://golangci-lint.run/">GolangCI-lint</a></p>
</li>
<li><p><a target="_blank" href="https://pmd.github.io/">PMD</a></p>
</li>
</ul>
<p><strong>Image sources</strong></p>
<ol>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/hand-coding-concept-illustration_21864184.htm#fromView=search&amp;page=1&amp;position=0&amp;uuid=94e6e7a6-3bf7-47f3-8fbb-91b39ac0875e">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/security-guard-cartoon-composition_30038792.htm#fromView=search&amp;page=1&amp;position=0&amp;uuid=b9461f76-2b6d-4853-88b2-24b8d4f2fdb5">Image #2</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/police-collection-concept_7851219.htm#fromView=search&amp;page=1&amp;position=0&amp;uuid=65f6f58d-2a83-468a-9fb3-245a8ed60f8f">Image #3</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/two-men-with-mobile-face-scan-digital_5597112.htm#fromView=search&amp;page=1&amp;position=6&amp;uuid=47a90b1d-bfda-461a-925a-0805b846fe59">Image #4</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[PydanticAI: Crafting Intelligent Agents with Ease]]></title><description><![CDATA[Introduction
In the rapidly evolving landscape of artificial intelligence, the ability to build robust, production-grade applications with generative AI is becoming increasingly essential. Enter PydanticAI, a Python agent framework designed to simpli...]]></description><link>https://nikhilakki.in/pydanticai-crafting-intelligent-agents-with-ease</link><guid isPermaLink="true">https://nikhilakki.in/pydanticai-crafting-intelligent-agents-with-ease</guid><category><![CDATA[pydantic-ai]]></category><category><![CDATA[llm-agents]]></category><category><![CDATA[Python]]></category><category><![CDATA[pydantic]]></category><category><![CDATA[ai agents]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 21 Dec 2024 12:51:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734785388548/7e732abf-a5e9-4086-8fe4-4f107697d001.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction"><strong>Introduction</strong></h3>
<p>In the rapidly evolving landscape of artificial intelligence, the ability to build robust, production-grade applications with generative AI is becoming increasingly essential. Enter PydanticAI, a Python agent framework designed to simplify this process by leveraging the power of Pydantic. Just as FastAPI revolutionized web development with its ergonomic design, PydanticAI aims to bring that same level of ease and efficiency to AI-driven projects. Built by the team behind Pydantic, this framework offers a model-agnostic approach, supporting a variety of AI models like OpenAI, Anthropic, and Gemini. Whether you're a seasoned developer or just starting out, PydanticAI provides the tools you need to create intelligent agents that can handle complex tasks with precision and reliability.</p>
<h3 id="heading-simpler-explanation">Simpler Explanation</h3>
<p>Imagine you have a smart assistant that can understand and respond to your questions. PydanticAI helps you build such assistants using AI models. It makes sure the assistant's responses are structured and correct, just like how a teacher checks your homework. With PydanticAI, you can easily create assistants for different tasks, like answering customer queries or providing weather updates, without worrying about the technical details.<strong>Use Cases</strong></p>
<ol>
<li><p><strong>Customer Support Agents</strong>: PydanticAI can be used to build intelligent customer support agents that provide real-time assistance. By integrating with databases, these agents can access customer information and offer personalized support, enhancing customer satisfaction.</p>
</li>
<li><p><strong>Financial Advisory Systems</strong>: In the financial sector, PydanticAI can power advisory systems that analyze market trends and provide investment recommendations. Its type-safe design ensures that the advice is accurate and reliable.</p>
</li>
<li><p><strong>Healthcare Assistants</strong>: PydanticAI can be employed to develop healthcare assistants that offer medical advice based on patient data. By validating responses, it ensures that the information provided is consistent and trustworthy.</p>
</li>
<li><p><strong>Educational Tools</strong>: Educators can use PydanticAI to create interactive learning tools that adapt to students' needs. These tools can provide instant feedback and personalized learning paths, making education more engaging.</p>
</li>
<li><p><strong>Content Generation</strong>: For content creators, PydanticAI can automate the generation of articles, reports, and other written materials. Its structured response system ensures that the content is coherent and well-organized.</p>
</li>
<li><p><strong>Data Analysis and Reporting</strong>: Businesses can leverage PydanticAI for data analysis and reporting, automating the generation of insights from large datasets. This can save time and improve decision-making processes.</p>
</li>
<li><p><strong>Chatbots for E-commerce</strong>: E-commerce platforms can integrate PydanticAI to develop chatbots that assist customers with product recommendations and order tracking, enhancing the shopping experience.</p>
</li>
<li><p><strong>Legal Document Review</strong>: In the legal field, PydanticAI can assist in reviewing and summarizing legal documents, ensuring accuracy and compliance with regulations.</p>
</li>
<li><p><strong>Weather Forecasting Agents</strong>: Meteorologists can use PydanticAI to build agents that provide real-time weather updates and forecasts, helping people plan their activities accordingly.</p>
</li>
<li><p><strong>Social Media Monitoring</strong>: Brands can utilize PydanticAI to monitor social media platforms for mentions and sentiment analysis, allowing them to respond promptly to customer feedback.</p>
</li>
</ol>
<p><strong>Example Code</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent

<span class="hljs-comment"># Define a simple agent using the Gemini model</span>
agent = Agent(
    <span class="hljs-string">'gemini-1.5-flash'</span>,
    system_prompt=<span class="hljs-string">'Provide a brief summary of the input text.'</span>,
)

<span class="hljs-comment"># Run the agent synchronously</span>
result = agent.run_sync(<span class="hljs-string">'When did USA got independence?'</span>)
print(result.data)
<span class="hljs-comment">## Output </span>
<span class="hljs-comment"># "The USA gained independence on July 4, 1776."</span>
</code></pre>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>PydanticAI is a powerful tool for developers looking to integrate AI into their applications. Its model-agnostic design, coupled with Pydantic's validation capabilities, ensures that your AI-driven projects are both reliable and efficient. Whether you're building customer support agents or educational tools, PydanticAI provides the flexibility and ease of use needed to bring your ideas to life.<strong>References</strong></p>
<ul>
<li><p><a target="_blank" href="https://github.com/pydantic/pydantic-ai"><strong>PydanticAI GitHub Repository</strong></a></p>
</li>
<li><p><a target="_blank" href="https://ai.pydantic.dev/"><strong>PydanticAI Documentation</strong></a></p>
</li>
<li><p><a target="_blank" href="https://fastapi.tiangolo.com/"><strong>FastAPI Documentation</strong></a></p>
</li>
</ul>
<p>Image attributions</p>
<ol>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/hand-drawn-pi-day-illustration_23180077.htm#fromView=search&amp;page=1&amp;position=6&amp;uuid=412845d6-42d2-4711-94a9-b4fa70db18d3">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-photo/robot-with-tick-symbol_958092.htm#fromView=search&amp;page=1&amp;position=16&amp;uuid=a99c0284-1135-4a9d-87e7-cb3d5f3e023f">Image #2</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-psd/ai-element-illustration_171327434.htm#fromView=search&amp;page=1&amp;position=21&amp;uuid=c2dd62f4-b049-4296-9f7e-88adac3fe335">Image #3</a></p>
</li>
<li><p><a target="_blank" href="https://ai.pydantic.dev/img/pydantic-ai-light.svg#only-light">PydanticAI Logo</a></p>
</li>
<li><p><a target="_blank" href="https://en.m.wikipedia.org/wiki/File:Python-logo-notext.svg">Python Logo</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[The Rise of AI Butlers: How LLM Agents are Reshaping Human-AI Interaction]]></title><description><![CDATA[Introduction
The landscape of artificial intelligence is witnessing a revolutionary transformation with the emergence of LLM (Large Language Model) Agents. Unlike traditional chat-bots that simply respond to queries, these AI agents act as autonomous...]]></description><link>https://nikhilakki.in/the-rise-of-ai-butlers-how-llm-agents-are-reshaping-human-ai-interaction</link><guid isPermaLink="true">https://nikhilakki.in/the-rise-of-ai-butlers-how-llm-agents-are-reshaping-human-ai-interaction</guid><category><![CDATA[msautogen]]></category><category><![CDATA[ms-autogen]]></category><category><![CDATA[react-agents]]></category><category><![CDATA[agentbench]]></category><category><![CDATA[Python]]></category><category><![CDATA[langchain]]></category><category><![CDATA[#llmagents]]></category><category><![CDATA[ai agents]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 14 Dec 2024 14:02:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734184299012/f0dfd55c-02d4-4c09-a8e1-47e331f04875.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>The landscape of artificial intelligence is witnessing a revolutionary transformation with the emergence of LLM (Large Language Model) Agents. Unlike traditional chat-bots that simply respond to queries, these AI agents act as autonomous digital assistants capable of planning, reasoning, and executing complex tasks through multiple steps. Think of them as AI butlers who don't just answer your questions but actively help you accomplish your goals. These agents combine the powerful language understanding capabilities of LLMs with specialized modules for memory, planning, and tool usage, creating systems that can navigate complex real-world scenarios. As we stand at the cusp of this technological revolution, LLM Agents are proving to be the bridge between simple language models and truly intelligent autonomous systems that can understand context, maintain long-term memory, and adapt to changing situations.</p>
<h3 id="heading-simpler-explanation">Simpler explanation</h3>
<p>Imagine you have a super-smart robot friend who not only talks to you but also helps you with your homework. This robot friend can remember your conversations, make plans, and even use different tools to help you. If you ask it to draw a picture, it knows it needs to first get paper and crayons. If you ask it to bake cookies, it knows it needs to check the recipe, gather ingredients, and follow steps in order. That's what an LLM Agent is – a smart AI helper that can think ahead, remember things, and use different tools to help you get things done.</p>
<h3 id="heading-novel-use-cases">Novel Use Cases</h3>
<ol>
<li><p><strong>Personal Health Coach</strong> An LLM Agent could serve as a comprehensive health coach by combining daily activity tracking, nutritional analysis, and personalized workout planning. The agent could access health devices' APIs, nutrition databases, and workout libraries while maintaining a long-term memory of your progress and preferences. It could adjust recommendations based on real-time data and even coordinate with healthcare providers when necessary.</p>
</li>
<li><p><strong>AI-Powered Legal Assistant</strong> Legal professionals could benefit from an LLM Agent that combines legal research capabilities with document drafting and case management. The agent could maintain context across multiple cases, automatically generate legal documents, track deadlines, and provide citations while ensuring compliance with jurisdictional requirements. It could also flag potential conflicts and suggest precedents based on case similarities.</p>
</li>
<li><p><strong>Autonomous Data Journalist</strong> Imagine an LLM Agent that monitors multiple data sources, identifies newsworthy trends, and automatically generates data-driven stories. The agent could access APIs for economic indicators, social media trends, and public databases, create visualizations, and even conduct basic fact-checking. It could maintain a memory of previous stories to avoid redundancy and ensure consistent reporting.</p>
</li>
<li><p><strong>Virtual Event Coordinator</strong> An LLM Agent could revolutionize event planning by handling multiple vendors, managing guest lists, and coordinating logistics simultaneously. The agent could maintain conversations with various stakeholders, track budgets, create timelines, and even simulate different scenarios to identify potential problems before they occur.</p>
</li>
<li><p><strong>Educational Curriculum Designer</strong> Teachers could leverage an LLM Agent to create personalized learning materials based on student performance data. The agent could access educational standards, learning resources, and assessment tools while maintaining memory of individual student progress. It could automatically generate assignments, quizzes, and lesson plans tailored to specific learning needs.</p>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>LLM Agents represent a significant leap forward in AI capabilities, moving us closer to truly intelligent systems that can understand, plan, and execute complex tasks autonomously. While challenges remain in areas such as long-term planning, reliability, and efficiency, the potential applications across industries are vast and promising. As these agents continue to evolve, we can expect to see more sophisticated implementations that combine multiple AI models, specialized tools, and advanced planning capabilities. The future of human-AI interaction lies not just in conversation, but in collaborative problem-solving through intelligent, autonomous agents.</p>
<h3 id="heading-references">References</h3>
<ol>
<li><p><a target="_blank" href="https://python.langchain.com/docs/get_started/introduction">LangChain Documentation</a></p>
</li>
<li><p><a target="_blank" href="https://platform.openai.com/docs/guides/gpt/function-calling">OpenAI Function Calling</a></p>
</li>
<li><p><a target="_blank" href="https://microsoft.github.io/autogen/">Microsoft AutoGen</a></p>
</li>
<li><p><a target="_blank" href="https://arxiv.org/abs/2308.03688">AgentBench Paper</a></p>
</li>
<li><p><a target="_blank" href="https://arxiv.org/abs/2210.03629">ReAct: Synergizing Reasoning and Acting in Language Models</a></p>
</li>
</ol>
<p><strong>Image attribution</strong></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/flat-international-mother-language-day-illustration_21530023.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=27d51118-71c9-4bf6-85a2-91aa45c0f3a7">Image #1</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/cute-robot-working-laptop-cartoon-vector-icon-illustration-science-technology-isolated-flat_214439541.htm#fromView=search&amp;page=1&amp;position=22&amp;uuid=440af676-63d2-493c-b4b0-d21e05a2aa06">Image #2</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/flat-hand-drawn-female-team-leader_12428199.htm#fromView=search&amp;page=1&amp;position=40&amp;uuid=7814e271-5306-45d0-9a0d-2ca884770875">Image #3</a></p>
]]></content:encoded></item><item><title><![CDATA[Understanding Django's Auto-discovery: A Deep Dive]]></title><description><![CDATA[Django's auto-discovery feature is one of those magical elements that makes the framework both powerful and developer-friendly. While many developers use it daily, few understand how it works under the hood or how to leverage it effectively in their ...]]></description><link>https://nikhilakki.in/understanding-djangos-auto-discovery-a-deep-dive</link><guid isPermaLink="true">https://nikhilakki.in/understanding-djangos-auto-discovery-a-deep-dive</guid><category><![CDATA[django-auto-discovery]]></category><category><![CDATA[Python]]></category><category><![CDATA[Django]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[MVVM]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Fri, 06 Dec 2024 18:30:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1733372979678/81553d02-4725-4958-a149-dea6afdd9e62.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Django's auto-discovery feature is one of those magical elements that makes the framework both powerful and developer-friendly. While many developers use it daily, few understand how it works under the hood or how to leverage it effectively in their applications. In this comprehensive guide, we'll explore Django's auto-discovery mechanism, its common use cases, and how you can implement custom auto-discovery in your projects.</p>
<h2 id="heading-what-is-auto-discovery">What is Auto-discovery?</h2>
<p>At its core, auto-discovery is Django's way of automatically finding and loading certain components from your installed applications without requiring explicit registration. This feature follows Python's "convention over configuration" principle, making it easier to maintain a clean and organized code-base while reducing boilerplate code.</p>
<h2 id="heading-common-use-cases">Common Use Cases</h2>
<h3 id="heading-1-admin-module-auto-discovery">1. Admin Module Auto-discovery</h3>
<p>The most familiar example of auto-discovery is Django's admin interface. When you include the admin URLs in your project, Django automatically searches for and registers models from each app's <a target="_blank" href="http://admin.py"><code>admin.py</code></a>:</p>
<pre><code class="lang-python"><span class="hljs-comment"># urls.py</span>
<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path

admin.autodiscover()  <span class="hljs-comment"># This line triggers admin autodiscovery</span>

urlpatterns = [
    path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
]
</code></pre>
<p>In your app's <a target="_blank" href="http://admin.py"><code>admin.py</code></a>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Product, Category

<span class="hljs-meta">@admin.register(Product)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProductAdmin</span>(<span class="hljs-params">admin.ModelAdmin</span>):</span>
    list_display = (<span class="hljs-string">'name'</span>, <span class="hljs-string">'price'</span>, <span class="hljs-string">'category'</span>)
    search_fields = (<span class="hljs-string">'name'</span>,)

<span class="hljs-meta">@admin.register(Category)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CategoryAdmin</span>(<span class="hljs-params">admin.ModelAdmin</span>):</span>
    list_display = (<span class="hljs-string">'name'</span>, <span class="hljs-string">'created_at'</span>)
</code></pre>
<h3 id="heading-2-management-commands">2. Management Commands</h3>
<p>Django automatically discovers custom management commands placed in the <code>management/commands</code> directory of your apps. This allows you to create powerful CLI commands without additional registration:</p>
<pre><code class="lang-plaintext">myapp/
    └── management/
        └── commands/
            ├── __init__.py
            └── import_data.py
</code></pre>
<h3 id="heading-3-template-tags-and-filters">3. Template Tags and Filters</h3>
<p>Custom template tags and filters are automatically discovered from the <code>templatetags</code> directory:</p>
<pre><code class="lang-plaintext">myapp/
    └── templatetags/
        ├── __init__.py
        └── custom_filters.py
</code></pre>
<h2 id="heading-how-auto-discovery-works">How Auto-discovery Works</h2>
<p>Under the hood, Django's auto-discovery mechanism follows these steps:</p>
<ol>
<li><p><strong>App Configuration</strong>: Django reads the <code>INSTALLED_APPS</code> setting to get a list of all installed applications.</p>
</li>
<li><p><strong>Module Search</strong>: For each app, Django looks for specific module names (e.g., <a target="_blank" href="http://admin.py"><code>admin.py</code></a>, <a target="_blank" href="http://signals.py"><code>signals.py</code></a>).</p>
</li>
<li><p><strong>Import Process</strong>: When found, these modules are imported, executing any registration code they contain.</p>
</li>
<li><p><strong>Registration</strong>: The discovered components are registered with their respective systems (admin site, URL patterns, etc.).</p>
</li>
</ol>
<h2 id="heading-implementing-custom-auto-discovery">Implementing Custom Auto-discovery</h2>
<p>You can implement your own auto-discovery mechanism for custom components. Here's a practical example:</p>
<pre><code class="lang-python"><span class="hljs-comment"># utils/discovery.py</span>
<span class="hljs-keyword">from</span> django.utils.module_loading <span class="hljs-keyword">import</span> autodiscover_modules

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">autodiscover_handlers</span>():</span>
    <span class="hljs-string">"""
    Automatically discover and register handlers from all installed apps.
    """</span>
    autodiscover_modules(<span class="hljs-string">'handlers'</span>)

<span class="hljs-comment"># handlers.py (in your app)</span>
<span class="hljs-keyword">from</span> .base <span class="hljs-keyword">import</span> BaseHandler

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomHandler</span>(<span class="hljs-params">BaseHandler</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">handle</span>(<span class="hljs-params">self, data</span>):</span>
        <span class="hljs-comment"># Handler implementation</span>
        <span class="hljs-keyword">pass</span>

<span class="hljs-comment"># Register the handler</span>
registry.register(CustomHandler)
</code></pre>
<h2 id="heading-best-practices-and-tips">Best Practices and Tips</h2>
<ol>
<li><p><strong>Module Organization</strong></p>
<ul>
<li><p>Keep auto-discovered modules focused and single-purpose</p>
</li>
<li><p>Use clear naming conventions for auto-discovered files</p>
</li>
<li><p>Include <code>__init__.py</code> files in all directories</p>
</li>
</ul>
</li>
<li><p><strong>Performance Considerations</strong></p>
<ul>
<li><p>Auto-discovery happens at startup, so keep initialization code lightweight</p>
</li>
<li><p>Use lazy loading when possible to defer expensive operations</p>
</li>
<li><p>Consider caching mechanisms for frequently accessed components</p>
</li>
</ul>
</li>
<li><p><strong>Error Handling</strong></p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.utils.module_loading <span class="hljs-keyword">import</span> autodiscover_modules

 <span class="hljs-keyword">try</span>:
     autodiscover_modules(<span class="hljs-string">'custom_module'</span>)
 <span class="hljs-keyword">except</span> ImportError <span class="hljs-keyword">as</span> e:
     logger.warning(<span class="hljs-string">f"Failed to load custom module: <span class="hljs-subst">{e}</span>"</span>)
</code></pre>
</li>
</ol>
<h2 id="heading-advanced-auto-discovery-patterns">Advanced Auto-discovery Patterns</h2>
<h3 id="heading-1-selective-loading">1. Selective Loading</h3>
<p>You can implement selective auto-discovery based on settings or environment:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings
<span class="hljs-keyword">from</span> django.utils.module_loading <span class="hljs-keyword">import</span> autodiscover_modules

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">conditional_autodiscover</span>():</span>
    <span class="hljs-keyword">if</span> settings.ENABLE_CUSTOM_HANDLERS:
        autodiscover_modules(<span class="hljs-string">'handlers'</span>)
</code></pre>
<h3 id="heading-2-custom-registry-pattern">2. Custom Registry Pattern</h3>
<p>Create a registry system for your auto-discovered components:</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Registry</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
        self._registry = {}

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">register</span>(<span class="hljs-params">self, name, component</span>):</span>
        self._registry[name] = component

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_component</span>(<span class="hljs-params">self, name</span>):</span>
        <span class="hljs-keyword">return</span> self._registry.get(name)

registry = Registry()
</code></pre>
<h2 id="heading-common-pitfalls-and-solutions">Common Pitfalls and Solutions</h2>
<ol>
<li><p><strong>Circular Imports</strong></p>
<ul>
<li><p>Use lazy imports or move imports inside functions</p>
</li>
<li><p>Structure your code to avoid circular dependencies</p>
</li>
</ul>
</li>
<li><p><strong>Load Order Issues</strong></p>
<ul>
<li><p>Use Django's app config and ready() method for initialization</p>
</li>
<li><p>Implement proper dependency handling in your auto-discovery code</p>
</li>
</ul>
</li>
<li><p><strong>Missing Modules</strong></p>
<ul>
<li><p>Implement proper error handling for missing modules</p>
</li>
<li><p>Provide clear error messages for debugging</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Django's auto-discovery feature is a powerful tool that can significantly improve code organization and maintainability. By understanding how it works and following best practices, you can leverage it effectively in your projects. Whether you're using built-in auto-discovery features or implementing custom ones, this pattern helps maintain a clean and scalable Django application.</p>
<p>Remember that while auto-discovery is powerful, it should be used judiciously. Always consider the trade-offs between convenience and explicit registration, especially in larger applications where clear dependency management becomes crucial.</p>
<p>By mastering Django's auto-discovery, you'll be better equipped to build more maintainable and scalable Django applications while reducing boilerplate code and improving overall code organization.</p>
<p><strong>Image attribution</strong></p>
<p>Django <a target="_blank" href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.djangoproject.com%2Fcommunity%2Flogos%2F&amp;psig=AOvVaw2UVhajFVjSc9CfLUDQchEH&amp;ust=1733459063728000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCNCq-rLkj4oDFQAAAAAdAAAAABAE">Logo</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/asian-auto-rickshaw-baby-taxi-transport_11058759.htm#fromView=search&amp;page=1&amp;position=2&amp;uuid=844a1c52-64a8-436e-aadc-b34597d2aa53">Image #1</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/discovery-concept-illustration_13766139.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=82b31d0a-9e9b-4441-86dc-baadb5cd2134">Image #</a>2</p>
]]></content:encoded></item><item><title><![CDATA[Exploring the Uncharted Territories of LangGraph in AI Development]]></title><description><![CDATA[Introduction
In the rapidly evolving landscape of artificial intelligence, LangGraph emerges as a powerful tool for orchestrating complex, stateful, multi-agent applications. While much has been discussed about its foundational capabilities, there re...]]></description><link>https://nikhilakki.in/exploring-the-uncharted-territories-of-langgraph-in-ai-development</link><guid isPermaLink="true">https://nikhilakki.in/exploring-the-uncharted-territories-of-langgraph-in-ai-development</guid><category><![CDATA[Python]]></category><category><![CDATA[langgraph]]></category><category><![CDATA[langchain]]></category><category><![CDATA[ai agents]]></category><category><![CDATA[generative ai]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 30 Nov 2024 06:53:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732949499212/02f192e2-47a9-4b1c-8b5a-10734ba67f63.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction"><strong>Introduction</strong></h3>
<p>In the rapidly evolving landscape of artificial intelligence, LangGraph emerges as a powerful tool for orchestrating complex, stateful, multi-agent applications. While much has been discussed about its foundational capabilities, there remains a vast expanse of unexplored potential within LangGraph's framework. This blog aims to delve into the lesser-known yet highly impactful applications of LangGraph, offering insights into how developers can leverage its advanced features to push the boundaries of AI development. From enhancing human-agent collaboration to enabling sophisticated decision-making processes, LangGraph is poised to redefine how we approach AI workflows. Join us as we explore these uncharted territories and uncover the innovative possibilities that LangGraph brings to the table.</p>
<p><strong>Simpler explanation</strong></p>
<p>LangGraph is like a conductor in an orchestra, coordinating different AI agents to work together harmoniously. It helps build smart applications that remember past interactions and can make decisions or ask for human help when needed. Think of it as a super-smart assistant that can handle complex tasks by working with other assistants.</p>
<h3 id="heading-use-cases"><strong>Use Cases</strong></h3>
<ol>
<li><p><strong>Dynamic Content Generation:</strong> Automate the creation of personalized content by coordinating multiple AI models to generate, review, and refine text.</p>
</li>
<li><p><strong>Real-time Data Analysis:</strong> Use LangGraph to orchestrate data collection, processing, and analysis in real-time, providing actionable insights on the fly.</p>
</li>
<li><p><strong>Interactive Storytelling:</strong> Develop immersive storytelling experiences where AI agents adapt the narrative based on user interactions and preferences.</p>
</li>
<li><p><strong>Autonomous Research Assistants:</strong> Create AI systems that autonomously gather, analyze, and summarize research data, aiding in academic and industrial research.</p>
</li>
<li><p><strong>Complex Task Automation:</strong> Automate multi-step processes in industries like finance or healthcare, where tasks require coordination between various AI models.</p>
</li>
<li><p><strong>AI-Driven Customer Support:</strong> Enhance customer service by deploying AI agents that can handle inquiries, escalate issues, and provide solutions autonomously.</p>
</li>
<li><p><strong>Predictive Maintenance Systems:</strong> Implement AI workflows that predict equipment failures and schedule maintenance, reducing downtime and costs.</p>
</li>
<li><p><strong>Smart Home Automation:</strong> Coordinate multiple AI agents to manage home devices, optimize energy usage, and enhance security.</p>
</li>
<li><p><strong>Personalized Learning Platforms:</strong> Develop educational tools that adapt to individual learning styles and progress, providing customized learning experiences.</p>
</li>
<li><p><strong>Advanced Simulation Models:</strong> Use LangGraph to simulate complex systems, such as climate models or urban planning scenarios, for better decision-making.</p>
</li>
</ol>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>LangGraph is not just a tool for building AI applications; it's a gateway to innovation in AI development. By exploring its advanced capabilities, developers can create applications that are not only intelligent but also adaptable and efficient. Whether you're automating complex tasks or enhancing human-agent collaboration, LangGraph offers the flexibility and control needed to bring your AI visions to life.</p>
<h3 id="heading-reference-links"><strong>Reference Links</strong></h3>
<ul>
<li><p><a target="_blank" href="https://www.langchain.com/langgraph"><strong>LangGraph Documentation</strong></a></p>
</li>
<li><p><a target="_blank" href="https://github.com/langchain-ai/langgraph"><strong>LangChain GitHub Repository</strong></a></p>
</li>
</ul>
<p><strong>Image source</strong></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/ai-technology-microchip-background-vector-digital-transformation-concept_16268313.htm#fromView=search&amp;page=1&amp;position=9&amp;uuid=b8ee37d9-2be8-4bb4-becf-b7e26339d324">Image #1</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/symphonic-orchestra-with-conductor-violins-cello-trumpet-musicians_3815735.htm#fromView=search&amp;page=1&amp;position=4&amp;uuid=822d0a49-4745-4ef4-a5f1-14afbd446ff9">Image #2</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/technological-background-with-lines-dots_1034748.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=22108192-5025-4ca0-873d-2222bf852298">Image #3</a></p>
<p><a target="_blank" href="https://www.google.com/imgres?q=langgraph%20logo&amp;imgurl=https%3A%2F%2Flangchain-ai.github.io%2Flanggraph%2Fstatic%2Fwordmark_dark.svg&amp;imgrefurl=https%3A%2F%2Flangchain-ai.github.io%2Flanggraph%2F&amp;docid=2GBetSSbIcaCiM&amp;tbnid=5SBP27JKXHRFxM&amp;vet=12ahUKEwjNqbjcu4OKAxXlaPUHHStnLLMQM3oECBkQAA..i&amp;w=1622&amp;h=251&amp;hcb=2&amp;ved=2ahUKEwjNqbjcu4OKAxXlaPUHHStnLLMQM3oECBkQAA">Logo</a></p>
]]></content:encoded></item><item><title><![CDATA[Integrating Celery with Django: A Comprehensive Guide]]></title><description><![CDATA[Celery is a powerful distributed task queue that can handle millions of tasks per minute. When combined with Django, it becomes an indispensable tool for handling asynchronous tasks, such as sending emails, processing images, or performing long-runni...]]></description><link>https://nikhilakki.in/integrating-celery-with-django-a-comprehensive-guide</link><guid isPermaLink="true">https://nikhilakki.in/integrating-celery-with-django-a-comprehensive-guide</guid><category><![CDATA[django-celery]]></category><category><![CDATA[django-celery-results]]></category><category><![CDATA[Python]]></category><category><![CDATA[Django]]></category><category><![CDATA[celery]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 23 Nov 2024 04:50:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1732337349555/18142aea-e0b9-45a8-a916-6946a454d4e6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Celery is a powerful distributed task queue that can handle millions of tasks per minute. When combined with Django, it becomes an indispensable tool for handling asynchronous tasks, such as sending emails, processing images, or performing long-running computations. This guide will walk you through the process of integrating Celery with Django, covering both the basics and some advanced topics that are not typically covered in standard tutorials.</p>
<h2 id="heading-setting-up-celery-in-a-django-project"><strong>Setting Up Celery in a Django Project</strong></h2>
<h3 id="heading-basic-setup"><strong>Basic Setup</strong></h3>
<ol>
<li><p><strong>Install Celery</strong>: First, ensure that Celery is installed in your Django project. You can do this using pip</p>
<pre><code class="lang-bash"> pip install celery
</code></pre>
</li>
<li><p><strong>Create a Celery Instance</strong>: In your Django project, create a new file named <a target="_blank" href="http://celery.py"><code>celery.py</code></a> in the same directory as your <a target="_blank" href="http://settings.py"><code>settings.py</code></a>. This file will define your Celery application instance.</p>
<pre><code class="lang-python"> <span class="hljs-comment"># proj/proj/celery.py</span>
 <span class="hljs-keyword">import</span> os
 <span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

 os.environ.setdefault(<span class="hljs-string">'DJANGO_SETTINGS_MODULE'</span>, <span class="hljs-string">'proj.settings'</span>)

 app = Celery(<span class="hljs-string">'proj'</span>)
 app.config_from_object(<span class="hljs-string">'django.conf:settings'</span>, namespace=<span class="hljs-string">'CELERY'</span>)
 app.autodiscover_tasks()
</code></pre>
</li>
<li><p><strong>Initialize Celery in Django</strong>: Ensure that your Celery app is loaded when Django starts by importing it in your <code>__init__.py</code> file.</p>
<pre><code class="lang-python"> <span class="hljs-comment"># proj/proj/__init__.py</span>
 <span class="hljs-keyword">from</span> .celery <span class="hljs-keyword">import</span> app <span class="hljs-keyword">as</span> celery_app

 __all__ = (<span class="hljs-string">'celery_app'</span>,)
</code></pre>
</li>
</ol>
<h3 id="heading-advanced-configuration"><strong>Advanced Configuration</strong></h3>
<ul>
<li><p><strong>Custom Task Classes</strong>: If your application requires custom behavior for tasks, consider creating custom task classes. For instance, you might want to log additional information or handle retries differently.</p>
<pre><code class="lang-python">  <span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Task

  <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomTask</span>(<span class="hljs-params">Task</span>):</span>
      <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">on_failure</span>(<span class="hljs-params">self, exc, task_id, args, kwargs, einfo</span>):</span>
          <span class="hljs-comment"># Custom error handling</span>
          <span class="hljs-keyword">pass</span>
</code></pre>
</li>
<li><p><strong>Using Django's ORM as a Result Backend</strong>: The <code>django-celery-results</code> extension allows you to store task results using Django's ORM. This can be particularly useful for tracking task states and results.</p>
<pre><code class="lang-bash">  pip install django-celery-results
</code></pre>
<p>  Add <code>django_celery_results</code> to your <code>INSTALLED_APPS</code> and run migrations:</p>
<pre><code class="lang-python">  INSTALLED_APPS = (
      ...,
      <span class="hljs-string">'django_celery_results'</span>,
  )
</code></pre>
<p>  <strong>bash</strong></p>
<pre><code class="lang-bash">  python manage.py migrate django_celery_results
</code></pre>
<p>  Configure the result backend in your <a target="_blank" href="http://settings.py"><code>settings.py</code></a>:</p>
<pre><code class="lang-ini">  <span class="hljs-attr">CELERY_RESULT_BACKEND</span> = <span class="hljs-string">'django-db'</span>
</code></pre>
</li>
</ul>
<h2 id="heading-advanced-topics"><strong>Advanced Topics</strong></h2>
<h3 id="heading-handling-transactions-with-celery"><strong>Handling Transactions with Celery</strong></h3>
<p>A common issue when using Celery with Django is ensuring that tasks are triggered only after a database transaction is committed. Celery 5.4 introduces the <code>delay_on_commit()</code> method, which simplifies this process.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> transaction
<span class="hljs-keyword">from</span> myapp.tasks <span class="hljs-keyword">import</span> send_email

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_user</span>(<span class="hljs-params">request</span>):</span>
    user = User.objects.create(username=request.POST[<span class="hljs-string">'username'</span>])
    transaction.on_commit(<span class="hljs-keyword">lambda</span>: send_email.delay(user.pk))
</code></pre>
<h3 id="heading-monitoring-and-managing-celery"><strong>Monitoring and Managing Celery</strong></h3>
<ul>
<li><p><strong>Flower</strong>: Flower is a real-time web-based monitoring tool for Celery. It provides insights into task progress, history, and statistics.</p>
<pre><code class="lang-bash">  pip install flower
  celery -A proj flower
</code></pre>
</li>
<li><p><strong>Prometheus and Grafana</strong>: For more advanced monitoring, consider integrating Celery with Prometheus and Grafana. This setup allows you to visualize task metrics and set up alerts.</p>
</li>
</ul>
<h3 id="heading-optimizing-celery-performance"><strong>Optimizing Celery Performance</strong></h3>
<ul>
<li><p><strong>Task Batching</strong>: If you have tasks that can be processed in batches, consider implementing batch processing to reduce overhead and improve throughput.</p>
</li>
<li><p><strong>Prefetch Limits</strong>: Adjust the <code>worker_prefetch_multiplier</code> setting to control how many tasks a worker prefetches. This can help balance load and reduce memory usage.</p>
<pre><code class="lang-ini">  <span class="hljs-attr">CELERY_WORKER_PREFETCH_MULTIPLIER</span> = <span class="hljs-number">1</span>
</code></pre>
</li>
</ul>
<h3 id="heading-security-considerations"><strong>Security Considerations</strong></h3>
<ul>
<li><p><strong>Task Signing</strong>: Enable task signing to ensure that tasks are not tampered with. This adds an extra layer of security, especially in distributed environments.</p>
<pre><code class="lang-ini">  <span class="hljs-attr">CELERY_TASK_SERIALIZER</span> = <span class="hljs-string">'json'</span>
  <span class="hljs-attr">CELERY_ACCEPT_CONTENT</span> = [<span class="hljs-string">'json'</span>]
  <span class="hljs-attr">CELERY_RESULT_SERIALIZER</span> = <span class="hljs-string">'json'</span>
  <span class="hljs-attr">CELERY_TASK_SIGNING</span> = <span class="hljs-literal">True</span>
</code></pre>
</li>
</ul>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Integrating Celery with Django can significantly enhance your application's ability to handle asynchronous tasks efficiently. By following this guide, you should have a solid foundation for setting up and optimizing Celery in your Django projects. For further exploration, consider diving into Celery's advanced features, such as chord and canvas, to orchestrate complex workflows.</p>
<h3 id="heading-other-topics-to-look-out-for"><strong>Other topics to look out for -</strong></h3>
<ul>
<li><p><strong>Using Celery with Django Channels</strong>: Explore how Celery can be used alongside Django Channels for real-time applications.</p>
</li>
<li><p><strong>Implementing Retry Strategies</strong>: Discuss advanced retry strategies for handling transient errors in tasks.</p>
</li>
<li><p><strong>Celery with Docker and Kubernetes</strong>: Guide on deploying Celery in containerized environments for scalability and resilience.</p>
</li>
</ul>
<p>By exploring these topics, you can further enhance your understanding and utilization of Celery in Django projects.</p>
<p><strong>Image attribution</strong></p>
<ol>
<li><p><a target="_blank" href="https://www.djangoproject.com/community/logos/">Django logo</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-photo/fresh-celery-isolated_8759357.htm#fromView=search&amp;page=1&amp;position=6&amp;uuid=b53e43c9-6c83-446f-b778-e912145d9bb5">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-photo/results-evaluate-progress-outcome-productivity-concept_16459052.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=06a099d9-0497-4b91-8180-be4041869ec5">Image #2</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Unlocking the Potential of AI with Flowise]]></title><description><![CDATA[In the rapidly evolving world of AI, developers are constantly seeking tools that streamline the process of building and deploying applications. Enter Flowise, an open-source, low-code platform designed to simplify the creation of customized LLM (Lar...]]></description><link>https://nikhilakki.in/unlocking-the-potential-of-ai-with-flowise</link><guid isPermaLink="true">https://nikhilakki.in/unlocking-the-potential-of-ai-with-flowise</guid><category><![CDATA[langchainjs]]></category><category><![CDATA[langchain-js]]></category><category><![CDATA[Flowise]]></category><category><![CDATA[FlowiseAi]]></category><category><![CDATA[AI]]></category><category><![CDATA[#NoCodeAI]]></category><category><![CDATA[langchain]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 16 Nov 2024 07:29:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731742066370/5e9f1f9a-80f5-4ee3-b50f-9aaf78e53e32.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the rapidly evolving world of AI, developers are constantly seeking tools that streamline the process of building and deploying applications. Enter <a target="_blank" href="https://flowiseai.com/">Flowise</a>, an open-source, low-code platform designed to simplify the creation of customized LLM (Large Language Model) orchestration flows and AI agents. While Flowise has gained popularity for its drag-and-drop interface and seamless integration capabilities, there are still untapped areas that developers can explore to maximize its potential. In this blog, we'll delve into some lesser-known features and innovative use cases of Flowise, offering fresh insights for both beginners and seasoned developers.</p>
<h3 id="heading-1-advanced-customization-with-flowise"><strong>1. Advanced Customization with Flowise</strong></h3>
<p>While Flowise is celebrated for its user-friendly interface, many developers may not be aware of the depth of customization it offers. Beyond the basic templates, Flowise allows for intricate modifications to suit specific project needs. By leveraging its API and SDK, developers can create bespoke solutions that integrate seamlessly with existing systems. This flexibility is particularly beneficial for enterprises looking to tailor AI applications to their unique workflows.</p>
<h3 id="heading-2-integrating-flowise-with-iot-devices"><strong>2. Integrating Flowise with IoT Devices</strong></h3>
<p>The Internet of Things (IoT) is transforming industries by connecting devices and enabling real-time data exchange. Flowise can be a powerful ally in this domain by facilitating the integration of LLMs with IoT devices. Imagine a smart home system where Flowise-powered AI agents manage energy consumption, security, and user preferences, all through natural language interactions. This integration can enhance user experience and operational efficiency across various sectors.</p>
<h3 id="heading-3-enhancing-data-privacy-with-on-premise-deployments"><strong>3. Enhancing Data Privacy with On-Premise Deployments</strong></h3>
<p>Data privacy is a growing concern for businesses and individuals alike. Flowise addresses this by offering on-premise deployment options, allowing organizations to maintain control over their data. This feature is crucial for industries dealing with sensitive information, such as healthcare and finance. By running Flowise in air-gapped environments, companies can ensure compliance with data protection regulations while still harnessing the power of AI.</p>
<h3 id="heading-4-building-multi-modal-applications"><strong>4. Building Multi-Modal Applications</strong></h3>
<p>Flowise is not limited to text-based applications. Developers can explore the creation of multi-modal applications that combine text, image, and even audio processing. This capability opens up new avenues for innovation, such as developing AI-powered educational tools that provide interactive learning experiences or creating virtual assistants that offer comprehensive support across different media formats.</p>
<h3 id="heading-5-leveraging-flowise-for-real-time-analytics"><strong>5. Leveraging Flowise for Real-Time Analytics</strong></h3>
<p>In today's fast-paced world, real-time analytics is a game-changer for businesses. Flowise can be integrated with real-time data streams to provide instant insights and decision-making support. For instance, retailers can use Flowise to analyze customer interactions and adjust marketing strategies on the fly, enhancing customer engagement and boosting sales.</p>
<h3 id="heading-6-community-driven-innovation"><strong>6. Community-Driven Innovation</strong></h3>
<p>One of the strengths of Flowise is its vibrant open-source community. Developers are encouraged to contribute to the platform, sharing their innovations and collaborating on new features. This community-driven approach not only accelerates the development of Flowise but also fosters a culture of learning and sharing among AI enthusiasts.</p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Flowise is more than just a tool for building LLM applications; it's a gateway to innovation in the AI landscape. By exploring its advanced features and integrating it with emerging technologies, developers can unlock new possibilities and drive the next wave of AI advancements. Whether you're looking to enhance data privacy, create multi-modal applications, or leverage real-time analytics, Flowise offers the tools and flexibility to bring your vision to life. Join the Flowise community today and start building the future of AI.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://flowiseai.com/">https://flowiseai.com/</a></div>
<p> </p>
<p>Image attribution</p>
<ol>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/abstract-colourful-mosaic-wave-line-background_24922632.htm#fromView=search&amp;page=1&amp;position=19&amp;uuid=0f501bba-d738-496c-a7cd-fb71604f0709">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/ancient-old-man-standing-cartoon-character-illustration_79639385.htm#fromView=search&amp;page=1&amp;position=0&amp;uuid=e82bfbf5-58ee-43a6-b04d-d665c0e9cd4a">Image #2</a></p>
</li>
<li><p><a target="_blank" href="https://flowiseai.com/">Flowise Logo</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[What is Livewire?]]></title><description><![CDATA[Livewire is a full-stack framework for Laravel that allows developers to build dynamic and interactive user interfaces without needing to write a lot of JavaScript. It works by combining server-side rendering with client-side interactions using AJAX ...]]></description><link>https://nikhilakki.in/what-is-livewire</link><guid isPermaLink="true">https://nikhilakki.in/what-is-livewire</guid><category><![CDATA[PHP]]></category><category><![CDATA[Livewire]]></category><category><![CDATA[Laravel-livewire]]></category><category><![CDATA[Laravel]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Fri, 08 Nov 2024 18:30:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730300650694/28efbd64-348f-49e0-90aa-a4cb96c980aa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Livewire</strong> is a full-stack framework for <strong>Laravel</strong> that allows developers to build dynamic and interactive user interfaces without needing to write a lot of JavaScript. It works by combining <strong>server-side rendering</strong> with client-side interactions using <strong>AJAX</strong> requests, which allows you to create reactive, real-time components within your Laravel application.</p>
<h3 id="heading-key-features-of-livewire">Key Features of Livewire:</h3>
<ol>
<li><p><strong>Reactive Components</strong>: You can create interactive components like forms, modals, or data tables that dynamically update without needing page reloads.</p>
</li>
<li><p><strong>Server-Side Logic</strong>: Instead of handling the logic in JavaScript, you write your logic in PHP. Livewire sends AJAX requests to the server to execute the PHP code and updates the frontend seamlessly.</p>
</li>
<li><p><strong>Simple State Management</strong>: Livewire components maintain their state on the server and automatically sync with the frontend.</p>
</li>
<li><p><strong>Tight Integration with Blade</strong>: Livewire works directly with Laravel's Blade templating engine, allowing you to write PHP and HTML together with very little JavaScript.</p>
</li>
</ol>
<h3 id="heading-example">Example:</h3>
<p>Here’s a simple example of a <strong>Livewire counter component</strong>:</p>
<ol>
<li><p><strong>Create the Livewire Component</strong>:</p>
<pre><code class="lang-bash"> php artisan make:livewire Counter
</code></pre>
</li>
<li><p><strong>In the Livewire Component (app/Http/Livewire/Counter.php):</strong></p>
<pre><code class="lang-php"> <span class="hljs-keyword">namespace</span> <span class="hljs-title">App</span>\<span class="hljs-title">Http</span>\<span class="hljs-title">Livewire</span>;

 <span class="hljs-keyword">use</span> <span class="hljs-title">Livewire</span>\<span class="hljs-title">Component</span>;

 <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span>
 </span>{
     <span class="hljs-keyword">public</span> $count = <span class="hljs-number">0</span>;

     <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">increment</span>(<span class="hljs-params"></span>)
     </span>{
         <span class="hljs-keyword">$this</span>-&gt;count++;
     }

     <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">render</span>(<span class="hljs-params"></span>)
     </span>{
         <span class="hljs-keyword">return</span> view(<span class="hljs-string">'livewire.counter'</span>);
     }
 }
</code></pre>
</li>
<li><p><strong>In the Blade View (resources/views/livewire/counter.blade.php):</strong></p>
<pre><code class="lang-php-template"><span class="xml"> <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{{ $count }}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">wire:click</span>=<span class="hljs-string">"increment"</span>&gt;</span>Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
</code></pre>
</li>
<li><p><strong>In a Laravel Blade Template (resources/views/welcome.blade.php):</strong></p>
<pre><code class="lang-php-template"><span class="xml"> <span class="hljs-tag">&lt;<span class="hljs-name">livewire:counter</span> /&gt;</span></span>
</code></pre>
</li>
</ol>
<p>In this example, clicking the "Increment" button sends a request to the server to execute the <code>increment()</code> method on the <code>Counter</code> component, which updates the <code>$count</code> property and automatically updates the displayed value in the browser.</p>
<h3 id="heading-when-to-use-livewire">When to Use Livewire:</h3>
<ul>
<li><p>When you need dynamic and interactive UIs without complex front-end frameworks like Vue.js or React.</p>
</li>
<li><p>When you want to leverage Laravel’s existing ecosystem and Blade templating.</p>
</li>
<li><p>When you prefer to write PHP over JavaScript for frontend behavior.</p>
</li>
</ul>
<h3 id="heading-benefits">Benefits:</h3>
<ul>
<li><p>Minimal JavaScript needed.</p>
</li>
<li><p>Seamless integration with Laravel Blade templates.</p>
</li>
<li><p>Simplifies the process of building dynamic, interactive components.</p>
</li>
</ul>
<p>Livewire is particularly useful for Laravel developers who want to build reactive, interactive user interfaces without diving deep into frontend frameworks.</p>
<p><strong>Image attribution</strong></p>
<ol>
<li><p>Livewire</p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/PHP#/media/File:PHP-logo.svg">PHP Logo</a></p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Laravel#/media/File:Laravel.svg">Laravel logo</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[What is Blade?]]></title><description><![CDATA[Blade is the simple, powerful templating engine provided with Laravel, a popular PHP framework. It allows developers to write dynamic HTML templates by mixing plain HTML with PHP code in a clean, expressive syntax. Blade templates are compiled into p...]]></description><link>https://nikhilakki.in/what-is-blade</link><guid isPermaLink="true">https://nikhilakki.in/what-is-blade</guid><category><![CDATA[blade-laravel]]></category><category><![CDATA[PHP]]></category><category><![CDATA[Laravel]]></category><category><![CDATA[#Blade Templates]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 02 Nov 2024 04:37:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730300390021/a9c5ff4e-7e18-413f-a45e-9be81ce0e14a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Blade</strong> is the simple, powerful templating engine provided with <strong>Laravel</strong>, a popular PHP framework. It allows developers to write dynamic HTML templates by mixing plain HTML with PHP code in a clean, expressive syntax. Blade templates are compiled into plain PHP and cached for better performance.</p>
<h3 id="heading-key-features-of-blade">Key Features of Blade:</h3>
<ol>
<li><p><strong>Template Inheritance</strong>: Blade makes it easy to define a layout or base structure and then extend it in child views.</p>
</li>
<li><p><strong>Display Dynamic Data</strong>: You can easily output dynamic content using Blade’s curly brace syntax (<code>{{ }}</code>).</p>
</li>
<li><p><strong>Control Structures</strong>: Blade offers clean directives for loops, conditionals, and more.</p>
</li>
<li><p><strong>Components and Slots</strong>: Blade allows reusable components and slots for organizing and reusing UI elements.</p>
</li>
<li><p><strong>Custom Directives</strong>: You can define custom Blade directives for repetitive logic.</p>
</li>
<li><p><strong>No Performance Overhead</strong>: Since Blade templates are compiled into plain PHP, it doesn't add any significant performance overhead.</p>
</li>
</ol>
<h3 id="heading-key-syntax-and-examples">Key Syntax and Examples:</h3>
<h4 id="heading-1-template-inheritance">1. <strong>Template Inheritance:</strong></h4>
<p>Template inheritance allows you to create a common layout that other views can extend.</p>
<ul>
<li><p><strong>Layout Template (resources/views/layouts/app.blade.php):</strong></p>
<pre><code class="lang-php-template"><span class="xml">  htmlCopy code<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>@yield('title')<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">header</span>&gt;</span>
          <span class="hljs-comment">&lt;!-- Common header content --&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
          @yield('content')
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">footer</span>&gt;</span>
          <span class="hljs-comment">&lt;!-- Common footer content --&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">footer</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
</li>
<li><p><strong>Child View (resources/views/pages/home.blade.php):</strong></p>
<pre><code class="lang-php">  @<span class="hljs-keyword">extends</span>(<span class="hljs-string">'layouts.app'</span>)

  @section(<span class="hljs-string">'title'</span>, <span class="hljs-string">'Home Page'</span>)

  @section(<span class="hljs-string">'content'</span>)
      &lt;h1&gt;Welcome to the Home Page&lt;/h1&gt;
      &lt;p&gt;This is some content <span class="hljs-keyword">for</span> the home page.&lt;/p&gt;
  @endsection
</code></pre>
</li>
</ul>
<h4 id="heading-2-outputting-dynamic-data">2. <strong>Outputting Dynamic Data:</strong></h4>
<p>You can output PHP variables using Blade’s curly brace syntax.</p>
<pre><code class="lang-php-template"><span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{{ $title }}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> <span class="hljs-comment">&lt;!-- Echoes the value of $title --&gt;</span></span>
</code></pre>
<p>To escape HTML characters, Blade automatically handles escaping. If you want to render raw HTML, you can use <code>{!! !!}</code>.</p>
<pre><code class="lang-php-template"><span class="xml">{!! $htmlContent !!}</span>
</code></pre>
<h4 id="heading-3-control-structures">3. <strong>Control Structures:</strong></h4>
<p>Blade offers clean syntax for control structures like <code>if</code>, <code>foreach</code>, <code>for</code>, etc.</p>
<ul>
<li><p><strong>Conditionals:</strong></p>
<pre><code class="lang-php-template"><span class="xml">  @if ($isLoggedIn)
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome back, user!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  @else
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Please log in.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  @endif</span>
</code></pre>
</li>
<li><p><strong>Loops:</strong></p>
<pre><code class="lang-php">  @<span class="hljs-keyword">foreach</span> ($users <span class="hljs-keyword">as</span> $user)
      &lt;p&gt;{{ $user-&gt;name }}&lt;/p&gt;
  @<span class="hljs-keyword">endforeach</span>
</code></pre>
</li>
</ul>
<h4 id="heading-4-components-and-slots">4. <strong>Components and Slots:</strong></h4>
<p>You can create reusable components with Blade.</p>
<ul>
<li><p><strong>Component (resources/views/components/alert.blade.php):</strong></p>
<pre><code class="lang-xml">  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"alert alert-{{ $type }}"</span>&gt;</span>
      {{ $message }}
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
</li>
<li><p><strong>Using the Component (in a Blade view):</strong></p>
<pre><code class="lang-xml">  <span class="hljs-tag">&lt;<span class="hljs-name">x-alert</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"success"</span> <span class="hljs-attr">:message</span>=<span class="hljs-string">"$successMessage"</span> /&gt;</span>
</code></pre>
</li>
</ul>
<h4 id="heading-5-custom-blade-directives">5. <strong>Custom Blade Directives:</strong></h4>
<p>Blade allows you to define your custom directives.</p>
<pre><code class="lang-php-template"><span class="xml">Blade::directive('datetime', function ($expression) {
    return "</span><span class="php"><span class="hljs-meta">&lt;?php</span> <span class="hljs-keyword">echo</span> ($expression)-&gt;format(<span class="hljs-string">'m/d/Y H:i'</span>); <span class="hljs-meta">?&gt;</span></span><span class="xml">";
});</span>
</code></pre>
<p>In your Blade view:</p>
<pre><code class="lang-php">@datetime($user-&gt;created_at)
</code></pre>
<h3 id="heading-why-use-blade">Why Use Blade?</h3>
<ul>
<li><p><strong>Readable and Clean</strong>: Blade templates are easy to read and write compared to raw PHP.</p>
</li>
<li><p><strong>Template Inheritance</strong>: Makes building consistent layouts easy.</p>
</li>
<li><p><strong>Reusability</strong>: Components and sections allow you to reuse code efficiently.</p>
</li>
<li><p><strong>Tight Integration</strong>: Blade is tightly integrated with Laravel, making it the default and easiest way to build views in Laravel applications.</p>
</li>
</ul>
<p>Blade simplifies building dynamic, maintainable, and structured views in Laravel applications by combining PHP logic and HTML in a clean, organized manner.</p>
<h4 id="heading-image-attribution">Image attribution</h4>
<ol>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Laravel#/media/File:Laravel.svg">Laravel logo</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/barber-blade-white-background_19785353.htm#fromView=search&amp;page=1&amp;position=22&amp;uuid=53b5b105-c03e-44ed-a2a9-578b3073c629">Blade image</a></p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/PHP#/media/File:PHP-logo.svg">PHP Logo</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[JSON manipulation in Go]]></title><description><![CDATA[Dealing with JSON manipulation in Go can involve several approaches, depending on the complexity of your JSON data, the desired performance, and how strict you want to be with your data structures. Below are some common methods:
1. Struct-based Encod...]]></description><link>https://nikhilakki.in/json-manipulation-in-go</link><guid isPermaLink="true">https://nikhilakki.in/json-manipulation-in-go</guid><category><![CDATA[json-in-go]]></category><category><![CDATA[manipulate-json-in-go]]></category><category><![CDATA[jsongo]]></category><category><![CDATA[go-json]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[json]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 26 Oct 2024 05:43:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729921357207/325a7575-5afa-4b85-9d5d-6a7ceaf6ea81.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Dealing with JSON manipulation in Go can involve several approaches, depending on the complexity of your JSON data, the desired performance, and how strict you want to be with your data structures. Below are some common methods:</p>
<h3 id="heading-1-struct-based-encoding-and-decoding">1. <strong>Struct-based Encoding and Decoding</strong></h3>
<p>The most idiomatic way to handle JSON in Go is by mapping JSON data directly to strongly-typed Go structs. This provides compile-time safety and clear structure.</p>
<h4 id="heading-example">Example:</h4>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name  <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span>
    Age   <span class="hljs-keyword">int</span>    <span class="hljs-string">`json:"age"`</span>
    Email <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"email,omitempty"`</span>
}
<span class="hljs-comment">// Encode (marshal)</span>
person := Person{Name: <span class="hljs-string">"John"</span>, Age: <span class="hljs-number">30</span>, Email: <span class="hljs-string">"john@example.com"</span>}
jsonData, _ := json.Marshal(person)
<span class="hljs-comment">// Decode (unmarshal)</span>
<span class="hljs-keyword">var</span> decodedPerson Person
json.Unmarshal(jsonData, &amp;decodedPerson)
</code></pre>
<h3 id="heading-advantages">Advantages:</h3>
<ul>
<li><p><strong>Strong typing</strong>: Fields are directly mapped to Go types.</p>
</li>
<li><p><strong>Validation</strong>: Go's type system ensures data is correctly structured.</p>
</li>
<li><p><strong>Compile-time checks</strong>: Errors in field types are caught early.</p>
</li>
</ul>
<h3 id="heading-2-mapstringinterface-for-dynamic-or-unknown-json">2. <code>map[string]interface{}</code> for Dynamic or Unknown JSON</h3>
<p>If you are dealing with dynamic or unknown JSON structures (like in APIs or flexible schemas), you can use a <code>map[string]interface{}</code> to handle arbitrary key-value pairs.</p>
<h4 id="heading-example-1">Example:</h4>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> data <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">interface</span>{}
jsonStr := <span class="hljs-string">`{"name": "John", "age": 30, "email": "john@example.com"}`</span>

json.Unmarshal([]<span class="hljs-keyword">byte</span>(jsonStr), &amp;data)
fmt.Println(data[<span class="hljs-string">"name"</span>], data[<span class="hljs-string">"age"</span>]) <span class="hljs-comment">// Output: John 30</span>
</code></pre>
<h3 id="heading-advantages-1">Advantages:</h3>
<ul>
<li><p><strong>Flexibility</strong>: Suitable for JSON with unknown or dynamic structures.</p>
</li>
<li><p><strong>Ad-hoc manipulation</strong>: You can dynamically access and modify fields.</p>
</li>
</ul>
<h3 id="heading-disadvantages">Disadvantages:</h3>
<ul>
<li><p><strong>Lack of type safety</strong>: You need to perform type assertions manually.</p>
</li>
<li><p><strong>Error-prone</strong>: More runtime errors may occur, e.g., wrong type assumptions.</p>
</li>
</ul>
<h3 id="heading-3-rawmessage-for-deferred-json-parsing">3. <code>RawMessage</code> for Deferred JSON Parsing</h3>
<p>For partial parsing or when you need to manipulate a portion of JSON without fully unmarshaling it, you can use <code>json.RawMessage</code>. This allows delaying or conditionally parsing part of the JSON data.</p>
<h4 id="heading-example-2">Example:</h4>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Envelope <span class="hljs-keyword">struct</span> {
    Type <span class="hljs-keyword">string</span>          <span class="hljs-string">`json:"type"`</span>
    Data json.RawMessage <span class="hljs-string">`json:"data"`</span>
}

<span class="hljs-comment">// Partial decode</span>
jsonStr := <span class="hljs-string">`{"type": "person", "data": {"name": "John", "age": 30}}`</span>
<span class="hljs-keyword">var</span> env Envelope
json.Unmarshal([]<span class="hljs-keyword">byte</span>(jsonStr), &amp;env)

<span class="hljs-keyword">if</span> env.Type == <span class="hljs-string">"person"</span> {
    <span class="hljs-keyword">var</span> person Person
    json.Unmarshal(env.Data, &amp;person)
    fmt.Println(person.Name, person.Age) <span class="hljs-comment">// Output: John 30</span>
}
</code></pre>
<h3 id="heading-advantages-2">Advantages:</h3>
<ul>
<li><p><strong>Lazy parsing</strong>: You can avoid parsing unnecessary parts of the JSON.</p>
</li>
<li><p><strong>Flexibility</strong>: Great for handling complex APIs with different payloads.</p>
</li>
</ul>
<h3 id="heading-4-third-party-libraries-for-more-complex-operations">4. <strong>Third-Party Libraries for More Complex Operations</strong></h3>
<p>For more advanced JSON handling, such as querying or mutating JSON paths, you can use libraries like:</p>
<ul>
<li><p><a target="_blank" href="http://github.com/tidwall/gjson"><code>github.com/tidwall/gjson</code></a> (for fast JSON querying)</p>
</li>
<li><p><a target="_blank" href="http://github.com/buger/jsonparser"><code>github.com/buger/jsonparser</code></a> (for efficient JSON parsing)</p>
</li>
<li><p><a target="_blank" href="http://github.com/yalp/jsonpath"><code>github.com/yalp/jsonpath</code></a> (for JSONPath expressions)</p>
</li>
</ul>
<h4 id="heading-example-using-gjson">Example using <code>gjson</code>:</h4>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"github.com/tidwall/gjson"</span>

jsonStr := <span class="hljs-string">`{"name": "John", "age": 30, "address": {"city": "New York"}}`</span>
name := gjson.Get(jsonStr, <span class="hljs-string">"name"</span>).String()         <span class="hljs-comment">// Get "John"</span>
city := gjson.Get(jsonStr, <span class="hljs-string">"address.city"</span>).String() <span class="hljs-comment">// Get "New York"</span>
fmt.Println(name, city)
</code></pre>
<h3 id="heading-advantages-3">Advantages:</h3>
<ul>
<li><p><strong>Efficiency</strong>: Some libraries are faster and optimized for large JSON data.</p>
</li>
<li><p><strong>Path queries</strong>: Libraries like <code>gjson</code> allow querying specific fields with dot notation.</p>
</li>
</ul>
<h3 id="heading-5-streaming-json-with-jsondecoder">5. <strong>Streaming JSON with</strong> <code>json.Decoder</code></h3>
<p>For handling very large JSON data or when working with streams, Go’s <code>json.Decoder</code> can be used to read the JSON incrementally without loading it entirely into memory.</p>
<h4 id="heading-example-3">Example:</h4>
<pre><code class="lang-go">file, _ := os.Open(<span class="hljs-string">"large.json"</span>)
<span class="hljs-keyword">defer</span> file.Close()

decoder := json.NewDecoder(file)
<span class="hljs-keyword">for</span> decoder.More() {
    <span class="hljs-keyword">var</span> person Person
    decoder.Decode(&amp;person)
    fmt.Println(person.Name, person.Age)
}
</code></pre>
<h3 id="heading-advantages-4">Advantages:</h3>
<ul>
<li><p><strong>Memory-efficient</strong>: Useful for large JSON data that cannot fit into memory at once.</p>
</li>
<li><p><strong>Streaming</strong>: Allows you to process JSON as it's being read.</p>
</li>
</ul>
<h3 id="heading-6-custom-marshalunmarshal-methods">6. <strong>Custom Marshal/Unmarshal Methods</strong></h3>
<p>You can define custom JSON encoding/decoding behavior by implementing the <code>json.Marshaler</code> and <code>json.Unmarshaler</code> interfaces. This is useful when you need fine-grained control over how JSON is generated or parsed.</p>
<h4 id="heading-example-4">Example:</h4>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> CustomPerson <span class="hljs-keyword">struct</span> {
    Name  <span class="hljs-keyword">string</span>
    Age   <span class="hljs-keyword">int</span>
}
<span class="hljs-comment">// Custom unmarshal</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(cp *CustomPerson)</span> <span class="hljs-title">UnmarshalJSON</span><span class="hljs-params">(data []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-title">error</span></span> {
    <span class="hljs-keyword">var</span> aux <span class="hljs-keyword">struct</span> {
        Name <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span>
        Age  <span class="hljs-keyword">int</span>    <span class="hljs-string">`json:"age"`</span>
    }
    err := json.Unmarshal(data, &amp;aux)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> err
    }
    cp.Name = strings.ToUpper(aux.Name) <span class="hljs-comment">// Custom logic: make the name uppercase</span>
    cp.Age = aux.Age
    <span class="hljs-keyword">return</span> <span class="hljs-literal">nil</span>
}
</code></pre>
<h3 id="heading-advantages-5">Advantages:</h3>
<ul>
<li><p><strong>Custom behavior</strong>: Allows special formatting or validation rules during marshaling/un-marshaling.</p>
</li>
<li><p><strong>Encapsulation</strong>: Keeps complex logic within the struct.</p>
</li>
</ul>
<hr />
<h3 id="heading-conclusion">Conclusion:</h3>
<ul>
<li><p>For structured JSON data: use <strong>struct-based</strong> encoding/decoding.</p>
</li>
<li><p>For dynamic or flexible JSON: use <code>map[string]interface{}</code>.</p>
</li>
<li><p>For partial or deferred parsing: use <code>json.RawMessage</code>.</p>
</li>
<li><p>For very large JSON or streams: use <code>json.Decoder</code>.</p>
</li>
<li><p>For advanced querying or manipulation: consider third-party libraries like <code>gjson</code>.</p>
</li>
<li><p>For custom handling: implement <strong>custom marshaling/un-marshaling</strong>.</p>
</li>
</ul>
<p>Choose the method based on your specific needs—performance, flexibility, and type safety.</p>
<p><strong>Image attribution</strong></p>
<p><a target="_blank" href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fscreenrant.com%2Fjason-bourne-movies-in-order%2F&amp;psig=AOvVaw28eOUaBUvZ9Vg_0Hbs5oD-&amp;ust=1730007671019000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCLCWsveqq4kDFQAAAAAdAAAAABAE">Jason Bourne image</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/boss-manipulating-employee_902031.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=fee08083-c645-47b1-9ef8-5be3d038cde4">Image #2</a></p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Go_%28programming_language%29#/media/File:Go_Logo_Blue.svg">Go logo</a></p>
]]></content:encoded></item><item><title><![CDATA[Going Green(let): Concurrency without the Chaos!]]></title><description><![CDATA[A greenlet is a lightweight, low-level coroutine-like primitive in Python, used primarily for concurrency. It is part of the greenlet module, which is often associated with gevent, a library for asynchronous I/O operations.
Here are some key points a...]]></description><link>https://nikhilakki.in/going-greenlet-concurrency-without-the-chaos</link><guid isPermaLink="true">https://nikhilakki.in/going-greenlet-concurrency-without-the-chaos</guid><category><![CDATA[greenlet]]></category><category><![CDATA[asyncpython]]></category><category><![CDATA[micro-threads-python]]></category><category><![CDATA[micro-threads]]></category><category><![CDATA[Python]]></category><category><![CDATA[AsyncProgramming]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 19 Oct 2024 05:36:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728915805420/81e738e1-c14d-473b-831d-605d1a7f5cbf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A <a target="_blank" href="https://greenlet.readthedocs.io/en/latest/"><strong>greenlet</strong></a> is a lightweight, low-level coroutine-like primitive in Python, used primarily for concurrency. It is part of the <code>greenlet</code> module, which is often associated with <strong>gevent</strong>, a library for asynchronous I/O operations.</p>
<p>Here are some key points about greenlets:</p>
<ol>
<li><p><strong>Micro-threading</strong>: Greenlets are like micro-threads that allow you to manage the execution of code blocks without creating actual OS-level threads. They are not parallel, but concurrent, meaning they give the appearance of multitasking by switching between different tasks.</p>
</li>
<li><p><strong>Explicit switching</strong>: Unlike Python's built-in coroutines or async/await syntax, greenlets require explicit control over when to switch from one greenlet to another, which is done using the <code>greenlet.switch()</code> method.</p>
</li>
<li><p><strong>Use Cases</strong>:</p>
<ul>
<li><p>Greenlets are often used in applications that require high concurrency but don't want the overhead of traditional multithreading.</p>
</li>
<li><p>They are commonly found in networking applications (for example, handling many client connections efficiently) through libraries like <strong>gevent</strong>.</p>
</li>
</ul>
</li>
<li><p><strong>Stack Saving</strong>: A greenlet can save the state of the current stack (variables, code location, etc.) and resume from that state later. This allows for cooperative multitasking between greenlets.</p>
</li>
</ol>
<h3 id="heading-simple-example">Simple Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> greenlet <span class="hljs-keyword">import</span> greenlet

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">task1</span>():</span>
    print(<span class="hljs-string">"Task 1 - Part 1"</span>)
    g2.switch()  <span class="hljs-comment"># Switch to task 2</span>
    print(<span class="hljs-string">"Task 1 - Part 2"</span>)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">task2</span>():</span>
    print(<span class="hljs-string">"Task 2 - Part 1"</span>)
    g1.switch()  <span class="hljs-comment"># Switch back to task 1</span>
    print(<span class="hljs-string">"Task 2 - Part 2"</span>)

g1 = greenlet(task1)
g2 = greenlet(task2)

g1.switch()  <span class="hljs-comment"># Start execution with task1</span>
</code></pre>
<p>In this example, <code>task1</code> and <code>task2</code> switch between each other, creating a form of cooperative concurrency.</p>
<h3 id="heading-related-libraries">Related Libraries:</h3>
<ul>
<li><a target="_blank" href="https://www.gevent.org/"><strong>gevent</strong></a>: A higher-level library that builds on greenlets and provides more abstract concurrency features like networking and I/O operations.</li>
</ul>
<p>Greenlets are quite powerful but are not used as widely as Python's modern asynchronous capabilities, such as <code>asyncio</code>, which provides a higher-level API for concurrency.</p>
<h4 id="heading-resources">Resources</h4>
<ol>
<li><p><a target="_blank" href="https://greenlet.readthedocs.io/en/latest/">https://greenlet.readthedocs.io/en/latest/</a></p>
</li>
<li><p><a target="_blank" href="https://www.gevent.org/">https://www.gevent.org/</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/gevent/gevent">https://github.com/gevent/gevent</a></p>
</li>
</ol>
<p>Image attribution</p>
<ul>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/File:Python-logo-notext.svg">Python logo</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/watercolor-emerald-background_39879210.htm#fromView=search&amp;page=1&amp;position=0&amp;uuid=f2f287b7-3cd6-4588-9cce-609604f010b1">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/multitasking-concept-illustration_9930923.htm#fromView=search&amp;page=1&amp;position=0&amp;uuid=9de926de-cd21-4adb-893c-9c31eaaa5532">Image #2</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[` Backticks ` in Go Lang]]></title><description><![CDATA[In Go, backtick tags are used in struct definitions to define metadata, typically for serialization or data validation. These tags are most commonly used with libraries like encoding/json, encoding/xml, or for other custom use cases. The backtick not...]]></description><link>https://nikhilakki.in/backticks-in-go-lang</link><guid isPermaLink="true">https://nikhilakki.in/backticks-in-go-lang</guid><category><![CDATA[backticks]]></category><category><![CDATA[golang]]></category><category><![CDATA[reflection]]></category><category><![CDATA[Meta Programming ]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 12 Oct 2024 05:36:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1728105658214/6ff6e857-db19-47c0-a88e-bc587fc34de0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Go, backtick tags are used in struct definitions to define metadata, typically for serialization or data validation. These tags are most commonly used with libraries like <code>encoding/json</code>, <code>encoding/xml</code>, or for other custom use cases. The backtick notation allows you to annotate struct fields with string-based metadata.</p>
<p>Here’s an example:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name  <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span>
    Age   <span class="hljs-keyword">int</span>    <span class="hljs-string">`json:"age"`</span>
    Email <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"email,omitempty"`</span>
}
</code></pre>
<h3 id="heading-explanation">Explanation:</h3>
<ul>
<li><p>The backticks enclose the struct field tags.</p>
</li>
<li><p><code>json:"name"</code> tells the JSON encoder/decoder to map the <code>Name</code> field to/from the <code>"name"</code> key in a JSON object.</p>
</li>
<li><p><code>json:"email,omitempty"</code> means the <code>Email</code> field is mapped to the <code>"email"</code> key, but will be omitted from the output if it is empty (<code>""</code> for strings, <code>0</code> for numbers, <code>nil</code> for pointers, etc.).</p>
</li>
</ul>
<p>Other libraries may use similar mechanisms to interact with struct fields based on these tags.</p>
<h3 id="heading-is-this-meta-programming">Is this Meta-programming?</h3>
<p>While Go struct tags resemble metadata, they are not considered full-fledged <strong>metaprogramming</strong> in the traditional sense. Go doesn't support dynamic code generation, reflection-based type alterations, or macros as seen in languages like Python or Lisp. However, Go does offer <strong>reflection</strong> through the <code>reflect</code> package, which allows inspecting types and values at runtime, and struct tags play a role in this.</p>
<p>In Go, struct tags are more like static metadata annotations. They're mainly used in tandem with reflection for libraries like <code>json</code>, <code>xml</code>, or ORM libraries, but they don't alter the behavior of the program at compile time (like traditional metaprogramming might).</p>
<h3 id="heading-how-it-works">How it works:</h3>
<ul>
<li>Struct tags are stored as part of the field’s definition and can be accessed at runtime via the <code>reflect</code> package. For instance, libraries read these tags to determine how to serialize or deserialize struct fields.</li>
</ul>
<p>Example of accessing tags using reflection:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"reflect"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name  <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"name"`</span>
    Email <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"email,omitempty"`</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    personType := reflect.TypeOf(Person{})
    field, _ := personType.FieldByName(<span class="hljs-string">"Name"</span>)
    fmt.Println(field.Tag.Get(<span class="hljs-string">"json"</span>)) <span class="hljs-comment">// Output: name</span>
}
</code></pre>
<p>This allows libraries to interpret and utilize struct tags but without changing the structure or logic of the program dynamically at runtime.</p>
<h3 id="heading-conclusion">Conclusion:</h3>
<p>This tag system makes it possible to control how data is marshaled and un-marshaled between Go structs and external data formats. While Go struct tags are reflective metadata that can be introspected at runtime, they don't fall under true <strong>metaprogramming</strong> as Go lacks dynamic code modification capabilities. Instead, Go focuses on simplicity and explicitness, using tools like reflection sparingly to provide extensibility.</p>
<p>Image attribution</p>
<p><a target="_blank" href="https://www.freepik.com/free-photo/young-man-pointing-away-t-shirt-looking-focused_10927594.htm#fromView=search&amp;page=1&amp;position=13&amp;uuid=ce8fe60e-c247-43e3-99b0-c5890d66d9af">#1</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/multiple-different-check-marks_35514630.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=57472b1b-df05-4472-9c3b-165039554068">#2</a></p>
]]></content:encoded></item><item><title><![CDATA[Implement an Abstract Class in Go!]]></title><description><![CDATA[Well in Go, there is no direct equivalent of Python's abstract classes, but you can achieve similar functionality using interfaces and struct embedding. Here's how you can replicate the behavior of an abstract class in Go.
Python Abstract Class Examp...]]></description><link>https://nikhilakki.in/implement-an-abstract-class-in-go</link><guid isPermaLink="true">https://nikhilakki.in/implement-an-abstract-class-in-go</guid><category><![CDATA[golang]]></category><category><![CDATA[Interfaces]]></category><category><![CDATA[structs]]></category><category><![CDATA[abstract class]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 05 Oct 2024 05:13:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725641261341/f4361ea2-c119-46fd-90ae-5b68055b5eb9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Well in Go, there is no direct equivalent of Python's abstract classes, but you can achieve similar functionality using interfaces and struct embedding. Here's how you can replicate the behavior of an abstract class in Go.</p>
<h3 id="heading-python-abstract-class-example">Python Abstract Class Example:</h3>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> abc <span class="hljs-keyword">import</span> ABC, abstractmethod

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>(<span class="hljs-params">ABC</span>):</span>
<span class="hljs-meta">    @abstractmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">make_sound</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">pass</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>(<span class="hljs-params">Animal</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">make_sound</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Woof"</span>
</code></pre>
<h3 id="heading-go-equivalent-using-interfaces-and-struct-embedding">Go Equivalent Using Interfaces and Struct Embedding:</h3>
<p>In Go, you can define an interface to represent the abstract methods and use struct embedding to simulate shared behavior.</p>
<ol>
<li><p><strong>Define the interface</strong> to represent the abstract method.</p>
</li>
<li><p><strong>Use structs</strong> to implement that interface.</p>
</li>
</ol>
<p>Here’s an equivalent example in Go:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-comment">// Define an interface similar to an abstract method</span>
<span class="hljs-keyword">type</span> Animal <span class="hljs-keyword">interface</span> {
    MakeSound() <span class="hljs-keyword">string</span>
}

<span class="hljs-comment">// Define a struct representing the base class (optional if you need shared fields)</span>
<span class="hljs-keyword">type</span> BaseAnimal <span class="hljs-keyword">struct</span> {
    <span class="hljs-comment">// you can add fields common to all animals here</span>
}

<span class="hljs-comment">// Define another struct implementing the abstract method</span>
<span class="hljs-keyword">type</span> Dog <span class="hljs-keyword">struct</span> {
    BaseAnimal <span class="hljs-comment">// Embedding BaseAnimal struct to inherit shared fields (if any)</span>
}

<span class="hljs-comment">// Implement the interface method for Dog</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(d Dog)</span> <span class="hljs-title">MakeSound</span><span class="hljs-params">()</span> <span class="hljs-title">string</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Woof"</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> animal Animal = Dog{}
    fmt.Println(animal.MakeSound()) <span class="hljs-comment">// Output: Woof</span>
}
</code></pre>
<h3 id="heading-key-concepts">Key Concepts:</h3>
<ul>
<li><p><code>Animal</code> interface is equivalent to the abstract class method in Python.</p>
</li>
<li><p><code>BaseAnimal</code> struct is used if you need shared fields or behavior, similar to a base class in Python (though it's not necessary if you're only using abstract methods).</p>
</li>
<li><p><strong>Struct</strong> <code>Dog</code> implements the <code>Animal</code> interface by providing the <code>MakeSound()</code> method, similar to a subclass overriding an abstract method in Python.</p>
</li>
</ul>
<h3 id="heading-summary">Summary</h3>
<p>In Go, interfaces define abstract methods, and structs implement those methods. You can combine them with struct embedding to share common functionality across different types.</p>
<p><strong>References</strong></p>
<p><a target="_blank" href="https://gobyexample.com/interfaces">https://gobyexample.com/interfaces</a></p>
<p><a target="_blank" href="https://www.alexedwards.net/blog/interfaces-explained">https://www.alexedwards.net/blog/interfaces-explained</a></p>
<p><strong>Image Attribution</strong></p>
<p><a target="_blank" href="https://www.freepik.com/free-vector/abstract-art-cover-collection_14570650.htm#fromView=search&amp;page=1&amp;position=0&amp;uuid=a4b46496-c537-4154-953e-75e93cd57f5b">Image #1</a></p>
<p><a target="_blank" href="https://www.freepik.com/free-photo/students-knowing-right-answer_13132985.htm#fromView=search&amp;page=1&amp;position=1&amp;uuid=5f443d43-21ae-4b1b-a1f0-0122ac145f24">Image #2</a></p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Go_(programming_language)#/media/File:Go_Logo_Blue.svg">Go</a> &amp; <a target="_blank" href="https://en.wikipedia.org/wiki/Go_(programming_language)#/media/File:Golang.png">Gopher</a></p>
]]></content:encoded></item><item><title><![CDATA[elixir 101]]></title><description><![CDATA[Elixir is a functional, concurrent language built on the Erlang VM (BEAM), known for its fault tolerance and scalability. To get started you'll need to understand basic syntax, concurrency, pattern matching, and working with data structures.
1. Basic...]]></description><link>https://nikhilakki.in/elixir-101</link><guid isPermaLink="true">https://nikhilakki.in/elixir-101</guid><category><![CDATA[Elixir]]></category><category><![CDATA[OTP]]></category><category><![CDATA[Erlang]]></category><category><![CDATA[Phoenix framework]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 28 Sep 2024 06:12:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725424628310/e930b1c4-e9db-431d-9048-edfadb135096.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Elixir is a functional, concurrent language built on the Erlang VM (BEAM), known for its fault tolerance and scalability. To get started you'll need to understand basic syntax, concurrency, pattern matching, and working with data structures.</p>
<h4 id="heading-1-basic-syntax">1. <strong>Basic Syntax</strong></h4>
<ul>
<li><strong>Variables and Immutability</strong>: Variables are immutable. Once you bind a value to a variable, it cannot be changed.</li>
</ul>
<pre><code class="lang-elixir">x = <span class="hljs-number">5</span>
<span class="hljs-comment"># x = 6  (will not work)</span>
</code></pre>
<ul>
<li><strong>Atoms</strong>: Constants whose name is their value, often used as labels or keys.</li>
</ul>
<pre><code class="lang-elixir"><span class="hljs-symbol">:ok</span>
<span class="hljs-symbol">:error</span>
</code></pre>
<ul>
<li><strong>Tuples</strong>: Fixed-size collections of values.</li>
</ul>
<pre><code class="lang-elixir">{<span class="hljs-symbol">:ok</span>, <span class="hljs-string">"Success"</span>}
{<span class="hljs-symbol">:error</span>, <span class="hljs-string">"Something went wrong"</span>}
</code></pre>
<ul>
<li><strong>Lists</strong>: Linked lists, frequently used for collections of data.</li>
</ul>
<pre><code class="lang-elixir">[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
</code></pre>
<ul>
<li><strong>Maps</strong>: Key-value stores for more complex data.</li>
</ul>
<pre><code class="lang-elixir">%{<span class="hljs-symbol">name:</span> <span class="hljs-string">"John"</span>, <span class="hljs-symbol">age:</span> <span class="hljs-number">30</span>}
</code></pre>
<h4 id="heading-2-pattern-matching">2. <strong>Pattern Matching</strong></h4>
<ul>
<li>Fundamental to Elixir, it’s used to de-structure data and bind variables.</li>
</ul>
<pre><code class="lang-elixir">{<span class="hljs-symbol">:ok</span>, result} = {<span class="hljs-symbol">:ok</span>, <span class="hljs-number">42</span>}
</code></pre>
<h4 id="heading-3-control-flow">3. <strong>Control Flow</strong></h4>
<ul>
<li><code>case</code>: Used for branching logic based on pattern matching.</li>
</ul>
<pre><code class="lang-elixir"><span class="hljs-keyword">case</span> x <span class="hljs-keyword">do</span>
  <span class="hljs-number">1</span> -&gt; <span class="hljs-string">"one"</span>
  <span class="hljs-number">2</span> -&gt; <span class="hljs-string">"two"</span>
  _ -&gt; <span class="hljs-string">"something else"</span>
<span class="hljs-keyword">end</span>
</code></pre>
<ul>
<li><code>cond</code>: Similar to <code>else if</code> in other languages.</li>
</ul>
<pre><code class="lang-elixir"><span class="hljs-keyword">cond</span> <span class="hljs-keyword">do</span>
  x == <span class="hljs-number">1</span> -&gt; <span class="hljs-string">"one"</span>
  x == <span class="hljs-number">2</span> -&gt; <span class="hljs-string">"two"</span>
  <span class="hljs-keyword">true</span> -&gt; <span class="hljs-string">"something else"</span>
<span class="hljs-keyword">end</span>
</code></pre>
<ul>
<li><code>with</code>: Chains pattern matching expressions, simplifying nested <code>case</code> statements.</li>
</ul>
<pre><code class="lang-elixir"><span class="hljs-keyword">with</span> {<span class="hljs-symbol">:ok</span>, result} &lt;- some_function(),
     {<span class="hljs-symbol">:ok</span>, processed} &lt;- another_function(result) <span class="hljs-keyword">do</span>
  {<span class="hljs-symbol">:ok</span>, processed}
else
  _ -&gt; {<span class="hljs-symbol">:error</span>, <span class="hljs-string">"Something went wrong"</span>}
<span class="hljs-keyword">end</span>
</code></pre>
<h4 id="heading-4-functions">4. <strong>Functions</strong></h4>
<ul>
<li>Functions are first-class citizens and can be defined with multiple clauses using pattern matching.</li>
</ul>
<pre><code class="lang-elixir"><span class="hljs-class"><span class="hljs-keyword">defmodule</span> <span class="hljs-title">Math</span></span> <span class="hljs-keyword">do</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sum</span></span>(a, b), <span class="hljs-symbol">do:</span> a + b
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">factorial</span></span>(0), <span class="hljs-symbol">do:</span> <span class="hljs-number">1</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">factorial</span></span>(n), <span class="hljs-symbol">do:</span> n * factorial(n - <span class="hljs-number">1</span>)
<span class="hljs-keyword">end</span>
</code></pre>
<h4 id="heading-5-concurrency-processes">5. <strong>Concurrency (Processes)</strong></h4>
<ul>
<li><strong>Processes</strong>: Lightweight and isolated. Use <code>spawn</code> to create a new process.</li>
</ul>
<pre><code class="lang-elixir">spawn(<span class="hljs-keyword">fn</span> -&gt; IO.puts(<span class="hljs-string">"Hello from another process"</span>) <span class="hljs-keyword">end</span>)
</code></pre>
<ul>
<li><strong>Messaging</strong>: Processes communicate via message passing.</li>
</ul>
<pre><code class="lang-elixir">send(<span class="hljs-keyword">self</span>(), {<span class="hljs-symbol">:hello</span>, <span class="hljs-string">"world"</span>})
receive <span class="hljs-keyword">do</span>
  {<span class="hljs-symbol">:hello</span>, msg} -&gt; IO.puts(msg)
<span class="hljs-keyword">end</span>
</code></pre>
<h4 id="heading-6-collections">6. <strong>Collections</strong></h4>
<ul>
<li><strong>Enum Module</strong>: Provides a set of algorithms for working with collections.</li>
</ul>
<pre><code class="lang-elixir">Enum.map([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], <span class="hljs-keyword">fn</span> x -&gt; x * <span class="hljs-number">2</span> <span class="hljs-keyword">end</span>)
Enum.filter([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>], <span class="hljs-keyword">fn</span> x -&gt; rem(x, <span class="hljs-number">2</span>) == 0 <span class="hljs-keyword">end</span>)
</code></pre>
<h4 id="heading-7-mix-build-tool">7. <strong>Mix (Build Tool)</strong></h4>
<ul>
<li>Elixir projects are managed with <code>mix</code>.</li>
</ul>
<pre><code class="lang-bash">mix new my_project
<span class="hljs-built_in">cd</span> my_project
mix compile
</code></pre>
<h4 id="heading-8-testing">8. <strong>Testing</strong></h4>
<ul>
<li>Elixir has built-in support for testing with <code>ExUnit</code>.</li>
</ul>
<pre><code class="lang-elixir"><span class="hljs-class"><span class="hljs-keyword">defmodule</span> <span class="hljs-title">MathTest</span></span> <span class="hljs-keyword">do</span>
  <span class="hljs-keyword">use</span> ExUnit.Case
  test <span class="hljs-string">"sum/2 adds two numbers"</span> <span class="hljs-keyword">do</span>
    assert Math.sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>) == <span class="hljs-number">3</span>
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>
</code></pre>
<h3 id="heading-advance-topics"><strong>Advance topics</strong></h3>
<ol>
<li><p><strong>Advanced OTP (Open Telecom Platform)</strong></p>
<ul>
<li>Supervisors, GenServer, GenStage, and more complex process management are key to building robust, fault-tolerant applications. These tools manage how processes are spawned, monitored, and restarted in case of failure.</li>
</ul>
</li>
<li><p><strong>Metaprogramming</strong></p>
<ul>
<li>Elixir allows you to write code that generates code, primarily through macros. This is useful for DSLs (Domain-Specific Languages) and compile-time optimizations but is often complex.</li>
</ul>
</li>
<li><p><strong>Distributed Systems</strong></p>
<ul>
<li>Elixir excels at building distributed systems. Understanding clustering, distributed databases (like Mnesia), and how to build scalable systems across nodes would fall into this category.</li>
</ul>
</li>
<li><p><strong>NIFs (Native Implemented Functions)</strong></p>
<ul>
<li>Integrating with C/C++ code for performance-critical tasks. This requires careful handling due to potential side effects.</li>
</ul>
</li>
<li><p><strong>Complex Multi-Process Architectures</strong></p>
<ul>
<li>Designing and implementing systems with complex inter-process communication, where you need to manage state and concurrency across many processes.</li>
</ul>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>The above concepts should help you build and maintain most Elixir applications, especially in web development, where tools like Phoenix leverage these concepts.</p>
<p>I recommend reading the official docs.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="http://elixir-lang.org/">http://elixir-lang.org/</a></div>
<p> </p>
<p><strong>Image attribution</strong></p>
<ol>
<li><p><a target="_blank" href="https://elixir-lang.org/">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/magic-potion-bottles-set_9175377.htm#fromView=search&amp;page=1&amp;position=3&amp;uuid=1682a432-bb4d-40f1-8192-751e162bac7e">Image #2</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[What is Actor Model?]]></title><description><![CDATA[The Actor Model is a conceptual model for dealing with concurrent computation. It was introduced by Carl Hewitt in the 1970s and has become a foundational model for designing distributed systems, particularly those requiring high levels of concurrenc...]]></description><link>https://nikhilakki.in/what-is-actor-model</link><guid isPermaLink="true">https://nikhilakki.in/what-is-actor-model</guid><category><![CDATA[actor model]]></category><category><![CDATA[Elixir]]></category><category><![CDATA[Akka]]></category><category><![CDATA[Erlang]]></category><category><![CDATA[concurrency]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 21 Sep 2024 04:37:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725424064465/b3209df8-f8e4-41f9-bd38-d7cea2bf74e7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The <strong>Actor Model</strong> is a conceptual model for dealing with concurrent computation. It was introduced by Carl Hewitt in the 1970s and has become a foundational model for designing distributed systems, particularly those requiring high levels of concurrency and fault tolerance.</p>
<h3 id="heading-key-concepts-of-the-actor-model">Key Concepts of the Actor Model</h3>
<ol>
<li><p><strong>Actors</strong>:</p>
<ul>
<li><p>An actor is the fundamental unit of computation in the Actor Model.</p>
</li>
<li><p>Each actor is an independent, isolated entity that encapsulates state, behavior, and communication.</p>
</li>
<li><p>Actors do not share state directly with other actors, which helps avoid common issues like race conditions.</p>
</li>
</ul>
</li>
<li><p><strong>Message Passing</strong>:</p>
<ul>
<li><p>Actors communicate with each other exclusively through <strong>message passing</strong>.</p>
</li>
<li><p>Messages are sent asynchronously, meaning that the sender does not wait for the receiver to process the message before continuing its own work.</p>
</li>
<li><p>Messages are delivered to the recipient actor's mailbox, where they are queued until the actor is ready to process them.</p>
</li>
</ul>
</li>
<li><p><strong>Concurrency</strong>:</p>
<ul>
<li><p>Each actor processes one message at a time, making its state changes atomic from the perspective of other actors.</p>
</li>
<li><p>This approach naturally avoids many concurrency problems like deadlocks and race conditions because actors do not directly interact with each other’s state.</p>
</li>
<li><p>The Actor Model is inherently concurrent, with each actor operating independently.</p>
</li>
</ul>
</li>
<li><p><strong>Behavior</strong>:</p>
<ul>
<li><p>When an actor receives a message, it can:</p>
<ol>
<li><p><strong>Change its state</strong>: Actors can update their internal state based on the message received.</p>
</li>
<li><p><strong>Send messages</strong>: Actors can send messages to other actors, thereby influencing their behavior.</p>
</li>
<li><p><strong>Create new actors</strong>: An actor can spawn new actors to handle subtasks or additional responsibilities.</p>
</li>
</ol>
</li>
</ul>
</li>
<li><p><strong>Decoupling and Fault Tolerance</strong>:</p>
<ul>
<li><p>The Actor Model naturally promotes <strong>decoupling</strong> of components. Since actors only interact via messages, they can operate independently, making the system more modular.</p>
</li>
<li><p><strong>Fault tolerance</strong> is often implemented by using supervisors (actors that monitor other actors). If an actor fails, the supervisor can restart it, isolate the error, or escalate the issue according to a predefined strategy.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-real-world-implementations">Real-World Implementations</h3>
<p>Several programming languages and frameworks have adopted the Actor Model for building concurrent and distributed systems:</p>
<ol>
<li><p><strong>Erlang</strong>:</p>
<ul>
<li><p>Erlang's entire concurrency model is based on the Actor Model. It uses lightweight processes (actors) that communicate via message passing.</p>
</li>
<li><p>Erlang’s OTP (Open Telecom Platform) framework provides tools for building fault-tolerant, scalable systems using the Actor Model.</p>
</li>
</ul>
</li>
<li><p><strong>Elixir</strong>:</p>
<ul>
<li><p>Elixir, running on the BEAM virtual machine (the same as Erlang), also uses the Actor Model extensively.</p>
</li>
<li><p>The language inherits Erlang's powerful tools for building distributed and fault-tolerant systems.</p>
</li>
</ul>
</li>
<li><p><strong>Akka (Scala/Java)</strong>:</p>
<ul>
<li><p>Akka is a toolkit and runtime for building concurrent, distributed, and fault-tolerant applications on the JVM.</p>
</li>
<li><p>It implements the Actor Model, allowing developers to create systems where actors communicate via message passing.</p>
</li>
</ul>
</li>
<li><p><strong>Microsoft Orleans</strong>:</p>
<ul>
<li><p>Orleans is a framework that brings the Actor Model to the .NET platform.</p>
</li>
<li><p>It is designed for building cloud-native applications with a focus on scalability and distributed systems.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-example-simple-actor-in-elixir">Example: Simple Actor in Elixir</h3>
<p>Here’s a basic example of an actor in Elixir:</p>
<pre><code class="lang-elixir"><span class="hljs-class"><span class="hljs-keyword">defmodule</span> <span class="hljs-title">SimpleActor</span></span> <span class="hljs-keyword">do</span>
  <span class="hljs-keyword">use</span> GenServer

  <span class="hljs-comment"># Client API</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">start_link</span></span>(initial_state) <span class="hljs-keyword">do</span>
    GenServer.start_link(__MODULE__, initial_state, <span class="hljs-symbol">name:</span> __MODULE__)
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_message</span></span>(msg) <span class="hljs-keyword">do</span>
    GenServer.cast(__MODULE__, {<span class="hljs-symbol">:message</span>, msg})
  <span class="hljs-keyword">end</span>

  <span class="hljs-comment"># Server Callbacks</span>
  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">init</span></span>(initial_state) <span class="hljs-keyword">do</span>
    {<span class="hljs-symbol">:ok</span>, initial_state}
  <span class="hljs-keyword">end</span>

  <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">handle_cast</span></span>({<span class="hljs-symbol">:message</span>, msg}, state) <span class="hljs-keyword">do</span>
    IO.puts(<span class="hljs-string">"Received message: <span class="hljs-subst">#{msg}</span>"</span>)
    {<span class="hljs-symbol">:noreply</span>, state}
  <span class="hljs-keyword">end</span>
<span class="hljs-keyword">end</span>

<span class="hljs-comment"># Usage</span>
SimpleActor.start_link(%{})
SimpleActor.send_message(<span class="hljs-string">"Hello, Actor!"</span>)
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>SimpleActor</code> is an actor.</p>
</li>
<li><p>It starts with an initial state.</p>
</li>
<li><p>It can receive messages using the <code>handle_cast/2</code> function, which processes messages asynchronously.</p>
</li>
</ul>
<h3 id="heading-advantages-of-the-actor-model">Advantages of the Actor Model</h3>
<ol>
<li><p><strong>Concurrency and Parallelism</strong>:</p>
<ul>
<li>The Actor Model naturally supports concurrent operations, making it easier to build systems that take advantage of multi-core processors.</li>
</ul>
</li>
<li><p><strong>Scalability</strong>:</p>
<ul>
<li>Due to its decoupled nature, systems built with the Actor Model can scale horizontally by distributing actors across multiple nodes.</li>
</ul>
</li>
<li><p><strong>Fault Tolerance</strong>:</p>
<ul>
<li>The model supports robust error handling strategies, making it suitable for building reliable systems that can recover from failures.</li>
</ul>
</li>
<li><p><strong>Modularity</strong>:</p>
<ul>
<li>Each actor is an isolated unit of computation, which encourages modular design and easier reasoning about system behavior.</li>
</ul>
</li>
</ol>
<h3 id="heading-summary">Summary</h3>
<p>The Actor Model is a powerful paradigm for building concurrent and distributed systems. By modeling each component as an actor that communicates via message passing, it simplifies the design of systems that require high concurrency, fault tolerance, and scalability. Languages and frameworks like Erlang, Elixir, Akka, and Orleans leverage the Actor Model to build robust, scalable systems, particularly in domains like telecommunications, real-time processing, and cloud services.</p>
<p><strong>Image attribution</strong></p>
<ol>
<li><p><a target="_blank" href="https://www.freepik.com/free-photo/young-beautiful-stylish-sexy-woman-cinema-backstage-holding-movie-clapper_13887245.htm#fromView=search&amp;page=1&amp;position=2&amp;uuid=65b6578f-e7a6-4da4-a565-02ac10fe0f2d">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://elixir-lang.org/">Elixir logo</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Channels in Go]]></title><description><![CDATA[Introduction
The Channels Model is another approach to handling concurrency, commonly associated with the Communicating Sequential Processes (CSP) paradigm. It is prominently used in languages like Go and Clojure (with core.async). In this model, cha...]]></description><link>https://nikhilakki.in/channels-in-go</link><guid isPermaLink="true">https://nikhilakki.in/channels-in-go</guid><category><![CDATA[golang]]></category><category><![CDATA[Channels]]></category><category><![CDATA[goroutines]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 14 Sep 2024 05:36:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725423987607/4a693964-2e90-474f-9e16-d138f9fceba6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>The <strong>Channels Model</strong> is another approach to handling concurrency, commonly associated with the <strong>Communicating Sequential Processes (CSP)</strong> paradigm. It is prominently used in languages like <strong>Go</strong> and <strong>Clojure</strong> (with core.async). In this model, <strong>channels</strong> are the primary means of communication between concurrent entities (like goroutines in Go).</p>
<h3 id="heading-key-concepts-of-the-channels-model">Key Concepts of the Channels Model</h3>
<ol>
<li><p><strong>Goroutines</strong> (in Go):</p>
<ul>
<li><p>Goroutines are lightweight threads managed by the Go runtime.</p>
</li>
<li><p>They run concurrently and can execute functions independently of each other.</p>
</li>
</ul>
</li>
<li><p><strong>Channels</strong>:</p>
<ul>
<li><p>Channels are conduits through which goroutines can communicate by sending and receiving messages.</p>
</li>
<li><p>Channels are typed, meaning that a channel can only transmit data of a specific type (e.g., <code>chan int</code> for integers).</p>
</li>
<li><p>Communication over channels can be <strong>synchronous</strong> or <strong>buffered</strong>:</p>
<ul>
<li><p><strong>Synchronous channels</strong> block the sender until the receiver is ready to receive.</p>
</li>
<li><p><strong>Buffered channels</strong> allow a limited amount of data to be sent without blocking, until the buffer is full.</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Communication via Channels</strong>:</p>
<ul>
<li><p>Goroutines communicate by passing messages through channels. This allows for coordination and synchronization without explicit locking mechanisms.</p>
</li>
<li><p>The sending and receiving of messages over channels form the basis for synchronization, making it easier to reason about shared data without the risk of race conditions.</p>
</li>
</ul>
</li>
<li><p><strong>Select Statement</strong>:</p>
<ul>
<li><p>Go provides a <code>select</code> statement that allows a goroutine to wait on multiple channel operations, handling whichever one is ready first.</p>
</li>
<li><p>This is akin to a switch statement for channels and is a powerful feature for managing complex concurrency scenarios.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-example-simple-channels-in-go">Example: Simple Channels in Go</h3>
<p>Here's a basic example in Go:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    messages := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)

    <span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> {
        messages &lt;- <span class="hljs-string">"Hello, Channel!"</span>
    }()

    msg := &lt;-messages
    fmt.Println(msg)
}
</code></pre>
<p>In this example:</p>
<ul>
<li><p>A channel <code>messages</code> is created.</p>
</li>
<li><p>A goroutine is spawned that sends <code>"Hello, Channel!"</code> through the <code>messages</code> channel.</p>
</li>
<li><p>The main function receives this message and prints it.</p>
</li>
</ul>
<h3 id="heading-comparison-with-the-actor-model">Comparison with the Actor Model</h3>
<p>Both the Actor Model and Channels Model are powerful paradigms for handling concurrency, but they differ significantly in how they approach communication, state management, and error handling.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td><strong>Actor Model</strong></td><td><strong>Channels Model</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Concurrency Approach</strong></td><td>Actor-based: Independent actors communicate via messages.</td><td>CSP-based: Goroutines communicate via channels.</td></tr>
<tr>
<td><strong>State Management</strong></td><td>Encapsulated within actors; no shared state.</td><td>State can be shared via channels, but typically encapsulated within goroutines.</td></tr>
<tr>
<td><strong>Communication</strong></td><td>Asynchronous message passing between actors.</td><td>Synchronous or buffered communication via channels.</td></tr>
<tr>
<td><strong>Error Handling</strong></td><td>Often uses supervisors to monitor and recover from actor failures.</td><td>Typically managed by the programmer, with no built-in supervision model.</td></tr>
<tr>
<td><strong>Fault Tolerance</strong></td><td>High, due to actor isolation and supervisor strategies.</td><td>Depends on implementation; not inherently fault-tolerant.</td></tr>
<tr>
<td><strong>Concurrency Granularity</strong></td><td>Fine-grained, each actor is a separate unit of concurrency.</td><td>Coarse-grained, with channels coordinating goroutines.</td></tr>
<tr>
<td><strong>Scalability</strong></td><td>High, especially in distributed systems (Erlang, Elixir).</td><td>High, with efficient lightweight threads (goroutines) in Go.</td></tr>
<tr>
<td><strong>Use Cases</strong></td><td>Distributed systems, fault-tolerant applications, telecoms.</td><td>Concurrent applications, parallel processing, cloud services.</td></tr>
</tbody>
</table>
</div><h3 id="heading-key-differences">Key Differences</h3>
<ol>
<li><p><strong>State and Isolation</strong>:</p>
<ul>
<li><p>In the <strong>Actor Model</strong>, each actor maintains its own private state, and there is no shared memory between actors. This strong isolation simplifies reasoning about concurrency and makes the system more resilient to faults.</p>
</li>
<li><p>In the <strong>Channels Model</strong>, goroutines may share state, but channels provide a structured way to communicate and synchronize changes to that state. This model requires careful handling to avoid race conditions but offers more flexibility.</p>
</li>
</ul>
</li>
<li><p><strong>Communication</strong>:</p>
<ul>
<li><p>The <strong>Actor Model</strong> uses asynchronous message passing, where each actor can decide how to handle messages (e.g., by changing state, sending new messages, or creating new actors).</p>
</li>
<li><p>The <strong>Channels Model</strong> uses synchronous or buffered communication, where one goroutine sends data into a channel and another goroutine receives it. This model can be simpler to reason about in some scenarios but may require explicit coordination to manage state and handle complex concurrency patterns.</p>
</li>
</ul>
</li>
<li><p><strong>Error Handling and Fault Tolerance</strong>:</p>
<ul>
<li><p>The <strong>Actor Model</strong> often includes built-in mechanisms for fault tolerance, such as supervisors that can restart failed actors. This makes it particularly well-suited for building highly reliable systems.</p>
</li>
<li><p>The <strong>Channels Model</strong> does not inherently include fault tolerance mechanisms. Error handling is typically the responsibility of the programmer, and recovery strategies must be implemented manually.</p>
</li>
</ul>
</li>
<li><p><strong>Scalability and Performance</strong>:</p>
<ul>
<li><p>Both models are highly scalable, but they shine in different areas. The <strong>Actor Model</strong> is particularly effective in distributed systems where the isolation of actors and fault tolerance are crucial.</p>
</li>
<li><p>The <strong>Channels Model</strong> excels in scenarios where lightweight concurrency (like thousands of goroutines) is needed, with Go's runtime efficiently managing these goroutines.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-when-to-use-which-model">When to Use Which Model?</h3>
<ul>
<li><p><strong>Actor Model</strong>:</p>
<ul>
<li><p>Best for systems requiring high fault tolerance and reliability, such as telecom systems, real-time messaging platforms, and distributed systems.</p>
</li>
<li><p>Ideal when you want strong guarantees about isolation and the ability to recover from failures automatically.</p>
</li>
</ul>
</li>
<li><p><strong>Channels Model</strong>:</p>
<ul>
<li><p>Best for systems requiring fine-grained concurrency and parallelism, such as web servers, parallel processing tasks, or any system where lightweight concurrency primitives (like goroutines) are advantageous.</p>
</li>
<li><p>Ideal when you need a simple, structured way to communicate between concurrent tasks without needing the full isolation and fault tolerance provided by the Actor Model.</p>
</li>
</ul>
</li>
</ul>
<p>In summary, both models offer robust approaches to concurrency, but they are suited to different types of problems. The Actor Model is more focused on isolation, fault tolerance, and message-driven design, while the Channels Model offers a straightforward way to handle communication and synchronization between lightweight concurrent tasks.</p>
<p><strong>Image attribution</strong></p>
<ol>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/uhd-smart-tv-abstract-concept-illustration_11667650.htm#fromView=search&amp;page=1&amp;position=13&amp;uuid=0b5f8d5e-1f1d-4e03-9eae-82ba9f703efc">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Go_(programming_language)#/media/File:Go_Logo_Blue.svg">Go logo</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Go vs Elixir for concurrency]]></title><description><![CDATA[Elixir and Go (Golang) are both powerful languages, but they cater to different types of applications and development philosophies. Below is a comparison of their features:
1. Concurrency Model

Elixir:

Uses the Actor Model for concurrency, built on...]]></description><link>https://nikhilakki.in/go-vs-elixir-for-concurrency</link><guid isPermaLink="true">https://nikhilakki.in/go-vs-elixir-for-concurrency</guid><category><![CDATA[golang]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Elixir]]></category><category><![CDATA[concurrency]]></category><category><![CDATA[actor model]]></category><category><![CDATA[Channels]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 07 Sep 2024 05:36:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725423208562/829c7c8f-8d7e-4d3e-be89-001a9a002dba.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Elixir and Go (Golang) are both powerful languages, but they cater to different types of applications and development philosophies. Below is a comparison of their features:</p>
<h3 id="heading-1-concurrency-model">1. <strong>Concurrency Model</strong></h3>
<ul>
<li><p><strong>Elixir:</strong></p>
<ul>
<li><p>Uses the <strong>Actor Model</strong> for concurrency, built on top of the BEAM (Erlang VM).</p>
</li>
<li><p>Processes in Elixir are lightweight and can be millions in a single application.</p>
</li>
<li><p><strong>Fault-tolerance</strong> and <strong>supervision trees</strong> are built-in, making it ideal for distributed and highly available systems.</p>
</li>
</ul>
</li>
<li><p><strong>Go:</strong></p>
<ul>
<li><p>Uses <strong>Goroutines</strong> for concurrency, which are managed by the Go runtime.</p>
</li>
<li><p>Goroutines are also lightweight, but more closely tied to OS threads compared to Elixir's processes.</p>
</li>
<li><p><strong>Channels</strong> provide a way to synchronize and communicate between Goroutines.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-2-performance">2. <strong>Performance</strong></h3>
<ul>
<li><p><strong>Elixir:</strong></p>
<ul>
<li><p>Generally slower in raw performance compared to Go, especially in CPU-bound tasks.</p>
</li>
<li><p>Excellent for I/O-bound tasks and systems that require high concurrency and fault tolerance.</p>
</li>
</ul>
</li>
<li><p><strong>Go:</strong></p>
<ul>
<li><p>Known for its <strong>speed</strong> and <strong>efficiency</strong>. It performs very well in CPU-bound tasks due to its compiled nature.</p>
</li>
<li><p>Suitable for performance-critical applications.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-3-ecosystem-and-libraries">3. <strong>Ecosystem and Libraries</strong></h3>
<ul>
<li><p><strong>Elixir:</strong></p>
<ul>
<li><p>Built on the Erlang ecosystem, which is robust and mature.</p>
</li>
<li><p><strong>Phoenix Framework</strong> is the go-to for web applications, known for its real-time features (like channels for WebSockets).</p>
</li>
<li><p>Strong ecosystem for <strong>distributed systems</strong>, <strong>telecommunications</strong>, and <strong>real-time applications</strong>.</p>
</li>
</ul>
</li>
<li><p><strong>Go:</strong></p>
<ul>
<li><p>Rich standard library, particularly strong in networking, HTTP, and concurrency.</p>
</li>
<li><p>Popular for building <strong>cloud services</strong>, <strong>microservices</strong>, <strong>CLI tools</strong>, and <strong>networking</strong> applications.</p>
</li>
<li><p>Strong tooling for DevOps and backend services.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-4-syntax-and-language-design">4. <strong>Syntax and Language Design</strong></h3>
<ul>
<li><p><strong>Elixir:</strong></p>
<ul>
<li><p>Functional programming language with immutable data structures.</p>
</li>
<li><p>Inspired by Ruby, so it has a very <strong>developer-friendly</strong> syntax.</p>
</li>
<li><p>Emphasizes on <strong>concurrency</strong>, <strong>fault-tolerance</strong>, and <strong>scalability</strong>.</p>
</li>
</ul>
</li>
<li><p><strong>Go:</strong></p>
<ul>
<li><p>Imperative language with a C-like syntax.</p>
</li>
<li><p>Designed with simplicity and readability in mind, avoiding complex features like inheritance and generics (until Go 1.18).</p>
</li>
<li><p>Emphasizes on <strong>simplicity</strong>, <strong>clarity</strong>, and <strong>easy learning curve</strong>.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-5-deployment-and-compilation">5. <strong>Deployment and Compilation</strong></h3>
<ul>
<li><p><strong>Elixir:</strong></p>
<ul>
<li><p>Uses BEAM VM, so the code is not compiled to native machine code but bytecode.</p>
</li>
<li><p>Deployment can be complex due to the need to manage the Erlang runtime and dependencies.</p>
</li>
<li><p>However, releases can be made with tools like <strong>Distillery</strong> and <strong>Mix</strong>.</p>
</li>
</ul>
</li>
<li><p><strong>Go:</strong></p>
<ul>
<li><p>Compiles to a single static binary, which simplifies deployment.</p>
</li>
<li><p>No external dependencies are required, making it easy to deploy and distribute Go applications.</p>
</li>
<li><p>Excellent cross-compilation support.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-6-scalability">6. <strong>Scalability</strong></h3>
<ul>
<li><p><strong>Elixir:</strong></p>
<ul>
<li><p>Designed for massive scalability, making it suitable for distributed systems.</p>
</li>
<li><p>The OTP (Open Telecom Platform) provides robust tools for building scalable applications.</p>
</li>
</ul>
</li>
<li><p><strong>Go:</strong></p>
<ul>
<li><p>Scalable in terms of handling large numbers of concurrent connections.</p>
</li>
<li><p>Typically used for building scalable microservices and backend systems.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-7-community-and-adoption">7. <strong>Community and Adoption</strong></h3>
<ul>
<li><p><strong>Elixir:</strong></p>
<ul>
<li><p>Strong community, particularly in startups and companies focusing on real-time systems.</p>
</li>
<li><p>Popular in industries like telecommunications, finance, and health tech.</p>
</li>
</ul>
</li>
<li><p><strong>Go:</strong></p>
<ul>
<li><p>Broad adoption across industries, particularly in the cloud-native and DevOps spaces.</p>
</li>
<li><p>Strong community with extensive corporate backing from companies like Google.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-8-use-cases">8. <strong>Use Cases</strong></h3>
<ul>
<li><p><strong>Elixir:</strong></p>
<ul>
<li><p>Real-time web applications (e.g., chat apps, gaming servers).</p>
</li>
<li><p>Distributed systems and services requiring fault tolerance.</p>
</li>
<li><p>Applications that need high concurrency with lightweight processes.</p>
</li>
</ul>
</li>
<li><p><strong>Go:</strong></p>
<ul>
<li><p>Cloud services, APIs, and microservices.</p>
</li>
<li><p>Systems programming, networking, and DevOps tools.</p>
</li>
<li><p>Performance-critical backend services.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<ul>
<li><p><strong>Elixir</strong> is ideal if you need to build fault-tolerant, highly concurrent, and scalable distributed systems, especially in scenarios requiring real-time capabilities.</p>
</li>
<li><p><strong>Go</strong> is better suited for performance-critical applications, especially in the cloud, microservices, and networked systems due to its simplicity, speed, and easy deployment.</p>
</li>
</ul>
<p>Each language excels in its domain, but choosing a language goes beyond just tech specs, one has to also consider existing dev ecosystem in their city, country or region, cost of developer accusition etc.</p>
<p><strong>Image attribution</strong></p>
<ol>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/File:Go_Logo_Blue.svg">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://commons.wikimedia.org/wiki/File:Official_Elixir_logo.png">Image #2</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/racing-wheel-with-flags_1538782.htm#fromView=search&amp;page=1&amp;position=24&amp;uuid=adb28412-26ba-47b1-a8be-dee2e2782934">Image #3</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Locking Down Data: Encrypting with Go]]></title><description><![CDATA[Intro
In today's digital age, data security is paramount. Whether you're a developer, a business owner, or just a tech enthusiast, understanding how to protect sensitive information is crucial. One of the most effective ways to secure data is through...]]></description><link>https://nikhilakki.in/locking-down-data-encrypting-with-go</link><guid isPermaLink="true">https://nikhilakki.in/locking-down-data-encrypting-with-go</guid><category><![CDATA[encryption-in-go]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[Cryptography]]></category><category><![CDATA[encryption]]></category><dc:creator><![CDATA[Nikhil Akki]]></dc:creator><pubDate>Sat, 31 Aug 2024 05:32:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1725028791071/5d93a0e3-7475-46c0-9689-df703d4c6f53.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-intro">Intro</h3>
<p>In today's digital age, data security is paramount. Whether you're a developer, a business owner, or just a tech enthusiast, understanding how to protect sensitive information is crucial. One of the most effective ways to secure data is through encryption. Go, a statically typed, compiled programming language designed at Google, offers robust libraries and tools to make encryption straightforward and efficient. This article will guide you through the process of encrypting data using Go, highlighting its use cases, providing a practical code example, and summarizing the key points in a handy table.</p>
<h3 id="heading-use-cases">Use Cases</h3>
<ol>
<li><p><strong>Secure Communication</strong>: Encrypt data transmitted over networks to prevent eavesdropping.</p>
</li>
<li><p><strong>Data Storage</strong>: Protect sensitive information stored in databases or files.</p>
</li>
<li><p><strong>User Authentication</strong>: Encrypt passwords and other authentication data.</p>
</li>
<li><p><strong>API Security</strong>: Secure API keys and tokens to prevent unauthorized access.</p>
</li>
<li><p><strong>Compliance</strong>: Meet regulatory requirements for data protection.</p>
</li>
<li><p><strong>Email Encryption</strong>: Ensure the confidentiality of email content.</p>
</li>
<li><p><strong>File Encryption</strong>: Protect files on disk from unauthorized access.</p>
</li>
<li><p><strong>Cloud Security</strong>: Encrypt data before uploading to cloud storage.</p>
</li>
<li><p><strong>IoT Devices</strong>: Secure data transmitted between IoT devices and servers.</p>
</li>
<li><p><strong>Backup Security</strong>: Encrypt backup data to prevent unauthorized access.</p>
</li>
</ol>
<h3 id="heading-code-example">Code Example</h3>
<p>Here's a simple example of how to encrypt and decrypt data using Go's <code>crypto/aes</code> and <code>crypto/cipher</code> packages:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"crypto/aes"</span>
    <span class="hljs-string">"crypto/cipher"</span>
    <span class="hljs-string">"crypto/rand"</span>
    <span class="hljs-string">"encoding/hex"</span>
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"io"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">encrypt</span><span class="hljs-params">(plainText, key []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">string</span>, error)</span></span> {
    block, err := aes.NewCipher(key)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, err
    }

    cipherText := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">byte</span>, aes.BlockSize+<span class="hljs-built_in">len</span>(plainText))
    iv := cipherText[:aes.BlockSize]
    <span class="hljs-keyword">if</span> _, err := io.ReadFull(rand.Reader, iv); err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, err
    }

    stream := cipher.NewCFBEncrypter(block, iv)
    stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)

    <span class="hljs-keyword">return</span> hex.EncodeToString(cipherText), <span class="hljs-literal">nil</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">decrypt</span><span class="hljs-params">(cipherTextHex <span class="hljs-keyword">string</span>, key []<span class="hljs-keyword">byte</span>)</span> <span class="hljs-params">(<span class="hljs-keyword">string</span>, error)</span></span> {
    cipherText, _ := hex.DecodeString(cipherTextHex)

    block, err := aes.NewCipher(key)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, err
    }

    <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(cipherText) &lt; aes.BlockSize {
        <span class="hljs-keyword">return</span> <span class="hljs-string">""</span>, fmt.Errorf(<span class="hljs-string">"cipherText too short"</span>)
    }

    iv := cipherText[:aes.BlockSize]
    cipherText = cipherText[aes.BlockSize:]

    stream := cipher.NewCFBDecrypter(block, iv)
    stream.XORKeyStream(cipherText, cipherText)

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">string</span>(cipherText), <span class="hljs-literal">nil</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    key := []<span class="hljs-keyword">byte</span>(<span class="hljs-string">"a very very very very secret key"</span>) <span class="hljs-comment">// 32 bytes</span>
    plainText := <span class="hljs-string">"Hello, World!"</span>

    encrypted, err := encrypt([]<span class="hljs-keyword">byte</span>(plainText), key)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        fmt.Println(<span class="hljs-string">"Error encrypting:"</span>, err)
        <span class="hljs-keyword">return</span>
    }
    fmt.Println(<span class="hljs-string">"Encrypted:"</span>, encrypted)

    decrypted, err := decrypt(encrypted, key)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        fmt.Println(<span class="hljs-string">"Error decrypting:"</span>, err)
        <span class="hljs-keyword">return</span>
    }
    fmt.Println(<span class="hljs-string">"Decrypted:"</span>, decrypted)
}
</code></pre>
<h3 id="heading-summary">Summary</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Use Case</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td>Secure Communication</td><td>Encrypt data over networks to prevent eavesdropping.</td></tr>
<tr>
<td>Data Storage</td><td>Protect sensitive information in databases or files.</td></tr>
<tr>
<td>User Authentication</td><td>Encrypt passwords and authentication data.</td></tr>
<tr>
<td>API Security</td><td>Secure API keys and tokens.</td></tr>
<tr>
<td>Compliance</td><td>Meet regulatory data protection requirements.</td></tr>
<tr>
<td>Email Encryption</td><td>Ensure email content confidentiality.</td></tr>
<tr>
<td>File Encryption</td><td>Protect files on disk from unauthorized access.</td></tr>
<tr>
<td>Cloud Security</td><td>Encrypt data before cloud storage.</td></tr>
<tr>
<td>IoT Devices</td><td>Secure data between IoT devices and servers.</td></tr>
<tr>
<td>Backup Security</td><td>Encrypt backup data to prevent unauthorized access.</td></tr>
</tbody>
</table>
</div><h3 id="heading-conclusion">Conclusion</h3>
<p>Encrypting data using Go is a powerful way to enhance security in your applications. With its robust libraries and straightforward syntax, Go makes it easy to implement encryption for various use cases. By following the provided code example and understanding the key use cases, you can ensure that your data remains secure and compliant with industry standards.</p>
<h3 id="heading-additional-resources">Additional Resources</h3>
<p>For further reading and more in-depth tutorials, check out these resources:</p>
<ol>
<li><p><a target="_blank" href="https://pkg.go.dev/crypto">Go's crypto package documentation</a></p>
</li>
<li><p><a target="_blank" href="https://earthly.dev/blog/cryptography-encryption-in-go/">Cryptography Encryption in Go</a></p>
</li>
</ol>
<p><strong>Image attribution</strong></p>
<ol>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/locker_2900480.htm#fromView=search&amp;page=1&amp;position=0&amp;uuid=df71a087-6c43-43d8-aeac-f276469b370f">Image #1</a></p>
</li>
<li><p><a target="_blank" href="https://www.freepik.com/free-vector/data-report-illustration-concept_6195527.htm#fromView=search&amp;page=1&amp;position=7&amp;uuid=4af1ef9a-541f-40b2-9ef1-1f8f76915eb6">Image #2</a></p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Go_(programming_language)">Image #3</a></p>
</li>
</ol>
]]></content:encoded></item></channel></rss>