<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Beatrice Dellacà]]></title><description><![CDATA[Bea's website and blog]]></description><link>https://www.mind-overflow.net/</link><image><url>https://www.mind-overflow.net/favicon.png</url><title>Beatrice Dellacà</title><link>https://www.mind-overflow.net/</link></image><generator>Ghost 5.52</generator><lastBuildDate>Wed, 06 May 2026 10:23:57 GMT</lastBuildDate><atom:link href="https://www.mind-overflow.net/post/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[The Java Virtual Machine]]></title><description><![CDATA[What is the Java Virtual Machine? Read about the JVM in this post, where I talk about the engine that powers our applications - both for newcomers and older developers.]]></description><link>https://www.mind-overflow.net/post/the-java-virtual-machine/</link><guid isPermaLink="false">608555635b7dae45c05248f2</guid><category><![CDATA[Java]]></category><dc:creator><![CDATA[Beatrice Dellacà]]></dc:creator><pubDate>Mon, 02 Aug 2021 19:00:00 GMT</pubDate><media:content url="https://www.mind-overflow.net/content/images/2021/03/jvm-banner.jpg" medium="image"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2><img src="https://www.mind-overflow.net/content/images/2021/03/jvm-banner.jpg" alt="The Java Virtual Machine"><p>This post aims at explaining the basics of the JVM, while also giving more in-depth information for those who are interested in it, but always without getting excessively technical. In fact, even if most newcomers prefer getting their hands dirty by starting to code straight away, I believe that learning about the Java Virtual Machine is particularly important - to know what you are doing, to be better at optimizing (and troubleshooting) - but mostly, to avoid running into walls when trying to raise your level and competence. And also, because I think it&apos;s very interesting to learn about the engine that powers our applications.</p><h2 id="the-principle">The principle</h2><p>The JVM is, by definition, a Virtual Machine. In other words, it is an abstract, virtualized computer with a very specific set of instructions. This definition, however, might bring a question to life:</p><blockquote>So, can it run an OS such as Linux?</blockquote><p>No, it can&apos;t. Not unless you develop a Linux emulator in Java, but that&apos;s not what we are considering. There is a fundamental difference between two kinds of virtual machines: <strong>system</strong> virtual machines, and <strong>process</strong> virtual machines.</p><h3 id="system-virtual-machines">System virtual machines</h3><p>Those are your typical OS emulators: <a href="https://www.qemu.org/?ref=mind-overflow.net">QEMU</a>, <a href="https://www.virtualbox.org/?ref=mind-overflow.net">VirtualBox</a>, <a href="https://www.vmware.com/?ref=mind-overflow.net">VMWare</a>. They provide complete system platforms, by emulating existing architectures and thus allowing the emulation of a complete operating system.</p><h3 id="process-virtual-machines">Process virtual machines</h3><p>This is where the JVM resides, alongside .NET Framework&apos;s <a href="https://docs.microsoft.com/en-us/dotnet/standard/clr?ref=mind-overflow.net">CLR</a> and others. PVMs allow running normal applications inside a host OS, and support a single process. They take life to spawn a process, and die when it ends. The purpose is to provide platform-independent environments, by abstracting the underlying hardware and OS, and allowing programs to run identically, independently from the platform. So, they adapt the codebase to run on any platform, <em>without </em>emulating the platform itself.</p><h4 id="the-jvm">The JVM</h4><p>The JVM, in particular, has the benefit of being supported by a huge variety of devices and hardware. This is because it is defined by a <a href="https://docs.oracle.com/javase/specs/jvms/se16/html/?ref=mind-overflow.net">specification</a>, maintained by Oracle. Everyone is free to make an implementation of that specification, and effectively produce a new JVM that can run bytecode. Thanks to this, there are multiple implementations, such as <a href="https://adoptopenjdk.net/?ref=mind-overflow.net">OpenJDK</a> and <a href="https://en.wikipedia.org/wiki/Jazelle?ref=mind-overflow.net">Jazelle</a>.</p><h3 id="back-to-general-vms">Back to general VMs</h3><p>As you can already tell, process and system VMs follow the same abstraction principles, but implement them in vastly different ways, to address different needs. We can say that a process VM (or multiple ones) can run inside a system VM, and clearly not the opposite.</p><p>While system virtual machines are general-purpose ones and, nowadays, they are even used dynamically to allocate resources and manage different services in medium to big corporations (see: <a href="https://www.proxmox.com/?ref=mind-overflow.net">Proxmox</a>), process virtual machines are very specific and limited to a certain scope: executing a program.</p><p>The argument could be a thread of its own, spacing from hardware-assisted virtualization to the roots of VMs in the <a href="https://en.wikipedia.org/wiki/Compatible_Time-Sharing_System?ref=mind-overflow.net">CTSS</a>. However, we are just trying to analyze and understand virtualization as how it is applied to Java, and this was a necessary premise to give a wider view and a general idea.</p><h2 id="the-structure">The structure</h2><p>The process of developing and running a Java program follows a very specific and invariable flow, which can be expanded and enriched (eg. by Maven, deployment, obfuscation...). We are going to skip everything that happens between you writing code, and the JVM creating a process to run it, since this post&apos;s purpose is to explain the JVM and we don&apos;t want to get off-topic. Basically, it consists of:</p><ol><li>a developer writes human-readable Java source code by using an <a href="https://it.wikipedia.org/wiki/Integrated_development_environment?ref=mind-overflow.net">IDE</a>;</li><li>a compiler &quot;translates&quot; this code to bytecode;</li><li>the bytecode is sent to a JVM that creates a process and runs it.</li></ol><h3 id="the-class-loader">The class loader</h3><p>As we already stated, Java code (<code>Main.java</code>) &#xA0;is converted into bytecode (<code>Main.class</code>). The bytecode is then sent to the JVM&apos;s <em>class loader</em>.</p><h4 id="loading">Loading</h4><p>The class loader subsystem is responsible for translating - <em>yet again</em> - the bytecode into binary data, which is then saved in a space named m<em>ethod area</em>. The stored information consists of the class&apos; fully qualified name (<code>net.mindoverflow.tutorial.Main</code>), the type of the class (<code>class</code>, <code>interface</code>, <code>enum</code>) and all of its methods, variables, constants. For each <code>.class</code> file, the JVM creates a <code>java.lang.Class</code> object that represents that particular class in memory. This allows usage of the <code>getClass()</code> method, that we can then expand with, eg., <code>getName()</code>, to get the class&apos; fully qualified name; <code>getSimpleName()</code> that just returns the class&apos; name, and so on. Since we don&apos;t want ambiguity and redundancy, but also to avoid a number of related issues (which one should we reference to?), only one single <code>Class</code> object is created and stored in memory for each class.</p><h4 id="linking">Linking</h4><p>The linking phase consists of three other steps: verification, preparation, and resolution.</p><p><strong>Verification</strong> serves the purpose of ensuring that the <code>.class</code> file has been properly generated, before actually compiling it to binary. If the file is malformed or badly formatted, the <em>Bytecode Verifier</em> component throws a <code>VerifyError</code> runtime exception. Else, the file is ready to be compiled.</p><p><strong>Preparation</strong> <em>prepares</em> the class for usage: the JVM allocates memory for all of the class&apos; variables and sets them to the default values.</p><p>During the <strong>resolution</strong> step, all symbolic references to methods, classes, interfaces... are replaced with direct references. This is done by querying the method area and locating the referenced entities. This is particulatly complex and many errors can be thrown, but for the scope of this article, this is enough. If you want to understand it more in depth, <a href="https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-5.html?ref=mind-overflow.net#jvms-5.4.3">here</a>&apos;s the official Oracle specification.</p><h4 id="initialization">Initialization</h4><p>This is the final step of the class loader. All static variables are assigned to their vaules specified in the code, following hierarchy (from parent to child) and order (from top to bottom). At the end, all classes are ready to be used. Or technically, what we have <em>extracted</em> from those classes, since we won&apos;t be running the <code>.class</code> files themselves.</p><h3 id="class-loaders">Class loaders</h3><p>There are three kinds of class loaders:</p><ol><li><strong>Bootstrap loader</strong>: this is the core class loader, used by the JVM to load trusted classes such as the core Java API ones found in the JRE library. The <code>JAVA_HOME/jre/lib/</code> directory is known as the bootstrap path, and it is implemented in native languagaes such as C and C++.</li><li><strong>Extension loader</strong>: this loads other classes in the <code>ext/</code> (<code>JAVA_HOME/jre/lib/ext/</code>) subdirectory in the bootstrap path, and thus, it is a child of the bootstrap loader.</li><li><strong>Application</strong>/<strong>System loader</strong>: finally, this loads all classes in the application&apos;s classpath, and it is a child of the extension loader.</li></ol><h3 id="jvms-memory">JVM&apos;s memory</h3><p>Memory is clearly the foundation of any running software, and the JVM has a very specific structure for handling <em>temporary things</em>.</p><h4 id="method-area">Method area</h4><p>We have already referenced the <em>method area</em> earlier. Here, all class-level info is stored: class and parent class names, variables (including static ones), methods. There is only one method area for each JVM instance, and it is shared.</p><h4 id="heap-area">Heap area</h4><p>As the <em>method area</em>, this too is unique per each JVM and shared. It contains info about every object of the running program.</p><h4 id="stack-area">Stack area</h4><p>This is not shared: for each thread, the JVM initializes a <em>runtime stack</em> and stores it in the <em>stack area</em>. Every stack is made of blocks, and every bock of each stack is named a <em>record</em> or <em>frame</em>, and traces method calls. Every <em>local variable</em> of those specific methods is stored in their relative record. When a thread is closed, the runtime stack is deleted too.</p><h4 id="program-counter-registers">Program counter registers</h4><p>The JVM supports multi-threading, and every thread has its own pc<em> register</em>. Each thread is always running a specific (and single) method. The <em>pc register</em> contains the address of the JVM instruction currently being executed if the method is <em>not native</em>. If, instead, the method is <em>native</em>, the address is null. </p><blockquote>A <strong>native method</strong> is a method that is developed and runs in a language different than Java, while <strong>non-native methods</strong> are Java methods. Native methods are used to access system functions that can&apos;t otherwise be accessed by the JVM. However, they limit portability of an application, because they are platfom-dependent.</blockquote><h4 id="native-method-stacks">Native method stacks</h4><p>In addition to all the previously described memory structures of the JVM, an application could still use other data, created by (or for) native methods. This is because the JVM has very little control over what native methods do, since they are not encapsulated under it, but ran separately. When a thread invokes a native method, it runs in a separate &quot;world&quot; from the JVM, without any kind of restriction. Clearly, then, native method stacks can&apos;t be inside the JVM&apos;s stack area, and thus, a new <em>native stack</em> is created, and the JVM links dynamically to that method. If the native method is, for example, a C method, then its stack will be a <em>C</em> stack, and not a <em>Java</em> one. A native method interface will, most likely (although it depends on its purpose and how the developer personally decided to implement it) be able to call back into the JVM, and invoke a Java method. In this case, the thread leaves the <em>native</em> stack and enters another <em>Java</em> stack.</p><h3 id="execution-engine">Execution engine</h3><p>The execution engine is what makes everything move. It reads the bytecode in the <code>.class</code> files line by line, and after querying the various memory areas, it compiles and executes the given instructions. It is made of three parts.</p><h4 id="the-interpreter">The interpreter</h4><p>The interpreter reads and verifies the bytecode, and then executes it. This is nice because it doesn&apos;t require compilation, but one of the main disadvantages of the interpreter is that if a method is called multiple times, it has to be interpreted each time.</p><h4 id="the-jit-compiler">The JIT compiler</h4><p>The just-in-time compiler complements the interpreter: it compiles everything into native code, and when the interpreter notices repeated method calls, it provides precompiled code to run, thus avoiding re-interpretation and increasing efficiency.</p><h4 id="the-garbage-collector">The garbage collector</h4><p>The garbage collector has the purpose of deleting unreferenced objects. An unreferenced object is any object that has been created, but not stored anywhere, and thus &quot;lost&quot; in memory. This happens, for example, every time you create an instance of something in a method, and then quit the method without storing that instance somewhere (in a List, a Map, ...) and without manually destroying it. The GC is a pretty complex matter, which we&apos;ll talk about in another post.</p><h2 id="conclusion">Conclusion</h2><p>This is pretty much everything you should know about the Java Virtual Machine, especially if you previously knew nothing about it. I understand that some things may be a little complex - specifically if you&apos;re just getting started - but don&apos;t worry. If you grasped the main concepts, you are already ahead of a big part of developers out there. You don&apos;t need to remember or understand everything I wrote here, specially if you are a developer and you don&apos;t work daily with the JVM specification. And if you, instead, <em>do</em> work daily on implementing the Oracle specification, you probably even know better than me and this was just a fun quick thing to read.</p><p>Either way, I hope this was an interesting thing to read and that I was able to make you learn something new and interesting.</p><p>See you soon!</p>]]></content:encoded></item><item><title><![CDATA[Creating a dynamic paragraphs sidebar with JS and jQuery]]></title><description><![CDATA[In this post, I explain how I created a dynamic sidebar that lists and links paragraphs from every blog post in my website using JavaScript and jQuery.]]></description><link>https://www.mind-overflow.net/post/creating-dynamic-paragraphs-sidebar-jquery/</link><guid isPermaLink="false">608555635b7dae45c05248ed</guid><category><![CDATA[WebDev]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[jQuery]]></category><dc:creator><![CDATA[Beatrice Dellacà]]></dc:creator><pubDate>Sun, 03 Jan 2021 00:00:00 GMT</pubDate><media:content url="https://www.mind-overflow.net/content/images/2021/03/jquery-banner.jpg" medium="image"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2><img src="https://www.mind-overflow.net/content/images/2021/03/jquery-banner.jpg" alt="Creating a dynamic paragraphs sidebar with JS and jQuery"><p>Having a sidebar that allows your visitors to get a general idea of the post&apos;s structure, and to skip and freely navigate to any point, is a nice little addition that can make the reading experience more clear and interactive. You can see an example of it in the left sidebar of this website, as long as you&apos;re not on mobile.</p><p>Creating such a component is really simple and requires a few lines of code, as long as you&apos;re already using jQuery on your website (which is very likely). If you aren&apos;t, you&apos;ll just need to import it.</p><h2 id="importing-jquery">Importing jQuery</h2><p>This is easy. Just add the following code between the <code>&lt;head&gt;&lt;/head&gt;</code> tags of your blog posts:</p><pre><code class="language-html">&lt;head&gt;
&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;</code></pre><blockquote>Remember to replace the <code>3.5.1</code> version string with the latest version of jQuery. It won&apos;t be a problem for now, but in a few years it might begin to be a little outdated.</blockquote><h2 id="structuring-your-post-s-html">Structuring your post&apos;s HTML</h2><p>If you want to have a fully functional sidebar, you&apos;ll need to make two divs. The first one is for the sidebar itself; the second one is for your post content. This is because the sidebar&apos;s JS code is going to search for titles in the post content&apos;s div; then it&apos;ll generate links for those paragraphs and add them to the sidebar&apos;s div. Remember to give IDs to the headers (if your CMS/SSG isn&apos;t doing it already)!</p><pre><code class="language-html">&lt;main&gt;
    &lt;aside&gt;
        &lt;div id=&quot;post__sidebar-left&quot;&gt;
            &lt;h4&gt;Paragraphs&lt;/h4&gt;
            &lt;!-- Leave this empty; the script will autofill it --&gt;
        &lt;/div&gt;
    &lt;/aside&gt;
    
    
    &lt;div class=&quot;post__content&quot;&gt;
        &lt;!-- Add your post here. The following lines are just examples --&gt;
      &lt;h2 id=&quot;hello&quot;&gt;Hello&lt;/h2&gt;
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed eu dui sit amet diam mollis facilisis sed sed lectus. Mauris vel risus maximus, molestie eros eu, lacinia massa. Ut quis ornare risus. Praesent vestibulum commodo dolor eu lacinia.
      &lt;h3 id=&quot;subtitle-1&quot;&gt;Subtitle 1&lt;/h3&gt;
      Sed faucibus, purus quis laoreet commodo, ante tellus auctor felis, faucibus tincidunt sapien nisi eu leo.
      &lt;h3 id=&quot;subtitle-2&quot;&gt;Subtitle 2&lt;/h3&gt;
      Sed faucibus, purus quis laoreet commodo, ante tellus auctor felis, faucibus tincidunt sapien nisi eu leo.
      &lt;h2 id=&quot;another-title&quot;&gt;Another title&lt;/h2&gt;
      Sed vulputate turpis massa, eget hendrerit nunc ullamcorper sed. Phasellus porttitor aliquet faucibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque gravida diam id erat interdum, eu bibendum massa interdum. Maecenas cursus nulla quis enim mollis accumsan. Aenean id blandit libero.
    &lt;/div&gt;
&lt;/main&gt;</code></pre><p>That&apos;s pretty much it for the HTML part. Again, pretty easy!</p><h2 id="making-the-sidebar-with-css">Making the sidebar with CSS</h2><p>We wouldn&apos;t have called this a sidebar if we didn&apos;t intend to make it stick to a side. This part really depends on how your pages are structured, but for this example I&apos;ll do it in an extremely simple way: flexbox. Note that this is just so that I can give you a working example, but your configuration might vary wildly and you might prefer to do this in some other way. Anyway, here&apos;s the code:</p><pre><code class="language-css">main {
  display: flex;
}</code></pre><p>Another thing you might want to do is give your currently viewed paragraph a different style - for example, by making it bold, or by coloring it a different way. You can do it, for example, like this:</p><pre><code class="language-css">#post__sidebar-left a.current {
  color: red;
}</code></pre><p>We are going to apply the <code>current</code> class via JS later on.</p><p>Also, since this is a sidebar, you probably want it to be sticky. Here&apos;s a way to do it:</p><pre><code class="language-css">#post__sidebar-left {
  position: sticky;
  top: 0;
}</code></pre><p>Yep, that&apos;s it in this case. Tada!</p><h2 id="connecting-everything-with-magic-writing-the-js-script">Connecting everything with magic: writing the JS script</h2><p>This is the hardest part, but fear not: I&apos;ll explain the different bits as we go on.</p><h3 id="initializing-needed-variables">Initializing needed variables</h3><p>First of all, we&apos;re gonna need two arrays to store the paragraphs&apos; headers and their respective links:</p><pre><code class="language-javascript">let headers;
let sidebarLinks;</code></pre><h3 id="generating-the-links">Generating the links</h3><p>Then, when the whole page has loaded, we want to check for every header in the post content&apos;s div, and store it in the array we just created:</p><pre><code class="language-javascript">$(document).ready(function () {
    
    headers = $(&quot;.post__content h2, .post__content h3&quot;).toArray();
    
    const sidebar = $(&quot;#post__sidebar-left&quot;);

    for (let i = 0; i &lt; headers.length; i++) {
        const currentHeader = headers[i];
        const headerText = $(currentHeader).text();
        const headerId = $(currentHeader).attr(&quot;id&quot;);
        const headerType = $(currentHeader).prop(&quot;nodeName&quot;).toLowerCase();

        const newLine = &quot;&lt;&quot; + headerType + &quot;&gt; &lt;a href=\&quot;#&quot; + headerId + &quot;\&quot;&gt;&quot; + headerText + &quot;&lt;/a&gt; &lt;/&quot; + headerType + &quot;&gt;&quot;;
        sidebar.append(newLine);
    }

    sidebarLinks = $(&quot;#post__sidebar-left a&quot;).toArray();
    
    &lt;...&gt;
});</code></pre><p>Let me explain this line by line.</p><pre><code class="language-javascript">$(document).ready(function () {
    &lt;...&gt;
}</code></pre><p>This means that we want to wait for the whole document (page) to be loaded before running the script. Also, we only want to run it once (again, when the document has loaded) because the content isn&apos;t going to suddenly change, and thus we don&apos;t need to check multiple times.</p><pre><code class="language-javascript">headers = $(&quot;.post__content h2, .post__content h3&quot;).toArray();</code></pre><p>This stores every <code>&lt;h2&gt;</code> and <code>&lt;h3&gt;</code> tag found in the <code>post__content</code> div into the <code>headers</code> array we just created.</p><pre><code class="language-javascript">const sidebar = $(&quot;#post__sidebar-left&quot;);</code></pre><p>This is because we need a way to edit the sidebar&apos;s content (by adding the paragraphs&apos; links to it). So, we are simply picking the sidebar&apos;s div by its unique id (<code>post__sidebar-left</code>).</p><pre><code class="language-javascript">for (let i = 0; i &lt; headers.length; i++) {
    &lt;...&gt;
}</code></pre><p>Now, we want to loop through the <code>headers</code> array, so that we can process every header, one at a time.</p><pre><code class="language-javascript">const currentHeader = headers[i];</code></pre><p>This is to load the current header we are referring to, inside of the loop.</p><pre><code class="language-javascript">const headerText = $(currentHeader).text();
const headerId = $(currentHeader).attr(&quot;id&quot;);
const headerType = $(currentHeader).prop(&quot;nodeName&quot;).toLowerCase();</code></pre><p>This is to load the different properties of the said header: its text (&quot;Title Number One&quot;); its ID (&quot;title-number-one&quot;) and its type (<code>h2</code>, <code>h3</code>, ...).</p><pre><code class="language-javascript">const newLine = &quot;&lt;&quot; + headerType + &quot;&gt; &lt;a href=\&quot;#&quot; + headerId + &quot;\&quot;&gt;&quot; + headerText + &quot;&lt;/a&gt; &lt;/&quot; + headerType + &quot;&gt;&quot;;</code></pre><p>We have to store all this data because we are gonna use it to generate the link in the sidebar. The <code>newLine</code> is a simple HTML string we are generating at the moment. This string is what we&apos;ll be adding to the sidebar&apos;s div. For example:</p><pre><code class="language-html">&lt;h2&gt; &lt;a href=&quot;header-link&quot;&gt; Header Name &lt;/a&gt; &lt;/h2&gt;</code></pre><p>Now, we want to add this string we just generated to the sidebar:</p><pre><code class="language-javascript">sidebar.append(newLine);</code></pre><p>Voil&#xE0;! That&apos;s it to generate a dynamic sidebar. However, we also want to highlight the currently viewed paragraph.</p><h3 id="highlighting-the-current-paragraph">Highlighting the current paragraph</h3><p>To do so, we need to run another, last, instruction in the <code>$(document).ready(function(){ }</code> method:</p><pre><code class="language-javascript">sidebarLinks = $(&quot;#mind-post_sidebar-left a&quot;).toArray();</code></pre><p>This is so that every link we just generated in the loop will get stored in the <code>sidebarLinks</code> array we defined at the beginning. Then, we need a new method that checks our reading position whenever we scroll:</p><pre><code class="language-javascript">$(document).ready(function () {
    &lt;...&gt;
        
    $(window).scroll(function () {
        let bottomScroll = $(window).scrollTop() + ($(window).height() / 2);
        let found = false;

        for (let i = headers.length - 1; i &gt;= 0; i--) {
            const currentHeader = headers[i];
            const currentSidebarLink = sidebarLinks[i];
            $(currentSidebarLink).removeClass(&quot;current&quot;);

            const headerVPPosition = $(currentHeader).offset().top;

            if (!found &amp;&amp; bottomScroll &gt; headerVPPosition) {
                $(currentSidebarLink).addClass(&quot;current&quot;);
                found = true;
            }
        }
    });
});</code></pre><p>Again, let me explain how and why this works.</p><pre><code class="language-javascript">$(window).scroll(function () {
    &lt;...&gt;
}</code></pre><p>This method, that goes inside of the other one (<code>$(document).ready(function () { }</code>), is called every time we scroll the page. We need this because, obviously, you&apos;ll be scrolling the page as you read, and eventually you&apos;ll switch to a new paragraph.</p><pre><code class="language-javascript">let bottomScroll = $(window).scrollTop() + ($(window).height() / 2);</code></pre><p>This is to know how may pixels you have scrolled so far. I&apos;m dividing the window height by 2 because this way we&apos;ll be looking at the middle of the window instead of the top (I believe most people keep the text they&apos;re reading near the middle of the screen, rather than the upmost side).</p><pre><code class="language-javascript">let found = false;</code></pre><p>This is a simple boolean that allows us to know if we have found the div we&apos;re looking for, so that we can stop. This will be clearer as you go on.</p><pre><code class="language-javascript">for (let i = headers.length - 1; i &gt;= 0; i--) {
    &lt;...&gt;
}</code></pre><p>Again, we are looping through all headers - however, we are doing this from the bottom side rather than from the beginning. This is because we want to stop at the lowest one you&apos;re looking at.</p><pre><code class="language-javascript">const currentHeader = headers[i];
const currentSidebarLink = sidebarLinks[i];</code></pre><p>These are two variables we need: the current header we are analyzing in the loop, and its link.</p><pre><code class="language-javascript">$(currentSidebarLink).removeClass(&quot;current&quot;);</code></pre><p>This is to remove the <code>current</code> class - we only want the currently viewed paragraph title to have it. We&apos;ll remove it from everything and eventually reapply it to the correct div. This is not an issue because if a div is already without that class, it will simply do nothing.</p><pre><code class="language-javascript">const headerVPPosition = $(currentHeader).offset().top;</code></pre><p>This is to know the header&apos;s position in pixels from the top, so that we can check if we are effectively looking at it (by comparing it to our current scrolling position).</p><pre><code class="language-javascript">if (!found &amp;&amp; bottomScroll &gt; headerVPPosition) {
    $(currentSidebarLink).addClass(&quot;current&quot;);
    found = true;
}</code></pre><p>This is the final step! We are checking if we had already found a paragraph we are looking at. If we haven&apos;t, then we need to check if the current one is actually the correct one. To check if, we are comparing the pixel coordinates of our screen (<code>bottomScroll</code>) and the current paragraph (<code>headerVPPosition</code>).</p><p>If this is the correct one, then set <code>found</code> to <code>true</code> and add the <code>current</code> class to the header.</p><h3 id="implementing-the-script">Implementing the script</h3><p>Now, the last thing you need to do is to save the script we just created, and include it in your HTML file, like this (let&apos;s suppose you saved the script in the <code>/scripts/</code> folder under the name of <code>sidebar.js</code>):</p><pre><code class="language-html">&lt;script src=&quot;/scripts/sidebar.js&quot;&gt;&lt;/script&gt;</code></pre><h2 id="conclusion">Conclusion</h2><h3 id="working-example">Working Example</h3><p>Finally, we are done! I hope this wasn&apos;t too painful, and that I was clear and exhaustive enough to make you understand everything. Now, to reward you for the super good job you did, here&apos;s a working CodePen that you can copy-paste wherever you want!</p><!--kg-card-begin: html--><p class="codepen" data-height="413" data-theme-id="dark" data-default-tab="js,result" data-user="mind-overflow" data-slug-hash="zYKWZvQ" style="height: 413px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="zYKWZvQ">
  <span>See the Pen <a href="https://codepen.io/mind-overflow/pen/zYKWZvQ?ref=mind-overflow.net">
  zYKWZvQ</a> by Lorenzo Dellac&#xE0; (<a href="https://codepen.io/mind-overflow?ref=mind-overflow.net">@mind-overflow</a>)
  on <a href="https://codepen.io/?ref=mind-overflow.net">CodePen</a>.</span>
</p>
<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script><!--kg-card-end: html-->]]></content:encoded></item><item><title><![CDATA[How to reset PulseAudio and ALSA on Ubuntu 20.04/20.10]]></title><description><![CDATA[Reconfiguring PulseAudio and ALSA as if you just installed the system is not the most straightforward thing. If you messed up, here I explain how to do it.]]></description><link>https://www.mind-overflow.net/post/how-to-reset-pulseaudio-and-alsa-on-ubuntu/</link><guid isPermaLink="false">608555635b7dae45c05248ee</guid><category><![CDATA[Ubuntu]]></category><category><![CDATA[Audio]]></category><dc:creator><![CDATA[Beatrice Dellacà]]></dc:creator><pubDate>Thu, 12 Nov 2020 21:19:12 GMT</pubDate><media:content url="https://www.mind-overflow.net/content/images/2021/03/how-to-reset-pulseaudio-1.jpg" medium="image"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2><img src="https://www.mind-overflow.net/content/images/2021/03/how-to-reset-pulseaudio-1.jpg" alt="How to reset PulseAudio and ALSA on Ubuntu 20.04/20.10"><p><strong>TL; DR</strong> - I don&apos;t care about your cool story, just give me the commands: <a href="#the-very-simple-process">click here</a>.</p><p>I&apos;ve recently began using Ubuntu 20 as my daily driver, and as I started migrating everything from my Windows installation, I finally got to the audio and video department. Since we all have to attend online meetings these days, I have worked on my setup too, which consists on two main things: <a href="https://www.dev47apps.com/droidcam?ref=mind-overflow.net">DroidCam</a>, to make my phone into a webcam, and <a href="https://github.com/lawl/NoiseTorch?ref=mind-overflow.net">NoiseTorch</a>, to remove anything that is not my voice from my audio stream.</p><p>Everything worked smoothly for a few days, until I installed a kernel update. This morning I had to attend an online lesson - and whoops! DroidCam was no longer working. I was getting the error <code>Device not found (/dev/video[0-9])</code>. Apparently, the <code>v4l2loopback-dc</code> module got removed somehow. Anyway, I started tinkering again, I installed the <code>droidcam-dkms</code> package but it failed, I tried uninstalling it but it removed everything... It was a mess. I finally got it to work - however, the video stream was freezing every few seconds, and the audio in my headphones was popping and crackling like crazy. Also, NoiseTorch was listing every one of my inputs as <code>(incompatible?)</code> - they were working fine a few minutes earlier.</p><p>My last chance was to try and fix PulseAudio. I knew something was messed up, but I really couldn&apos;t figure out what. My configuration file wasn&apos;t changed, nor was the system one. Disabling timer-based audio scheduling (<code>tsched=0</code>) helped a little, but it didn&apos;t fix the issue. I really didn&apos;t know what to do.</p><p>I had the idea of trying to completely purge and reinstall the <code>pulseaudio</code> and <code>alsa*</code> packages. However, if you try:</p><pre><code class="language-bash">apt autoremove --purge pulseaudio</code></pre><p>You will be greeted with an awesome list of dependency packages that will be removed too, and those will include <code>ubuntu-desktop</code>, <code>ubuntu-desktop-minimal</code> and other completely unrelated system stuff. That&apos;s obviously something you <strong>do not</strong> want to uninstall.</p><p>I was lucky, however. I had a brilliant idea: I could bypass <code>apt</code> entirely and use <code>dpkg</code>. It felt like magic, when everything suddenly started to work.</p><h2 id="the-very-simple-process">The very simple process</h2><p>As long as your audio configuration and settings were working when you installed Ubuntu, and the malfunctioning state is caused by your misconfiguration and/or fault, restoring the audio driver to default state might actually be helpful.</p><p>First of all, completely purge and remove your <code>pulseaudio</code> and <code>alsa</code> packages by running:</p><pre><code class="language-bash">sudo dpkg --purge --force-depends pulseaudio alsa-base alsa-utils</code></pre><p>Don&apos;t worry about dependency warnings - we are aware of that; that&apos;s the purpose of bypassing <code>apt</code>. We want to only uninstall those specific packages, and since we are reinstalling them in a few seconds, there&apos;s no need to worry about missing dependencies.</p><p>Then, run the following command:</p><pre><code class="language-bash">sudo apt install pulseaudio alsa-base alsa-utils</code></pre><p>Voil&#xE0;. Reboot your machine and your audio will be good to go, ready to play your favorite tunes, meme videos and whatnot.</p>]]></content:encoded></item><item><title><![CDATA[Fixing Ubuntu's fractional scaling "duplicate cursor" bug]]></title><description><![CDATA[Ubuntu 20.04 (and 20.10) has a weird bug, which causes a second, dead cursor to appear on screen when you have fractional scaling enabled. In this post, I explain how to fix it!]]></description><link>https://www.mind-overflow.net/post/fixing-ubuntu-fractiona-scaling-bug/</link><guid isPermaLink="false">608555635b7dae45c05248ec</guid><category><![CDATA[Ubuntu]]></category><category><![CDATA[GNOME]]></category><dc:creator><![CDATA[Beatrice Dellacà]]></dc:creator><pubDate>Sun, 08 Nov 2020 17:41:27 GMT</pubDate><media:content url="https://www.mind-overflow.net/content/images/2021/03/ubuntu-duplicate-cursor.jpg" medium="image"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2><img src="https://www.mind-overflow.net/content/images/2021/03/ubuntu-duplicate-cursor.jpg" alt="Fixing Ubuntu&apos;s fractional scaling &quot;duplicate cursor&quot; bug"><p>Since you are here, you probably know what I&apos;m talking about. Ubuntu 20.04 Focal Fossa (and 20.10 Groovy Gorilla) has a pretty unusual bug, if you have the experimental &quot;fractional scaling&quot; feature enabled: when you log-in with your password, your mouse cursor gets stuck at its current position, while a new, bigger one appears and tracks your mouse movements. The bug is caused by <a href="https://bugs.launchpad.net/ubuntu/+source/mutter/+bug/1873052?ref=mind-overflow.net">this</a> issue, described on the Ubuntu mutter issue tracker. However, since an official fix is not currently available, I&apos;ve found a workaround that pretty much fixes it every reboot, and made it into a program:</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://github.com/mind-overflow/gnome-fs-duplicate-cursor-fix?ref=mind-overflow.net"><div class="kg-bookmark-content"><div class="kg-bookmark-title">mind-overflow/gnome-fs-duplicate-cursor-fix</div><div class="kg-bookmark-description">Fix Ubuntu/GNOME&#x2019;s &#x201C;duplicate cursor&#x201D; fractional scaling bug. - mind-overflow/gnome-fs-duplicate-cursor-fix</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://github.githubassets.com/favicons/favicon.svg" alt="Fixing Ubuntu&apos;s fractional scaling &quot;duplicate cursor&quot; bug"><span class="kg-bookmark-author">GitHub</span><span class="kg-bookmark-publisher">mind-overflow</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://avatars3.githubusercontent.com/u/67104846?s=400&amp;v=4" alt="Fixing Ubuntu&apos;s fractional scaling &quot;duplicate cursor&quot; bug"></div></a></figure><h2 id="installation">Installation</h2><p>The installation process is pretty easy, although admittedly not one of the shortest.</p><h3 id="step-1-fractional-scaling">Step 1 - Fractional Scaling</h3><p>Make sure that fractional scaling is enabled, by going in your System Settings &#x2799; Monitors &#x2799; Fractional Scaling. If it&apos;s disabled, turn it on and configure your monitors.</p><h3 id="step-2-installing-java">Step 2 - Installing Java</h3><p>Open up a new Terminal window and type <code>java -version</code>. If your output looks similar to this, you are good to go:</p><pre><code>openjdk version &quot;1.8.0_272&quot;
OpenJDK Runtime Environment (build 1.8.0_272-8u272-b10-0ubuntu1~20.10-b10)
OpenJDK 64-Bit Server VM (build 25.272-b10, mixed mode)</code></pre><p>If, instead, you get <code>java: command not found</code>, just run <code>sudo apt install -y default-jre</code> and finally re-check the correct installation with the previous command.</p><h3 id="step-3-adding-the-fix">Step 3 - Adding the fix</h3><p>While still in the Terminal, download the latest version of the fix from the official GitHub repo linked above, with the following command:</p><pre><code class="language-bash">wget -O ~/ScreenScalingFixer.jar https://github.com/mind-overflow/gnome-fs-duplicate-cursor-fix/releases/download/v1.0/ScreenScalingFixer-1.0-SNAPSHOT.jar</code></pre><p>Then, create a new directory for the program and move it inside:</p><pre><code class="language-bash">mkdir ~/screen-scaling-fixer/</code></pre><pre><code class="language-bash">mv ~/ScreenScalingFixer.jar ~/screen-scaling-fixer/ScreenScalingFixer.jar</code></pre><p>The next step is to create a startup script, which will run every time after you login. Run the commands:</p><pre><code class="language-bash">echo &quot;sh -c \&quot;cd ~/screen-scaling-fixer/ &amp;&amp; java -jar ~/screen-scaling-fixer/ScreenScalingFixer.jar\&quot;&quot; &gt; ~/screen-scaling-fixer/start.sh</code></pre><pre><code class="language-bash">chmod +x ~/screen-scaling-fixer/start.sh</code></pre><p>Finally, enable the recently created script by executing the following lines in the Terminal:</p><pre><code class="language-bash">mkdir ~/.config</code></pre><pre><code class="language-bash">mkdir ~/.config/autostart</code></pre><pre><code class="language-bash">printf \
&quot;[Desktop Entry]\n\
Name=fs-fixer\n\
GenericName=fs-fixer\n\
Comment=fix gnome scaling duplicate cursor\n\
Exec=sh -c ~/screen-scaling-fixer/start.sh\n\
Terminal=false\n\
Type=Application\n\
X-GNOME-Autostart-enabled=true\n\
X-GNOME-Autostart-Delay=1\n&quot; &gt; ~/.config/autostart/fractional-scaling-fix.desktop</code></pre><pre><code class="language-bash">chmod +x ~/.config/autostart/fractional-scaling-fix.desktop</code></pre><h3 id="step-4-final-configuration">Step 4 - Final configuration</h3><p>At this point, you have correctly installed and enabled the fix. Now, the last thing you need to do is configure it!</p><p>Move into the correct directory and launch it:</p><pre><code class="language-bash">cd ~/screen-scaling-fixer &amp;&amp; ./start.sh</code></pre><p>It will generate the configuration file and quit instantly. Now, type <code>xrandr</code>. You should get a list containing all of your monitors. What you need to do is find the correct port your fractional-scaling-enabled monitor is plugged into. It should be something like <code>DisplayPort-1</code>, <code>HDMI-A-0</code> or <code>eDP-1</code>... Write that down somewhere. Don&apos;t worry if you have multiple scaled monitors, one is enough.</p><p>Now, edit the <code>config.yml</code> file in the <code>~/screen-scaling-fixer</code> directory. In my case, I&apos;m going to use the text editor <strong>nano</strong>:</p><pre><code class="language-bash">nano ~/screen-scaling-fixer/config.yml</code></pre><p>The file will look like this:</p><pre><code class="language-yaml">enable: false
delay: 2000
monitor-connector: &apos;DisplayPort-1&apos;
scale: 1.5</code></pre><p>Change <code>enable: false</code> to <code>enable: true</code>, or the script won&apos;t run.</p><p>Then, change <code>monitor-connector: &apos;DisplayPort-1&apos;</code> to the one you just found with <code>xrandr</code>, such as <code>monitor-connector: &apos;HDMI-A-1&apos;</code>.</p><p>Now you need to set the <code>scale</code>. This is the effective scale you want your monitor to be at, and this <strong>must</strong> be the same you used in the system settings. So, 150% becomes 1.5; 125% is 1.25, etc.</p><p>Finally, set the delay, in milliseconds. The delay is how long the script needs to wait before actually running. Set it to something that you think is enough for your computer to fully complete the login sequence. If you are running from an SSD with a decent processor, <code>2000</code> will be enough. If the delay is too short, you will simply see no effect. If this is the case, try opening the <code>config.yml</code> file again and increasing the delay. Then, close nano by pressing <code>CTRL+X</code> and then <code>Y</code> to save the file.</p><h3 id="step-5-check-that-everything-works">Step 5 - Check that everything works</h3><p>You are finally done! I really hope this didn&apos;t take too long. Now, to test that everything works correctly, run the program again from Terminal:</p><pre><code class="language-bash">cd ~/screen-scaling-fixer &amp;&amp; ./start.sh</code></pre><p>Your screen should flash twice for a few seconds, and when it ends flashing, your monitor configuration should be the very same one you had before running it. Congratulations! Now, you just need to logout and log back in, to see it work its magic and make the dead cursor disappear.</p><h2 id="conclusion">Conclusion</h2><p>Until the development teams of Ubuntu, GNOME and mutter have a fix ready for this, I think this is the best solution to the problem. It certainly isn&apos;t the prettiest, but it works, and it does it well enough, at least for me. I think waiting 2 seconds after logging in is not a big deal, especially since this solves the problem of having an ugly cursor always stuck on the screen.</p><p>If you were unable to follow some steps or have any problem/question about this, please leave a comment below and I&apos;ll try to help you as soon as possible!</p>]]></content:encoded></item></channel></rss>