<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jessish Pothancheri on Medium]]></title>
        <description><![CDATA[Stories by Jessish Pothancheri on Medium]]></description>
        <link>https://medium.com/@kaljessy?source=rss-e946fbd4b9f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*osj8QNLEYsrWFTzu</url>
            <title>Stories by Jessish Pothancheri on Medium</title>
            <link>https://medium.com/@kaljessy?source=rss-e946fbd4b9f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 11:36:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kaljessy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dependency Injection in Python with injector]]></title>
            <link>https://medium.com/@kaljessy/dependency-injection-in-python-with-injector-63137790c482?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/63137790c482</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 13:30:34 GMT</pubDate>
            <atom:updated>2024-10-21T11:40:15.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7t8uGFdCNMmB-TdPAAAfRQ.png" /><figcaption>Coutesy ChatGPT</figcaption></figure><p>I’ve always been a fan of dependency injection. Having a framework or container manage all my dependencies and their scopes has always seemed incredibly clean and efficient.</p><p>I like how it makes code more flexible by reducing direct dependencies between classes, making it easy to swap out or update parts of the system. It also helps with testing by allowing you to easily mock dependencies.</p><p>Lifecycle management through scopes is another great feature of dependency injection. It handles the creation and lifespan of objects behind the scenes, making development easier and helping to keep the code clean and organized.</p><p>My first encounter with dependency injection was through Autofac, a powerful IoC container in the .NET ecosystem. As .NET evolved, I was thrilled to see DI become a first-class citizen in .NET Core. Later, when I transitioned to working with Spring Boot in Java, I admired how it integrated dependency injection with annotations, making DI feel seamless and effortless. Even in React, I found the use of InversifyJS to implement DI quite exciting. I have an article on this.</p><p><a href="https://medium.com/@kaljessy/react-dependency-injection-using-inversify-b4e1d63abc72">React Dependency Injection using Inversify</a></p><p>Throughout my exploration of different technologies, one thing that remained constant was my search for effective dependency injection mechanisms.</p><p>Today, I’ll walk you through how you can implement dependency injection in Python using Injector — a lightweight, easy-to-use library that brings this powerful pattern into the Python ecosystem.</p><p>To demonstrate dependency injection, let’s consider the following use case (I love BDD syntax!):</p><p><strong>Given</strong> a collection of books,<br><strong>When</strong> performing CRUD (Create, Read, Update, Delete) operations,<br><strong>Then</strong> store the books either in an in-memory cache or on disk (file).</p><p><strong>Dependencies</strong></p><pre># Install this dependency, that is only thing you need :)<br>pip install injector</pre><p><strong>Project Structure:</strong></p><pre>├── book.py               # Book class is a data class that represents a book.<br>├── book_service.py       # CRUD operations for managing books in cache<br>├── book_cache.py         # Abstract class for caching<br>├── book_disk_cache.py    # Disk cache implementation of BookCache<br>├── book_memory_cache.py  # In-memory cache implementation of BookCache<br>├── app_module.py         # Dependency injection wiring<br>└── main.py               # Application entry point</pre><p><strong>The Code:</strong></p><pre># Book class<br>@dataclass<br>class Book:<br>    id: int<br>    title: str<br>    author: str<br>    price: float<br><br># The BookService class is the main service class that <br># interacts with the BookCache.<br>class BookService:<br><br>    @inject<br>    def __init__(self, book_cache: BookCache):<br>        &quot;&quot;&quot;<br>        Constructor for BookService<br>        :param book_cache:<br>        The @inject decorator tells the injector<br>        which BookCache implementation to use.<br>        &quot;&quot;&quot;<br>        self.book_cache = book_cache<br>        self.logger = logging.getLogger(__name__)<br>        self.logger.info(&quot;BookService initialized&quot;)<br><br>    def get_all_books(self) -&gt; list[Book]:<br>        return self.book_cache.get_all_books()<br><br>    def get_book_by_id(self, book_id) -&gt; Book:<br>        return self.book_cache.get_book_by_id(book_id)<br>    ......</pre><pre># The BookCache abstract class defines the interface that all cache <br># implementations must implement. This ensures that all cache implementations <br># have the same set of methods, making it easy to switch between <br># different implementations<br>class BookCache(ABC):<br>    @abstractmethod<br>    def get_all_books(self):<br>        pass<br><br>    @abstractmethod<br>    def get_book_by_id(self, book_id):<br>        pass<br><br>    @abstractmethod<br>    def create_book(self, book):<br>        pass<br><br>    @abstractmethod<br>    def update_book(self, book):<br>        pass<br><br>    @abstractmethod<br>    def delete_book(self, book_id):<br>        pass</pre><pre># Thpe MemoryCache class is a simple in-memory cache implementation that <br># stores books in a dictionary.<br>class MemoryCache(BookCache):<br>    def __init__(self):<br>        self.logger = logging.getLogger(__name__)<br>        self.logger.info(&quot;MemoryCache initialized&quot;)<br>        self.books = {}<br><br>    def get_all_books(self):<br>        return list(self.books.values())<br><br>    def get_book_by_id(self, book_id):<br>        return self.books.get(book_id)<br><br>   ....</pre><pre># The DiskCache class is a cache implementation that stores books in a <br># JSON file on disk.<br>class DiskCache(BookCache):<br>    def __init__(self, file_path=&#39;books_cache.json&#39;):<br>        self.logger = logging.getLogger(__name__)<br>        self.logger.info(&quot;DiskCache initialized&quot;)<br>        self.file_path = file_path<br>        self.books = {}<br>        self.load_from_disk()<br><br>    def load_from_disk(self):<br>        if os.path.exists(self.file_path):<br>            with open(self.file_path, &#39;r&#39;) as f:<br>                self.books = json.load(f)<br><br>    def save_to_disk(self):<br>        with open(self.file_path, &#39;w&#39;) as f:<br>            json.dump(self.books, f, indent=2)<br><br>    def get_all_books(self):<br>        return list(self.books.values())<br><br>    def get_book_by_id(self, book_id):<br>        return self.books.get(str(book_id))<br><br>   ....</pre><p><strong>Dependency wiring using Injector:</strong></p><pre># This is the main module that binds the interfaces to the implementations <br># This approach allows you to centralize and manage all your dependency <br># bindings in one place<br><br># There are several ways to wire dependency injection in Python, <br># but I find using AppModule to be the cleanest approach.<br><br>class AppModule(Module):<br>    def configure(self, binder):<br>        from book_cache import BookCache<br>        from book_memory_cache import MemoryCache<br>        from book_service import BookService<br>        # Essentially, I am telling the container that I wan&#39;t to use the<br>        # Memory Cache implementaion  <br>        # binder.bind(BookCache, DiskCache, scope=singleton)<br>        binder.bind(BookCache, MemoryCache, scope=singleton)<br>        binder.bind(BookService, BookService)</pre><p><strong>Putting it all together:</strong></p><pre>def create_injector() -&gt; Injector:<br>    return Injector([AppModule()])<br><br>if __name__ == &#39;__main__&#39;:<br>    injector = create_injector()<br>    setup_logging()<br>    logger = logging.getLogger(__name__)<br>    logger.info(&quot;Application started&quot;)<br><br>    book_service = injector.get(BookService);<br><br>    # create 3 books and add them to the cache<br>    book1 = Book(id=1, title=&#39;To Kill a Mockingbird&#39;, author=&#39;Harper Lee&#39;, price=12.99)<br>    book_service.create_book(book1)<br><br>    book2 = Book(id=2, title=&#39;1984&#39;, author=&#39;George Orwell&#39;, price=10.99)<br>    book_service.create_book(book2)<br><br>    book3 = Book(id=3, title=&#39;The Alchemist&#39;, author=&#39;Paulo Coelho&#39;, price=9.99)<br>    book_service.create_book(book3)<br><br>    # Get the book from cache and print<br>    book1 = book_service.get_book_by_id(3)<br>    print(book1)<br><br>    logger.info(&quot;Application finished&quot;)</pre><p><strong>Application Output:</strong></p><pre>C:\Projects\Python\python_dependency_injection\.venv\Scripts\python.exe C:\Projects\Python\python_dependency_injection\main.py <br>2024-10-03 20:57:09,063 - __main__ - INFO - Application started<br># Based on our binding, the books were inserted to Memory Cache<br>2024-10-03 20:57:09,065 - book_memory_cache - INFO - MemoryCache initialized<br>2024-10-03 20:57:09,066 - book_service - INFO - BookService initialized<br>2024-10-03 20:57:09,066 - __main__ - INFO - Application finished<br>Book(id=3, title=&#39;The Alchemist&#39;, author=&#39;Paulo Coelho&#39;, price=9.99)</pre><p><strong>Github code for reference:</strong></p><p><a href="https://github.com/jpothanc/python_dependency_injection">GitHub - jpothanc/python_dependency_injection: Dependency injection in python.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63137790c482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TailwindCSS: A Love Story]]></title>
            <link>https://medium.com/@kaljessy/tailwindcss-a-love-story-22681317ee84?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/22681317ee84</guid>
            <category><![CDATA[tailwind-css-tutorial]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 20:09:59 GMT</pubDate>
            <atom:updated>2024-09-04T16:51:57.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7b4LkKsX-hclxFi3" /><figcaption>Courtesy ChatGPT</figcaption></figure><p>I typically develop web applications using Sass, a powerful CSS preprocessor that helps manage styles with features like variables, inheritance, and nesting.</p><p>A year ago, I encountered TailwindCSS and experimented with a few simple examples. I had reservations about adopting it fully and soon set it aside.</p><p>Tailwind CSS is a utility-first CSS framework renowned for its wide range of predefined classes that enable developers to build custom, responsive designs directly within HTML markup. This facilitates rapid UI development without the need to write extensive CSS from scratch.</p><p>A simple comparison of standard CSS and TailwindCSS below</p><pre>/*standard css button*/<br><br>.button {<br>    background-color: #007bff;<br>    color: white;<br>    padding: 8px 16px;<br>    font-size: 16px;<br>    border: none;<br>    border-radius: 4px;<br>    cursor: pointer;<br>    transition: background-color 0.3s;<br>}<br><br>.button:hover {<br>    background-color: #0056b3;<br>}<br><br>&lt;button class=&quot;button&quot;&gt;Click Me&lt;/button&gt;<br><br>/*tailwind implementation of the button*/<br>&lt;button class=&quot;bg-blue-500 text-white py-2 px-4 text-lg border-none <br>rounded cursor-pointer transition-colors duration-300 hover:bg-blue-700&quot;&gt;<br>    Click Me<br>&lt;/button&gt;</pre><p>A few months ago, while building my portfolio site in Svelte, I revisited TailwindCSS. Many had mentioned that it takes some time to appreciate its benefits, and they were right. I soon started to enjoy its ease and efficiency.</p><p>In web projects, you typically need to</p><ul><li><strong>Style Elements</strong>: This involves using CSS to customize the appearance of the web pages.</li><li><strong>Implement Themes</strong>: Including support for different visual appearances like dark and light modes, which are popular for enhancing user experience and accessibility.</li><li><strong>Ensure Responsiveness</strong>: Making sure the website looks good and functions well on a variety of devices and screen sizes, which is essential in today’s multi-device environment.</li></ul><p>Let me demonstrate how you can develop a NavBar using Sass and TailwindCSS.</p><h3><strong>NavBar using Sass</strong></h3><pre>[1] npm install sass<br><br>[2] create a theme-config file.<br>   for e.g, define background and text-color for dark and light theme<br>    $themes: (<br>      &quot;light&quot;: (<br>        background-color: #fff,<br>        text-color: #000,<br>        nav-color: #313030,<br>        nav-text-color: #fff,<br>        hover-color: #e17a19,<br>      ),<br>      &quot;dark&quot;: (<br>        background-color: #333,<br>        text-color: #fff,<br>        nav-color: #0d65b2,<br>        hover-color: #080807,<br>      ),<br>    );<br><br>[3] create a nested stylesheet for Navbar using sass mixin<br>    mixin is a like a function where you pass the active theme name <br>    and render the component?<br><br>    // Mixin for creating theme-specific styles<br>    @mixin theme($theme-name) {<br>      @if map-has-key($themes, $theme-name) {<br>        // Retrieve theme-specific colors from the theme map<br>        $theme-map: map-get($themes, $theme-name);<br><br>        $nav-color: map-get($theme-map, nav-color);<br>        $hover-color: map-get($theme-map, hover-color);<br>        $nav-text-color: map-get($theme-map, nav-text-color);<br>    <br>        // Styles for the NavBar component<br>        .NavBar {<br>           position: sticky;<br>          top: 0;<br>          z-index: 1000;<br>          font-size: larger;<br>          display: flex;<br>          justify-content: space-between;<br>          background-color: $nav-color;<br>          color: $nav-text-color;<br>    <br>          // Styles for the navigation list<br>          ul {<br>            list-style: none;<br>            display: flex;<br>            gap: 10px;<br>          }<br>          // Styles for list items<br>          li {<br>            display: inline-block;<br>          }<br>         .....<br>        }<br>       }<br><br>[4] Apply the theme mixin to light and dark themes.<br>    This is where you invoke the mixin with theme name<br><br>      .light {<br>        @include theme(&quot;light&quot;);<br>      }<br>      .dark {<br>        @include theme(&quot;dark&quot;);<br>      }<br><br>[5] Responsive styles for smaller screen<br>  <br>     @media screen and (max-width: 768px) {<br>      .NavBar {<br>        flex-direction: column;<br>        gap: 10px;<br>        font-size: medium;<br><br>        a {<br>          padding: 1px;<br>          font-size: small;<br>        }<br>      }<br><br>[5] Create a button in react to toggle the active theme.<br></pre><h3><strong>NavBar using TailwindCSS</strong></h3><pre>[1] install Tailwind<br><br>    npm install -D tailwindcss postcss autoprefixer<br>    npx tailwindcss init -p<br><br>    //add below tailwind.config.js<br>    content: [<br>      &quot;./src/**/*.{js,jsx,ts,tsx}&quot;,<br>    ]<br><br>    //add below index.scss<br>    @tailwind base;<br>    @tailwind components;<br>    @tailwind utilities;<br><br>[2] Create the theme config in tailwind.config.js<br>    export default {<br>      content: [&quot;./src/**/*.{html,js,ts,jsx,tsx}&quot;],<br>      //you are specifying that dark mode styles should be activated by <br>      //adding a specific class (usually dark) to an element, often the &lt;html&gt; <br>      //or &lt;body&gt; tag. This provides a high degree of control over when <br>      //and where dark mode is applied.<br>      darkMode: &quot;class&quot;,<br>      //Add your theme config<br>      theme: {<br>        extend: {<br>          colors: {<br>            light: {<br>              background: &quot;#f8fafc&quot;,<br>              text: &quot;#2d3748&quot;,<br>              navcolor: &quot;#313030&quot;,<br>            },<br>            dark: {<br>              background: &quot;#1a202c&quot;,<br>              text: &quot;#e2e8f0&quot;,<br>              navcolor: &quot;#0D65B2&quot;,<br>            },<br>          },<br>        },<br>      },<br><br>[3] Style the Navbar inline <br><br>     // flex container with turns to row alignment on large screens<br>     // background of NavBar and text size changes on dark and light theme<br>      div<br>        className=&quot;<br>         sticky top-14 z-999<br>         flex flex-col justify-between items-center<br>         bg-light-navcolor dark:bg-dark-navcolor<br>         text-white text-base md:text-xl <br>         md:flex-row p-2 gap-4&quot;<br>      &gt;<br>        Themeing &amp; Styling (TailwindCSS)<br>        //by default text size is small, <br>        //for medium and larger screens text size is xl   <br>        &lt;ul className=&quot;flex gap-4 text-sm md:text-xl&quot;&gt;<br>          {navItemsTw.map((item) =&gt; (<br>            //hover colors for dark theme (black) and default settings (orange)<br>            &lt;li<br>              className=&quot;hover:text-orange-500 transition-all duration-500<br>              dark:hover:text-black&quot;<br>              key={item.name}<br>            &gt;<br>              &lt;a href={item.link} target=&quot;_&quot;&gt;{item.name}&lt;/a&gt;<br>            &lt;/li&gt;<br>          ))}<br>        &lt;/ul&gt;<br>      &lt;/div&gt;</pre><p>React Toggle code</p><pre>const App = () =&gt; {<br>  const [theme, setTheme] = useState(&quot;light&quot;);<br><br>  useEffect(() =&gt; {<br>    document.body.className = theme;<br>    setTheme(theme);<br>  }, [theme]); // Re-run this effect when &#39;theme&#39; changes<br>  return (<br>    &lt;&gt;<br>      &lt;div&gt;<br>        &lt;NavBar /&gt;<br>        &lt;NavBarTw /&gt;<br>        &lt;div className=&quot;flex justify-center items-center h-screen&quot;&gt;<br>          &lt;button<br>            className=&quot;p-2 bg-black text-white font-semibold<br>          dark:bg-blue-500&quot;<br>            onClick={() =&gt; setTheme(theme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;)}<br>          &gt;<br>            {theme === &quot;light&quot; ? &quot;Dark Mode&quot; : &quot;Light Mode&quot;}<br>            &lt;section<br>               className=&quot;mt-1 p-2 text-center text-xs md:text-sm<br>                          transition-all duration-500  <br>                          hover:dark:bg-yellow-500 text-black<br>                          hover:bg-white <br>                          &quot;<br>            &gt;<br>              &lt;p&gt;click me!&lt;/p&gt;<br>            &lt;/section&gt;<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default App;</pre><p>See the app live here (Reduce the screen size and check)</p><p><a href="https://react-styling-neon.vercel.app/">Vite + React + TS</a></p><p>Refer code in GitHub</p><p><a href="https://github.com/jpothanc/react-styling">https://github.com/jpothanc/react-styling</a></p><p>While I love TailwindCSS for my small projects, I still have reservations about its usage for large projects.</p><p>I stumbled upon the below article.</p><p><a href="https://medium.com/javascript-in-plain-english/we-give-up-on-tailwindcss-our-decision-behind-switching-back-to-sass-modules-949e58225798">https://medium.com/javascript-in-plain-english/we-give-up-on-tailwindcss-our-decision-behind-switching-back-to-sass-modules-949e58225798</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22681317ee84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easier and Faster Web Applications Using Svelte]]></title>
            <link>https://medium.com/@kaljessy/svelt-felt-better-ff7ce0f81977?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff7ce0f81977</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 11:49:24 GMT</pubDate>
            <atom:updated>2024-08-29T19:48:59.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7KFcZryNxq2DrD_yFjyqw.png" /></figure><p><a href="https://svelte.dev/"><strong>Svelte</strong></a><strong> </strong>is an open-source modern web framework for creating user interfaces on the web. It was ranked as the most admired and most loved JavaScript web framework in 2022 on the <a href="https://survey.stackoverflow.co/2022/#most-loved-dreaded-and-wanted-webframe-love-dread">Stack Overflow Developer Survey</a>.</p><p>It employs a clear, concise, and readable way to write code. Svelte is easier to write and learn. Unlike traditional JavaScript frameworks, Svelte shifts much of the workload from the browser to the build step, resulting in highly optimized and fast applications. This innovative technique not only enhances runtime performance but also leads to smaller bundle sizes. By leveraging modern JavaScript features and clean syntax, Svelte allows developers to write less code and achieve more, making it an attractive choice for both new projects and existing applications.</p><p>Svelte was created by Rich Harris in November 2016. Since its creation, Svelte has undergone several major versions, each introducing significant improvements and new features.</p><p>Svelte 5 is around the corner, boasting further optimizations, reduced bundle sizes, and numerous other enhancements.</p><p><a href="https://svelte.dev/blog/svelte-5-release-candidate">Svelte 5 Release Candidate</a></p><p>Let&#39;s peek into Svelte with a few examples. If you are a web programmer, you might find yourself admiring its elegance and simplicity.</p><p>I first heard about it a year ago but didn’t explore it until recently, when I realized what I had been missing. I want to ensure that readers of this blog get a quick glimpse and can decide if this framework is a valuable addition to their toolkit.</p><p><strong>A basic Svelte component:</strong> consists of three sections: &lt;script&gt;, &lt;style&gt;, and markup (HTML).</p><pre><br>&lt;script&gt;<br>  let name = &#39;world&#39;;<br>&lt;/script&gt;<br><br>&lt;style&gt;<br>  h1 {<br>    color: purple;<br>  }<br>&lt;/style&gt;<br><br>&lt;h1&gt;Hello {name}!&lt;/h1&gt;</pre><p><strong>Reactive Declarations:</strong> Reactive declarations allow you to automatically update values when dependencies change. This is done using the $: syntax.</p><pre>&lt;script&gt;<br>  let count = 0;<br>  $: doubled = count * 2;<br>&lt;/script&gt;<br><br>&lt;p&gt;Count: {count}&lt;/p&gt;<br>&lt;p&gt;Doubled: {doubled}&lt;/p&gt;<br><br>&lt;button on:click={() =&gt; count++}&gt;Increment&lt;/button&gt;</pre><p><strong>Props: </strong>Props are used to pass data from a parent component to a child component.</p><pre>//App.svelte<br>&lt;script&gt;<br>  import Button from &#39;./Button.svelte&#39;;<br>&lt;/script&gt;<br><br>&lt;Button text=&quot;Submit&quot; /&gt;<br>&lt;Button text=&quot;Cancel&quot; /&gt;<br><br>-----------------------------------------------------------------------------<br><br>//Button.svelte:<br>&lt;script&gt;<br>  export let text = &#39;Click me&#39;;<br>&lt;/script&gt;<br><br>&lt;button&gt;{text}&lt;/button&gt;</pre><p><strong>Slots: </strong>Slots allow you to pass markup from a parent component to a child component.</p><pre>//App.svelte<br>&lt;Label&gt;<br>  &lt;p&gt;Slot content&lt;/p&gt;<br>&lt;/Label&gt;<br>-----------------------------------------------------------------------------<br><br>//Label.svelte<br>&lt;slot&gt;&lt;/slot&gt;</pre><p><strong>Bindings: </strong>Bindings create a two-way binding between a variable and a form element.</p><pre>// Bind the input value to the &#39;name&#39; variable and display it<br>&lt;script&gt;<br>  let name = &#39;&#39;;<br>&lt;/script&gt;<br><br>&lt;input bind:value={name} /&gt;<br>&lt;p&gt;{name}&lt;/p&gt;</pre><p><strong>Context API: </strong>The Context API allows you to pass data deeply through the component tree without props.</p><pre>//App.svelte:<br>&lt;script&gt;<br>  import { setContext } from &#39;svelte&#39;;<br>  setContext(&#39;theme&#39;, &#39;dark&#39;);<br>&lt;/script&gt;<br><br>-----------------------------------------------------------------------------<br><br>//Child.svelte:<br>&lt;script&gt;<br>  import { getContext } from &#39;svelte&#39;;<br>  const value = getContext(&#39;theme&#39;);<br>&lt;/script&gt;<br><br>//displays dark<br>&lt;p&gt;{value}&lt;/p&gt;</pre><p><strong>Stores: </strong>Stores are a reactive way to manage shared state across multiple components in Svelte. You can create, update, and subscribe to stores to handle state management efficiently.</p><p>In one of my previous articles, I had described how you can manage state in <a href="https://medium.com/@kaljessy/react-state-management-using-rxjs-58a4d523d611"><strong>React using RxJs</strong></a>. However, Svelte brings this natively.</p><p>Moreover, Svelt 5 is coming up with something called <a href="https://svelte.dev/blog/runes"><strong>runes</strong> </a>which combines reactive declaration (used within components) and stores (used across components).</p><pre>// authStore.js<br>import { writable } from &quot;svelte/store&quot;;<br><br>// Create a writable store for user authentication status<br>export const isAuthenticated = writable(false);<br><br>-----------------------------------------------------------------------------<br>//App.svelte<br>&lt;script&gt;<br>  import { isAuthenticated } from &quot;../lib/authStore&quot;;<br><br>  function login() {<br>    //code to login and udpate the store.<br>    isAuthenticated.update(true);<br>  <br>  }<br>&lt;/script&gt;<br>-----------------------------------------------------------------------------<br>//LoggedStatusComponent.svelte<br>&lt;script lang=&quot;ts&quot;&gt;<br>  import { onDestroy } from &quot;svelte&quot;;<br>  import { isAuthenticated } from &quot;../lib/authStore&quot;;<br><br>  let loggedIn = false;<br> //Subscribe to isAuthenticated in this component<br>  const unsubscribe = isAuthenticated.subscribe((value) =&gt; {<br>    loggedIn = value;<br>  });<br><br>  onDestroy(() =&gt; {<br>    unsubscribe();<br>  });<br>&lt;/script&gt;<br><br>//Change the status label based on condition<br>//look at how if else is used.<br>&lt;div&gt;<br>  &lt;p&gt;<br>  {#if loggedIn}<br>    logged in<br>  {:else}<br>    not logged in<br>  {/if}<br>&lt;/p&gt;<br>&lt;/div&gt;<br></pre><p><strong>Lifecycle Hooks:</strong> Lifecycle hooks allow you to run code at specific times in a component’s lifecycle.</p><pre>&lt;script&gt;<br>  import { onMount, beforeUpdate, afterUpdate, onDestroy } from &#39;svelte&#39;;<br><br>  // onMount: Runs after the component is first rendered in the DOM<br>  onMount(() =&gt; {<br>    console.log(&#39;Component mounted&#39;);<br>    // Perform setup tasks here<br>  });<br><br>  // beforeUpdate: Runs before the DOM is updated when reactive values change<br>  beforeUpdate(() =&gt; {<br>    console.log(&#39;Before update&#39;);<br>    // Perform actions before the DOM updates<br>  });<br><br>  // afterUpdate: Runs immediately after the DOM has been updated<br>  afterUpdate(() =&gt; {<br>    console.log(&#39;After update&#39;);<br>    // Perform actions after the DOM updates<br>  });<br><br>  // onDestroy: Runs just before the component is removed from the DOM<br>  onDestroy(() =&gt; {<br>    console.log(&#39;Component destroyed&#39;);<br>    // Clean up resources here<br>  });<br>&lt;/script&gt;</pre><p><strong>Looping:</strong> Looping through items can be done with the each block.</p><pre>&lt;script&gt;<br>  let items = [&#39;apple&#39;, &#39;banana&#39;, &#39;cherry&#39;];<br>&lt;/script&gt;<br><br>&lt;ul&gt;<br>  {#each items as item}<br>    &lt;li&gt;{item}&lt;/li&gt;<br>  {/each}<br>&lt;/ul&gt;</pre><p><strong>Animations and Transitions: </strong>Svelte includes built-in support for animations.</p><pre>&lt;script&gt;<br>  import { fade } from &#39;svelte/transition&#39;;<br>&lt;/script&gt;<br><br>&lt;div transition:fade&gt;Content&lt;/div&gt;</pre><p>What do you think?</p><p>Have a look at the test svelte project in my GitHub</p><p><a href="https://github.com/jpothanc/go-svelte">GitHub - jpothanc/go-svelte: admiring svelte</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff7ce0f81977" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swagger with SpringBoot 3]]></title>
            <link>https://medium.com/@kaljessy/swagger-with-springboot-3-496aff51b438?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/496aff51b438</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Wed, 03 Jul 2024 11:44:28 GMT</pubDate>
            <atom:updated>2024-07-30T19:22:01.406Z</atom:updated>
            <content:encoded><![CDATA[<p>Swagger is an open-source framework for designing, building, and documenting RESTful APIs with tools for easy visualization, testing, and integration.</p><p>I have extensive experience using Swagger in .NET Core and recently in Python Flask. However, integrating it with Spring posed a challenge for me. Once I finally got it working, the process turned out to be straightforward. I decided to share my experience to help others facing similar issues.</p><p>This is a very basic example of how to get this working.</p><h3>Swagger Spring Integration in 3 steps</h3><pre>1. Install Maven/Gradle dependency.<br>2. Create a SwaggerConfig class.<br>3. Add documentation in to your Controller class.</pre><p><strong>Maven/Gradle Dependency</strong></p><pre>//Gradle<br>implementation &#39;org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0&#39;<br><br>//Maven<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>    &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>    &lt;version&gt;2.5.0&lt;/version&gt;<br>&lt;/dependency&gt;<br><br>//Note: Make sure that you have the below dependancies configured for Gradle/Maven<br><br>implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>implementation &#39;com.fasterxml.jackson.core:jackson-core:2.17.0&#39;<br><br> &lt;dependency&gt;<br>  &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>  &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br> &lt;/dependency&gt;<br><br> &lt;dependency&gt;<br>   &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;<br>   &lt;artifactId&gt;jackson-core&lt;/artifactId&gt;<br>   &lt;version&gt;2.17.0&lt;/version&gt;<br>  &lt;/dependency&gt;</pre><p>Create a SwaggerConfig.Java</p><pre>import io.swagger.v3.oas.models.OpenAPI;<br>import io.swagger.v3.oas.models.info.Info;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class SwaggerConfig {<br><br>    @Bean<br>    public OpenAPI customOpenAPI() {<br>        return new OpenAPI()<br>                .info(new Info()<br>                        .title(&quot;Greeting API&quot;)<br>                        .version(&quot;1.0&quot;)<br>                        .description(&quot;API for greeting users&quot;));<br>    }<br>}</pre><p>Document Controller using Tag and Operation and API response annotation.</p><pre>import io.swagger.v3.oas.annotations.Operation;<br>import io.swagger.v3.oas.annotations.responses.ApiResponse;<br>import io.swagger.v3.oas.annotations.tags.Tag;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@Tag(name = &quot;greeting&quot;, description = &quot;the greeting API&quot;)<br>@RestController<br>public class GreetingController {<br><br>    @Operation(summary = &quot;Say hello&quot;)<br>    @ApiResponse(responseCode = &quot;200&quot;, description = &quot;Successful operation&quot;)<br>    @GetMapping(&quot;/hello&quot;)<br>    public String hello(@RequestParam String name) {<br>        return &quot;Hello, &quot; + name;<br>    }<br><br>    @Operation(summary = &quot;Say goodbye&quot;)<br>    @ApiResponse(responseCode = &quot;200&quot;, description = &quot;Successful operation&quot;)<br>    @GetMapping(&quot;/goodbye&quot;)<br>    public String goodbye(@RequestParam String name) {<br>        return &quot;Goodbye, &quot; + name;<br>    }<br>}</pre><p>Access Swagger using the following link</p><pre>http://localhost:8080/swagger-ui.html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*zm3-F3aZXUTyz-owMb4Q8w.png" /></figure><p>Happy Coding…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=496aff51b438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Personal AI Assistant using RAG and ChromaDB]]></title>
            <link>https://medium.com/@kaljessy/personal-ai-assitant-using-rag-and-chromadb-6fd5c259da41?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fd5c259da41</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 08:47:07 GMT</pubDate>
            <atom:updated>2024-06-12T10:47:23.736Z</atom:updated>
            <content:encoded><![CDATA[<p>When I was in school, tired of studying endless hours, I would sometimes pick up the hefty book and, in a moment of whimsical fantasy, flip through its pages rapidly. As the pages blurred before my eyes, I imagined a world where all this information could be instantly transferred to my brain. I wouldn’t have to memorize each detail laboriously. Instead, I could effortlessly access any fact or concept, ready to answer any question effortlessly.</p><p>What if I told you that a version of this fantasy is becoming a reality?</p><p>Enter the world of Retrieval-Augmented Generation, or RAG.</p><h3><strong>What is RAG?</strong></h3><p>Retrieval-augmented generation (RAG) is an innovative approach in the field of artificial intelligence that brings us closer to the idea of instant knowledge access. While it doesn’t download entire textbooks into your brain, it combines two powerful AI techniques to deliver information swiftly and accurately.</p><p><strong>How Does RAG Work?</strong><br>RAG operates through a seamless integration of two components:</p><p><strong>Retrieval:</strong> Imagine having an assistant that can instantly scan a vast library of books, articles, and documents. When a question is posed, this assistant retrieves the most relevant information from this extensive corpus.</p><p><strong>Generation:</strong> Once the relevant information is retrieved, it is then sent to the generative model to formulate a coherent and contextually accurate response. This is like having an expert who not only finds the right page in the textbook but also reads, understands, and explains the content in a way that directly answers your question.</p><p>In essence, RAG allows us to do what I had once dreamed of as a student: access vast amounts of information quickly and use it to provide accurate answers on demand.</p><h3>Let’s get this working</h3><p>Recently I have been preparing for Azure AZ-900 certification. I thought of applying this concept to the documentation I prepared for this exam.</p><p>I will be using Python to demonstrate this. The below are the 6 steps in which we could achieve this.</p><pre>// Retrieval<br>1. Load my Azure Notes which is in Markdown format.<br>2. Split the data into paragraphs.<br>3. Save the split chunks in the form of &quot;embeddings&quot; in to Chroma DB <br><br>// Generation<br>1. Ask a question like &quot;what is iaas, paas and saas?&quot;<br>2. Get the possible responses from chroma db.<br>3. Feed in these responses to OpenAI to get the best response.</pre><pre>&quot;ChromaDB&quot; is like a super-smart library that can remember and quickly <br>find information. Instead of books, it stores &quot;embeddings,&quot; which are like <br>summaries or important points of data. It helps find similar information <br>very quickly, which is great for tasks like finding recommendations or <br>answering questions. It can manage and search through a huge amount of data <br>efficiently</pre><pre><br>&quot;Embeddings&quot; are just like a map helps you see how close one place is to <br>another, embeddings help a computer see how similar one word or piece of data <br>is to another. Basically this helps understand relations with each other.<br><br>For example, in an embedding, the words &quot;king&quot; and &quot;queen&quot; would be close <br>together because they have similar meanings.<br><br>Computers can process numbers quickly and easily. <br>By turning words into numbers, it makes it faster and easier for computers <br>to work with text.<br><br>Simple Example:<br>Imagine you have three words: &quot;apple,&quot; &quot;banana,&quot; and &quot;cat.&quot; <br>You want the computer to understand that &quot;apple&quot; and &quot;banana&quot; are more <br>similar to each other than to &quot;cat.&quot;<br><br>You could turn them into embeddings like this:<br><br>Apple: [1, 0, 0]<br>Banana: [1, 0.1, 0]<br>Cat: [0, 0, 1]<br>In this list of numbers (vector):<br><br>The first number could represent &quot;is it a fruit?&quot;<br>The second number could represent &quot;how sweet is it?&quot;<br>The third number could represent &quot;is it an animal?&quot;<br>So, &quot;apple&quot; and &quot;banana&quot; have similar numbers because they are both fruits, <br>while &quot;cat&quot; is very different because it’s an animal.<br><br>How Embeddings are Used?<br><br>Search Engines:  <br>To find information similar to what you’re looking for.<br><br>Recommendations: <br>To suggest things like movies or products that are similar to what you like.<br><br>Language Translation: <br>To understand and translate languages by comparing meanings of words.<br><br>Finding Similarity Between Words ?<br><br>To determine if these words are similar or different, we can calculate the <br>distance between their vectors. One common method is the &quot;cosine similarity&quot;, <br>which measures the cosine of the angle between two vectors. A cosine similarity closer to 1 indicates that the vectors are similar (close),<br>while a value closer to 0 indicates that they are different (far apart).<br><br>Go to this url to learn about cosine similarity:<br>https://www.datastax.com/guides/what-is-cosine-similarity<br></pre><p><strong>Setup:</strong></p><pre>1. python version 3.12<br><br>2. dependancies<br>  langchain==0.2.2<br>  langchain-community==0.2.3<br>  langchain-openai==0.1.8 # For embeddings<br>  unstructured==0.14.4 # Document loading<br>  chromadb==0.5.0 # Vector storage<br>  openai==1.31.1 # For embeddings<br>  tiktoken==0.7.0  # For embeddings<br>  # install markdown depenendies with: `pip install &quot;unstructured[md]&quot;<br><br>3. A paid OpenAI account ( look at the useful links section) <br>   We can do this using a locally hosted LLM, that will another article.</pre><p><strong>Retriever:</strong></p><pre>from langchain_community.document_loaders import DirectoryLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain.schema import Document<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores import Chroma<br>import openai<br>import os<br>import shutil<br><br>from constants import DATA_PATH, CHROMA_DB_PATH, CHUNK_SIZE, CHUNK_OVERLAP<br><br># assuming that environment called &quot;OPENAI_API_KEY&quot; is set.<br># This is your openai api key that you can get from openai.com<br>openai.api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br><br><br>def retrieve_data():<br>    documents = load_documents()<br>    chunks = split_text(documents)<br>    save_to_chroma(chunks)<br><br><br># Load my Azure Notes which is in Markdown format.<br>def load_documents():<br>    loader = DirectoryLoader(DATA_PATH, glob=&quot;*.md&quot;)<br>    documents = loader.load()<br>    return documents<br><br><br># Split the data into paragraphs.<br>def split_text(documents: list[Document]):<br>    text_splitter = RecursiveCharacterTextSplitter(<br>        chunk_size=CHUNK_SIZE,<br>        chunk_overlap=CHUNK_OVERLAP,<br>        length_function=len,<br>        add_start_index=True,<br>    )<br>    chunks = text_splitter.split_documents(documents)<br>    print(f&quot;Split {len(documents)} documents into {len(chunks)} chunks.&quot;)<br><br>    document = chunks[10]<br>    print(document.page_content)<br>    print(document.metadata)<br><br>    return chunks<br><br><br># Chroma is a vector store that can be used to store and retrieve embeddings of text data.<br># Save the split chunks in to Chroma DB after converting this in to embeddings.<br># We use openai embeddings to convert the text to embeddings.<br>def save_to_chroma(chunks: list[Document]):<br>    # Delete the existing DB first.<br>    if os.path.exists(CHROMA_DB_PATH):<br>        shutil.rmtree(CHROMA_DB_PATH)<br><br>    # Create a new DB from the documents.<br>    db = Chroma.from_documents(<br>        chunks, OpenAIEmbeddings(), persist_directory=CHROMA_DB_PATH<br>    )<br>    db.persist()<br>    print(f&quot;Saved {len(chunks)} chunks to {CHROMA_DB_PATH}.&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    retrieve_data()</pre><p><strong>Generator:</strong></p><pre>from langchain_community.vectorstores import Chroma<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_openai import ChatOpenAI<br>from langchain.prompts import ChatPromptTemplate<br>from constants import CHROMA_DB_PATH, PROMPT_TEMPLATE<br><br><br># Query the Chroma DB with the user input.<br># If the similarity score is less than 0.7, then we will not return any results.<br># Pass the context text and the question to the ChatOpenAI model and get the response.<br>def query_chroma(query_text):<br>    # Prepare the DB.<br>    embedding_function = OpenAIEmbeddings()<br>    db = Chroma(persist_directory=CHROMA_DB_PATH, embedding_function=embedding_function)<br><br>    # Search the DB.<br>    results = db.similarity_search_with_relevance_scores(query_text, k=3)<br>    if len(results) == 0 or results[0][1] &lt; 0.7:<br>        print(f&quot;Unable to find matching results.&quot;)<br>        return<br><br>    context_text = &quot;\n\n---\n\n&quot;.join([doc.page_content for doc, _score in results])<br>    prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)<br>    prompt = prompt_template.format(context=context_text, question=query_text)<br><br>    model = ChatOpenAI()<br>    response_text = model.invoke(prompt)<br>    # sources = [doc.metadata.get(&quot;source&quot;, None) for doc, _score in results]<br>    formatted_response = f&quot;Response: {response_text.content}&quot;<br>    print(formatted_response)<br><br><br>def query_data():<br>    while True:<br>        user_input = input(&quot;Enter your question:&quot;).lower()<br>        if user_input == &quot;exit&quot;:<br>            break<br>        query_text = user_input<br>        query_chroma(query_text)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    query_data()</pre><p><strong>Running the code:</strong></p><pre>//load, split save my azure notes.<br>python retrieve_data.py<br><br>//query, get response and optimize it.<br>python query_data.py</pre><p><strong>Response:</strong></p><pre>Enter your question:what is iaas, paas and saas in detail?<br><br>Response: IaaS (Infrastructure as a Service) provides cloud resources such <br>as servers, storage, and networking as a service, giving consumers high contr<br>ol over their cloud infrastructure.Consumers are responsible for managing applications, data, runtime, <br>middleware, and OS in the IaaS model.<br><br>PaaS (Platform as a Service) allows consumers to manage applications and data,<br>with the cloud provider handling the underlying infrastructure. This <br>model simplifies the development and deployment of applications by providing a platform for developers to build upon.<br><br>SaaS (Software as a Service) is a cloud model where most responsibilities are <br>handled by the cloud provider. Consumers access software applications over<br>the internet without needing to manage the underlying infrastructure, making it a convenient option for users.</pre><p><strong>Useful links:</strong></p><p><a href="https://medium.com/@kaljessy/chating-with-openai-using-python-3ae5a14b4501">Chating with OpenAI using Python</a></p><p>Also, feel free to look at the code in Git.</p><p><a href="https://github.com/jpothanc/my-ai-assistant">GitHub - jpothanc/my-ai-assistant: My AI Assistant using RAG and ChromaDB</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fd5c259da41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chating with OpenAI using Python]]></title>
            <link>https://medium.com/@kaljessy/chating-with-openai-using-python-3ae5a14b4501?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ae5a14b4501</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Fri, 31 May 2024 19:48:28 GMT</pubDate>
            <atom:updated>2024-06-04T00:45:17.268Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide will walk you through the process of building your very own custom ChatGPT, leveraging the flexibility and simplicity of Python programming.</p><p><strong>Prerequisite: </strong>Knowledge of Python and a paid OpenAI account ( I thought there would be some free credits, but there weren’t. So, I bought $5 worth to test it out)</p><p><a href="https://platform.openai.com/settings/organization/billing/overview">https://platform.openai.com/settings/organization/billing/overview</a></p><p>Create an OpenAI key using the Create New Secret Key Option.<a href="https://platform.openai.com/settings/profile?tab=api-keys">https://platform.openai.com/settings/profile?tab=api-keys</a></p><h3>Cost and Tokens?</h3><pre>Cost is calculated based on openAI model and input/output tokens in millions.<br><br>e.g. <br>Model              Input               Output<br>----------------------------------------------------------<br>gpt-4o             $5.00  / 1M tokens  $15.00 / 1M tokens<br>gpt-4-turbo        $10.00 / 1M tokens  $30.00 / 1M tokens<br>gpt-3.5-turbo-0125 $0.50  / 1M tokens  $1.50  / 1M tokens<br><br>What are tokens?<br><br>Tokens can be thought of as pieces of words.Before the API processes <br>the request, the input is broken down into tokens.Here are some helpful <br>rules of thumb for understanding tokens in terms of lengths:<br><br>1 token ~= 4 chars in English<br>1 token ~= ¾ words<br>100 tokens ~= 75 words<br><br>Or <br><br>1-2 sentence ~= 30 tokens<br>1 paragraph ~= 100 tokens<br>1,500 words ~= 2048 tokens<br><br></pre><p><strong>OpenAI Pricing information:</strong><a href="https://openai.com/api/pricing/">https://openai.com/api/pricing/</a></p><p><strong>What are tokens and how do you count them?</strong><a href="https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them">https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them</a></p><h3>The Code</h3><p>I tried the async approach and encapsulated the logic into an AsyncOpenAIBot class. To use the AsyncOpenAIBotclass, you must provide a valid OpenAI API key when creating an instance of the class. This key is used to authenticate your requests to the OpenAI API.</p><p>AsyncOpenAIBotClass</p><pre>import openai<br>from openai import AsyncOpenAI<br>from typing import Callable, Any<br>class AsyncOpenAIBot:<br><br>    def __init__(self, api_key):<br>        self.client = AsyncOpenAI(api_key = api_key)<br><br>    async def get_response(self, prompt:str, callback: Callable[[Any], None], model: str = &quot;gpt-3.5-turbo&quot;):<br>        try:<br>            response = await  self.client.chat.completions.create(<br>                model=model,<br>                messages=[{&quot;role&quot;: &quot;user&quot;,&quot;content&quot;: prompt}]<br>            )<br>            callback(response.choices[0].message.content.strip())<br>            <br>        except openai.RateLimitError as e:<br>            raise Exception(f&quot;Rate limit exceeded. Please try again later. {e}&quot;);<br>        except openai.AuthenticationError as e :<br>            raise Exception(f&quot;Authentication failed. Please check your API key. {e}&quot;);<br>        except openai.OpenAIError as e:<br>            raise Exception(f&quot;An error occurred:. {e}&quot;);</pre><p>Calling OpenAIBot</p><pre>def my_callback(response):<br>    print(&quot;Received response:&quot;, response)<br><br>def run_bot_async():<br>    import asyncio<br>    openai_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>    if openai_key is None:<br>        print(&quot;Please set OPENAI_API_KEY environment variable&quot;)<br>        exit(1)<br>   <br>   openai_bot = AsyncOpenAIBot(openai_key)<br>    while True:<br>        user_input = input(&quot;Enter your question:&quot;).lower()<br>        if user_input == &quot;exit&quot;:<br>            break<br>        asyncio.run(openai_bot.get_response(user_input, my_callback))<br><br><br>if __name__ == &quot;__main__&quot;:<br>    try:<br>        run_bot_async()<br>    except Exception as e:<br>        print(e)</pre><h3>How does the program work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*takxhNWR_BTf3zvYNwQmOA.png" /></figure><h3>Other Useful Links</h3><p><strong>OpenAI Usage Stats: </strong><a href="https://platform.openai.com/usage">https://platform.openai.com/usage</a></p><p><strong>OpenAI Python SDK: </strong><a href="https://github.com/openai/openai-python">https://github.com/openai/openai-python</a></p><h3>Library and Code</h3><p>I have encapsulated this functionality into my Python library . It has both synchronous and async ways to connect to OpenAI.</p><pre>pip install omnijp</pre><p>Go through the readme for more details.</p><p><a href="https://pypi.org/project/omnijp/2.7.0/">omnijp</a></p><p>Also, feel free to look at the code in Git.</p><p><a href="https://github.com/jpothanc/omnijp">GitHub - jpothanc/omnijp: Python tools</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ae5a14b4501" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Web Desktop Apps using Electron]]></title>
            <link>https://medium.com/@kaljessy/build-web-desktop-apps-using-electron-a4c6e226290c?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4c6e226290c</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Mon, 27 May 2024 19:24:02 GMT</pubDate>
            <atom:updated>2024-05-28T03:42:38.968Z</atom:updated>
            <content:encoded><![CDATA[<p>Electron is a popular framework that allows developers to build cross-platform desktop applications using web technologies.</p><p>My goal here is to demonstrate how you can build your first Electron app using React and Vite on Windows with a simple working solution.</p><h3>Prerequisites</h3><ul><li>Node.js: Required for managing the development toolchain.</li></ul><h3>Electron Stand-Alone App in 11 Steps</h3><pre>///Install node.js and check thier versions<br>1. check node version using node -v <br><br>//Create react app called my-first-tauri-app using vite<br>2. npm create vite@latest react-electron-desktop-app -- --template react-ts<br>3. cd react-electron-desktop-app<br>4. npm install<br><br>//Electron: Framework for building cross-platform desktop apps <br>//with web technologies.<br>//Wait-on: CLI tool that waits for resources like files and ports <br>//to be available before proceeding.<br>//Concurrently: Allows running multiple commands simultaneously <br>//in the same terminal.<br>//Cross-env: Facilitates setting environment variables across <br>//different operating systems.<br>5. npm i electron wait-on concurrently cross-env<br><br>// Open the react app in VS Code<br>6. code .<br><br>7. create a electron folder and create preload.js (keep this empty<br>  and electron.js (see electron.js contents section)  files<br><br>8. Edit package.json <br>  {<br>    &quot;name&quot;: &quot;react-electron-desktop-app&quot;,<br>    &quot;private&quot;: true,<br>    &quot;version&quot;: &quot;0.0.0&quot;,<br>    &quot;type&quot;: &quot;module&quot; //remove this<br>    &quot;main&quot;: &quot;electron/electron.js&quot;, // add this<br>    .....<br><br>//Edit vite.config.ts to override the port to 3000<br>9. update scripts section as below<br>   &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;build&quot;: &quot;tsc --noEmit &amp;&amp; vite build&quot;,<br>    &quot;serve&quot;: &quot;vite preview&quot;,<br>    &quot;electron&quot;: &quot;wait-on tcp:3001 &amp;&amp; cross-env IS_DEV=true NODE_ENV=development electron .&quot;,<br>    &quot;electron:pack&quot;: &quot;electron-builder --dir&quot;,<br>    &quot;electron:dev&quot;: &quot;concurrently -k \&quot;cross-env BROWSER=none npm run dev\&quot; \&quot;npm run electron\&quot;&quot;,<br>    &quot;electron:builder&quot;: &quot;electron-builder&quot;,<br>    &quot;build:for:electron&quot;: &quot;tsc --noEmit &amp;&amp; cross-env ELECTRON=true vite build&quot;,<br>    &quot;app:build&quot;: &quot;npm run build:for:electron &amp;&amp; npm run electron:builder&quot;<br>  },<br><br>//Edit vite.config.ts to override the port to 3001<br>10. By default react app runs on 5173, we need to override this to 3001<br>   To do this, open vite.config.ts and add the server and port options.<br>    export default defineConfig({<br>      plugins: [react()],<br>    //override port<br>      server:{<br>        port: 3001,<br>      }<br>    })<br><br>//bring up the standalone app<br>11. npm run electron:dev</pre><p>electron.js contents</p><pre>const { app, BrowserWindow } = require(&quot;electron&quot;);<br>const path = require(&quot;path&quot;);<br><br>function createWindow() {<br>  const win = new BrowserWindow({<br>    width: 800,<br>    height: 600,<br>    webPreferences: {<br>      preload: path.join(__dirname, &quot;preload.js&quot;),<br>      nodeIntegration: true,<br>      contextIsolation: false,<br>    },<br>  });<br>  if (process.env.NODE_ENV == &quot;development&quot;) {<br>    win.loadURL(&quot;http://localhost:3001&quot;);<br>    win.webContents.openDevTools();<br>  } else {<br>    console.log(<br>      `Development Mode: Loading from localhost = ${process.env.NODE_ENV}`<br>    );<br>    win.loadFile(path.join(__dirname, &quot;../index.html&quot;));<br>  }<br>}<br><br>app.whenReady().then(() =&gt; {<br>  createWindow();<br><br>  app.on(&quot;activate&quot;, () =&gt; {<br>    if (BrowserWindow.getAllWindows().length === 0) {<br>      createWindow();<br>    }<br>  });<br>});<br><br>app.on(&quot;window-all-closed&quot;, () =&gt; {<br>  if (process.platform !== &quot;darwin&quot;) {<br>    app.quit();<br>  }<br>});</pre><p>Desktop app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*iac4AVLni7Nl5R4ePVaGOA.png" /></figure><p>Check out the code in git.</p><p><a href="https://github.com/jpothanc/react-electron-desktop-app">GitHub - jpothanc/react-electron-desktop-app: A Electron desktop app using React and Vite.</a></p><p>Also, check my article on Tauri.</p><p><a href="https://medium.com/@kaljessy/build-web-desktop-apps-using-tauri-6fe12586016a">Build Web Desktop Apps using Tauri</a></p><p>Differences and similarities between these two popular frameworks for building desktop applications with web technologies. (courtesy Chatgpt)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*WHwBiOlD9QNjdc2NjDcWfQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c6e226290c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Web Desktop Apps using Tauri]]></title>
            <link>https://medium.com/@kaljessy/build-web-desktop-apps-using-tauri-6fe12586016a?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fe12586016a</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Mon, 27 May 2024 18:53:02 GMT</pubDate>
            <atom:updated>2024-08-05T03:40:17.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AP61ybUmXPt7xa33Lq_l8A.png" /><figcaption>Courtesy: ChatGPT</figcaption></figure><p>Tauri is a toolkit for developing desktop applications with web frontends. It allows you to compile web apps into native applications on Windows, macOS, and Linux. Tauri integrates with the front-end framework of your choice, whether it’s React, Vue, Svelte, or even vanilla JavaScript. Developers create their user interface as if designing a regular web application. Tauri then acts as a bridge, converting this web content into a native application. it is a minimalistic, performant and more secure alternative to other similar tools like Electron.</p><p>My goal here is to demonstrate how you can build your first Tauri app using React and Vite on Windows.</p><h3>Prerequisites</h3><ul><li>Node.js: Required for managing the development toolchain.</li><li>Rust: As Tauri compiles to Rust, having the Rust toolchain installed via rustup is essential.</li><li>Webview2 (for Windows users): Necessary for rendering web content in Tauri apps on Windows platforms. If you have Microsoft Edge installed on your system, you do not need to separately install WebView2 for Tauri applications on Windows.</li></ul><h3>Tauri Stand-Alone App in 10 Steps</h3><pre>//Install node.js and rust and check thier versions<br>1. check node and rest versions using node -v and rustc --version commands<br><br>//Install Tauri CLI.The is essential for initializing <br>//new Tauri projects, building, and managing the development process. <br>2. npm install @tauri-apps/cli<br><br>//Create react app called my-first-tauri-app using vite<br>3. npm create vite@latest react-tauri-desktop-app -- --template react-ts<br>4. cd react-tauri-desktop-app<br>5. npm install<br><br>//Initializes a new Tauri project within your existing web application. <br>//It sets up the necessary Tauri configuration files and directories <br>//in your project. Press enter and accept the defaults.code<br>6. npx tauri init<br><br>C:\Projects\React\react-tauri-desktop-app&gt;npx tauri init<br>✔ What is your app name? · react-tauri-desktop-app<br>✔ What should the window title be? · react-tauri-desktop-app<br>? Where are your web assets (HTML/CSS/JS) located, relative to the &quot;&lt;current dir&gt;/src-tauri/tauri.conf.json&quot; file that w✔ Where are your web assets (HTML/CSS/JS) located, relative to the &quot;&lt;current dir&gt;/src-tauri/tauri.conf.json&quot; file that will be created? · ../build<br>✔ What is the url of your dev server? · http://localhost:3000<br>✔ What is your frontend dev command? · npm run dev<br>✔ What is your frontend build command? · npm run build<br><br><br>// Open the react app in VS Code<br>7. code .<br><br>//Edit vite.config.ts to override the port to 3000<br>8. By default react app runs on 5173, we need to override this to 3000<br>   To do this, open vite.config.ts and add the server and port options.<br>    export default defineConfig({<br>      plugins: [react()],<br>    //override port<br>      server:{<br>        port: 3000,<br>      }<br>    })<br><br>//Edit tauri.conf.json<br>9. Change distDir from ../build to ../dist and identifier option.<br>&quot;build&quot;: {<br>    ....<br>    &quot;distDir&quot;: &quot;../dist&quot;<br>  },<br>  ....<br>// It cannot be the default(com.tauri.dev) <br>// if you don&#39;t change this, npx tauri build command will give following error.<br>// ***Error You must change the bundle identifier in `tauri.conf.json &gt; tauri &gt; bundle <br>// &gt; identifier`. The default value `com.tauri.dev` is not allowed as it must <br>// be unique across applications.***<br> &quot;identifier&quot;: &quot;com.example.tauri&quot;,<br><br>//bring up the standalone app<br>10. npx tauri dev </pre><h3>Building and Running as an Executable</h3><pre>npx tauri build<br>//This will create the release package \src-tauri\target\release folder.<br>//click react-tauri-desktop-app to run the application<br></pre><p>Check out the code in git.</p><p><a href="https://github.com/jpothanc/react-tauri-desktop-app">GitHub - jpothanc/react-tauri-desktop-app: A Tauri desktop app using React and Vite.</a></p><p>Also, check my article on Electron.</p><p><a href="https://medium.com/@kaljessy/build-web-desktop-apps-using-electron-a4c6e226290c">Build Web Desktop Apps using Electron</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fe12586016a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Discovering Python Through Microservice Development]]></title>
            <link>https://medium.com/@kaljessy/discovering-python-through-microservice-development-cda7b8f97848?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/cda7b8f97848</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 04:52:03 GMT</pubDate>
            <atom:updated>2024-08-30T05:42:12.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>Microservice in Python</h3><p>As someone deeply rooted in the .Net and Java ecosystems, my programming journey has been full of strongly typed languages and enterprise-level frameworks. However, the allure of Python, with its simplicity and versatility, recently captured my interest. Eager to understand the essence of Python and how it contrasts with the familiar territories of .Net and Java, I embarked on a project that would not only allow me to peek into Python but also to apply it in a real-world scenario. This project took the form of a microservice, aptly named “Equity Store,” designed to fetch stock information by code and exchange.</p><p>With “Equity Store,” my objective was to explore Python’s capabilities in microservice architecture, addressing various critical aspects that are pivotal in microservice development, regardless of the programming language used.</p><p>Let&#39;s look at the essential considerations for building a robust microservice Please note that I am not adding details code snippets here but will provide the link to my repo.</p><h4>API Design</h4><p>Crafting endpoints that are intuitive and well-structured, ensuring they align with RESTful principles.</p><h4>API Versioning</h4><p>Implementing URL path versioning (e.g., /api/v1/resource) manage changes and maintain backward compatibility with older versions of the API.</p><pre>eq_api = Api(eq_app, version=&#39;1.0&#39;, title=&#39;Equity Store API&#39;, description=&#39;Equity Store API&#39;, prefix=&#39;/api/v1&#39;)</pre><h4>Modularity</h4><p>Organizing the codebase into distinct modules or blueprints for different areas of functionality, enhancing maintainability and scalability.</p><pre><br>&quot;&quot;&quot;<br>Register blueprints and api<br>&quot;&quot;&quot;<br>def register_blueprints_and_api(app, api):<br>    api.add_namespace(eq_ns)<br>    api.add_namespace(eq_ex_ns)<br>    app.register_blueprint(health_bp, url_prefix=&#39;/api&#39;)</pre><h4>Error Handling</h4><p>Utilizing Flask’s error handling mechanisms (like @app.errorhandler) to catch exceptions and return informative error responses, improving reliability and user experience.</p><pre>&quot;&quot;&quot;<br>Global error handlers<br>&quot;&quot;&quot;<br>def register_error_handlers(app):<br>    app.register_error_handler(404, error_handlers.not_found)<br>    app.register_error_handler(500, error_handlers.internal_server_error)</pre><h4>Configuration</h4><p>Utilized JSON file to configure application settings. This file will be loaded based on the environment variable settings</p><pre>FLASK_ENV =&quot;development&quot; or FLASK_ENV =&quot;testing&quot; or FLASK_ENV =&quot;production&quot;</pre><pre>{<br>  &quot;port&quot;: 8080,<br>  &quot;log_path&quot;: &quot;/var/log/stock_info.log&quot;,<br>  &quot;preload_exchanges&quot;: &quot;NASDAQ,NYSE&quot;,<br>  &quot;data_source&quot;: &quot;database&quot;,<br>  &quot;exchange_query&quot;: &quot;SELECT * FROM stocks WHERE exchange = ?&quot;,<br>  &quot;data_sources&quot;: {<br>    &quot;database&quot;: {<br>      &quot;host&quot;: &quot;localhost&quot;,<br>      &quot;port&quot;: 3306,<br>      &quot;user&quot;: &quot;root&quot;,<br>      &quot;password&quot;: &quot;password&quot;,<br>      &quot;database&quot;: &quot;stocks&quot;<br>    }<br>  }<br>}</pre><h4>Swagger Documentation</h4><p>Integrating Swagger UI with Flask using extensions like flasgger to auto-generate interactive API documentation, making it easier for developers to understand and test the API.</p><pre>@eq_ns.route(&#39;&#39;)<br>class Equity(Resource):<br>    @eq_ns.doc(&#39;get_equity&#39;)<br>    @eq_ns.response(201, &#39;equity details&#39;)<br>    @eq_ns.response(400, &#39;Internal Error&#39;)<br>    @eq_ns.response(500, &#39;Internal Server Error&#39;)<br>    @eq_ns.expect(eq_parser)<br>    def get(self):<br>        &quot;&quot;&quot;Get equity&quot;&quot;&quot;<br>        try:<br>            args = eq_parser.parse_args()<br>            code = args.get(&#39;product_code&#39;)<br>            if not code:<br>                return {&quot;message&quot;: &quot;Product code is required.&quot;}, 400<br>            eq_service = g.flask_injector.injector.get(EquityService)<br>            equity =  eq_service.get_equity(code)<br>            if equity is None:<br>                return {&quot;message&quot;: &quot;Equity not found&quot;}, 404<br>            return equity,200<br>        except Exception as e:<br>            return {&quot;message&quot;: &quot;Internal Server Error&quot;, &quot;error&quot;: str(e)}, 500</pre><h4>Logging</h4><p>Setting up Flask’s built-in logging to capture detailed logs, facilitating easier debugging and monitoring of the microservice.</p><pre>&quot;&quot;&quot;<br>Initialize logging<br>&quot;&quot;&quot;<br>def init_logging(log_path):<br>        os.makedirs(log_path, exist_ok=True)<br>        log_file = os.path.join(log_path, &#39;equity_store.log&#39;)<br>        logging.basicConfig(<br>            level=logging.INFO,<br>            format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;,<br>            handlers=[<br>                logging.FileHandler(log_file),<br>                #This handler outputs log messages to the console<br>                logging.StreamHandler()])</pre><h4>Dependency Injection</h4><p>Applied dependency injection using injector, to decouple components and services, thereby enhancing testability and modularity.</p><pre>&quot;&quot;&quot;<br>This class is used to bind the services to their implementations and scopes<br>Steps<br>1. Add the bindings to factory.development.json<br>2. Make sure the dependencies are added in the order of their dependencies<br>3. import the services and their implementations<br>&quot;&quot;&quot;<br>class DependencyInjectionModules(Module):<br>    def configure(self, binder):<br>        try:<br><br>            file_path = get_env_factory_file()<br>            with open(file_path, &#39;r&#39;) as file:<br>                factory_config = json.load(file)<br><br>            for binding in factory_config.get(&#39;bindings&#39;):<br>                binder.bind(<br>                    eval(binding[&#39;service&#39;]),<br>                    to=eval(binding[&#39;implementation&#39;]),<br>                    scope=eval(binding[&#39;scope&#39;]))<br>            binder.bind(ConfigProvider, to=ConfigProvider, scope=singleton)<br><br>        except FileNotFoundError:<br>            print(f&quot;File not found: {FACTORY_FILE}&quot;)<br>        except Exception as e:<br>            print(f&quot;Error Configuring Dependency Injection: {e}&quot;)</pre><p>A factory file is used to configure dependency injection.</p><pre>{<br>  &quot;bindings&quot;: [<br>     {<br>      &quot;service&quot;: &quot;EncryptionService&quot;,<br>      &quot;implementation&quot;: &quot;EncryptionService&quot;,<br>      &quot;scope&quot;: &quot;singleton&quot;<br>    },<br>    {<br>      &quot;service&quot;: &quot;EquityService&quot;,<br>      &quot;implementation&quot;: &quot;EquityService&quot;,<br>      &quot;scope&quot;: &quot;singleton&quot;<br>    },<br>    {<br>      &quot;service&quot;: &quot;DatabaseService&quot;,<br>      &quot;implementation&quot;: &quot;DbPostgresService&quot;,<br>      &quot;scope&quot;: &quot;request&quot;<br>    },<br>    {<br>      &quot;service&quot;: &quot;StockRepository&quot;,<br>      &quot;implementation&quot;: &quot;StockRepositoryDisk&quot;,<br>      &quot;scope&quot;: &quot;singleton&quot;<br>    }<br>  ]<br>}</pre><p>This is useful when we need variations in deployments.</p><p>For example, use the below variations when you want to read the stock information from the database or disk.</p><pre>{<br>      &quot;service&quot;: &quot;StockRepository&quot;,<br>      &quot;implementation&quot;: &quot;StockRepositoryDB&quot;,<br>      &quot;scope&quot;: &quot;singleton&quot;<br>}</pre><pre>{<br>      &quot;service&quot;: &quot;StockRepository&quot;,<br>      &quot;implementation&quot;: &quot;StockRepositoryDisk&quot;,<br>      &quot;scope&quot;: &quot;singleton&quot;<br>}</pre><p>This factory file will be loaded based on the environment variable settings.</p><h4>Authentication</h4><p>Securing endpoints using a simple authentication mechanism. We could also use Flask extensions (e.g., Flask-JWT-Extended) for JWT-based authentication, ensuring that only authorized users can access certain API functionalities.</p><pre>   @eq_ns.expect(stock_info)<br>    @requires_auth<br>    def post(self):<br>        &quot;&quot;&quot;Create a new equity &quot;&quot;&quot;<br>        return {&quot;message&quot;: &quot;Stock info received&quot;, &quot;data&quot;: eq_ns.payload}, 201<br><br><br>def check_auth(username, password):<br>    &quot;&quot;&quot;This function is called to check if a username /<br>    password combination is valid.&quot;&quot;&quot;<br>    return username in users and password == users[username]<br><br>def authenticate():<br>    &quot;&quot;&quot;Sends a 401 response that enables basic auth&quot;&quot;&quot;<br>    return Response(<br>    &#39;Could not verify your access level for that URL.\n&#39;<br>    &#39;You have to login with proper credentials&#39;, 401,<br>    {&#39;WWW-Authenticate&#39;: &#39;Basic realm=&quot;Login Required&quot;&#39;})<br><br>def requires_auth(f):<br>    @wraps(f)<br>    def decorated(*args, **kwargs):<br>        auth = request.authorization<br>        if not auth or not check_auth(auth.username, auth.password):<br>            return authenticate()<br>        return f(*args, **kwargs)<br>    return decorated</pre><h4>Encryption of Passwords</h4><p>Utilizing libraries like Fernet to hash and verify passwords securely, protecting user credentials effectively.</p><h4>Health Check</h4><p>Implementing a health check endpoint (e.g., /health) to provide a simple way to monitor the microservice&#39;s status, which is crucial for maintaining service reliability and performance.</p><pre># Create a Blueprint for the health check endpoints<br>health_bp = Blueprint(&#39;health_bp&#39;, __name__)<br><br>@health_bp.route(&#39;/health&#39;, methods=[&#39;GET&#39;])<br>def health_check():<br>    return jsonify({&#39;status&#39;: &#39;UP&#39;}), 200</pre><h4>Tests</h4><p>Implemented basic tests to demonstrate the API end-point testing.</p><pre>class ControllerTestCase(unittest.TestCase):<br>    def setUp(self):<br>        self.client = eq_app.test_client()<br>        self.client.testing = True<br><br>    @parameterized.expand([<br>        (&quot;0005.HK&quot;, 200),<br>        (&quot;XXX.TW&quot;, 404),<br>    ])<br>    def test_get_equity_by_product_code_returns_correct_product_code(self, product_code, expected_status):<br>        response = self.client.get(f&#39;/api/v1/equity?product_code={product_code}&#39;)<br>        self.assertEqual(response.status_code, expected_status)<br>        if response.status_code == 200:<br>            data = response.get_json()<br>            self.assertEqual(data[&#39;product_code&#39;], product_code)<br><br>    @parameterized.expand([<br>        (&quot;HKSE&quot;, 200),<br>        (&quot;XXXX&quot;, 404),<br>    ])<br>    def test_get_equity_by_exchange_returns_correct_exchange_products(self, exchange_code, expected_status):<br>        response = self.client.get(f&#39;/api/v1/equity/exchange?exchange_code={exchange_code}&#39;)<br>        self.assertEqual(response.status_code, expected_status)<br>        if response.status_code == 200:<br>            data = response.get_json()<br>            self.assertGreater(len(data), 0)</pre><p>Code: <a href="https://github.com/jpothanc/equity-store/tree/main">https://github.com/jpothanc/equity-store/tree/main</a></p><p>Details: <a href="https://github.com/jpothanc/equity-store/blob/main/README.md">https://github.com/jpothanc/equity-store/blob/main/README.md</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cda7b8f97848" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating and Uploading Python Libraries]]></title>
            <link>https://medium.com/@kaljessy/building-and-sharing-a-guide-to-creating-and-uploading-python-libraries-56998a001a2c?source=rss-e946fbd4b9f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/56998a001a2c</guid>
            <dc:creator><![CDATA[Jessish Pothancheri]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 02:45:59 GMT</pubDate>
            <atom:updated>2024-09-17T17:23:13.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HWTMYP1coUcKqY5D7OjwFQ.png" /><figcaption>Courtesy: ChatGPT</figcaption></figure><p>In the vast landscape of Python development, encapsulating reusable code into libraries enhances code organisation and fosters collaboration and code-sharing within the community. Crafting a Python library allows developers to package their solutions, making them easily shareable, maintainable, and deployable.</p><p>This article serves as a simple guide to creating a Python library and uploading it to the Python Package Index (PyPI), the central repository for Python packages.</p><p>For demonstration purposes, let’s create a simple Python library called “example_library” with a function to add two numbers.</p><h3>Set up the project structure</h3><pre>example_library/<br>|-- example_library/<br>|   |-- __init__.py<br>|   |-- calculator.py<br>|-- setup.py<br>|-- README.md<br></pre><h3>Write the code</h3><pre>def add_numbers(a, b):<br>    return a + b</pre><h3>Create setup.py</h3><pre>from setuptools import setup, find_packages<br><br>setup(<br>    name=&#39;example_library&#39;,<br>    version=&#39;0.1&#39;,<br>    packages=find_packages(),<br>    install_requires=[<br>        # Add any dependencies here<br>    ],<br>    entry_points={<br>        &#39;console_scripts&#39;: [<br>            # Add any command-line scripts here<br>        ],<br>    },<br>)</pre><h3>Create README.md</h3><pre>##Test python library</pre><h3>__init__.py</h3><p>In Python, the __init__.py file serves a special purpose. It is used to indicate that a directory should be treated as a Python package, and it may also contain package-level initialization code. Lets keep it empty for now.</p><h3>Create an account on PyPI</h3><pre>  - Go to https://pypi.org/<br>  - Create an account<br>  - Enable 2 factor authentication. I used Google Authenticator.<br>  - It will give a token which should be used while uploading your package.<br>    username = __token__<br>    password = pypi-XXXXX.... </pre><h3>Install twine</h3><pre>pip install twine</pre><h3>Build the distribution package</h3><p>Go to the Pycharm terminal to run these commands.</p><pre>python setup.py sdist<br>python setup.py bdist_wheel<br><br><br>The commands python setup.py sdist and python setup.py bdist_wheel are used to create distribution packages for a Python package. These commands are typically run in the context of a Python project that follows the setuptools conventions.<br><br>Here&#39;s what each command does:<br><br>python setup.py sdist<br><br>sdist stands for &quot;source distribution.&quot;<br>This command creates a source distribution package that contains the source <br>code of your Python library along with other necessary files (like setup.py).<br>The generated package will have a .tar.gz extension.<br>This distribution format is suitable for platforms where the users need to <br>compile and install the library locally.<br><br>python setup.py bdist_wheel<br><br>bdist_wheel stands for &quot;binary distribution in wheel format.&quot;<br>This command creates a binary distribution package in the wheel format, which <br>is a binary distribution format that can be easily installed.<br>The generated package will have a .whl extension.<br>This distribution format is suitable for platforms where the users want to <br>install the library without compiling.</pre><h3>Upload to PyPI using twine</h3><pre>twine upload dist/*<br><br># You will be asked for username and password<br># Pls provide the token name and token which you have created.<br>Uploading distributions to https://upload.pypi.org/legacy/<br>Enter your username: __token__<br>Enter your password:<br>Uploading example_library-0.1-py3-none-any.whl<br>100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 4.3/4.3 kB • 00:00 • ?<br><br></pre><h3>Verify on PyPI</h3><pre>pip install example_library<br># verify version<br>pip show example_library</pre><h3>Verify on Python code</h3><pre>from example_library.calculator import add_numbers<br><br>result = add_numbers(3, 4)<br>print(result)</pre><h3>Modifying library code</h3><p>Add new function</p><pre>def add_numbers(a, b):<br>    return a + b<br><br># Add a new function<br>def sub_numbers(a, b):<br>    return a - b</pre><p>Update the version in setup.py</p><pre>from setuptools import setup, find_packages<br><br>setup(<br>    name=&#39;example_library&#39;,<br>    # update the version from 0.1 to 0.2<br>    version=&#39;0.2&#39;,<br>  .....</pre><p>Build and Upload</p><pre>python setup.py sdist<br>python setup.py bdist_wheel<br>twine upload dist/*</pre><p>In the client, upgrade the version of your library</p><pre>pip install --upgrade example_library</pre><p>Happy Coding…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56998a001a2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>