<?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 Shreyansh Gupta on Medium]]></title>
        <description><![CDATA[Stories by Shreyansh Gupta on Medium]]></description>
        <link>https://medium.com/@backslashzero?source=rss-6c5c85d8f62f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nEpz5ShVKZfLxqqo5D4YYA.png</url>
            <title>Stories by Shreyansh Gupta on Medium</title>
            <link>https://medium.com/@backslashzero?source=rss-6c5c85d8f62f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:16:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@backslashzero/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[Understand CORS and how to fix a CORS error]]></title>
            <link>https://backslashzero.medium.com/understand-cors-and-how-to-fix-a-cors-error-87eeb31cf8f4?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/87eeb31cf8f4</guid>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[cross-origin-resource]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 08:46:05 GMT</pubDate>
            <atom:updated>2024-07-22T02:41:28.917Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PmhWsLgtbYh6Az5M" /><figcaption>Photo by <a href="https://unsplash.com/@adriencesard?utm_source=medium&amp;utm_medium=referral">Adrien CÉSARD</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is CORS?</h3><p>CORS stands for Cross-Origin-Resource-Sharing.</p><p>Let us say your backend is an API-only app and it is deployed on Heroku. Your frontend is deployed on Netlify. So your frontend will be communicating with your backend which is on a different origin. This would be termed as Cross-Origin-Resource-Sharing.</p><p>Similarly, let us say that your full-stack application is hosted on www.example.com. It is making a request to a public API, say <a href="https://thronesapi.com/">this GOT API</a> which is hosted on www.thronesapi.com. This would be a cross-origin resource sharing.</p><h3>CORS error</h3><p>CORS error occurs when the server receiving the request is not allowed to share the resource with a different origin.</p><p>For instance, let’s say that www.thronesapi.com is not allowed to respond to any request coming from an origin other than thronesapi.com. In that case, when we make a request to the API from a browser, we will see a CORS error.</p><h3>See the CORS error in action</h3><p>To see the CORS error in action, carry out the following steps -</p><ol><li>Open a new tab and visit guptashreyansh.github.io.</li><li>Open the browser console.</li><li>Make a request to the following URL — <a href="https://shreyanshgupta.hashnode.dev/rss.xml.">https://shreyanshgupta.hashnode.dev/rss.xml.</a></li></ol><p>You can simply copy this code and paste it in the console -</p><pre>fetch(&quot;https://shreyanshgupta.hashnode.dev/rss.xml&quot;)<br>    .then(res =&gt; res.text())<br>    .then(console.log)</pre><p>You will see the following error -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHbqsfr4RlcjhE_JgV4d7w.png" /><figcaption>CORS error</figcaption></figure><h3>Why does a CORS error occur?</h3><p>The CORS error is a security measure that is implemented in the browsers. If the browsers do not find an Access-Control-Allow-Origin header (with the current origin whitelisted) in the response, it will block the response from being loaded. In the case of preflight requests, the absence of the required value will simply block the actual request from being executed.</p><h3>How to fix the CORS error?</h3><p>To fix the CORS error, we need to set the Access-Control-Allow-Origin header in the response.</p><p>A value like this — Access-Control-Allow-Origin: https://guptashreyansh.github.io - will allow us to query Hashnode&#39;s RSS XML page on my website.</p><p>A value like this — Access-Control-Allow-Origin: * - will allow us to query Hashnode&#39;s RSS XML page on any website.</p><p>This value needs to be set on shreyanshgupta.hashnode.dev server.</p><p>We did not try requesting the thronesapi because it has CORS enabled. You can try it out by making a fetch request to this API from any origin -</p><pre>fetch(&quot;https://thronesapi.com/api/v2/characters&quot;)<br>    .then(res =&gt; res.json())<br>    .then(console.log)</pre><p>You can check out more public APIs, and whether or not CORS is enabled for them, on <a href="https://github.com/public-apis/public-apis?tab=readme-ov-file">this page</a>.</p><h3>Using a CORS proxy</h3><p>One way to bypass CORS is to simply update the response’s headers on the server. But what if we don’t have access to the server? For instance, we are querying the RSS XML page from Hashnode but we don’t have access to Hashnode’s server. So we can’t update the response’s headers.</p><p>In this case, we can use a CORS proxy.</p><p>CORS blocking is implemented in the browsers. This means that if you were to make the same request from a server, you’d load the response without any problems.</p><p>In CORS proxy, we set up a proxy server. We provide that server with the URL we want to query from. The proxy server queries the response and forwards it to us with appropriate headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hvNexmr7cSaTADVsZVTPmg.png" /><figcaption>CORS proxy</figcaption></figure><h3>Make a request through a CORS proxy</h3><p>Let us make the same request through a CORS proxy. Follow the following steps -</p><ol><li>Visit — https://cors-anywhere.herokuapp.com/corsdemo - and request temporary access to the demo server.</li><li>Open a new tab and visit guptashreyansh.github.io.</li><li>Open the browser console.</li><li>Make a request to the following URL — https://shreyanshgupta.hashnode.dev/rss.xml - this time through the CORS proxy.</li></ol><pre>fetch(&quot;https://cors-anywhere.herokuapp.com/https://shreyanshgupta.hashnode.dev/rss.xml&quot;)<br>    .then(res =&gt; res.text())<br>    .then(console.log)</pre><p>You’ll see that the response loads successfully.</p><h3>Set up your own CORS proxy</h3><p>This is the technique that I am using to query and render the Hashnode articles on <a href="https://guptashreyansh.github.io/">my website</a>. But I am not using https://cors-anywhere.herokuapp.com since it is a test-only server.</p><p>Instead, I deployed my CORS proxy on Cloudflare (since Heroku does not have a free tier anymore). Cloudflare provides free-tier limits that are good enough for me but YMMV.</p><p>Take a look at the <a href="https://github.com/Zibri/cloudflare-cors-anywhere">following repository</a> to deploy your Cloudflare proxy. If you’d like to deploy on Heroku, you can check out the <a href="https://github.com/Rob--W/cors-anywhere?tab=readme-ov-file">cors-anywhere repository</a>.</p><h3>Further readings</h3><p>If you’d like to know more about CORS, I recommend checking out this MDN article — <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.">https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.</a></p><p>This article was originally published on <a href="https://shreyanshgupta.hashnode.dev/understand-cors-and-how-to-fix-a-cors-error">Hashnode</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87eeb31cf8f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking and Profiling]]></title>
            <link>https://backslashzero.medium.com/benchmarking-and-profiling-6fd2b428f6f0?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fd2b428f6f0</guid>
            <category><![CDATA[benchmark]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Wed, 22 May 2024 21:49:24 GMT</pubDate>
            <atom:updated>2024-05-26T01:01:44.327Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide is applicable to all languages and frameworks. Some suggestions are tailored for Ruby.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yWGpaWnvDqv0EX6q" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Benchmark</strong></h3><p>Benchmark is a SYNTHETIC MEASUREMENT of the RESOURCES or TIME consumed by a defined PROCEDURE.</p><p><em>Synthetic measurement</em> — It does not exactly replicate the conditions in the production. It just aims to give a ballpark estimate.</p><p><em>Resources or time, procedure— </em>We can get information like how much time it took to run a method, how many iterations were run per second or how many objects were created — all this by a defined procedure like a method or a controller action.</p><p><strong>3 kinds of benchmarks</strong> with different levels of scopes —</p><ol><li>Micro — These benchmarks test small functionality. A lot of iterations are run. e.g. a single line of code run 1 million times. That line of code, might call more methods in itself. Optimizations to this single LOC might not be useful if the LOC is not being called in many places.</li><li>Macro — These benchmarks test comparatively bigger functionality. Comparatively lesser iterations are run. e.g. controller actions or service objects executed 1000s of times. Optimizations here might be useful. Results can be seen in the benchmarking results.</li><li>App — These benchmarks test much larger functionality. Much lesser iterations are run. e.g. entire features run 100s of times. Optimizations here might be useful. However, the effect of the optimization might not be visible in the benchmarking results since it is executing a lot of code.</li></ol><p>Some <strong>benchmarking gems in the Ruby world</strong> are — benchmark-ips and benchmark-ipsa.</p><p>Some<strong> benchmarking parameters </strong>—</p><ol><li>Warm up time — It is needed to allow the code to achieve steady state by loading the data and filling in the cache before benchmarking. Make sure to Warm up the code long enough for stable results. e.g. CRuby achieves steady state much faster than JRuby or TruffleRuby. Therefore, for the latter we might need longer warm up time.</li><li>Benchmark time — It determines the times that the actual benchmark will be run for. It should be long enough to keep the variance low. If the variance is high, increasing the benchmarking time might help.</li></ol><p><strong>Tip</strong>: Ensure to only measure the stuff that you actually care about. Make sure you know the code that you’re benchmarking. Keep all the unneeded code outside the benchmarking block.</p><p><strong>Tip: </strong>It’s good to check in all the benchmarks that you write in something like the/benchmarks folder so that they’re readily accessible.</p><h3><strong>Profiling</strong></h3><p>A profile is a STEP BY STEP ACCOUNTING of the RELATIVE CONSUMPTION of RESOURCES by a procedure’s many SUBROUTINES.</p><p><em>Step by step accounting </em>— Instead of getting a cumulative or a single value at the end like how many iterations were run per second, we get a lot of information. e.g. we spent 10% of our time on line 1, 5% on line 2 and so on. We can get the information on a extremely granular level based on the tool.</p><p><em>Relative consumption — </em>It does not give an absolute number like we spent a 100ms of time here like a benchmark would do. It gives us relative measurements like percentages.</p><p><em>Resources — </em>We can profile different resources like memory or time.</p><p><em>Subroutines </em>— We are going to profile a procedure’s subroutines which in the context of a programming language like Ruby might refer to methods. e.g. how much time was spent on each method within a procedure.</p><p><strong>Profiling answers — “What’s slow?”</strong>. It tries to give you very granular details which inevitably makes the app even slower. So production profilers like New relic, Scout and Skylight will make tradeoffs to give you just enough data without impacting the app too much.</p><p>To get in depth results, we need to have a <strong>profiling environment</strong> that works almost identically to production, especially with regards to the amount of data present. Here, we can enable in depth profiling.</p><p>Below are some <strong>settings to get production like behavior</strong> out of development environment on Ruby on Rails. You might want to put these behind a conditional. e.g. if RAILS_ENV == “PROFILE”, only then apply these changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DOO7CaLKZvYfXlFMRUdX3Q.png" /><figcaption>Settings to get production like behavior out of development ENV on Ruby on Rails</figcaption></figure><p>There are <strong>two modes for measuring time</strong> in almost all profilers —</p><ol><li>CPU time — This mode measures the time based on CPU cycles. This means that things like waiting on IO and sleeping don’t show up in those profiles because no time has passed relative to how many CPU cycles have occurred for this process.</li><li>WALL time — This is based on the clock. So everything shows up like waiting on IO and sleeping.</li></ol><p>Depending upon your use case, you might want to use CPU time sometimes while WALL time at other times.</p><p>There are <strong>2 kinds of profilers —</strong></p><ol><li>Statistical — They sample a percentage of the available stack frame. So they interrupt the process execution every X milliseconds to take a snapshot of the stack frame and then allow the process to continue. Then all of those stack frames get aggregated into a profile.</li><li>Tracing — They hook into the language. Every time we call a method, it increments the relevant counters and record that the method was executed.</li></ol><p>So tracing profilers can record everything that happens. While statistical profilers might process only, say, 1 percent of the total data.</p><p>There are <strong>2 main time-profilers in the Ruby world</strong> that we use —</p><ol><li>Stackprof — This is statistical.</li><li>Ruby-prof — This is tracing.</li></ol><p><strong>Profile memory in Ruby world</strong> using memory_profiler.</p><p><strong>In the Ruby world, the best way to interact </strong>with memory_profiler and stackprof is using rack-mini-profiler.</p><p>Write <strong>performance tests in Rails </strong>using rails-perftest.</p><p>No matter how good you measure, at the end of the day, you simply cannot replicate every production scenario in non-production.</p><p>Follow these <strong>steps to measure performance in production —</strong></p><ol><li>Read production metrics — e.g. upon investigation, you find out that the search is working too slow.</li><li>Profile to find hotspots —Do profiling to find where exactly the problem is. i.e. which actions are the slowest. e.g. say the search method is the slowest.</li><li>Create benchmark — Take those slow parts and create benchmarks for it. e.g. try to figure out how long does it take to render each line of the result which searching for something.</li><li>Iterate — Once we benchmark and find the problem, it’s pretty straightforward to implement a solution. Iterate/Work on the slowest areas to see the improvements. e.g. say earlier you were rendering 1000 results per second. Now after implementing the solution, you can benchmark 10000 results per second.</li><li>Deploy — Deploy the solution.</li></ol><p>These notes have been prepared from Nate Berkopec’s talk. You can watch the talk here —</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXL51vf-XBTs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXL51vf-XBTs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXL51vf-XBTs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c721f94ed8042d97c650e3c89853c7f0/href">https://medium.com/media/c721f94ed8042d97c650e3c89853c7f0/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fd2b428f6f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Ruby memory usage]]></title>
            <link>https://backslashzero.medium.com/optimizing-ruby-memory-usage-f519f31f7d6b?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f519f31f7d6b</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[memory-improvement]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Tue, 21 May 2024 17:38:49 GMT</pubDate>
            <atom:updated>2024-05-26T01:01:42.693Z</atom:updated>
            <content:encoded><![CDATA[<p>These suggestions are tailored to CRuby.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bnizjf-5HuzypmS4" /><figcaption>Photo by <a href="https://unsplash.com/@ffstop?utm_source=medium&amp;utm_medium=referral">Fotis Fotopoulos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>1. Dial back the instance counts — discover the true steady state memory usage per instance.</h4><p>The idea behind this is simple. When you start a Rails app, as different URLs are hit and different modules and classes are loaded into the memory, the memory usage of the app will increase over time. However, it is expected to level off after some time as all/most of the objects have been instantiated.</p><p>Don’t just presume you’ve got a memory leak by looking at a memory graph of a short duration. Give the application some time. Make sure you don’t have too restrictive limits (e.g. worker killers) that kill off processes as their memory usage increase.</p><p><strong>Tip:</strong> For most applications, aim for 300 mb per instance in a steady state. Also applies to Sidekiq worker processes.</p><h4>2. Stop allocating too many objects at once</h4><p>Once the memory slots are no longer in use, the memory usage doesn’t just go down. There are several reasons behind this.</p><ol><li><strong>Thresholds</strong> — GC doesn’t run based on timers. GC runs based on threshold. A threshold is hit when more memory is needed but the Ruby VM has run out of slots. In this case, the GC will first try to clear out the existing unused slots before allocating new memory.</li><li><strong>Heap fragmentation </strong>— In object space we have pages and in each page we have slots. There are around 408 slots per page. Each <strong>page</strong> is of 16 KB and each <strong>slot</strong> is of 40 bytes. Ruby cannot move objects between slots amongst pages. (Reason? C is pointer based. Moving objects will break those pointers.) This means that if there is even 1 slot filled out of the 408 slots in a page, that page cannot be released back to the OS. Check GC::INTERNAL_CONSTANTS for seeing the limits. These limits are dependent upon implementation.</li><li><strong>Malloc and free are suggestions, not commands</strong> — When free is called, the allocator might decide to hold onto the memory instead of freeing it if it thinks that the memory might be requested again. Or the OS might not reclaim the memory.</li><li>Allocators don’t work well if memory is used up in either ends of the heap with free pages in the middle. In such a case, the free pages might not be released back to the OS.</li></ol><p>All this might cause long-term slow “leaks” even when the app is in steady state. But it is not really a memory leak. It is Heap fragmentation.</p><p>So, to reduce memory usage, instead of focusing of reducing overall memory usage (which doesn’t really go down, as we saw), focus on reducing the memory required by individual actions. This can be done by allocating less objects. Or fixing the N+1s.</p><p>Following steps show how to find the problems where a lot of objects are being allocated.</p><h4>2 (a). Use APM</h4><p>e.g. Scout, Skylight, New relic.</p><h4>2 (b). Use memory_profiler or oink</h4><p>Ruby gems that are free.</p><p>oink shows which actions are blowing up the heap. memory_profiler shows how much memory is used by each block of code.</p><p><strong>Tip: </strong>Look for bad actions using oink and dig deeper with memory_profiler.</p><p>Or, build your own solutions using GC.stat or ObjectSpace.count_objects.</p><h4>2 (c). If all else fails, move to rake tasks</h4><p>Throwaway VMs are better than bloated VMs. The idea is that if an action is going to trash our VM, better move the action in a dedicated VM and then trash that VM.</p><p>e.g. We can move big export tasks to rake task or Sidekiq workers. Bloated Sidekiq jobs can be run in a separate queue and that queue can be run in a separate dyno on Heroku, so that is the only VM that gets blown.</p><h4>3. Gemfile audit with derailed</h4><p>It basically goes through each gem in the Gemfile and tells you how much memory requiring each gem takes. Require only those dependencies that you need.</p><p>You can also add — require: false — for assets. e.g. if you’re precompiling your assets, then you don’t need sass in production.</p><h4>4. Jemalloc</h4><p>In ruby we have a choice of memory allocator. Normally, the program uses glibc memory allocator but we can also use jemalloc (written by Facebook).</p><p>They mentioned that the idea behind this was, “Emphasizing fragmentation avoidance and scalable concurrency support.”</p><p>This can be done by using LD_PRELOAD env variable or compile ruby with --with-jemalloc flag.</p><h4>5. Use copy-on-write with preloading</h4><p>Use Puma, Unicorn or passenger with preloading in production.</p><p>Copy-on-write increases memory usage between processes. Check this link to know more about copy-on-write — <a href="https://www.geeksforgeeks.org/copy-on-write/">https://www.geeksforgeeks.org/copy-on-write/</a></p><p>Reality is that some copy-on-write is better than no copy-on-write.</p><p>Preloading basically loads and initializes your application code and forks after that point. Before the fork, the code that is loaded is in the shared memory. After that point the workers have their private memory. From the perspective of the workers, they are not aware of this shared memory, it happens at the OS level. When the workers read memory, that works fine but upon writing to the shared memory, the data is copied. Hence it is called copy-on-write. We want to avoid writing to shared memory.</p><p>I suppose the idea here is to use preloading to minimize memory usage by loading common modules in the shared memory while using copy-on-write when the workers absolutely need to write to data in the shared memory.</p><p>Memory is difficult to measure. Make sure you are measuring the right value. When we look at how much memory will be freed up when we kill a worker, we are considering the private memory of the worker.</p><p>If you see that copy-on-write with preloading is not resulting in any benefits, then maybe you need to dig into your memory measurement tool a little more and understand it better. Make sure you’re measuring the right value.</p><h4><strong>6. Use a threaded web server</strong></h4><p>Puma, Passenger enterprise have this enabled.</p><p>Threads allow us to use the same memory instead of allocating more memory.</p><p>Most people aren’t writing code that is so complicated that it wouldn’t be thread safe. So you might want to try it for your application.</p><p>You can try running your test suite with minitest/hell to find threading bugs.</p><h4>7. Keep Ruby and gems up to date</h4><h4>8. Tune malloc</h4><p>For people running threaded web server in production.</p><p>The default malloc — glibc — will create arenas. By doing this, it’s trying to reduce contention for memory reading and writing between threads. It creates arenas every time it detects contention between threads. But the default limit on the number of arenas it can create is 4 or 8 times the number of cores. That can end up being a lot of memory. Reducing this number can reduce the memory usage but it would also reduce the performance by increasing the contention.</p><p>Constant — MALLOC_ARENA_MAX</p><p>You can also tune mallopt . Check it out yourself.</p><h4>9. Tune GC</h4><p>Not recommended unless you are ready to deep dive into the C source code for GC.</p><p>But GC tuning can fix issues like too many free slots, slow startups, too many or too few GCs.</p><p>Remember that any amount of optimization work before establishing that you have a problem, is premature. Focus on benchmarking, measurement and profiling. Prove that you have a problem. Only then move on to optimization.</p><p>These notes have been prepared from Nate Berkopec’s talk. Watch the talk here —</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkZcqyuPeDao%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkZcqyuPeDao&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkZcqyuPeDao%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/eebdec28494261dfa58b8ec3703b4e8a/href">https://medium.com/media/eebdec28494261dfa58b8ec3703b4e8a/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f519f31f7d6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data structure — Heap]]></title>
            <link>https://backslashzero.medium.com/data-structure-heap-6ccfb4f1026a?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ccfb4f1026a</guid>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[heapify]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[heapsort]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 22:22:13 GMT</pubDate>
            <atom:updated>2024-01-20T22:22:13.869Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data structure — Heap</h3><p>In this blog we’re going to take a look at Heap data structure.</p><h3>Table of contents</h3><ol><li>Array representation of binary tree</li><li>Complete binary tree</li><li>Heap</li><li>Insert (in a Max Heap)</li><li>Delete (in a Max Heap)</li><li>Heap sort (in a Max Heap)</li><li>Heapify</li><li>Priority Queue</li><li>References</li></ol><h3>1. Array representation of Binary tree</h3><p>A binary tree is a tree where each node can have 2 elements at most. One way to represent a binary tree is using an array.</p><p>In the array, every element at position i represents a node in the binary tree.</p><ul><li>Position of any given node — i</li><li>Position of left child of the node — 2 * i</li><li>Position of right child of the node — (2 * i) + 1</li></ul><p><strong>Note:</strong> I have used the term position since i is 1-indexed.</p><figure><img alt="Array representation of a binary tree" src="https://cdn-images-1.medium.com/max/1024/1*vGvEQ9Y-kdy25wVdxtH7Mw.jpeg" /><figcaption>Arrows show the left and right children of the node.</figcaption></figure><h3>2. Complete binary tree</h3><p>A <strong>full binary tree</strong> is a tree where all levels are full. To add another element, we’d need to increase the height of the binary tree.</p><p>A <strong>complete binary tree</strong> is a binary tree in which all levels are full. The last level may not be full. In that case, the last level is filled from left to right. Every full binary tree is a complete binary tree but not vice-versa.</p><p>In the array representation of a complete binary tree, there are no empty slots.</p><p>An <strong>incomplete binary tree </strong>is a binary tree where intermediate levels may not have all the elements. There may be empty slots in the array representation of the incomplete binary tree.</p><figure><img alt="Full, complete and incomplete binary trees" src="https://cdn-images-1.medium.com/max/1024/1*vOQJknnC_XgncqDn96Zwig.jpeg" /><figcaption>The incomplete binary tree has empty slots since the children of node 2 are missing.</figcaption></figure><h3>3. Heap</h3><p>A heap is a complete binary tree.</p><h4>Types of Heap</h4><ol><li>Max Heap — Every parent node is greater than all its children.</li><li>Min Heap — Every parent node is less than all its children.</li></ol><figure><img alt="Max Heap and Min Heap" src="https://cdn-images-1.medium.com/max/1024/1*KkAFAITIdSIz7nvKda5Jxg.jpeg" /><figcaption>Max Heap and Min Heap</figcaption></figure><h3>4. Insert (in a Max Heap)</h3><p>To insert a node, we insert the node at the end of the array. Then we repeatedly compare it with the parent node and swap the nodes if the child is greater than the parent.</p><p>Time complexity — O(logN) (Equal to the height of the Heap)</p><figure><img alt="Gif showing insertion of a node in Max Heap." src="https://cdn-images-1.medium.com/max/1024/1*qYRTvt3uQ3e30Dn0dDd1SQ.gif" /><figcaption>Insertion of a node in Max Heap</figcaption></figure><h3>5. Delete (in a Max Heap)</h3><p>While deleting a node, we can only delete the root node from a Heap. The last node takes the place of the root node. Now we repeatedly compare this node with its children and swap it with the child whose value is greater.</p><p>Time complexity — O(logN) (Equal to the height of the Heap)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sfWLygxa5gHKqnzJyZHAAQ.gif" /><figcaption>Deletion of a node in a Max Heap.</figcaption></figure><h3>6. Heap sort (in a Max Heap)</h3><p>Every time we delete a node from the Heap, we delete the largest node. If we start placing the deleted nodes in an array in the reverse order, we’d get a sorted array as a result.</p><p>We remove N nodes. Time to remove each node is logN . Time complexity of Heap sort — O(NlogN) .</p><p>With Heap sort, we can do in-place sorting. When a node is removed, it is replaced by the last node in the array. Simply keep placing the removed node at the end of the array.</p><h3>7. Heapify</h3><p>Heapify is the process of creating a Heap from a given binary tree.</p><p>We start at the last node in the array, and adjust it downwards (like we did when deleting a node). We do this for every node starting at the last node in the array. As a result, we get a Heap in the end.</p><p>Time complexity — O(N)</p><p>Time complexity if we would have created a Heap using N insert operations — O(NlogN) .</p><h3>8. Priority Queue</h3><p>Queue = FIFO (First in first out)</p><p>Priority Queue = FIFO with priorities.</p><p>In a Max Heap, larger number has higher priority. In a Min Heap, smaller number has higher priority.</p><p>To implement Priority Queue, Heap is the best Data structure.</p><p>Time complexity to find and delete a node from an array — O(N) .</p><p>Time complexity to delete a node from a Heap — O(logN) .</p><h3>9. References</h3><p>Abdul Bari sir’s <a href="https://youtu.be/HqPJF2L5h9U?si=lMEjWvMcqg7Gpx-3">lecture 2.6.3</a> on YouTube.</p><p>If you find any mistakes, feel free to let me know in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ccfb4f1026a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove dead code in Ruby on Rails applications]]></title>
            <link>https://backslashzero.medium.com/remove-dead-code-in-ruby-on-rails-applications-4746a7781cb6?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4746a7781cb6</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[dead-code-elimination]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Wed, 17 Jan 2024 20:02:54 GMT</pubDate>
            <atom:updated>2024-05-26T01:01:46.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*T0F2NQr-mufIUMQH.png" /><figcaption>Dead code = Unused / Unreachable code</figcaption></figure><p>Recently I had the opportunity to work on a legacy Ruby on Rails application (~8 years old). An application running for this long comes with its own problems. More than 20 different developers had worked on the application. Around 10 were still actively working on it. In these circumstances, it was not a surprise that it was filled will dead code. The task to clean it up was assigned to me.</p><p>I did some research on how to clean up dead code in Ruby on Rails application. I came up with following tools and techniques through different blogs. Here you can get the consolidated list of these tools and techniques.</p><p>Cleaning up dead code comes with three steps —</p><ol><li>Find the dead code.</li><li>Ensure it is actually dead. There can be many false positives. It is pertinent to ensure that the code is actually unused before removing it.</li><li>Remove the dead code.</li></ol><h3>1. Find the dead code</h3><p>Depending upon where you doing the cleanup, there can be different tool/techniques that you can use.</p><ol><li><strong>Controllers and routes </strong>— You can run the script mentioned in <a href="https://stackoverflow.com/a/14161807">this SO answer</a> to find the list of actions that are being called. Match these actions with the exhaustive list of actions in the application. As a result, you get a list of actions that are present but not getting called.</li><li><strong>Methods</strong> — To find unused methods, you can do a static or a dynamic analysis. Refer to <strong>Further readings </strong>section to understand the different between the two.</li></ol><ul><li>Dynamic analysis — <a href="https://github.com/danmayer/coverband">coverband</a> / <a href="https://github.com/michaelfeathers/scythe">scythe</a> gem.</li><li>Static analysis — <a href="https://github.com/seattlerb/debride">debride</a> / <a href="https://github.com/unused-code/unused">unused</a> gem.</li></ul><p>3. <strong>Views</strong> — To find unused views, use <a href="https://github.com/vinibaggio/discover-unused-partials">discover-unused-partials</a> gem.</p><p>4. <strong>Tables/Columns</strong> — Find tables and columns that are not being used or columns where all the rows have the same value using the script given in <a href="https://boringrails.com/articles/spring-cleaning/">this article</a>.</p><p>5. <strong>Translations</strong> — Find unused translations using <a href="https://github.com/glebm/i18n-tasks">i18n-tasks</a> gem.</p><h3>2. Ensure the code is actually dead</h3><p>All the above methods give you a list of resources that MIGHT be unused. You still need to check each entry manually to ensure it is actually unused. For methods/controllers, you can add log statements in the suspected methods/controllers. If you find these logs in the log-files, you know it was a false positive. You can use gems like <a href="https://github.com/clio/dead_code_detector">dead-code-detector</a> for adding such logs.</p><h3>3. Remove the dead code.</h3><p>You know what to do here. 🧹</p><p>Let me know in the comments if you know of a better tool/technique than the ones listed here.</p><h3>Further readings</h3><ul><li><a href="https://blog.kiprosh.com/dead-code-removal-approaches/">https://blog.kiprosh.com/dead-code-removal-approaches/</a></li><li><a href="https://boringrails.com/articles/spring-cleaning/">https://boringrails.com/articles/spring-cleaning/</a></li><li><a href="https://levelup.gitconnected.com/cleaning-up-your-rails-application-how-to-identify-and-categorize-unused-controller-methods-7288ee88b5c5">https://levelup.gitconnected.com/cleaning-up-your-rails-application-how-to-identify-and-categorize-unused-controller-methods-7288ee88b5c5</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4746a7781cb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to do calculations with very large integers in JavaScript? (Hint — use BigInt)]]></title>
            <link>https://backslashzero.medium.com/how-to-do-calculations-with-very-large-integers-in-javascript-e5f577a5bd11?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5f577a5bd11</guid>
            <category><![CDATA[today-i-learned]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[large-integers]]></category>
            <category><![CDATA[bigint]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 18:20:21 GMT</pubDate>
            <atom:updated>2024-01-07T04:32:56.582Z</atom:updated>
            <content:encoded><![CDATA[<p>Use BigInt.</p><p>JavaScript converts integers with more than 21 digits to scientific notation.</p><pre>Number(1000000000000000000000)<br>// -&gt; 1e+21</pre><p>To operate with such integers in decimal notation, use BigInt .</p><pre>BigInt(1000000000000000000000)<br>// -&gt; 1000000000000000000000n<br>BigInt(1000000000000000000000).toString()<br>// -&gt; 1000000000000000000000</pre><p>We can also perform arithmetic with different BigInt integers.</p><pre>BigInt(1000000000000000000000) * BigInt(1000000000000000000000)<br>// -&gt; 1000000000000000000000000000000000000000000n</pre><p>Read more about BigInt on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt">MDN page.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5f577a5bd11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PRG design pattern of web development]]></title>
            <link>https://backslashzero.medium.com/prg-design-pattern-of-web-development-a43aa6a885a1?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a43aa6a885a1</guid>
            <category><![CDATA[today-i-learned]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 23:30:00 GMT</pubDate>
            <atom:updated>2023-08-05T01:55:14.551Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been learning development in Java. As a part of the learning process, I built a Todo app using the Java Servlet API. Problems I faced during the development, introduced me to the PRG design pattern.</p><p>A <strong>design pattern </strong>is a pre-defined way of solving a problem.</p><p><strong>PRG</strong> stands for Post/Redirect/Get design pattern.</p><p>Let’s take a look at the demo for the Todo app —</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdKl5z26VCjk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdKl5z26VCjk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdKl5z26VCjk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0791d8dccce299f355bd07972108442/href">https://medium.com/media/e0791d8dccce299f355bd07972108442/href</a></iframe><h3>The Problem</h3><p>Notice how the <em>Todo create form</em> is on the same page as the <em>list of Todos</em>. When we submit the form, a POST request is sent. If we return the updated Todo list in the response for the POST request, then refreshing the page would cause the form to resubmit.</p><p>Let’s understand this with the help of a diagram —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34y7djvCZxUeuOwgE-znRw.png" /><figcaption>Causes POST request to be resent</figcaption></figure><h3>The Solution</h3><p>The solution is pretty straightforward. In the response to the POST request, instead of sending the list of todos, we send a <em>redirect response</em>. This redirect response, requests the client browser to redirect to the todo list page using a GET request.</p><p>Check the diagram below —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q211aJHYwgJheY0Vi8gGZA.png" /><figcaption>Post/Redirect/Get design pattern</figcaption></figure><p>Subsequently refreshing the page, does not resubmit the form. Instead, it just queries the todo list page.</p><p>This design pattern is called Post/Redirect/Get design pattern.</p><h3>Further reading</h3><p>I found the following article a very good explanation on this topic. You can check if out if you’d like to know more.</p><p><a href="https://www.theserverside.com/news/1365146/Redirect-After-Post">https://www.theserverside.com/news/1365146/Redirect-After-Post</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a43aa6a885a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to exploit GitHub’s Contributions Graph]]></title>
            <link>https://backslashzero.medium.com/how-to-exploit-githubs-contributions-graph-5019e120a60e?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5019e120a60e</guid>
            <category><![CDATA[today-i-learned]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[exploit]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Tue, 09 Feb 2021 18:58:58 GMT</pubDate>
            <atom:updated>2024-06-18T11:16:40.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Doge with Guy Fawkes Mask." src="https://cdn-images-1.medium.com/max/492/1*ik5a7isfcWxHBx-LOmhxpw.jpeg" /></figure><p>Let’s talk about the Contributions Graph on GitHub. For those of you who don’t know, the contributions graph on GitHub shows your contributions history using squares ranging from white to dark green depending upon the number of contributions made each day. Let’s face it, we all want it — the perfectly filled graph. It’s the weirdest flex of all.</p><p>You can get the perfectly filled graph within 10 minutes.</p><p>It’s no secret that the Contributions Graph on GitHub is not very secure. It’s a collection of data from your contributions on GitHub, displayed in a Graph. So, basically, you can push a repository with preset commit history and gain all those commits as contributions on GitHub. And reverting it is simple as well! Just delete the repo from your account.</p><h3>Steps to make it work</h3><ol><li>Create a new repository on GitHub.</li><li>Clone that repository to your local.</li><li>Add the <em>script</em> to generate commits and then, execute it on your repository.</li><li>Push the repo to your remote.</li></ol><h3>Let’s talk in detail about the script</h3><p>The script’s pretty straightforward. All it does is — makes some change in the repository &amp; commits those changes with a fake timestamp — over and over again, as many time as you’d like.</p><p>The timestamp can be changed by updating two environment variables that git uses to set the timestamp for the commits<strong> — GIT_COMMITER_DATE</strong> &amp; <strong>GIT_AUTHOR_DATE — </strong>which store the timestamps in the standard ISO format.<strong> </strong>Also <em>commit</em> using that timestamp, just to be sure.</p><pre>echo &quot;$i on $M/$D/$Y&quot; &gt; commit.md<br>export GIT_COMMITTER_DATE=&quot;$Y-$M-$D 12:$i:00&quot;<br>export GIT_AUTHOR_DATE=&quot;$Y-$M-$D 12:$i:00&quot;<br>git add commit.md -f<br>git commit --date=&quot;$Y-$M-$D 12:0$i:00&quot; -m &quot;$i on $M $D $Y&quot;</pre><p>Now, to do it <strong>over and over, </strong>wrap it in a loop —</p><pre>for Y in {1980..2040}<br>do<br>  for M in {01..12}<br>  do<br>    for D in {01..31}<br>    do<br>      for i in {01..12}<br>      do<br>        echo &quot;$i on $M/$D/$Y&quot; &gt; commit.md<br>        export GIT_COMMITTER_DATE=&quot;$Y-$M-$D 12:$i:00&quot;<br>        export GIT_AUTHOR_DATE=&quot;$Y-$M-$D 12:$i:00&quot;<br>        git add commit.md -f<br>        git commit --date=&quot;$Y-$M-$D 12:0$i:00&quot; -m &quot;$i on $M $D $Y&quot;<br>      done<br>    done<br>  done<br>done<br><br>git push origin master<br>echo &quot;&quot; &gt; commit.md<br>git commit -am &quot;Cleanup&quot;<br>git push origin master</pre><p>— <em>or 4 loops. </em>As you might have noticed, you can generate commits both — way into the past and the future. Though 1970, I suppose, is as far back as you can go.</p><p>Next, you can make the script executable and run it using the following commands from your terminal —</p><pre>chmod a+x script.sh<br>./script.sh</pre><h3>Conclusion</h3><p>All the snippets assume that the script is within the repository you created. If you don’t want to push the script to remote, you can update the script to traverse to the directory of your choice. You can use the <strong><em>cd</em></strong> command for that.</p><p>Although, I will warn you, the script can take quite a bit of time depending upon how many commits you aim for.</p><p>I did face multiple issues while running the script. For some reason, all the contributions, that were generated, were not being shown on the GitHub — either only the ones for the last year in the timeframe, or only for partial year.</p><p>While I couldn’t find the cause or the fix for this — after playing around a bit, it seemed that the issue occurred only when I generated and pushed over a 1000 commits together. If you find the <strong><em>cause</em></strong> or <strong><em>the fix </em></strong>for this, do share in the comments.</p><p><a href="https://hackernoon.com/how-to-hack-github-kind-of-12b08a46d02e">Here’s the amazing article</a> that introduced me to this exploit. But I don’t understand why he needs to create a new directory for each commit. Anyhow, do give it a read as well, if this doesn’t satiate you.</p><p>Finally, check out <a href="https://github.com/gelstudios/gitfiti">Gitfiti</a>. Using this you can draw some crazy pixel art on your contributions graph.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5019e120a60e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1. How To JavaScript: An Introduction]]></title>
            <link>https://backslashzero.medium.com/1-how-to-javascript-an-introduction-55c1a7d6b140?source=rss-6c5c85d8f62f------2</link>
            <guid isPermaLink="false">https://medium.com/p/55c1a7d6b140</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Shreyansh Gupta]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 18:01:40 GMT</pubDate>
            <atom:updated>2019-03-25T18:01:40.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yDeiyRJ3hAR4GdLGD_e5bw.jpeg" /></figure><h4><strong>What is a programming language?</strong></h4><p>In their essence all programming languages are just different ways of communicating with the computer. For those new to programming, they can just look at programming languages as languages corresponding to the spoken languages but with the special purpose of allowing humans to communicate with the computer, all at their core, based on the same concepts as others. Since writing in machine code (1’s &amp; 0’s) isn’t the most convenient way to write instructions for the computer, programming languages provide a way for the developers to not only write code in a language more familiar to them but also allow other programmers to easily comprehend their work.</p><h4>What is JavaScript?</h4><p>JavaScript was initially made to “make web pages alive”. The programs in this language are called scripts. They can be written in a web page’s HTML and executed automatically as the page loads. Scripts, contrary to compiled languages, can be simply provided in plain text and run as is without any special preparation or compilation processes as such. This is one of the aspects of JavaScript that differs it from Java (another programming language, albeit a compiled one). The only similarity both languages share is their name which to someone, new to programming, might give the wrong idea as to the relationship of both languages.</p><h4>Why “Java”Script?</h4><p>JavaScript was initially made with another name “LiveScript”, however as a marketing ploy its name was switched to JavaScript to match with “Java” in order to capitalise on its popularity, which at the time was rather high. But as it evolved it grew into a fully independent language with its own specifications- so much so that its popularity is breaking all bounds, especially now that it can be used on the back-end as well with the introduction of Node.js. Today it can run not only on the browser but any device that has a special program called the JavaScript Engine.<br>Different Engines have different “code names”. For example:<br>* V8 in Chrome and Opera.<br>* Spider-Monkey in Firefox.<br>These terms are good to remember because they’re often used in developer articles on internet. For instance, if a feature X is supported by V8, then it probably works in Chrome and Opera.</p><h4>How do Engines Work?</h4><p>Engines are pretty complicated. But the basics are easy:<br>1. The engine reads (“parses”) the script.<br>2. Then it converts (“compiles”) the script to the machine language.<br>3. And then the machine code instructs the computer for what’s and what-not’s.<br>So yes, at its core, even scripting languages like JavaScript and Python are compiled to machine code because that’s all a computer can understand.</p><p><em>Now that we’re done with the basics of what’s a programming language, it’s time to dive into and start off with our first program:</em></p><h4>Hello, World!</h4><p>The tutorial you’re about to read is about core JavaScript, which is platform independent. To start off with your first program you can simply open a browser, preferably Chrome or Firefox but others would work too. Once there, you’re gonna want to open the developer’s console which can be opened by pressing [Ctrl + Shift + I] in Chrome or you can simply right click and choose “Inspect” and then click on the “console” tab.<br>Here you can start writing code for now.<br>You can of course choose to save your code in a file with “.js” extension for JavaScript which can be linked to an HTML file and run on any browser or simply run in the terminal as is, the “How-To” for which I’m gonna refrain from writing lest I should end up insulting your intelligence.<br>Now to stop rambling, we’ll just dive into out first line of code: Have the browser pop up with a “Hello, World!” message.</p><p><em>To do that all you would want to do is to write:</em></p><pre>alert(“Hello, World!”);</pre><p><em>and press enter, and voila!</em></p><p>For those working on a terminal, you might want to try the function: console.log(“Hello, World!”);as alert(); is a browser specific function.</p><p>Let us understand the statements above first before proceeding. The semi-colon at the end of a statement signifies an end of the statement. You’ll notice that your code runs just fine without a semi-colon as the Engine adds it for you but it’s considered good practice to append one at the end of each statement yourself to avoid some situations that you might run into in the future where the Engine does not implicitly add a semi-colon. The circular braces “()” signifies that a function is being called, in this case “alert” which is a predefined function but more on that in later chapters; and in the quotes we write the message that we want to have the browser pop up for us. Contrary to alert, console.log simply logs the message in the console.</p><p>Now back to the code, you can write as many statements in a line as you want, each statement separated by a semi-colon:</p><pre>alert(“Hello,”); alert(“World!”);</pre><p>JavaScript only “implicitly” assumes a semi-colon at the end of the statement if the statements are separated by a line-break, like this:</p><pre>alert(“Hello,”)<br>alert(“World!”)</pre><p>Hence this would throw an error:</p><pre>alert(“Hello,”) alert(“World!”)</pre><p>However, there are cases where a line-break does not mean a semi-colon:</p><pre>alert(3 +<br>1<br>+ 2);</pre><p>The code outputs 6 because JavaScript does not assume a semicolon at the end of each line as the same statement is spanning over multiple lines.</p><h4>Comments</h4><p>Comments form an integral part of a programming language as not only do they help other programmers quickly grasp what a block of code, written by some other developer, does but they also help you get going real quick when you revisit your own code after a while.<br>To leave comments in JavaScript all you need to do is to use double forward slashes like:</p><pre>// This is a comment spanning over a single line. <br>alert(&quot;Hello, World!&quot;); // This comment follows the statement</pre><p>Everything following the slashes would be ignored by the engine while parsing the code. Consequently, you cannot continue the code on the same line as you’ve written a comment on:</p><pre>alert(“Hello, World!”); // Following code will be ignored alert(“Hello again!”);</pre><p>Sometimes you might want to write a comment that spans mulitple lines, this can be done by adding two asterisks in between the 2 forward slashes like this:</p><pre>/* This comment<br>spans<br>multiple<br>lines */<br>alert(“Hello, World!”);</pre><p>Why you would want to nest a comment is anyone’s guess but I guess it’s worth mentioning that it is not supported, such a code will die of an error:</p><pre>/*<br> /*<br>   A nested comment that would kill the code’s execution with an    error<br> */<br>*/<br>alert(“Hello, World!”);</pre><p>Hopefully this was a good start to your programming journey. In the subsequent chapters we’ll focus on variables and other concepts that make a programming language what it is. To finish off here’s a comment that actually describes the code it’s used for:</p><pre>// Outputs Hello World<br>alert(&quot;Hello, World!&quot;);<br>// logs the message on console.<br>console.log(&quot;Hello, World!&quot;);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55c1a7d6b140" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>