<?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 Kumar Chetan Sharma on Medium]]></title>
        <description><![CDATA[Stories by Kumar Chetan Sharma on Medium]]></description>
        <link>https://medium.com/@kumarchetansharma?source=rss-dc63f97fa15f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LIhXa90j_oaaQygaZRRiGA.jpeg</url>
            <title>Stories by Kumar Chetan Sharma on Medium</title>
            <link>https://medium.com/@kumarchetansharma?source=rss-dc63f97fa15f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 15:41:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kumarchetansharma/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[RAGging my personal expenses]]></title>
            <link>https://kumarchetansharma.medium.com/ragging-my-personal-expenses-eff8eb2b6642?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/eff8eb2b6642</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 14:45:52 GMT</pubDate>
            <atom:updated>2026-10-15T14:48:40.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mVMVl3a6W6naWCfhnbNdg.png" /><figcaption>Pie chart of my expenses</figcaption></figure><p>tl;dr - I failed, but learned along the way.</p><p>For the last 5-6 years, I have religiously documented every single paisa I spent. The digital payment revolution in India made this easy. Every Sunday, I would compile all my expenses into a Google Sheet. Since everything was categorised, I could create pie charts and line graphs telling me which month I spent more, where I spent more, and so on.</p><p>And with the last 1-2 years of AI washing everywhere, I developed an itch that needed to be scratched: building some “AI” on this vast amount of data I had accumulated.</p><p>Long story short, I tried to build a RAG using structured data. And that was my mistake.</p><p>It was an evening project and I didn’t want to spend money, so everything ran on my laptop.</p><p><strong>Stack:</strong> Ollama, mxbai-embed-large for embeddings (1,024 dimensions), llama3.2 (3B) for answers, pandas. No cloud, no API keys.</p><p>Before moving ahead, what exactly is RAG?</p><p>Assume I upload my expense Google Sheet to ChatGPT and ask it for my most expensive purchase. It should be able to answer. Works well. Then I spend money on an expensive phone and ask ChatGPT the same question again. It doesn’t know about my new purchase until I upload the updated sheet. What if there were a mechanism where I could update the sheet any time and ask the same question without any uploads? That system would be RAG: Retrieval-Augmented Generation.</p><ol><li>The data, or knowledge base, is constantly updated.</li><li>A system “Retrieves” the information needed for context from this data store or knowledge base.</li><li>It then “Augments” the prompt with this information.</li><li>The LLM receives the “Augmented” prompt and “Generates” the response.</li></ol><p>To achieve all this, one must understand how RAG actually works.</p><p>To begin with, for any LLM to reply to your prompts, it needs knowledge about the subject. In the case of ChatGPT, OpenAI provides that knowledge to its models. Anthropic does the same for the models you see in Claude, and Google for theirs. For a model to answer anything about my expenses, it needs to know about the relevant expenses.</p><p>For my Google Sheet data to be “compatible” with a RAG system, I had to “process” it.</p><p>LLMs read text as tokens, but the retrieval part of a RAG doesn’t search by words. It searches by meaning, and for that it talks to a vector database. Vector what???</p><p>A vector, also called an embedding, is a long list of numbers that represents what a piece of text <em>means</em>. An embedding model turns “2025-12-03, Dinner at Pirates of Grills, ₹2,250, paid by credit card” into 1,024 numbers. Texts with similar meanings get similar numbers. Words like “UPI”, “Paytm” and “GPay” sit close to each other in this mathematical space. So finding relevant expenses becomes simple geometry: find the vectors closest to the question’s vector. That’s the “Retrieve” in RAG.</p><h3>Step 1: Turn rows into sentences</h3><p>Embedding models understand sentences, not spreadsheet rows. So every row of my sheet became a little sentence:</p><pre>def create_document(row):<br>    return (f&quot;Expense on {row[&#39;Date&#39;]}. Category: {row[&#39;Type&#39;]}. &quot;<br>            f&quot;Merchant/detail: {row[&#39;Detail&#39;]}. Payment method: {row[&#39;Payment Mechanism&#39;]}. &quot;<br>            f&quot;Amount: ₹{row[&#39;Amount&#39;]}.&quot;)</pre><p>For a category like “Grocery”, I never entered details. But for “Doctor Visit”, I would mention the name of the person the visit was for. So I had to do a bit of clean-up wherever details were missing.</p><h3>Step 2: Create the embeddings</h3><pre>texts = [d[&quot;text&quot;] for d in documents]<br>response = ollama.embed(model=&quot;mxbai-embed-large&quot;, input=texts)<br>for doc, vector in zip(documents, response[&quot;embeddings&quot;]):<br>    doc[&quot;embedding&quot;] = vector</pre><p>Done in seconds!</p><h3>Step 3: Retrieve and generate</h3><p>Retrieval is just geometry. Normalise the vectors once, take a dot product with the question’s vector (that’s cosine similarity), and keep the top 5. Those 5 sentences go into a prompt for llama3.2, with a strict instruction: answer only from these.</p><h3>Where it fell flat</h3><p>Lookups worked. “What did I spend at Pirates of Grills?” Perfect. But two kinds of questions failed every single time.</p><ul><li><strong>Totals.</strong> “How much did I spend on ice cream in total?” Retrieval hands the model 5 rows, not hundreds. And small models can’t add reliably anyway.</li><li><strong>Order.</strong> “When was my last breakfast?” It found breakfasts from 2021 to 2023. The real answer was 31 Mar 2026. Embeddings capture <em>meaning</em>, not order, so every breakfast looks equally relevant.</li></ul><p>That’s when it hit me: I was asking a search engine to be a calculator.</p><h3>🤦‍♂️</h3><h3>When RAG isn’t the answer</h3><p>tl;dr — Let the model read the question. Let code do the maths.</p><p>After that, the lesson was clear: my questions were about totals and order, and RAG is bad at both. So I flipped it around. The LLM only understands the question; pandas does the calculation. Accuracy went from 62% to 86%, and I didn’t even change the model. Most of the gain came from small, boring checks in code.</p><h3>Step 1: The LLM writes filters, pandas computes</h3><p>Ollama has a neat trick: give format a JSON schema, and the model&#39;s reply is forced to match it.</p><pre>SCHEMA = {&quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: {<br>    &quot;operation&quot;: {&quot;enum&quot;: [&quot;none&quot;, &quot;sum&quot;, &quot;count&quot;, &quot;max&quot;, &quot;latest&quot;]},<br>    &quot;category&quot;: {&quot;enum&quot;: [&quot;any&quot;] + CATEGORIES},   # read from the CSV<br>    &quot;start_date&quot;: {&quot;type&quot;: &quot;string&quot;}, &quot;end_date&quot;: {&quot;type&quot;: &quot;string&quot;}}}<br>filters = json.loads(ollama.chat(model=&quot;llama3.2&quot;, messages=msgs, format=SCHEMA)[&quot;message&quot;][&quot;content&quot;])</pre><p>The enums stop the model from inventing categories. pandas then filters and sums, exactly.</p><h3>Step 2: Expect mistakes, and catch them in code</h3><p>A 3B model is like an enthusiastic intern. llama3.2 kept making the same kinds of mistake. The pattern I followed was simple, <strong>the LLM interprets, code verifies anything that is knowable.</strong></p><h3>Step 3: Tool calling, and never let the model compare numbers</h3><p>With tool calling, the model picks functions (aggregate_expenses, compare_spending, spending_by_period, search_expenses) and can call several of them per question. My first comparison? The model announced that dinner beat breakfast: ₹4,356 against ₹5,899.79.</p><p>🤦‍♂️ 🤦‍♂️ Maths is hard, apparently.</p><p>So code ranks the results and returns a highest field, plus a result_meaning label, so a max is never reported as a &quot;total&quot;. Every tool also checks its arguments and returns an error the model can act on: &quot;Unknown category &#39;UPI&#39;. Valid: [...]&quot;.</p><p>One more surprise: after an error, llama3.2 sometimes just gave up and made up an answer (&quot;You didn&#39;t have any ice creams&quot;). Now code sends it back to retry, at most twice.</p><h3>Step 4: Stop eyeballing, start measuring</h3><p>I wrote 21 test questions. The expected answers are computed by plain pandas at runtime, never typed in by hand. Each question gets two scores:</p><ul><li><strong>Tool correct:</strong> the right value appears in the tool results. If not, the routing or filters were wrong.</li><li><strong>Answer correct:</strong> the right value appears in the final answer. If not, the model misreported a correct result.</li></ul><p>Two scores tell me <em>where</em> to fix. The baseline was 62%. After the checks, 86% on tool correctness.</p><h3>Step 5: Bigger model, or better code?</h3><p>Thanks to Mukesh Ambani, Airtel had to up its game, and I can now download a large model in seconds. I pulled gemma4:latest, just 6.6 GB. I knew my meagre Apple M5 with 16 GB RAM would struggle, but hey, this is a fun project. I had also built a small memory for follow-up questions. So I swapped the model and fired off my evaluation script.</p><p>On single questions, the code checks closed the gap completely. Model size mattered for follow-ups, where questions get rewritten into standalone ones: “and in 2024?” becomes “How much did I spend on snacks in 2024?”. That memory lives in the running process, so if the app crashes, it’s gone. Fine for a hello-world RAG.</p><p>Till now, I had dumped everything into a JSON file. So I moved the vectors from this JSON file into Chroma, a local vector database. Each ID is a hash of the row’s content, so editing the CSV re-embeds only the rows that changed.</p><h3>The real lesson</h3><p>The questions kept needing new tools. List these dates. Group by payment method. Who visited the doctor most? That’s the giveaway of a structured dataset. The only truly RAG-shaped part was the free-text detail column: ice cream spelled three different ways, names buried in notes. <strong>Knowing when not to use RAG is the first RAG skill.</strong></p><h3>RAGging 9,840 RFCs</h3><p>tl;dr — Most failures weren’t where I first looked. And the one fix I was sure about made things worse.</p><p>After my expenses, I wanted data RAG was actually built for: lots of unstructured text. So I downloaded every IETF RFC, the documents that define how the internet works. Plain text, long, technical. Perfect.</p><p><strong>Corpus:</strong> 9,840 text files, 538 MB, 526,133 chunks. Embedding took around 8 hours on an Apple M5 with 16 GB RAM. Yes, 8 hours.</p><h3>Step 1: Chunk it, because the embedding model only reads so much</h3><p>mxbai-embed-large reads at most 512 tokens at a time. And here&#39;s the sneaky part: Ollama silently cuts off anything longer by default. Embed a whole RFC, and only its first page or so counts. So I split every RFC into chunks:</p><ol><li><strong>Clean</strong> the page furniture: form feeds, [Page N] footers, repeated page headers.</li><li><strong>Skip</strong> the table of contents. Its lines look exactly like section headings.</li><li><strong>Split</strong> by section, then pack paragraphs into chunks of about 350 tokens, with one paragraph of overlap.</li><li><strong>Prefix</strong> every chunk with RFC 5533 — Shim6 Protocol — Section 4.2. Without it, a chunk saying &quot;the timer MUST be reset&quot; has no clue which protocol it belongs to.</li></ol><p>Real data found two bugs. Titles with a colon (“Shim6: Level 3…”) were rejected. And numbered lists at the start of a line looked like section headings, which created duplicate chunk IDs and crashed the indexing. Numbering chunks sequentially within each RFC fixed that for good.</p><h3>Step 2: Index so that a crash costs minutes, not hours</h3><p>When a job runs for 8 hours, it <em>will</em> get interrupted. So: record every finished RFC in a progress file, write with upsert, and start with --limit 50. I ran a test. And the strategy worked. The first small run wasn&#39;t a throwaway test; it was part of the real index, and it measured chunks per second for the ETA. Also I embeded with truncate=False, so an oversized chunk fails loudly instead of being cut silently.</p><p>Could better hardware help? Embedding is GPU work. More RAM or a faster CPU wouldn’t have changed much; more GPU cores would. But try the free options first: skip the boilerplate sections thousands of RFCs share, or index fewer documents.</p><h3>Step 3: How a question gets answered</h3><ol><li><strong>Embed</strong> the question with the <em>same</em> model used for indexing, plus its query prefix.</li><li><strong>Retrieve</strong> the 24 closest chunks from Chroma, optionally filtered by RFC number.</li><li><strong>Select</strong> the best 6, at most 3 from any single RFC.</li><li><strong>Augment:</strong> number them [1] to [6] in the prompt.</li><li><strong>Generate:</strong> the model answers only from those sources and cites [n].</li><li><strong>Verify</strong> in code that every cited number actually exists.</li></ol><p>Gotchas I learned the hard way: set num_ctx explicitly, because Ollama also silently truncates long prompts. If nothing relevant was found, don&#39;t call the LLM at all, or it will happily answer from memory. Hallucinations galore! And a valid citation only proves the source exists, not that it supports the claim.</p><h3>Step 4: Is it retrieval, or is it the model?</h3><p>I asked: “Are there any RFCs related to birds?” (Yes, there are. RFC 1149 describes IP over Avian Carriers. Pigeons carrying packets. And later RFCs even extended this work!) The answer came back: “I could not find this.”</p><p>So I wrote a small diagnostic script. Is RFC 1149 in the index? Where does it rank? What outranks it? It ranked <strong>2nd out of 526,133</strong>. Retrieval was fine! llama3.2 had the right source in front of it and still refused. gemma4 answered correctly.</p><p>The same output taught me three more things:</p><ul><li><strong>Scores cluster.</strong> The right RFC scored 0.762, and so did an unrelated glossary. A similarity threshold can’t separate them; only the ranking means anything.</li><li><strong>Words in the question pull in the wrong documents.</strong> “RFC” matched RFCs <em>about</em> RFCs: “Fifty Years of RFCs”, author instructions, glossaries.</li><li><strong>Some questions aren’t retrieval at all.</strong> “Which was the first RFC about email?” needs sorting by date across all candidates. Same lesson as “last breakfast” earlier.</li></ul><p>I cleaned up my queries a bit and started stripping “What is the” and “RFC” before searching.</p><h3>Step 5: The eval that proved me wrong</h3><p>I wrote 30 test questions, each with the RFCs that count as correct (old and new versions). The query cleaning I was so proud of? It <em>hurt</em>. “Birds” on its own landed closest to a coding scheme called Raptor. (A raptor is a bird. Technically, not wrong.) The full question had kept the search on track. I switched the cleaning off. What had really fixed the bird question was a softer prompt.</p><p>The bigger finding is the ceiling: no model can cite an RFC it never received. gemma4 got 2 more answers right at 5 times the time, while retrieval lost 37% of the questions before any model even saw them. Most of those misses were old, foundational RFCs: UDP, ICMP, DNS, MUST/SHOULD.</p><p>I am still trying to improve this further. Meanwhile, here are the dos and don’ts I learned along the way. They apply to building any RAG, not just this one.</p><ul><li><strong>Do</strong> check that RAG fits your data. Free text: yes. Totals, counts or “latest” over a table: use SQL or pandas and let the LLM only read the question and use tools that convert Text to SQL</li><li><strong>Do</strong> evaluate first. Sort of TDD. Write 10-30 questions with known answers before tuning anything, and keep a change only if the numbers improve.</li><li><strong>Do</strong> score retrieval and generation separately. “Was the right document retrieved?” and “Did the answer use it?” have different fixes.</li><li><strong>Do</strong> find out <em>why</em> a piece of information (a document) wasn’t retrieved before changing anything. Is it indexed? Where does it rank? What outranks it?</li><li><strong>Do</strong> look at your data, not just your code. Read the chunks of documents you know, and check that your vectors aren’t all identical.</li><li><strong>Do</strong> chunk to fit the embedding model, and prefix every chunk with its source (title, section). A chunk without context is a sentence without a home.</li><li>This may sound common sense. <strong>Do</strong> use the same embedding model, and its query prefix, for indexing and for questions.</li><li>While developing, <strong>Do</strong> make silent limits loud.</li><li><strong>Do</strong> let code do the maths and the checks: ranking, comparing, validating arguments and citations. The LLM does language.</li><li>While developing, <strong>Do</strong> always show the retrieved sources, even when the model refuses. The evidence stays visible.</li><li><strong>Don’t</strong> call the LLM when nothing relevant was retrieved. It will answer from memory. Hallucinations galore! And costly as well.</li><li><strong>Don’t</strong> trust a fix tested on one question. Mine helped the bird question and hurt the rest.</li><li><strong>Don’t</strong> strip questions down to keywords for vector search. Embedding models are trained on natural questions.</li><li><strong>Don’t</strong> use similarity thresholds without looking at real score distributions. Relevant and irrelevant chunks can score the same. Raptors, pigeons, avians and birds are same but different.</li><li><strong>Don’t</strong> upgrade the model before checking what retrieval hands it. Retrieval sets the ceiling.</li><li><strong>Don’t</strong> treat a valid citation as proof. It shows the source exists, not that it supports the answer.</li><li><strong>Don’t</strong> assume your ground truth is right. Check the reference answers too, not just the model.</li></ul><h3>So, did I fail?</h3><p>Kind of. I set out to build a RAG on my expenses, and the honest answer is that my expenses never needed one. They needed SQL with a friendly face. RAG only made sense for the free-text bits: ice creams spelled three ways, names in doctor visits. The RFCs were where RAG finally felt at home, and even there, most of my problems were not where I first looked.</p><p>What I really took away is a habit: measure, find out why, change one thing, measure again. Iterations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eff8eb2b6642" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Errors and Exceptions]]></title>
            <link>https://kumarchetansharma.medium.com/errors-and-exceptions-5c967d5105d1?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c967d5105d1</guid>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 18:37:16 GMT</pubDate>
            <atom:updated>2025-01-14T18:37:16.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Errors and exceptions are bane of any developer. However, these are two different things. Simply put:</p><blockquote>Error — Damn! Something is wrong, causing problem, can not be recovered, stop doing whatever you are doing…</blockquote><blockquote>Exception — Ah! This could have been avoided, we can probably handle it and move on…</blockquote><p>I have been working with JavaScript, PHP, Java and sometimes with Python. All of these handle errors and exceptions differently. Let’s take a look.</p><h3>Errors</h3><p>JavaScript doesn’t differentiate between errors and exceptions. True to JavaScript’s nature, both errors and exceptions are objects. If you look at <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">MDN</a> it says</p><blockquote>Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.</blockquote><p>Let’s temporarily set aside modern development tools and consider the following code:</p><pre>console.log(&quot;Hello World!&quot;);<br>I am a piece of JavaScript code;</pre><p>Running this will throw the following error in the browser JavaScript console:</p><pre>Uncaught SyntaxError: Unexpected identifier &#39;am&#39;</pre><p>In Node.js, the error would look like this:</p><pre>I am a piece of JavaScript code;<br>  ^^<br><br>Uncaught SyntaxError: Unexpected identifier</pre><p>This is a SyntaxError. Syntax errors will halt the program in any language. In fact, Java will not even compile due to syntax errors. Thankfully, modern IDEs will warn you about syntax errors before you deploy your code. If you’re still working on your code, you can configure your version control system to check for syntax errors. In any case, syntax errors are largely avoidable with modern tooling and proper attention to detail.</p><p>Some fatal conditions are often not caught by your IDE. Examples include:</p><ul><li>Resource exhaustion</li><li>Stack over flow</li><li>Calling methods or functions that aren’t available due to library linkage errors</li><li>Issues with the underlying engine, such as the JVM or V8</li></ul><p>PHP allows you to create custom error handler functions. However, these do not handle fatal errors, such as syntax errors. PHP also enables you to register a shutdown function to handle errors to some extent. This combination provides some control over error handling. <a href="https://github.com/laravel/framework/blob/11.x/src/Illuminate/Foundation/Bootstrap/HandleExceptions.php">You can explore error and exception handling in Laravel for more details</a>.</p><p>In Java, the JVM will throw an error and leave you to resolve it. You’ll need to dig into your toolbox and fix the issue manually.</p><h3>Exceptions</h3><p>Every number can be divided by another number — except for zero. Dividing a number by zero is undefined and represents an exception.</p><p>Consider this scenario: Your program is performing computations, and it may encounter a “divide by zero” situation. This is a typical example of an exception. You can handle such exceptions using try, catch, and finally blocks. Here’s an example in Java:</p><pre>try {<br>    int result = 10 / 0;<br>} catch (ArithmeticException e) {<br>    System.out.println(&quot;Caught an exception: &quot; + e.getMessage());<br>} finally {<br>    return 42;//The Answer to the Ultimate Question of Life, The Universe, and Everything<br>}</pre><p>JavaScript, PHP, and Java all allow you to create custom exception classes or objects. These custom exceptions usually extend the main error or exception class of the respective language to offer specialized error-handling functionality. It’s advisable to use these custom exception mechanisms rather than relying on the default Exception (or Error in JavaScript) class. Custom exceptions provide more control and clarity when managing errors.</p><h3>Handling errors and exceptions</h3><p>All programs should log errors and exceptions using appropriate logging libraries. In my Node.js projects, <a href="https://medium.com/@kumarchetansharma/how-to-add-module-or-file-names-for-log-lines-in-winston-8338d1cf53ad">I utilize such libraries for effective error tracking</a>. Spring Boot and Laravel also offer strong logging mechanisms. Logging must be a core component of every project, with logs forwarded to a log analysis platform for monitoring and alerting. I have implemented variations of the ELK stack (Elasticsearch, Logstash, Kibana) to build alerting systems. For instance, exceptions during a user’s checkout process require immediate action, while issues like a user being unable to view a five-year-old order can be prioritized lower. At a leadership level, tracking the number of errors and the speed of resolution has been valuable in identifying top-performing developers. In case you are not logging, I highly recommend reading <a href="https://12factor.net/logs">this article</a> from 12 factor app.</p><p>In conclusion, effective error and exception handling is crucial for building robust and reliable applications. By understanding the differences between errors and exceptions and using the appropriate tools and techniques in your programming language, you can manage issues more efficiently. Whether you’re using custom exceptions in JavaScript, PHP, or Java, or leveraging modern development tools, good error handling practices not only prevent crashes but also enhance the maintainability and scalability of your projects. Always prioritize error logging, detection, and resolution to ensure a smoother user experience and a more resilient codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c967d5105d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to be 10x productive at work?]]></title>
            <link>https://kumarchetansharma.medium.com/how-to-be-10x-productive-at-work-ce109085f8b9?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce109085f8b9</guid>
            <category><![CDATA[time-management]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[efficient-working]]></category>
            <category><![CDATA[10x-engineer]]></category>
            <category><![CDATA[productive-tips]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Sat, 11 May 2024 07:12:56 GMT</pubDate>
            <atom:updated>2024-05-29T01:56:24.241Z</atom:updated>
            <content:encoded><![CDATA[<p>Since this article is on being productive, this is gonna be supershort. You may need sudo or admin privileges to accomplish the procedure. Here are the steps</p><ul><li>Locate hosts file on your computer. For Windows, it is usually in C:\Windows\System32\drivers\etc folder. On Mac or Linux, the location is /etc/ folder</li><li>Open this file in some sort of text editor, such as notepad or gedit or textedit, as mentioned earlier, you may need sudo or admin privileges</li><li>Add following lines in the end of this file</li></ul><pre>127.0.0.1 www.reddit.com old.reddit.com<br>127.0.0.1 www.youtube.com youtube.com<br>127.0.0.1 www.instagram.com instagram.com<br>127.0.0.1 www.facebook.com fb.com<br>127.0.0.1 www.twitter.com twitter.com x.com<br>127.0.0.1 url.for.your.fav.news.site.com</pre><ul><li>Save the file</li><li>You are welcome!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce109085f8b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop treating URLs as strings!]]></title>
            <link>https://kumarchetansharma.medium.com/stop-treating-urls-as-strings-fa2c42f0577a?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa2c42f0577a</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[application-development]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Wed, 01 May 2024 08:30:34 GMT</pubDate>
            <atom:updated>2024-05-01T08:30:34.215Z</atom:updated>
            <content:encoded><![CDATA[<p>tl;dr — Regardless of programming language, treat URLs as first class citizens or objects</p><p>Now the longer version.</p><p>If you look at a URL, it is a string. Hence, the common sense tells you to just find the question mark and divide the string to find query parameters from URL.</p><pre>const URL = &quot;https://www.google.com/search?q=Is this correct?&amp;let=me ask you again&amp;are=you sure?&quot;;<br>const queryParametersString = URL.split(&quot;?&quot;);<br>const queryParameters = queryParametersString[1];<br>console.log(queryParameters); // &#39;q=Is this correct&#39;</pre><p>Or in Java</p><pre>String URL = &quot;https://www.google.com/search?q=Is this correct?&amp;let=me ask you again&amp;are=you sure?&quot;;<br>// Splitting the URL string to separate the query parameters<br>String[] queryParametersString = URL.split(&quot;\\?&quot;);        <br>// Extracting the query parameters<br>String queryParameters = queryParametersString.length &gt; 1 ? queryParametersString[1] : &quot;&quot;;<br>// Printing the query parameters<br>System.out.println(queryParameters);</pre><p>You might have seen variation of this in your favorite or hated programming language. This is just the tip of code icebergs I have seen.</p><p>What most of the developers miss out is that URLs can represent state. And they are not always made up of ASCII characters. URLs can have UTF-8 or UTF-16 characters. Or are not always pointing to http protocol</p><pre>const ohShit = &quot;https://www.google.com/search?q=💩&quot;;<br>const habibi = &quot;https://www.google.com/search?q=!حبيبي&quot;<br>const exampleFTPURL = &quot;ftp://example.com/path/to/some/file.txt&quot;;<br>const emailMe = &quot;mailto:user@example.com?subject=MessageTitle&amp;body=Message Content&quot;;</pre><p>Manipulating these URLs as string introduce bugs one can avoid. All of the programming languages provide ways to manage URLs using either build in function and APIs or through sphisticated libraries.</p><pre>import okhttp3.HttpUrl; //Import okHttp or Apache http client libs<br><br>// boiler plate ... <br><br>String URL = &quot;https://www.google.com/search?q=Is this correct?&amp;let=me ask you again&amp;are=you sure?&quot;;<br>// Parsing the URL with OkHttp<br>HttpUrl httpUrl = HttpUrl.parse(URL);<br>        <br>if (httpUrl != null) {<br>    // Extracting the query parameters<br>    String queryParameters = httpUrl.query();<br>    // Printing the query parameters<br>    System.out.println(queryParameters);<br>} else {<br>    System.out.println(&quot;Invalid URL format&quot;);<br>}</pre><p>Or</p><pre>const exampleURL = new URL(&quot;https://www.google.com/search?q=Is this correct?&amp;let=me ask you again&amp;are=you sure?&quot;);<br>console.log(exampleURL.search); //&#39;?q=Is%20this%20correct?&amp;let=me%20ask%20you%20again&amp;are=you%20sure?&#39;<br>exampleURL.searchParams.keys().forEach(k =&gt; console.log(`${k}=${exampleURL.searchParams.get(k)}`));</pre><p>In all the patterns I have seen, most are around constructing URLs.</p><pre>    const res = await fetch(`/api/common?baseUrl=${baseUrl}&amp;${encodeURI(`data=${data}`)}`)</pre><p>The above example is from a production branch of an application. In case of JavaScript one can use URL interface. Here is an example</p><pre>const baseURL = &#39;https://jsonplaceholder.typicode.com/&#39;;<br>const apiURL = new URL(`comments`, baseURL);<br>apiURL.searchParams.set(&#39;postId&#39;, &#39;1&#39;);<br>const response = await axios.get(apiURL.toString());</pre><p>Or in Java you can use okhttp or Apache http client</p><pre>import org.apache.http.client.utils.URIBuilder;<br>import java.net.URI;<br>import java.net.URISyntaxException;<br><br>//boilerplate<br><br>try {<br>    URIBuilder uriBuilder = new URIBuilder(&#39;https://jsonplaceholder.typicode.com/comments&#39;)<br>            .addParameter(&#39;postId&#39;, &#39;1&#39;);<br>    URI uri = uriBuilder.build();<br>    String constructedUrl = uri.toString();<br>    System.out.println(&quot;Constructed URL: &quot; + constructedUrl);<br>} catch (URISyntaxException e) {<br>    System.err.println(&quot;Error constructing URL: &quot; + e.getMessage());<br>}</pre><p>These libraries take care of constructing the URL, encoding query params and everything else you need with URLs. Do you have to write few extra line of code? Yes! And it is worth. No one wants to fix bugs on Friday evening.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2c42f0577a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to add module or file names for log lines in winston?]]></title>
            <link>https://kumarchetansharma.medium.com/how-to-add-module-or-file-names-for-log-lines-in-winston-8338d1cf53ad?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8338d1cf53ad</guid>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[winston]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Tue, 23 Apr 2024 18:32:04 GMT</pubDate>
            <atom:updated>2024-04-23T18:32:04.536Z</atom:updated>
            <content:encoded><![CDATA[<p>Every application I have shipped in past 15 years had logging enabled in one way or another. The <a href="https://12factor.net/logs">12 Factor App</a> also mentions importance of logging. In node.js applications I have been using <a href="https://github.com/winstonjs/winston">Winston</a> as a logging package. Unlike Java or PHP logging package managers, getting module name or file name in logs was not straightforward. Here is how I do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e224f81e11d7e2b2c47feb83dc804a0/href">https://medium.com/media/7e224f81e11d7e2b2c47feb83dc804a0/href</a></iframe><p>For obvious reasons, do not just copy paste. I am using a JSON format, you may not need it. Add 🧂 per your taste and enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8338d1cf53ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to automate volume snapshots on Digital Ocean & save money]]></title>
            <link>https://kumarchetansharma.medium.com/automate-volume-snapshots-on-digital-ocean-save-money-fffdf6445e88?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fffdf6445e88</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[save-money-tips]]></category>
            <category><![CDATA[automated-backup]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[digitalocean]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 18:32:08 GMT</pubDate>
            <atom:updated>2025-01-19T04:23:56.011Z</atom:updated>
            <content:encoded><![CDATA[<p>This isn’t going to be a super long story — just a quick and useful guide for automating volume snapshots on DigitalOcean.</p><h3>The Problem</h3><p>Unlike some other cloud providers, <strong>DigitalOcean doesn’t offer a built-in feature for automatically scheduling snapshots of your volumes</strong>. For those unfamiliar with the terminology or for AWS enthusiasts:</p><ul><li>Volumes are network-based block storage devices that provide extra space for your Droplets. Think of them as detachable hard drives for your virtual machines. You can resize or move them between Droplets as needed.</li><li>Droplets are DigitalOcean’s virtual machines, analogous to EC2 instances on AWS. Volumes are typically used when your primary storage doesn’t suffice, for example, when storing profile images, videos, or other large files.</li></ul><h3>Why No Automated Snapshots?</h3><p>I’m guessing that DigitalOcean leaves snapshot scheduling out of its core feature set because the need varies greatly. You might need snapshots hourly, daily, or not at all. It’s your call.</p><p>While manual snapshots are always an option, relying on human intervention is far from ideal. There are third-party services that can automate the process, but they come with trade-offs:</p><ul><li>Starting at $19/month</li><li>Limited to daily snapshots for up to three resources</li><li>And a few other nice-to-have features</li></ul><p>But why pay for something when you can automate it yourself for free?</p><h3>The DIY Solution</h3><p>DigitalOcean provides a robust set of RESTful APIs for managing block storage, which allows you to:</p><ul><li>List all your volumes</li><li>List snapshots for each volume</li><li>Create snapshots on demand</li><li>Delete old snapshots to control storage costs</li></ul><p>By leveraging these APIs, I built a simple Node.js cron job that:</p><ul><li>Creates a snapshot of a volume every hour</li><li>Deletes excess snapshots to prevent unnecessary costs (because every snapshot adds up)</li></ul><h3>Example Code</h3><p>The full source code for this solution is available here: <a href="https://github.com/kumarldh/do-volume-backup-job">https://github.com/kumarldh/do-volume-backup-job</a></p><p>It’s straightforward to set up and comes with minimal dependencies. The job does exactly what you need:</p><ul><li>Hourly snapshot creation</li><li>Snapshot cleanup to manage expenses</li></ul><h3>Licensing</h3><p>The code is free to use with just a couple of conditions:</p><ul><li>Feel free to modify and use it however you want</li><li>Just credit me and please, don’t sue me</li></ul><h3>Final Thoughts</h3><p>Automating DigitalOcean snapshots can save time, reduce risks, and avoid unnecessary expenses. Give it a try — and if it works well for you, I’d love to hear your feedback or suggestions for improvement!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fffdf6445e88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Set up A/B testing using Nginx]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">A/B testing, also known as split testing, is a powerful method used by businesses to compare two versions of a webpage or app to determine&#x2026;</p><p class="medium-feed-link"><a href="https://kumarchetansharma.medium.com/set-up-a-b-testing-using-nginx-4b6b4d61461a?source=rss-dc63f97fa15f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kumarchetansharma.medium.com/set-up-a-b-testing-using-nginx-4b6b4d61461a?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b6b4d61461a</guid>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 06:02:10 GMT</pubDate>
            <atom:updated>2024-04-08T06:02:10.999Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Set up A/B testing using Cloudflare workers]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Learn how to quickly &amp; easily set up a/b testing using Cloudflare workers</p><p class="medium-feed-link"><a href="https://kumarchetansharma.medium.com/set-up-a-b-testing-using-cloudflare-workers-909a644039e7?source=rss-dc63f97fa15f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://kumarchetansharma.medium.com/set-up-a-b-testing-using-cloudflare-workers-909a644039e7?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/909a644039e7</guid>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[a-b-testing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[cloudflare-workers]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 07:56:13 GMT</pubDate>
            <atom:updated>2024-03-22T08:07:00.637Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Event Delegation: Save thou webpage]]></title>
            <link>https://kumarchetansharma.medium.com/event-delegation-save-thou-webpage-0abaf221d1b3?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0abaf221d1b3</guid>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[browsers]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 00:31:37 GMT</pubDate>
            <atom:updated>2023-12-24T00:31:37.849Z</atom:updated>
            <content:encoded><![CDATA[<p>To make a web page interactive web developers rely on Events on the page. Event handling could be as easy as reloading the page on click of a button or as complex as following mouse pointer and responding to it. The usual way to do this is onEvent do some thing.</p><pre>&lt;button name=&quot;aButton&quot; id=&quot;aButton&quot; onclick=&quot;alert(&#39;Hello World!&#39;)&quot;&gt;CLICK ME!!!&lt;/button&gt;</pre><p>Easy.</p><p>There are so many ways to handle events and then do something. Inline, shown above, unobtrusive, shown below.</p><pre>&lt;button name=&quot;anotherButton&quot; id=&quot;anotherButton&quot;&gt;CLICK ME!!!&lt;/button&gt;<br>&lt;script&gt;<br>document.getElementById(&#39;anotherButton&#39;).addEventListener(&#39;click&#39;, function(){alert(&#39;Hello World!&#39;)}, false);<br>&lt;/script&gt;</pre><p>One can add as many as event listeners required for an event occurring for an element. Well, not really a wise idea. Think of Gmail inbox set to display 100 emails in a row. Does that mean 100 addEventListener? Not a good idea. Here comes a very simple technique called <strong>Event Delegation</strong>. Example:</p><pre>&lt;ol id=&quot;olElem&quot;&gt;<br> &lt;li id=&quot;li1&quot;&gt;One&lt;/li&gt;<br> &lt;li id=&quot;li2&quot;&gt;Two&lt;/li&gt;<br> &lt;li id=&quot;li3&quot;&gt;Three&lt;/li&gt;<br> &lt;li id=&quot;li4&quot;&gt;Four&lt;/li&gt;<br> &lt;li id=&quot;li5&quot;&gt;Five&lt;/li&gt;<br> &lt;li id=&quot;li6&quot;&gt;Six&lt;/li&gt;<br> &lt;li id=&quot;li7&quot;&gt;Seven&lt;/li&gt;<br> &lt;li id=&quot;li8&quot;&gt;Eight&lt;/li&gt;<br> &lt;li id=&quot;li9&quot;&gt;Nine&lt;/li&gt;<br> &lt;li id=&quot;lin&quot;&gt;n&lt;/li&gt;<br>&lt;/ol&gt;<br>&lt;script&gt;<br>document.getElementById(&#39;olElem&#39;).onclick = (e) =&gt; {<br> e = e || window.event;<br> const target = e.target || e.srcElement;<br> const textClicked = document.getElementById(target.id).innerHTML;<br> alert(&#39;You clicked &#39; + textClicked);<br>}<br>&lt;/script&gt;</pre><p>This is all due to Event Bubbling which simply means that an event bubbles up to document root. So, when I click on “Nine”, the element li9 tells its parent that it got clicked, which in turn informs its parent and so on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0abaf221d1b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to remove blank lines from text files or js files]]></title>
            <link>https://kumarchetansharma.medium.com/how-to-remove-blank-lines-from-text-files-or-js-files-307b15388ad3?source=rss-dc63f97fa15f------2</link>
            <guid isPermaLink="false">https://medium.com/p/307b15388ad3</guid>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Kumar Chetan Sharma]]></dc:creator>
            <pubDate>Mon, 11 Dec 2023 00:32:14 GMT</pubDate>
            <atom:updated>2023-12-11T00:32:14.754Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>By running this command…</strong></h3><pre>egrep --include=*.js -lRZ &quot;^$&quot;  ./ | xargs -0 -l   sed -i -e &#39;/^$/d&#39;</pre><p>Just two parts to it, search for all *.js files and use sed to replace new lines with nothing.</p><p>That’s all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=307b15388ad3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>