<?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 Sachin Vedaraj on Medium]]></title>
        <description><![CDATA[Stories by Sachin Vedaraj on Medium]]></description>
        <link>https://medium.com/@sachincv?source=rss-8aca79282bf5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ly_cTUY67hag2qbdiEAwGg@2x.jpeg</url>
            <title>Stories by Sachin Vedaraj on Medium</title>
            <link>https://medium.com/@sachincv?source=rss-8aca79282bf5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:13:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sachincv/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[Dynamic Goroutine Scaling: Optimising SQS Message Consumption]]></title>
            <link>https://medium.com/codex/dynamic-goroutine-scaling-optimising-sqs-message-consumption-f39fc6e7285f?source=rss-8aca79282bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f39fc6e7285f</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sachin Vedaraj]]></dc:creator>
            <pubDate>Thu, 16 May 2024 16:18:26 GMT</pubDate>
            <atom:updated>2024-05-20T04:40:05.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v15A8Ifnmp2lZJ88hWqALg.png" /></figure><p><strong>Premise</strong>: We receive webhooks of SMS and email from our provider through Simple Queuing Service. The status of each message is received over the SQS which is consumed by our service written in Golang. We use basic aws SDK for SQS to receive messages and no other library to handle our polling logic.</p><p>The crux of the problem we faced was two-fold</p><ol><li>The inherent limitations imposed by SQS, such as the maximum batch size of 10 messages per retrieval, constrained our ability to scale up message processing dynamically.</li><li>The metrics used by Kubernetes (K8s) for autoscaling, primarily CPU and memory utilization, did not accurately reflect the processing load and latency within the SQS message queue.</li><li>As a result, even though the CPU and memory resources were scarcely used, leading to no autoscaling triggers by K8s, a <em>significant backlog of messages</em> accumulated in the queue. This scenario created a bottleneck, of timely processing of messages and undermined the overall efficiency and responsiveness of our services.</li></ol><p>Therefore we wanted to devise a solution that could dynamically adapt to the workload by efficiently managing concurrency and resource utilisation.</p><p><strong>Our Solution:</strong></p><ol><li>Dynamic Go Routine Scaling</li><li>Resource Aware Scaling</li></ol><pre>type SMSWebhookConsumerService interface {<br>	Start()<br>	Stop()<br>}<br><br>// Start begins the polling process.<br>func (qc *SMSWebhookConsumer) Start() {<br>	go qc.manageGoroutines()<br>}<br><br>// Stop signals the polling to stop.<br>func (qc *SMSWebhookConsumer) Stop() {<br>	qc.cancel()<br>}<br><br>// Increase/Decrease number of polling routines based on queue size<br>func (qc *SMSWebhookConsumer) manageGoroutines() {<br> var currentRoutines int<br> var cancels []context.CancelFunc = []context.CancelFunc{}<br> for {<br>  select {<br>  case &lt;-qc.ctx.Done():<br>   // Handle graceful shutdown of all goroutines<br>   return<br>  default:<br>   queueLength, err := qc.checkQueueLength() // Implement this function to check the queue length<br>   if err != nil {<br>    logger.Error(qc.ctx, &quot;error checking queue length: &quot;, err)<br>    time.Sleep(30 * time.Second)<br>    continue<br>   }<br>   // Calculate the desired number of routines based on queue length or other heuristics<br>   desiredRoutines := syshealthUtil.CalculateDesiredRoutines(queueLength, syshealthUtil.MIN_ROUTINES, syshealthUtil.MAX_ROUTINES)<br>   // Rebalance the desired number of routines<br>   desiredRoutines = syshealthUtil.RebalanceDesiredRoutines(currentRoutines, desiredRoutines)<br>   // Adjust the number of goroutines based on the desired count<br>   for i := currentRoutines; i &lt; desiredRoutines; i++ {<br>    ctx, cancel := context.WithCancel(qc.ctx)<br>    cancels = append(cancels, cancel)<br>    ctx = context.WithValue(ctx, contextKeys.PollContextKey, len(cancels))<br>    logger.Info(qc.ctx, fmt.Sprintf(&quot;starting goroutine with context id: %d&quot;, len(cancels)))<br>    go qc.poll(ctx)<br>    currentRoutines++<br>   }<br>   for i := currentRoutines; i &gt; desiredRoutines; i-- {<br>    // Signal one goroutine to stop through context<br>    cancels[len(cancels)-1]()<br>    cancels = cancels[:len(cancels)-1] // Remove the last cancel function<br>    logger.Info(qc.ctx, fmt.Sprintf(&quot;stopping goroutine with context id: %d&quot;, len(cancels)))<br>    currentRoutines--<br>   }<br>   time.Sleep(10 * time.Second)<br>  }<br> }<br>}</pre><p>Our Manage Routines simply checks whether it needs to add more routines or gracefully bring down routines every 10 seconds. Contexts are passed to the poll function to cancel them when needed.</p><p>We try to match current routines and desired routines. The functions <em>CalculateDesiredRoutines</em> and <em>RebalanceDesiredRoutines</em> are used to determine the desired routines. We’ll understand these two functions and the algorithm towards the end.</p><p><strong>Polling logic</strong></p><pre>// poll continuously polls the SQS queue for messages.<br>func (qc *SMSWebhookConsumer) poll(ctx context.Context) {<br> errorBackoff := 5 * time.Second<br> contextID := ctx.Value(contextKeys.PollContextKey).(int)<br> logger.Info(ctx, fmt.Sprintf(&quot;polling started for queue with context id: %d&quot;, contextID))<br> for {<br>  select {<br>  case &lt;-qc.ctx.Done():<br>   logger.Info(qc.ctx, &quot;polling stopped.&quot;)<br>   return<br>  case &lt;-ctx.Done():<br>   logger.Info(qc.ctx, fmt.Sprintf(&quot;polling stopped, reduced by goroutines. Context id: %d&quot;, contextID))<br>   return<br>  default:<br>   // receives call the aws sdk function within it<br>   messages, err := qc.receiveMessages()<br>   <br>   // Process the received messages<br>   <br>   // Sleep for a short period to avoid throttling in case of empty receives<br>   tts := 2 * time.Second<br>   if len(messages) == 0 {<br>    tts = 5 * time.Second<br>   }<br>   time.Sleep(tts)<br>  }<br> }<br>}</pre><p>A crucial part is knowing approximately how many messages are available in SQS. The AWS <strong>SDK</strong> provides us function to query that.</p><p>Now onto our desired routines logic</p><p>The <em>CalculateDesiredRoutines</em> function estimates the optimal number of Goroutines based on the current queue length, ensuring that there’s a proportional relationship between workload and processing capacity. This function adheres to predefined minimum and maximum Goroutine thresholds to maintain operational integrity under various conditions.</p><pre>func CalculateDesiredRoutines(queueLength, minRoutines, maxRoutines int) int {<br> desiredRoutines := queueLength / MAX_MSG_PER_ROUTINE<br> if desiredRoutines &lt; minRoutines {<br>  return minRoutines<br> }<br> if desiredRoutines &gt; maxRoutines {<br>  return maxRoutines<br> }<br> return desiredRoutines<br>}</pre><p>The <em>RebalanceDesiredRoutines</em> function takes the desired Goroutine count and adjusts it based on current resource utilisations, reducing the count if necessary to prevent resource saturation. This rebalancing act not only preserves system health but also ensures that scaling decisions are both responsive and prudent.</p><pre>func RebalanceDesiredRoutines(currentRoutines int, desiredRoutines int) int {<br> if desiredRoutines &lt;= currentRoutines {<br>  return desiredRoutines<br> }<br> <br>    // gopsutil library is used to get cpu and memory utilisation<br>    <br> cpu, err := CheckCPUUtilization()<br> if err != nil {<br>  logger.Error(context.Background(), &quot;error checking CPU utilization: &quot;, err)<br>  return currentRoutines<br> }<br><br> mem, err := CheckMemoryUtilization()<br> if err != nil {<br>  logger.Error(context.Background(), &quot;error checking memory utilization: &quot;, err)<br>  return currentRoutines<br> }<br><br> if cpu &gt; MAX_CPU_PC || mem &gt; MAX_MEM_PC {<br>  return max(currentRoutines-1, MIN_ROUTINES)<br> }<br><br> multiple := desiredRoutines/currentRoutines + 1<br><br> if (cpu*float64(multiple) &lt; 95) &amp;&amp; (mem*float64(multiple) &lt; 95) {<br>  return desiredRoutines<br> }<br><br> for ((cpu*float64(multiple) &gt; 100) || (mem*float64(multiple) &gt; 100)) &amp;&amp; multiple &gt; 1 {<br>  multiple -= 1<br> }<br><br> return currentRoutines * multiple<br>}</pre><h3>Iterative Approach and Monitoring</h3><p>Implementing this solution was an iterative process, involving continuous monitoring and tweaking. We closely observed the system’s behavior under different load conditions, adjusting our scaling factors and thresholds to find the optimal balance between performance and resource utilization.</p><p>Through this solution, we successfully addressed the initial challenge of resource underutilization and message backlog in the queue. Our service became more resilient to fluctuations in demand, capable of scaling efficiently in response to the incoming workload, all while maintaining a vigilant watch over system resource thresholds to ensure uninterrupted service stability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f39fc6e7285f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/dynamic-goroutine-scaling-optimising-sqs-message-consumption-f39fc6e7285f">Dynamic Goroutine Scaling: Optimising SQS Message Consumption</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XHR Request — Micro task vs Macro task]]></title>
            <link>https://medium.com/@sachincv/xhr-request-micro-task-vs-macro-task-89441c443046?source=rss-8aca79282bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/89441c443046</guid>
            <dc:creator><![CDATA[Sachin Vedaraj]]></dc:creator>
            <pubDate>Sat, 15 Jul 2023 05:15:38 GMT</pubDate>
            <atom:updated>2023-07-15T05:15:38.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>XHR Request — Micro task vs Macro task</h3><p>In Node.js, both the Fetch API and XHR (XMLHttpRequest) requests are considered asynchronous operations and are typically handled as part of the IO (Input/Output) tasks. In the event loop of Node.js, IO tasks are categorized as macro tasks.</p><p>When you make a Fetch API or XHR request, the execution does not block the main thread, allowing the program to continue executing other tasks while waiting for the response. Once the response is received, a callback or a Promise is resolved, depending on the method you use to handle the request.</p><p>Promises, on the other hand, are a mechanism for handling asynchronous operations in JavaScript, and they are not directly related to IO. Promises allow you to write asynchronous code in a more readable and manageable manner, making it easier to handle the results or errors of asynchronous tasks.</p><p>In summary, Fetch API and XHR requests fall under the IO category in Node.js’s event loop, while Promises are a mechanism for handling asynchronous operations, including IO tasks.</p><p>Here’s an <strong>example</strong> of an XHR request in JavaScript that makes an API call and pushes the completion into the macro task queue:</p><pre>const xhr = new XMLHttpRequest();<br><br>xhr.onreadystatechange = function() {<br>  if (xhr.readyState === 4) { // Request is complete<br>    if (xhr.status === 200) { // Successful response<br>      const response = JSON.parse(xhr.responseText);<br>      // Handle the response here<br>      console.log(response);<br>    } else {<br>      // Handle error cases here<br>      console.log(&#39;Error:&#39;, xhr.status);<br>    }<br>  }<br>};<br><br>xhr.open(&#39;GET&#39;, &#39;https://api.example.com/data&#39;);<br>xhr.send();</pre><p>In this example, we create a new instance of XMLHttpRequest. We then set the onreadystatechange event handler, which is triggered when the state of the XHR request changes. When the readyState reaches 4, it means that the request is complete.</p><p>If the status is 200, indicating a successful response, we parse the responseText and handle the response accordingly. In this case, we simply log the response to the console. If the status is not 200, we handle the error case by logging the status code.</p><p>When you execute this code, the XHR request will be made asynchronously, and upon completion, the onreadystatechange event will be triggered. At this point, the event will be pushed into the macro task queue, and it will be processed by the event loop when it reaches the macro task phase.</p><p>To push the completion of an XHR request into the micro task queue, you can wrap the XHR request in a Promise and resolve or reject it accordingly. Here’s an example:</p><pre>function makeRequest() {<br>  return new Promise((resolve, reject) =&gt; {<br>    const xhr = new XMLHttpRequest();<br><br>    xhr.onreadystatechange = function() {<br>      if (xhr.readyState === 4) { // Request is complete<br>        if (xhr.status === 200) { // Successful response<br>          const response = JSON.parse(xhr.responseText);<br>          resolve(response); // Resolve the Promise with the response<br>        } else {<br>          reject(xhr.status); // Reject the Promise with the status code<br>        }<br>      }<br>    };<br><br>    xhr.open(&#39;GET&#39;, &#39;https://api.example.com/data&#39;);<br>    xhr.send();<br>  });<br>}<br><br>makeRequest()<br>  .then(response =&gt; {<br>    // Handle the response here<br>    console.log(response);<br>  })<br>  .catch(error =&gt; {<br>    // Handle error cases here<br>    console.log(&#39;Error:&#39;, error);<br>  });</pre><p>In this example, the makeRequest() function returns a Promise. Inside the Promise constructor, we perform the XHR request as before. However, this time, when the request completes successfully, we call resolve(response) to fulfill the Promise with the response. In case of an error, we call reject(xhr.status) to reject the Promise with the status code.</p><p>By wrapping the XHR request in a Promise, the resolution or rejection of the Promise will be treated as a micro task. We can then use .then() and .catch() to handle the result or error of the Promise asynchronously, ensuring it&#39;s processed in the micro task queue.</p><p>When you execute this code, the XHR request will be made asynchronously, and upon completion, the Promise will either be resolved with the response (pushing the .then() callback into the micro task queue) or rejected with the status code (pushing the .catch() callback into the micro task queue).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89441c443046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSRF — Cross Site Request Forgery]]></title>
            <link>https://medium.com/@sachincv/csrf-cross-site-request-forgery-ccf5cd76b2d2?source=rss-8aca79282bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccf5cd76b2d2</guid>
            <dc:creator><![CDATA[Sachin Vedaraj]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 08:32:28 GMT</pubDate>
            <atom:updated>2023-07-11T08:32:28.682Z</atom:updated>
            <content:encoded><![CDATA[<h3>CSRF — Cross Site Request Forgery</h3><p>How it works &amp; how to prevent it?</p><p>Cross-Site Request Forgery (CSRF or XSRF) is another common web security vulnerability that allows an attacker to trick a victim into performing actions they didn’t intend to do. Unlike XSS, which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user’s browser.</p><p>Here’s a simplified example of how CSRF might work:</p><p>1. Let’s say you’re logged into your online banking website, which trusts any requests made from your browser because you’re authenticated.</p><p>2. While you’re still logged in, you navigate to a malicious site in another tab that was set up by an attacker. This malicious site has a hidden form that’s set up to transfer money from your bank account to the attacker’s account.</p><p>3. The malicious site automatically submits the form to your bank’s website using JavaScript. Because you’re logged into your bank’s website, the request appears to be legitimate, and your bank carries out the transfer.</p><p>In this example, the attacker used CSRF to trick you into making a request that you didn’t intend to make, effectively forging the request.</p><p>CSRF attacks can be <strong><em>mitigated</em></strong> using a number of methods:</p><p>1. <strong>Synchronizer Token Pattern</strong>: The server embeds a secret token in forms when it generates a page. When the user submits the form, the server checks the token and only processes the request if the token is valid.</p><p>2. <strong>Same-Site Cookies</strong>: These are a more recent defense and can be used to assert that a particular cookie should only be sent with requests initiated from the same registrable domain.</p><p>3. <strong>Checking the HTTP Referer header</strong>: Although this is a weaker defense, it can be used to verify that the request is coming from the correct domain.</p><p>It’s important to note that while these methods can greatly reduce the risk of CSRF attacks, none of them can guarantee absolute security. Security is a complex, multifaceted issue that requires a layered defense strategy.</p><p><strong>How can one site access or send request to server of another open tab or domain?</strong></p><p>One site cannot directly access the content or send requests on behalf of another open tab or domain due to a key security feature in modern web browsers known as the Same-Origin Policy (SOP). SOP is a critical aspect of web security that restricts how a document or script loaded from one origin can interact with resources from another origin.</p><p>However, Cross-Site Request Forgery (CSRF) attacks can take advantage of the fact that cookies are automatically included with requests. Here’s an illustrative example:</p><p>Imagine you’re logged into your bank website in one browser tab. The bank uses a cookie to keep you logged in. You then visit a malicious website in another tab. This website contains a form that sends a POST request to your bank’s server to transfer money. The form could be automatically submitted using JavaScript as soon as the page loads.</p><p>Even though this request is coming from the malicious site, your browser will still automatically include the cookies for your bank’s website, because the request is being sent to your bank’s domain. If your bank’s website isn’t properly protected against CSRF attacks, it will think that this is a legitimate request from you, because the correct cookies are included.</p><p>To protect against this type of attack, websites can use techniques such as CSRF tokens (also known as synchronizer tokens), which involve including a hidden field in the form that contains a value that the server has to verify before accepting the request. The server generates this token, ties it to your session, and expects to receive it back. If it doesn’t get this token back, or if the token doesn’t match what it expects, it knows the request is forged and won’t process it.</p><p>The SameSite cookie attribute can also be used to instruct the browser not to send cookies along with cross-site requests, which can provide protection against CSRF attacks.</p><p>It’s worth noting that in the case of Cross-Site Scripting (XSS) attacks, if an attacker can run arbitrary JavaScript on a page, they can make requests to any site on behalf of the user (regardless of the Same-Origin Policy), potentially leading to a CSRF attack. Therefore, mitigating XSS vulnerabilities is also crucial in preventing CSRF attacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf5cd76b2d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XSS — Cross Site Scripting]]></title>
            <link>https://medium.com/@sachincv/xss-cross-site-scripting-3ba1d27118db?source=rss-8aca79282bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ba1d27118db</guid>
            <dc:creator><![CDATA[Sachin Vedaraj]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 08:28:17 GMT</pubDate>
            <atom:updated>2023-07-11T08:28:17.265Z</atom:updated>
            <content:encoded><![CDATA[<h3>XSS — Cross Site Scripting</h3><p>Understanding the vulnerability</p><p>XSS, or Cross-Site Scripting, is a type of security vulnerability that is typically found in web applications. It enables attackers to inject malicious scripts into webpages viewed by other users.</p><p>A web application is vulnerable to XSS if it uses unsanitized user input in the output it generates without proper validation or escaping. This user input could be anything: the value of a parameter in the URL, a form field, or even something pulled from a database.</p><p>Here’s a high-level example of how an XSS attack might work:</p><p>1. An attacker finds a website that has an XSS vulnerability, for example, a website that takes a URL parameter directly and includes it in the body of the HTML page it returns to the user.</p><p>2. The attacker crafts a URL that contains a malicious JavaScript payload in the parameter.</p><p>For example, if the original URL is `<a href="http://vulnerable-website.com/comment?text=Hello`">http://vulnerable-website.com/comment?text=Hello`</a>, the attacker might create a malicious URL like `<a href="http://vulnerable-website.com/comment?text=">http://vulnerable-website.com/comment?text=</a>&lt;script&gt;malicious JavaScript here&lt;/script&gt;`.</p><p>3. The attacker distributes this URL. They could send it via email, post it on social media, etc.</p><p>4. When a victim clicks the link (the one containing the malicious script), the vulnerable website includes the malicious script in the HTML page that it returns to the user’s browser.</p><p>5. The victim’s browser then executes the malicious script. This script can do a variety of things, depending on the attacker’s goals. For instance, it might steal sensitive data like session cookies, alter the appearance or functionality of the web page, or even redirect the victim to another website.</p><p>To mitigate XSS attacks, it’s essential to sanitize and escape all user inputs before using them to generate output. This process typically involves removing or encoding characters that have special meanings in HTML, like `&lt;`, `&gt;`, and `&amp;`. Modern web development frameworks often include functionality to help with this.</p><p>It’s also a good practice to set the HttpOnly flag on cookies, which prevents them from being accessed by JavaScript. This can prevent session cookies from being stolen even if an XSS vulnerability exists. However, this won’t stop all potential harm from an XSS vulnerability; it just limits the damage.</p><p>Let’s delve a little deeper into Cross-Site Scripting (XSS).<br>XSS attacks can be divided into three types: Stored XSS, Reflected XSS, and DOM-based XSS.</p><ol><li><strong>Stored XSS (Persistent XSS)</strong>: This is the most damaging type of XSS attack. The attacker injects a script (often called the payload) that is permanently stored (persisted) on the target server, such as a database, a message forum, a comment field, etc. When a user navigates to the affected web page in their browser, they unwittingly trigger the malicious script.</li><li><strong>Reflected XSS (Non-Persistent XSS)</strong>: This is the most common type of XSS attack. In this case, the injected script is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. The attacker needs to trick the victim into clicking a malicious link (often via a phishing email or similar), which sends the payload to the server, reflecting it back to the user’s browser to execute the script.</li><li><strong>DOM-Based XSS</strong>: This type of XSS attack occurs entirely on the client side, with the payload manipulating the Document Object Model (DOM) of the web application. The web application’s client-side scripts write user-provided data to the Document Object Model. The data is subsequently read from the document and executed by the web browser. If the data isn’t handled correctly, the attacker can inject a payload that will be stored as part of the DOM and subsequently executed.</li></ol><p>XSS attacks can lead to serious implications, including identity theft, session hijacking, and defacement of websites. It’s critical to employ a range of prevention techniques, including <em>input validation, output encoding, using appropriate response headers</em>, and more, to help safeguard against such attacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ba1d27118db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontloading — Here’s how]]></title>
            <link>https://medium.com/@sachincv/frontloading-heres-how-669b001a0e2b?source=rss-8aca79282bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/669b001a0e2b</guid>
            <dc:creator><![CDATA[Sachin Vedaraj]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 08:23:54 GMT</pubDate>
            <atom:updated>2023-07-11T08:23:54.297Z</atom:updated>
            <content:encoded><![CDATA[<h3>Frontloading — Here’s how</h3><h4>What it means and how you do it to keep your audience engaged</h4><p>Audience today are impatient, they probably have always been this way. Frontloading is where you get the attention of impatient readers. Let’s learn about this with a small interesting story and see where you can apply this in your life.</p><p>Since then I have been observing the way people talk, tweet and write articles and what gets the most attention. Look at the below tweet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgeqG9526tpdHkhcNfQrhQ.png" /></figure><p>It starts with the fact that it’s a masterclass in storytelling, sets the intention of what they are about to tell upfront and lures you in with here’s how.</p><p>Let’s look at 1 more example from the web. We have all used chatgpt but do you know how you could make $2000 per week with it? Now after reading this you immediately get curious. This is exactl what the writer has done with the next tweet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z5qq5YT0CXoj6_6Hah7snA.png" /></figure><p>Not just on the web, we could apply it to the conversations we have. One fine night, around 2 me and my friends were having a casual conversation. One of them has the habit of not getting to the point. So he starts off with something unrelated and connects to something else, he does this until he himself looses his chain of thought or is interrupted. After observing this for years, I start addressing everyone about this concept that I recently learnt, <strong>Frontloading</strong>. It simply tells you where this conversation is headed before taking them into the rabbit hole.</p><p>Inorder to explain the concept better, I took the example of trigonometry. Starting with why and where trigonometry is useful, gets the students’ attention and sets a clear goal in the students’ mind. If a teacher starts with simply writing a bunch of formulae, the number of students who pay attention will be a lot lower. The other friend in the room was immediately able to spot how this was a problem for him in school.</p><p>You probably wouldn’t have gotten to this point in reading if I had started with the stories.</p><p>This works really well when you are talking to your friends and want to share something important. Your friends being friends might put up with your story for the love and affection they have for you, but they’ll be much more affectionate if you simply start frontloading. Craft your speech and win your audience.</p><p>Hope this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=669b001a0e2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Order of execution of tests — Mocha, Chai]]></title>
            <link>https://medium.com/@sachincv/order-of-execution-of-tests-mocha-chai-e2dd7e7fcc05?source=rss-8aca79282bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2dd7e7fcc05</guid>
            <dc:creator><![CDATA[Sachin Vedaraj]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 08:18:20 GMT</pubDate>
            <atom:updated>2023-07-11T08:19:43.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Order of execution of tests — Mocha, Chai</h3><h3>Can we declare multiple “before() &amp; after()” blocks at global scope, if Yes and what will be sequence of execution?</h3><p>You can declare multiple `<em>before</em>` and `<em>after</em>` hooks at the global level in Mocha. The execution sequence of `before` hooks will be in the order they are defined, and `<em>after</em>` hooks will be run in reverse order.</p><p>Here’s an example:</p><pre>before(function() {<br> console.log(&#39;global before 1&#39;);<br>});<br><br>before(function() {<br> console.log(&#39;global before 2&#39;);<br>});<br><br>describe(&#39;Test suite&#39;, function() {<br>   before(function() {<br>     console.log(&#39;suite before&#39;);<br>   });<br>  <br>   it(&#39;test&#39;, function() {<br>     console.log(&#39;test&#39;);<br>   });<br>  <br>   after(function() {<br>     console.log(&#39;suite after&#39;);<br>   });<br>});<br><br>after(function() {<br> console.log(&#39;global after 1&#39;);<br>});<br><br>after(function() {<br> console.log(&#39;global after 2&#39;);<br>});</pre><p>This will print:</p><pre>global before 1<br>global before 2<br>suite before<br>test<br>suite after<br>global after 2<br>global after 1</pre><p>In this code:</p><p>- The `<em>before</em>` hooks run first. Hooks at the global level run before those inside `<em>describe</em>` blocks. Within each level, hooks run in the order they’re defined.<br>- The `<em>it</em>` blocks run after all `before` hooks have completed.<br>- The `<em>after</em>` hooks run after all `<em>it</em>` blocks have completed. Hooks inside `<em>describe</em>` blocks run before those at the global level. Within each level, hooks run in reverse order of how they’re defined.</p><p>This ensures that setup and teardown steps happen in a predictable order.</p><h3>What if before/after blocks contain async functions — will the next before/after block run only after done() block is executed?</h3><p>Yes, if your `<em>before</em>` or `<em>after</em>` hooks contain asynchronous code, you should use the `<em>done</em>` callback to tell Mocha when the asynchronous operation has completed. Mocha will not run the next hook or test until `<em>done</em>` is called.</p><p>Here’s an example:</p><pre>before(function(done) {<br>   someAsyncOperation(function(err, result) {<br>     // Perform setup with result<br>     done(); // Call done when the async operation is complete<br>   });<br>});<br><br>before(function(done) {<br>   someOtherAsyncOperation(function(err, result) {<br>     // Perform more setup with result<br>     done(); // Call done when this async operation is complete<br>   });<br>});<br><br>describe(&#39;Test suite&#39;, function() {<br>   it(&#39;test&#39;, function(done) {<br>     // Your test code here<br>     done();<br>   });<br>});</pre><p>In this code:</p><p>- The first `<em>before</em>` hook starts an asynchronous operation. Mocha will wait until `done` is called before running the next hook.<br>- The second `<em>before</em>` hook also starts an asynchronous operation. Again, Mocha will wait until `done` is called before running the tests.<br>- The `<em>it</em>` block can also contain asynchronous code. Mocha will wait until `<em>done</em>` is called before considering the test to be complete.</p><p>Remember to handle errors correctly in your asynchronous code. If an error occurs, you can pass it to `done` to signal to Mocha that the operation failed:</p><pre>before(function(done) {<br>   someAsyncOperation(function(err, result) {<br>     if (err) {<br>       done(err);<br>     } else {<br>       // Perform setup with result<br>       done();<br>     }<br>   });<br>});</pre><p>In this code, if `<em>someAsyncOperation</em>` produces an error, the `<em>before</em>` hook will fail and Mocha will not run the tests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2dd7e7fcc05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ABCDEF — SPOJ PROBLEM]]></title>
            <link>https://medium.com/@sachincv/abcdef-spoj-problem-4409cdc44d77?source=rss-8aca79282bf5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4409cdc44d77</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algo]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[spoj-solutions]]></category>
            <dc:creator><![CDATA[Sachin Vedaraj]]></dc:creator>
            <pubDate>Sat, 23 Nov 2019 00:28:14 GMT</pubDate>
            <atom:updated>2019-11-23T00:28:14.492Z</atom:updated>
            <content:encoded><![CDATA[<h3>ABCDEF — SPOJ PROBLEM</h3><p>So if you have come across this problem or something similar, here’s how you go about solving it.</p><p>First the problem statement.</p><p>You are given a set S of integers between -30000 and 30000 (inclusive).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/0*FwHbumfmdsGYHz4b" /></figure><p>that satisfy:</p><p><em>d!=0</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/107/0*guVRCJccdYhq1aVz" /><figcaption>Equation</figcaption></figure><h3>Input</h3><p>The first line contains integer N (1 ≤ N ≤ 100), the size of a set S.</p><p>Elements of S are given in the next N lines, one integer per line. Given numbers will be distinct.</p><h3>Output</h3><p>Output the total number of possibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*dilAdqU7O9_D2vXAkBuELg.png" /><figcaption>Problem Statement</figcaption></figure><p><strong>This editorial is not just a solution to he problem, but a thought process, that we are gonna build on over time so that you can think next time when a similar problem comes.</strong></p><p>Let’s start!</p><p>When we interpret the problem , these are the conclusions.<br>1.Out of the given array we have to select 6 numbers.<br>2.Numbers can be repeated. That means, you don’t need minimum 6 numbers(Don’t worry even if that were the condition ,you’ll be able to solve it after we are done).<br>example, lets say you have to pic 4 numbers from array [2,1,3] to form 6: You can choose 2 three times, or 3 two times, or 1 six times or 1,2 and 3 to form 6.<br>3.Those 6 numbers have to satisfy the equation. Meaning the LHS and RHS have to be same.</p><p>So, first the brute force approach that any beginner competitive programmer would think about is how do we pic ’n’ numbers from an array, what are the combinations. Lets look at picking in detail now.<br>lets say array = [1,3,4] and we need to pick 4 numbers<br>you can choose<br>1,1,1,1<br>1,1,1,3<br>1,1,1,4<br>1,1,3,1<br>1,1,3,3<br>1,1,3,4<br>1,1,4,1<br>…. and so on .</p><p>Observe carefully now! I’m only changing 1 number at a time with all possible numbers.<br>That means to choose 4 numbers out of any array, you need 4 loops where the index changes one after the other (i,j,k,l)<br>So the psuedo code would go as follows.</p><blockquote>var combinations = empty array<br>for i=0 to i&lt;length of array: <br> for j=0 to j&lt;length of array:<br> for k=0 to k&lt;length of array:<br> for l=0 to l&lt;length of array:<br> var combination = [array[i],array[j],array[k],array[l]]<br> append combination to an array of combinations</blockquote><ul><li>Mind the indentation.</li></ul><p>So we just got every combination in combinations</p><p>Now all we have to do is check for combinations which match a certain criteria</p><p>But , isn’t this a worst possible way to solve our problem.<br>Our problem would have a time complexity of n power 6.</p><p><em>So lets think of a way in which we can reduce this.</em></p><p>Look at the equation given to us.<br>((a*b+c)/d)-e=f<br>can we modify this to select only 3 numbers<br>Yes we can <br>a*b+c = (f+e)d</p><p>So now we can put, left hand side(lhs) combinations in one array and right hand side(rhs) combinations in another, and we’ll need only 3 loops for that.<br>Cool, right?</p><p>Let us do that</p><blockquote>for i=0 to i&lt;length of array:<br> for j=0 to j&lt;length of array:<br> for k=0 to k&lt;length of array:<br> lhs.append(arr[i]*arr[j]+arr[k])<br> rhs.append(arr[k]*(arr[i]-arr[j]))</blockquote><p>So now all we need to do is see how many numbers in lhs match numbers in rhs.</p><p>1 more concept(small) — Example “c1&quot;.</p><p>Let us say you have an array [2,2,3,4,5,5,6]<br>and other as [2,3,3,5,5,5,6,6]</p><p>Each one in both the array has a unique way of arriving at that number</p><p>so if i ask you now in how many ways(combinations) can you get a number 5 which is in both the arrays what would be your answer?</p><p>Number of 5’s in array1(x) multiplied by number of times in array2(y)!</p><p>Which is 2*3 = 6(x*y)</p><p>If there were 3 arrays, you would multiply the appearance count in all three arrays(x*y*z)</p><p>So we are gonna apply this concept to lhs and rhs arrays.<br>Sum it up to get total number of times!</p><p>Total = sum of possibilities</p><p>Like in example “c1” : Total = 2*1 + 1*2 + 1*0 + 2*3 + 1*6</p><p>which is nothing but possibilities of 2 ,3,4,5,6 respectively.</p><p>The last part involves Lower Bound and Upper Bound to get count in each arrays, which everybody is familiar with(I guess).</p><p>Also remember there’s a condition d!=0: So if d is 0 don’t consider that combination.</p><p>That’s it, until next time. Chill!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4409cdc44d77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>