<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Varun S</title>
    <description>The latest articles on Forem by Varun S (@varuns924).</description>
    <link>https://forem.com/varuns924</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F518143%2Ff400de90-c7c2-4974-a698-c16f30dc6e22.jpg</url>
      <title>Forem: Varun S</title>
      <link>https://forem.com/varuns924</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/varuns924"/>
    <language>en</language>
    <item>
      <title>Creating a Status Page with Pure HTML, CSS, and JavaScript</title>
      <dc:creator>Varun S</dc:creator>
      <pubDate>Sun, 10 Apr 2022 02:42:46 +0000</pubDate>
      <link>https://forem.com/varuns924/creating-a-status-page-with-pure-html-css-and-javascript-9pe</link>
      <guid>https://forem.com/varuns924/creating-a-status-page-with-pure-html-css-and-javascript-9pe</guid>
      <description></description>
      <category>html</category>
      <category>css</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Running multiple local PHP web servers</title>
      <dc:creator>Varun S</dc:creator>
      <pubDate>Sat, 17 Apr 2021 00:16:07 +0000</pubDate>
      <link>https://forem.com/varuns924/running-multiple-local-php-web-servers-5ab5</link>
      <guid>https://forem.com/varuns924/running-multiple-local-php-web-servers-5ab5</guid>
      <description>&lt;p&gt;PHP is a both a front-end and back-end scripting language. If you've also used PHP for both ends of a full-stack application, you might relate to the frustration of looking for a free, high-quality local development tool for full-stack PHP developers. &lt;/p&gt;

&lt;p&gt;With JavaScript, you can start a server directly in code, choose the port, and rewrite the urls without hassle, using Node's core http module. &lt;/p&gt;

&lt;p&gt;Similarly, Java supports the feature through, for example, &lt;a href="https://www.codeproject.com/tips/1040097/create-a-simple-web-server-in-java-http-server"&gt;Sun's NET HttpServer package&lt;/a&gt; and C# &lt;a href="https://www.codeproject.com/tips/485182/create-a-local-server-in-csharp"&gt;as well&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;But PHP is different from other languages. To start up the built-in web server, you use the following command:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;php -S localhost:8000&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Unfortunately, this creates only a very basic server that cannot rewrite files or interact with a database easily. &lt;/p&gt;

&lt;p&gt;To resolve this, the recommended approach for hobbyists like myself is to use an Apache distribution:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.apachefriends.org/download.html"&gt;XAMPP&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.wampserver.com/en/"&gt;WAMPServer&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;LAMP (Linux)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The above are all tech stacks with PHP, MySQL, and Apache. The Apache server will read the &lt;code&gt;.htaccess&lt;/code&gt; file before serving a page, which means you can make more user-friendly URL names. &lt;/p&gt;

&lt;h1&gt;
  
  
  The Problem
&lt;/h1&gt;

&lt;p&gt;And now comes a problem. You can only run one server at a time using Apache, so let's say you choose the front-end. &lt;/p&gt;

&lt;p&gt;What do you do with the back-end? My initial reaction when trying this out myself was to use the PHP command for this. &lt;/p&gt;

&lt;p&gt;This works, only partly. The REST API also uses url rewrites on the live server, and I want to make it as close as possible so I can minimize or even eliminate "development mode" conditionals. &lt;/p&gt;

&lt;h1&gt;
  
  
  The Solution
&lt;/h1&gt;

&lt;p&gt;The solution is to use a &lt;code&gt;router.php&lt;/code&gt; file. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

chdir(__DIR__);
$filePath = realpath(ltrim($_SERVER["REQUEST_URI"], '/'));
if ($filePath &amp;amp;&amp;amp; is_dir($filePath)){
    // attempt to find an index file
    foreach (['index.php', 'index.html'] as $indexFile){
        if ($filePath = realpath($filePath . DIRECTORY_SEPARATOR . $indexFile)){
            break;
        }
    }
}
if ($filePath &amp;amp;&amp;amp; is_file($filePath)) {
    // 1. check that file is not outside of this directory for security
    // 2. check for circular reference to router.php
    // 3. don't serve dotfiles
    if (strpos($filePath, __DIR__ . DIRECTORY_SEPARATOR) === 0 &amp;amp;&amp;amp;
        $filePath != __DIR__ . DIRECTORY_SEPARATOR . 'router.php' &amp;amp;&amp;amp;
        substr(basename($filePath), 0, 1) != '.'
    ) {
        if (strtolower(substr($filePath, -4)) == '.php') {
            // php file; serve through interpreter
            include $filePath;
        } else {
            // asset file; serve from filesystem
            return false;
        }
    } else {
        // disallowed file
        header("HTTP/1.1 404 Not Found");
        echo "404 Not Found";
    }
} else {
    // rewrite to our index file
    include __DIR__ . DIRECTORY_SEPARATOR . 'index.php';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I then ran &lt;code&gt;php -S localhost:8100 router.php&lt;/code&gt; in the root directory of my API. &lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;And &lt;em&gt;Voila!&lt;/em&gt; I was able to communicate between the front-end and back-end server without needing to deploy until I was ready!&lt;/p&gt;

&lt;p&gt;Here is the StackOverflow question that helped to this solution: &lt;a href="https://stackoverflow.com/questions/27381520/php-built-in-server-and-htaccess-mod-rewrites"&gt;https://stackoverflow.com/questions/27381520/php-built-in-server-and-htaccess-mod-rewrites&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I hope you found this post useful. Do you know any alternatives or easier ways to accomplish the same task? Leave a comment down below!&lt;/p&gt;

</description>
      <category>php</category>
      <category>tutorial</category>
      <category>localdevelopment</category>
    </item>
    <item>
      <title>How I Wrote A Background Noise Remover from Start to Finish</title>
      <dc:creator>Varun S</dc:creator>
      <pubDate>Wed, 31 Mar 2021 15:26:23 +0000</pubDate>
      <link>https://forem.com/varuns924/how-i-wrote-a-background-noise-remover-from-start-to-finish-3h9m</link>
      <guid>https://forem.com/varuns924/how-i-wrote-a-background-noise-remover-from-start-to-finish-3h9m</guid>
      <description>&lt;p&gt;How do so many communication apps, like Signal and Telegram, get rid of all the static-y noise and background noise before the sound reaches the other people on the call?&lt;/p&gt;

&lt;p&gt;These companies include noise removal in their software, and in a recent coding project, I wanted to do just that. &lt;/p&gt;

&lt;p&gt;In this article, I will break down what I needed, how I made it, and the obstacles I faced along the way.&lt;/p&gt;

&lt;p&gt;When I say ambient noise, background noise, or simply, noise, I am talking about sound that you do not want to hear in an audio file. This sound disrupts the signal, sound you do want to hear, in an audio file or incoming sound.&lt;/p&gt;

&lt;p&gt;My plan was to somehow identify the noise so I could filter it out, then write the noise-removed-audio file to an "output" file once the program did its main functions so that I could compare and collect data. &lt;/p&gt;

&lt;h1&gt;
  
  
  Research
&lt;/h1&gt;

&lt;p&gt;Researching this was hard. It took me a while, but I found a &lt;a href="https://kalmanfilter.net" rel="noopener noreferrer"&gt;tutorial on the Kalman Filter&lt;/a&gt;. This explained all the background knowledge needed to understand the Kalman Filter, explained the Kalman Filter, and gave examples. &lt;/p&gt;

&lt;p&gt;The Kalman Filter has two types: One-Dimensional and Multi-Dimensional. The Multi-Dimensional Kalman Filter involves linear algebra concepts that I had to learn. So, I started learning linear algebra concepts and buried myself in lengthy research papers on the covariance matrix and eigenvectors. &lt;/p&gt;

&lt;p&gt;I eventually found that the only concepts needed for the Kalman Filter with regards to linear algebra were matrices, vectors, and their operations. I also found a helpful &lt;a href="https://www.youtube.com/watch?v=152tSYtiQbw" rel="noopener noreferrer"&gt;video&lt;/a&gt; on the covariance matrix that explained what the research papers were describing, in 10 minutes. &lt;/p&gt;

&lt;p&gt;In addition, I learned the Java Sound API on Oracle's &lt;a href="https://docs.oracle.com/javase/8/docs/technotes/guides/sound/programmer_guide/contents.html" rel="noopener noreferrer"&gt;official programming guide&lt;/a&gt; so that I could use Java to apply the Kalman Filter to sound. Unfortunately, the Java Sound API did not provide the low-level functions that I needed. The only useful function was the byte data, which is binary data that represents the sound, of the audio file. I then had to use Linear Pulse Code Modulation to determine the sound wave, and then apply the Kalman Filter from there.&lt;/p&gt;

&lt;h2&gt;
  
  
  Kalman Filter
&lt;/h2&gt;

&lt;p&gt;The Kalman Filter is an estimation algorithm that lets you find the value of an object that you may never know for sure, called a "hidden state" but get very close to it by measuring the object and going through a series of equations that lets you &lt;em&gt;converge&lt;/em&gt; to the true value.&lt;/p&gt;

&lt;p&gt;For example, if you want to use the Kalman Filter to find the weight of a bronze Trojan horse, its hidden state might be 200kg (because of all the men inside) and your &lt;strong&gt;final state estimate&lt;/strong&gt;, which is what you get when you put your measurement through a bunch of equations, is 198.4 kg. &lt;/p&gt;

&lt;p&gt;In the Kalman Filter, every time you &lt;strong&gt;measure&lt;/strong&gt;, you &lt;strong&gt;update&lt;/strong&gt; your state estimate using an equation. Then, you &lt;strong&gt;predict&lt;/strong&gt; the next state estimate, which you calculate after your next measurement. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flyb8no1unvveap4lk85r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Flyb8no1unvveap4lk85r.png" alt="Prediction Correction Mechanism"&gt;&lt;/a&gt;&lt;br&gt;
The Kalman Filter uses the prediction-correction mechanism. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiw23kfw6jbvynntenz7s.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiw23kfw6jbvynntenz7s.png" alt="Kalman Filter Algorithm"&gt;&lt;/a&gt;&lt;br&gt;
The Kalman Filter follows the "measure, update, predict" cycle.&lt;/p&gt;

&lt;h3&gt;
  
  
  How it Works
&lt;/h3&gt;

&lt;p&gt;Going back to the Trojan Horse example, let's say you set your initial guess to 100kg. The sole purpose of the initial guess is to get the cycle started. &lt;/p&gt;

&lt;p&gt;In addition, you need to set your initial guess for the &lt;strong&gt;estimate uncertainty.&lt;/strong&gt; In other words, use a number between 0 and 1 representing how uncertain you are about 100kg being the hidden state.&lt;/p&gt;

&lt;p&gt;Then, you finish the "0th" iteration of the Measure, Update, Predict cycle. These initial guesses are the "estimates," so now you need to make the prediction. Because you don't have a measurement yet, the predictions are the same as the estimate, and they are going to be used in the 1st iteration. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;You put the Trojan Horse on a scale and you see "195kg." This is your measurement&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Calculate the Kalman Gain. As this factor increases, the measurement is given more weight and as it decreases, the measurement is given less weight and the estimate is given more weight, as shown below. &lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fes9z3ci53ie6yu3yzh64.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fes9z3ci53ie6yu3yzh64.png" alt="Kalman Gain Equation"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Kalman Gain Equation&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The Kalman Gain uses the &lt;strong&gt;estimate uncertainty&lt;/strong&gt; and the &lt;strong&gt;measurement uncertainty&lt;/strong&gt; in its calculation. The measurement uncertainty is a constant value between 0 and 1 that you set in the beginning. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Now, plugging in the prediction from the 0th iteration (the previous state prediction) - 100kg - and your current measurement - 195kg - into the &lt;strong&gt;State Update Equation&lt;/strong&gt;, you get your &lt;strong&gt;state estimate&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frlguam7ze4yxjjirnmu8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frlguam7ze4yxjjirnmu8.png" alt="State Update Equation"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;em&gt;State Update Equation&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Next, you &lt;strong&gt;update&lt;/strong&gt; the estimate uncertainty with another equation, the &lt;strong&gt;Covariance Update Equation.&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Finally, you &lt;strong&gt;predict&lt;/strong&gt; the next estimate and the next estimate uncertainty using the final 2 equations in the Kalman Filter algorithm.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;And that's the cycle for the One Dimensional Kalman Filter. You can make it even simpler by ignoring the uncertainty. You now make another measurement and keep cycling through until you've made all the measurements you would like. &lt;/p&gt;

&lt;p&gt;When you graph the estimate and hidden state as the y values and the iteration # as the x-value, you'll see the estimate converge to the true value. &lt;/p&gt;

&lt;h3&gt;
  
  
  Implementing the Kalman Filter
&lt;/h3&gt;

&lt;p&gt;The kalmanfilter package was the first module I worked on after experiment a little bit with the Java Sound API (and mostly failing). Because I love to code, I didn't even implement the Kalman Filter first. I implemented simpler filters that also follow the "measure, update, predict" cycle: &lt;code&gt;AlphaFilter&lt;/code&gt;, &lt;code&gt;AlphaBetaFilter&lt;/code&gt;, and &lt;code&gt;AlphaBetaGammaFilter&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Following test-driven development, I tested these with the values in the examples from the same site that taught me the filters themselves: &lt;a href="https://kalmanfilter.net" rel="noopener noreferrer"&gt;kalmanfilter.net&lt;/a&gt;. I made the right decision testing, for I immediately faced lots of failing tests because of lots of bugs. &lt;/p&gt;

&lt;p&gt;In addition to giving me testing experience, of which I have very little, implementing similar and simpler filters helped me hammer out the bugs that would likely have appeared in the Kalman Filter had I started with that. Starting off simpler let me focus on the more complicated bugs when I finally got to the more complicated filters. &lt;/p&gt;

&lt;h2&gt;
  
  
  Linear Pulse Code Modulation and Sound Manipulation
&lt;/h2&gt;

&lt;p&gt;Sound files use a format called Linear Pulse Code Modulation to represent sound as numbers. At a specified &lt;strong&gt;sample rate&lt;/strong&gt;, the bytes of data are specific amplitudes, and together they make sine waves, which is how sound is represented. &lt;/p&gt;

&lt;p&gt;At first, I thought that the byte data itself were the samples that could be directly converted to sine waves. When the audio file was corrupted and produced unintelligible noise. &lt;/p&gt;

&lt;p&gt;More than two months into my project, I discovered an algorithm on Stack Overflow that let me abstract the [bitwise operations], the intermediate step between the byte data and the sine waves which I knew how to manipulate. &lt;/p&gt;

&lt;p&gt;And these worked like a charm! Increase the a value (amplitude) and its louder, increase the product inside the &lt;code&gt;Math.sin()&lt;/code&gt; and the pitch goes higher. I could then combine &lt;code&gt;float&lt;/code&gt; (a data type for decimal numbers) samples together to add sine or sound waves. &lt;/p&gt;

&lt;p&gt;And when I added an amplitude and its negative, I got the expected silence. This is called destructive interference - when you add a sound sine wave and the inverse sine wave together. In mathematical terms, you got a horizontal line, and in sound terms, that's complete silence. &lt;/p&gt;

&lt;h2&gt;
  
  
  Modeling Matrices and Vectors
&lt;/h2&gt;

&lt;p&gt;The multidimensional Kalman Filter uses &lt;a href="https://en.wikipedia.org/wiki/Matrix_(mathematics)" rel="noopener noreferrer"&gt;matrices&lt;/a&gt;, which are rectangular arrays of numbers, and vectors, which are single-dimensional arrays of numbers. I had the most fun building this because I was working with a concept that I had already been introduced to in school, and I was using Java syntax that I was familiar with.&lt;/p&gt;

&lt;p&gt;I created a Matrix class that held a two dimensional array for the matrix and a Vector class that extends the Matrix class and held a one dimensional array. &lt;/p&gt;

&lt;p&gt;Following test-driven development, I first made a Matrix test class and VectorTest class. &lt;/p&gt;

&lt;p&gt;For the matrix addition test, I called my &lt;code&gt;Matrix#add()&lt;/code&gt; method on the first matrix passing in the second matrix. I then checked if the sum matrix was the correct value by creating a third &lt;code&gt;Matrix&lt;/code&gt; object. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Test
public void testMatrixAddition() {
    Matrix addend = new Matrix(new double[][] { { 1, 2, 3 }, { 4, 5, 6 } });
    Matrix augend = new Matrix(new double[][] { { 10, 14, -8 }, { 3, 1, 5 } });

    Matrix sum = addend.plus(augend);

    assertArrayEquals(new double[][] { { 11, 16, -5 }, { 7, 6, 11 } }, sum.getMatrixElements());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

public Matrix plus(Matrix augend) {
    if (!(getRows() == augend.getRows() &amp;amp;&amp;amp; getColumns() == augend.getColumns()))
        throw new IllegalArgumentException("Cannot add matrices of different dimensions");
     Matrix toReturn = new Matrix(new double[getRows()][getColumns()]);

    for (int i = 0; i &amp;lt; getRows(); i++) {
        for (int j = 0; j &amp;lt; getColumns(); j++) {
            toReturn.set(i, j, matrixElements[i][j] + augend.getMatrixElements()[i][j]);
        }
    }

    return toReturn;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;After implementing &lt;code&gt;Matrix#add&lt;/code&gt;, I continued for the subtraction, multiplication, inverse (which was so complicated I ended up extracting into its own class), and transpose operations, each time testing before implementing. I also included various methods concerning properties of the matrix, such as&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;getDeterminant()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;isSquare()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;isIdentityMatrix()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;isInverse(Matrix inverse)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Finally, I implemented static factory methods for generic matrix types, which right now is only for the identity matrix, which is where 1's span the major diagonal and everything else in the matrix is a zero, and it is a square matrix. For example, the 3x3 identity matrix is [[1,0,0],[0,1,0],[0,0,1]]&lt;/p&gt;

&lt;h2&gt;
  
  
  Results
&lt;/h2&gt;

&lt;p&gt;When I got rid of all &lt;code&gt;Math.random()&lt;/code&gt;s, &lt;code&gt;NullPointerException&lt;/code&gt;s and &lt;code&gt;UnsupportedOperationException&lt;/code&gt;s, which stopped my program from fully running, I found no change in the audio file. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Ambient Noise Remover was a huge challenge, and I have not successfully removed background noise, yet. I, however, learned so much from the experience, from sound engineering to linear algebra to Java APIs. &lt;/p&gt;

&lt;p&gt;Here is the link to the code (open source!): &lt;a href="https://github.com/Ambient-Noise-Remover" rel="noopener noreferrer"&gt;https://github.com/Ambient-Noise-Remover&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;It is also available as a JAR file, just make sure you have installed the Java JDK before downloading my program!&lt;/p&gt;

&lt;p&gt;If you'd like to learn the Kalman Filter in detail, I suggest the tutorial website (&lt;a href="https://kalmanfilter.net" rel="noopener noreferrer"&gt;https://kalmanfilter.net&lt;/a&gt;), as it explains everything very simply. &lt;/p&gt;

&lt;p&gt;Thanks for reading my article! Do you have a project that involves a complex math topic, such as linear algebra? Leave a link to it in the comments!&lt;/p&gt;

</description>
      <category>java</category>
      <category>showdev</category>
      <category>tutorial</category>
      <category>noiseremoval</category>
    </item>
    <item>
      <title>How I Documented, Encrypted, and Tested My First REST API</title>
      <dc:creator>Varun S</dc:creator>
      <pubDate>Mon, 11 Jan 2021 02:30:19 +0000</pubDate>
      <link>https://forem.com/varuns924/how-i-documented-encrypted-and-tested-my-first-rest-api-e06</link>
      <guid>https://forem.com/varuns924/how-i-documented-encrypted-and-tested-my-first-rest-api-e06</guid>
      <description>&lt;p&gt;I added a lot more to my REST API than just the JSON responses. Borum Jot was the first project I tried seriously unit testing my code, encrypting the data, and documenting my back-end. In this article, I will discuss cybersecurity, software testing, and documentation of my REST API.&lt;/p&gt;

&lt;h1&gt;
  
  
  Encryption
&lt;/h1&gt;

&lt;p&gt;I encrypted my data using &lt;a href="https://github.com/defuse/php-encryption/" rel="noopener noreferrer"&gt;defuse/php-encryption&lt;/a&gt;. This library, claiming to be secure, unlike other libraries, did the encryption and decryption for me. To encrypt and decrypt, I needed my own key, which I generated by running&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ composer require defuse/php-encryption
$ vendor/bin/generate-defuse-key
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Composer is a package manager for PHP applications. The key is 256 bits long and can be stored either in a file (unsecure), or in the environmental variables. Vercel has a built-in way of storing environmental variables, and was the best place, without extra tools, for me to store the key. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Truthfully, I stored the key in a text file in the &lt;code&gt;etc&lt;/code&gt; folder in the root directory because I didn't realize I could store it in the &lt;code&gt;$_ENV&lt;/code&gt; at the time. This is highly insecure, so I am going to move this into a secure environmental variable soon&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Then, at each request that updated or created data that I wanted to encrypt - task and note details - I loaded the key and called the encryption function. Similarly, for each request that fetched data that I encrypted, I loaded the key and decrypted before sending the response. This way, the front-ends never had to worry about encryption or decryption because I wrote everything on the backend, once. &lt;/p&gt;

&lt;h1&gt;
  
  
  Documentation
&lt;/h1&gt;

&lt;p&gt;To document my APIs, I got inspiration from the Stack Exchange API documentation. I used &lt;a href="https://nextjs.org" rel="noopener noreferrer"&gt;NextJS&lt;/a&gt; to make a static documentation site for the entire Borum ecosystem, including Borum Jot. Then, for each page, I specified the request method, request headers, query string, request body (for POST, PUT, and DELETE requests), and response body. &lt;/p&gt;

&lt;p&gt;Here is a given page of my developer documentation website, which is &lt;a href="https://developer.bforborum.com" rel="noopener noreferrer"&gt;live&lt;/a&gt;, hosted by Vercel, and &lt;a href="https://github.com/Borumer/Borum-Dev-Documentation" rel="noopener noreferrer"&gt;open-source on GitHub&lt;/a&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fjb9wvigr2allyt7ehqa3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fjb9wvigr2allyt7ehqa3.png" alt="A sample Borum Jot endpoint API reference on my Borum Dev Documentation site"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;A sample Borum Jot endpoint API reference on my Borum Dev Documentation site&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Because I am fluent in JavaScript, I did not have any trouble setting up the documentation site. I have a JSON file with data on each endpoint that I update whenever I update the Borum Jot REST API. &lt;/p&gt;

&lt;p&gt;I suggest including the following as a bare minimum when documenting REST or other Web API's: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Request Headers&lt;/li&gt;
&lt;li&gt;Request Query String&lt;/li&gt;
&lt;li&gt;Request Method&lt;/li&gt;
&lt;li&gt;Request Body&lt;/li&gt;
&lt;li&gt;Response Body&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Testing
&lt;/h1&gt;

&lt;p&gt;I used &lt;a href="https://phpunit.de/" rel="noopener noreferrer"&gt;PHPUnit&lt;/a&gt;, a PHP unit-testing framework, and &lt;a href="https://docs.guzzlephp.org/en/stable/" rel="noopener noreferrer"&gt;GuzzleHttp&lt;/a&gt;, a PHP HTTP client, to unit test my application. GuzzleHttp acts as a client to the REST API server, making requests and asserting information about the responses.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;namespace BorumJot\Tests;

use PHPUnit\Framework\TestCase;
use GuzzleHttp\Client;

class LoginTest extends TestCase {
    private $http;

    public function setUp() : void {
        $this-&amp;gt;http = new Client(["base_uri" =&amp;gt; "https://api.jot.bforborum.com/api/v1/"]);
    }

    public function testPost() {
        $response = $this-&amp;gt;http-&amp;gt;post('login');

        $this-&amp;gt;assertEquals(200, $response-&amp;gt;getStatusCode());

        $contentType = $response-&amp;gt;getHeaders()["Content-Type"][0];
        $this-&amp;gt;assertEquals("application/json; charset=UTF-8", $contentType);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The TestCase is a superclass in PHPUnit that indicates that the class contains test cases. The &lt;code&gt;setUp()&lt;/code&gt; method is called by PHPUnit before each test. GuzzleHttp's &lt;code&gt;Client&lt;/code&gt; class's "request-method methods" (like &lt;code&gt;.get()&lt;/code&gt; and &lt;code&gt;.post()&lt;/code&gt;) provide information on the response, such as the headers and status code as shown above. &lt;/p&gt;

&lt;h2&gt;
  
  
  Setting Up Unit Testing
&lt;/h2&gt;

&lt;p&gt;First I had to run &lt;code&gt;composer install phpunit/phpunit guzzlehttp/guzzle&lt;/code&gt; to install the PHPUnit and GuzzleHttp packages. &lt;/p&gt;

&lt;p&gt;I added the following to composer.json into the top-level object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"scripts": {
   "test": "phpunit tests"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will substitute phpunit tests for composer test. It is a common practice to substitute the unit testing framework command for the package manager's command to have one command prefix to rule them all. However, this is not necessary, for you could simply run phpunit tests.&lt;/p&gt;

&lt;p&gt;The last step is to configure phpunit to find the folder with all the unit tests. I put mine in the root directory and called it &lt;code&gt;tests&lt;/code&gt;, but you can call it and place it anywhere you would like, except maybe in auto-generated folders.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;phpunit bootstrap="vendor/autoload.php"&amp;gt;
    &amp;lt;testsuites&amp;gt;
        &amp;lt;testsuite name="Borum Jot REST API Test Suite"&amp;gt;
            &amp;lt;directory suffix=".php"&amp;gt;./tests/&amp;lt;/directory&amp;gt;
        &amp;lt;/testsuite&amp;gt;
    &amp;lt;/testsuites&amp;gt;
&amp;lt;/phpunit&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace &lt;code&gt;./tests/&lt;/code&gt; with the path to the folder with the unit tests. The test suite is an arbitrary name you give to a group of tests to identify it. &lt;/p&gt;

&lt;p&gt;And that's how I documented, tested, and encrypted the data of my first REST API. Have you ever documented your own API? What tools did you use? Share your own projects down below!&lt;/p&gt;

</description>
      <category>cybersecurity</category>
      <category>testing</category>
      <category>documentation</category>
      <category>restapi</category>
    </item>
    <item>
      <title>How I Wrote My First Web API</title>
      <dc:creator>Varun S</dc:creator>
      <pubDate>Wed, 16 Dec 2020 13:14:31 +0000</pubDate>
      <link>https://forem.com/varuns924/how-i-wrote-my-first-web-api-37jp</link>
      <guid>https://forem.com/varuns924/how-i-wrote-my-first-web-api-37jp</guid>
      <description>&lt;p&gt;As part of my &lt;a href="https://jot.bforborum.com"&gt;Borum Jot&lt;/a&gt; project, I made a Web API for all my front-end platforms to create, retrieve, update, and delete (CRUD) data on the database. In this article, I'll discuss what exactly an API is and how I made my own Web API. &lt;/p&gt;

&lt;p&gt;There are two main kinds of APIs. &lt;/p&gt;

&lt;p&gt;One is a &lt;strong&gt;software and its documentation&lt;/strong&gt;, and this is used &lt;em&gt;very&lt;/em&gt; liberally. For example, the old JavaScript library jQuery has a documentation so developers know how to use it. This documentation web site is referred to as the jQuery API. Other examples are documentations for &lt;a href="https://docs.oracle.com/javase/7/docs/api/"&gt;programming languages&lt;/a&gt;, &lt;a href="https://reactjs.org/docs/react-dom.html"&gt;frameworks&lt;/a&gt;, or even &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/"&gt;ecosystems&lt;/a&gt;. It is usually specified in the URL, even if it's not directly on the page. &lt;/p&gt;

&lt;p&gt;Thanks to &lt;a href="https://twitter.com/mankms"&gt;@mankms on Twitter&lt;/a&gt;, I learned that a &lt;strong&gt;Web API&lt;/strong&gt; refers to sets of pages to which clients make network requests, and they return back data, possibly querying a database, in a specific structure.  I like to think of a Web API as part of a filtration system:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kxW9w_KN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/r495o1f51nzi54e4vjkx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kxW9w_KN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/r495o1f51nzi54e4vjkx.png" alt="API as a filtration system"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This concept is called information hiding, and it is important for simplicity and security. But before I could begin hiding information, I had to obtain information. I began by choosing a language. &lt;/p&gt;

&lt;h1&gt;
  
  
  Choosing a Language and Content Type
&lt;/h1&gt;

&lt;p&gt;I used PHP, a back-end language, for my API. A back-end language sits on the server and accesses data. &lt;/p&gt;

&lt;p&gt;I used JSON, or JavaScript Object Notation, for the content type. It is used to represent data in nested objects. In my API, I sent JSON that looked like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "statusCode": 200,
    "data": [
        {
            "id": "10",
            "title": "Go to Grocery Store",
            "body": "Go to this grocery store",
            "user_id": "115",
            "completed": "1",
            "time_updated": "1038829292",
            "parent_id": "0",
            "priority": "0",
            "source": "task"
        }
    ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Once the client receives the above response and parses the JSON, it can retrieve the value of any property, such as &lt;code&gt;statusCode&lt;/code&gt;.&lt;/p&gt;
&lt;h1&gt;
  
  
  Host Configuration and File Structure
&lt;/h1&gt;

&lt;p&gt;I now knew I was writing in PHP to make a Web API that sends JSON to a client (the front-end). Surprisingly, where I hosted was very important at this point. I deployed on &lt;a href="https://vercel.com"&gt;Vercel&lt;/a&gt;, a hosting platform. Although Vercel is designed for JavaScript and React-type projects, the &lt;a href="https://github.com/juicyfx/vercel-php"&gt;vercel-php&lt;/a&gt; runtime allows developers to host backend PHP projects on a secure domain (as opposed to directly on the domain registrar, which may require configuring GitHub, paying for an SSL certificate, etc.). &lt;/p&gt;

&lt;p&gt;Because I was deploying on Vercel, I needed to store all the &lt;em&gt;endpoints&lt;/em&gt; in the api directory and configure the &lt;code&gt;now.json&lt;/code&gt; file. The &lt;code&gt;now.json&lt;/code&gt; file tells vercel-php which files were serverless functions. These serverless functions served as the API endpoints that sent the response data in JSON format. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--N7CX9kP9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/4ibd3j4wptb69y96brb6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--N7CX9kP9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/4ibd3j4wptb69y96brb6.png" alt="Vercel Function Logs"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Vercel Function Logs&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In addition, I've seen APIs specify their version (e.g. v1). So far, this was my file structure (note the composer.json is for including PHP libraries)&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;api/
    v1/
       ?
now.json
composer.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;What would go inside the v1 subdirectory?&lt;/p&gt;
&lt;h1&gt;
  
  
  Writing my First Endpoint
&lt;/h1&gt;

&lt;p&gt;Finally, I could begin writing the code (the fun part!).&lt;/p&gt;

&lt;p&gt;In its simplest form, a Web API is one PHP file that returns the JSON, such as one of the examples above, on every request.&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php 

header("HTTP/1.1 200 OK");
header("Content-Type: application/json; charset=UTF-8");

echo json_encode(["english" =&amp;gt; "Hello world!", "french" =&amp;gt; "Bonjour!", "german" =&amp;gt; "Guten tag!"];

?&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Notice the header function calls, establishing the server response headers. The &lt;code&gt;200 OK&lt;/code&gt; is an HTTP Status Code that tells the client that everything ran okay and it can now access the data. The &lt;code&gt;json_encode&lt;/code&gt; turns a PHP Associative Array into JSON format. The API deploys through Vercel and has the following as its &lt;code&gt;now.json&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "functions": {
    "api/v1/*.php": {
      "runtime": "vercel-php@0.3.1"
    },
  },
  "routes": [ 
   { "src": "/v1/greeting", "dest": "/v1/greeting.php" }
  ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The &lt;code&gt;functions&lt;/code&gt; object specifies the directories that have API endpoints and will always have the same runtime property. The &lt;code&gt;routes&lt;/code&gt; array contains paths at the location of &lt;code&gt;dest&lt;/code&gt; that rewrite the url to &lt;code&gt;src&lt;/code&gt;. In the above example, &lt;code&gt;/v1/greeting.php&lt;/code&gt; simply becomes &lt;code&gt;/v1/greeting&lt;/code&gt;. &lt;/p&gt;


&lt;h1&gt;
  
  
  Helper Classes and Added Complexity
&lt;/h1&gt;

&lt;p&gt;The second level of complexity was to interact with the database. I created a separate folder called &lt;code&gt;include&lt;/code&gt; and put it in the &lt;code&gt;api&lt;/code&gt; directory in case I wanted to have a &lt;code&gt;v2&lt;/code&gt;. Remember, putting everything in one file still makes it an API, but I put database handling in a separate class to make my code &lt;a href="https://en.wikipedia.org/wiki/Don't_repeat_yourself"&gt;DRY&lt;/a&gt; and modular. When I have more than one response object (such as a GET and POST request to the same endpoint, or multiple endpoints), I could call code I had already written. My modified file structure looked like this:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;api/
    include/
       Config.php
       SimpleRest.php
       DBHandler.php  
    v1/
       greeting.php
now.json
composer.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;I copied the &lt;code&gt;SimpleRest&lt;/code&gt; code from &lt;a href="https://www.dropbox.com/s/eob6p9su51t6wsz/fragrances.zip?dl=0&amp;amp;file_subpath=%2Ffragrances%2FSimpleRest.php"&gt;another site&lt;/a&gt;, expanding to fit to my  API. &lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;For every response from this point, I had only to call &lt;code&gt;SimpleRest::setHttpHeaders(200)&lt;/code&gt; or another status code, replacing multiple &lt;code&gt;header()&lt;/code&gt; calls with one method call of my own class. &lt;/p&gt;

&lt;h2&gt;
  
  
  Database Interaction
&lt;/h2&gt;

&lt;p&gt;First and foremost is a Config.php file for database interaction. I used the &lt;code&gt;mysqli_connect()&lt;/code&gt; call to connect with my database credentials to the MySQL database I host on GoDaddy. Next, I stored the PHP Connection object inside an instance variable named &lt;code&gt;$conn&lt;/code&gt; in the &lt;code&gt;DBHandler&lt;/code&gt; class in the constructor. &lt;/p&gt;

&lt;p&gt;For every database-querying function, I wrote an instance method in the DBHandler class. Once my database, app, and API got larger, I expanded this into its own folder and namespace, but for now, I could keep everything in one class. &lt;/p&gt;

&lt;p&gt;For instance, I wrote the &lt;code&gt;createNewUser()&lt;/code&gt; method for a POST request to the &lt;code&gt;register.php&lt;/code&gt; endpoint. Below is the code of this method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function createNewUser($firstname, $lastname, $email, $password) {
        if ($this-&amp;gt;newUserValid($email)) {
            $query = "INSERT INTO firstborumdatabase.users 
                (first_name, last_name, email, pass, registration_date) 
                VALUES ('$firstname', '$lastname', '$email', SHA2('$password', 512), NOW())
            ";
            $newBorumUserResult = $this-&amp;gt;executeQuery($query);
            if (mysqli_affected_rows($dbc) == 1) { # Query ran okay
                $accountId = $this-&amp;gt;executeQuery("SELECT id FROM firstborumdatabase.users ORDER BY registration_date DESC LIMIT 1");
                $accountId = mysqli_fetch_array($accountId, MYSQLI_BOTH);
                $apikey = $this-&amp;gt;generateApiKey();

                // If the generated api key is taken, keep generating until a unique one is found
                while ($this-&amp;gt;apiKeyExistsInDatabase($apikey) != true) {
                    $apikey = $this-&amp;gt;generateApiKey();
                }

                // Insert the newly created Borum user into the Borum Jot `users` table
                $newBorumJotUserResult = $this-&amp;gt;executeQuery("INSERT INTO users (borum_user_id, time_created, api_key) VALUES ($accountId, NOW(), '$apikey')");
                if (mysqli_affected_rows($dbc) == 1) { # Query ran okay
                    return [
                        "ok" =&amp;gt; true,
                        "statusCode" =&amp;gt; 200
                    ];
                }
            }             
            return [
                "error" =&amp;gt; [
                    "message" =&amp;gt; "The user could not be validated at this time"
                ],
                "statusCode" =&amp;gt; 500
            ];
        } else {
            return [
                "error" =&amp;gt; [
                    "message" =&amp;gt; "User with that email already exists on Borum"
                ],
                "statusCode" =&amp;gt; 500
            ];
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in the endpoint file, I would call it and my helper methods inside of one case of a switch statement that checks the request method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;case 'POST':
        SimpleRest::handlePostParameterValidation("name");

        $newnoteres = $handler-&amp;gt;createNote($_POST['name']);

        SimpleRest::setHttpHeaders($newnoteres["statusCode"]);
        echo json_encode($newnoteres);
break;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;$handler&lt;/code&gt; variable instantiates a new &lt;code&gt;DBHandler&lt;/code&gt; object (or a subclass of that). I put a &lt;code&gt;statusCode&lt;/code&gt; property in each JSON response so I could easily set the status code header. &lt;/p&gt;

&lt;p&gt;And that's what I did for every new response that I needed to create - I made a new method that queried the database in a &lt;code&gt;DBHandler&lt;/code&gt; class. If you know how to use PHP with MySQL, and you followed everything described above, you're ready to make your own Web API! &lt;/p&gt;

&lt;p&gt;Don't I have to document it? What about unit tests? Stay tuned for Part 2, where I'll be covering all of this and more! &lt;/p&gt;

</description>
      <category>php</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How I wrote my first full-stack Android app</title>
      <dc:creator>Varun S</dc:creator>
      <pubDate>Sun, 29 Nov 2020 21:47:49 +0000</pubDate>
      <link>https://forem.com/varuns924/how-i-wrote-my-first-full-stack-android-app-2c11</link>
      <guid>https://forem.com/varuns924/how-i-wrote-my-first-full-stack-android-app-2c11</guid>
      <description>&lt;p&gt;In the span of 4 months, I planned out a mobile app idea, self-taught myself the Android framework, wrote my first REST API, and released my finished Android app on the Google Play Store. I learned a lot along the way, so I thought I'd share what I learned.&lt;/p&gt;

&lt;p&gt;The app I made was a to-do app combined with a note-taking app. Users would be able to filter out and in their notes and tasks as they please, and maybe I'd even allow them to convert a task to a note, and vice versa. &lt;/p&gt;

&lt;p&gt;This project had 5 major components: Preparation, Front-end, Back-end, Unit Testing, and Play Store Releasing. Below are all the things that helped me make my app. &lt;/p&gt;

&lt;h1&gt;
  
  
  Preparation
&lt;/h1&gt;

&lt;p&gt;Even though I did not know a line of Android code, I knew that one could write an Android app in Java. I knew a lot of languages, but didn't know the frameworks for many of them, rendering my knowledge of most of them useless. Learning Android was a chance for me to make Java a useful language for me by getting into mobile app development. &lt;/p&gt;

&lt;p&gt;I used &lt;a href="https://www.tutorialspoint.com/android/index.htm" rel="noopener noreferrer"&gt;TutorialsPoint&lt;/a&gt;  to learn XML and Java within the Android framework. In addition to taking notes, I coded along with the tutorial to make one giant app that didn't really do anything, but demonstrated everything I learned. &lt;/p&gt;

&lt;p&gt;Meanwhile, I was looking for a good wireframing desktop app. Wireframing is a set of sketches for an app that shows the &lt;strong&gt;structure&lt;/strong&gt; and the &lt;strong&gt;layout&lt;/strong&gt;. I was starting to focus on user interface more in my projects, and I had started employing more software development skills. I read up on how to plan a mobile app, and after sketching a few screens in my paper notebook, I found &lt;a href="https://pencil.evolus.vn/" rel="noopener noreferrer"&gt;Pencil&lt;/a&gt;. It was lightweight, but some other developers said they prefer lightweight software for wireframing, so I went with it. It's also free of charge, another criterion for which I was searching. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1606188260968%2FuZ7iAAoUT.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1606188260968%2FuZ7iAAoUT.jpeg" alt="i7pqE6A-o.jpg"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;My low-fidelity wireframe on paper of Borum Jot &lt;/p&gt;

&lt;p&gt;The benefit of going through multiple stages before beginning coding, is, especially for a brand new platform, I could make the critical design choices here so that I could focus on functionality when I finally got to coding. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1606169997127%2FueqSBOFH0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1606169997127%2FueqSBOFH0.png" alt="image.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Pencil was what I considered my high-fidelity, or "hi-fi", wireframe. I actually drew almost every screen, but I didn't focus on the color theme. I just wanted to figure out &lt;strong&gt;how and where&lt;/strong&gt; I would &lt;strong&gt;lay out&lt;/strong&gt; the features. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1606171144510%2FaDTtOqB0Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1606171144510%2FaDTtOqB0Q.png" alt="image.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Next, I moved on to my mockup. I knew that this was still a personal project that only so many people would look at, so I chose the same software for mockup as I did for prototype: Adobe XD. Adobe XD is a powerful free Windows app for making mockups and prototypes. The thing is, it has a learning curve. After watching tutorials, I was well on my way to...&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1606170998203%2FfWl96Wbow.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1606170998203%2FfWl96Wbow.png" alt="image.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And for the prototype, I wired the "artboards" together in Adobe XD. The rectangles were perfectly aligned, the colors were exactly how I planned it to look, and the prototype functioned to the good extent that a dataless software could. &lt;/p&gt;

&lt;p&gt;After two months of planning and learning, I was ready to begin my app.&lt;/p&gt;

&lt;h1&gt;
  
  
  Front End
&lt;/h1&gt;

&lt;p&gt;I started with the XML, of course. The XML layout files were the &lt;strong&gt;markup&lt;/strong&gt;, meaning they didn't really use logic. I made one activity (that's what Android calls a screen) a day, and in around 2 weeks, I had nearly imitated my mockup (except for a lot of the details within, for example, the task screen). &lt;/p&gt;

&lt;p&gt;Next, I worked on implementing navigation between the activities using Java. I didn't worry about any data fetching, just on UI, including styles and logic. And for almost every non-lifecycle Java method I wrote, I attached a multiline comment to it. &lt;/p&gt;

&lt;p&gt;%[&lt;a href="https://gist.github.com/Borumer/d76ef92e042f62507e7de5250ffad27d" rel="noopener noreferrer"&gt;https://gist.github.com/Borumer/d76ef92e042f62507e7de5250ffad27d&lt;/a&gt;]&lt;/p&gt;

&lt;p&gt;In even less time, I had successfully mocked a lot of my mockup with actual code. &lt;/p&gt;

&lt;h1&gt;
  
  
  Back End
&lt;/h1&gt;

&lt;p&gt;This was my first time, or so I thought, separating the back end from the front end. I wondered what voodoo magic developers used to create a REST API and an "external API endpoint" and I wanted to make one myself. &lt;/p&gt;

&lt;p&gt;However, it turns out I had already made full-stack web apps before, just not technically REST APIs. I knew PHP and a REST API is simply a set of pages written in a backend language, like PHP, that give either XML, HTML (rare), or JSON output and return the standard HTTP status codes. If one knows how to use PHP to query a database, he or she can make a REST API. &lt;/p&gt;

&lt;p&gt;The key part here is REST, which stands for Representational State Transfer, is an architectural style. No extra classes are required, except those that help the developer give output and set HTTP headers. I created a class called &lt;a href="https://gist.github.com/Borumer/3b15f8075151c77f16127658736fbf10" rel="noopener noreferrer"&gt;RestService&lt;/a&gt; that had a static method for setting the header with a status code, and setting the &lt;code&gt;Content-Type&lt;/code&gt; to &lt;code&gt;application/json&lt;/code&gt;. With classes that queried the database, classes that helped with validation and header sending, and the PHP pages that instantiated and invoked all of their methods, called the API endpoints, I effectively created a REST API. &lt;/p&gt;

&lt;h1&gt;
  
  
  API Deployment
&lt;/h1&gt;

&lt;p&gt;I went back and forth between writing new backend code and writing new frontend code for the remaining two months, except for one hiccup. I used &lt;a href="https://vercel.com" rel="noopener noreferrer"&gt;Vercel&lt;/a&gt;, a great freemium hosting platform, for hosting my API and GoDaddy for the domain. Vercel uses Amazon Web Services to deploy its site, and Amazon Web Services used dynamic, or constantly changing, IP addresses. In order to fetch data from the database I created on my GoDaddy hosting account, I needed to whitelist the IP Address of the API that I made. This created a problem because there &lt;em&gt;was&lt;/em&gt; no specific IP for Vercel's servers. After calls for help, I ended up (very insecurely, but without any other viable option) whitelisting ALL addresses with &lt;code&gt;%.%.%.%&lt;/code&gt; to resolve the issue. &lt;/p&gt;

&lt;h1&gt;
  
  
  Unit Testing
&lt;/h1&gt;

&lt;p&gt;As I mentioned earlier, I wanted to employ techniques used by professional software developers. One of these was software development testing. I had done a course on EdX that covered how to write unit tests, so I wanted to make this a norm for my programming projects. &lt;/p&gt;

&lt;p&gt;Android Studio, the IDE I used for making the front end of the project, has as part of every Android project a folder for testing. The Android framework starts with Mockito and JUnit for unit testing. I wrote a few unit tests for my simpler modules (such as the purely Java ones) and didn't bother with the Context and interface-based ones. Here's an example that tested if my &lt;code&gt;LoginValidation&lt;/code&gt; returned the correct string based on whether the email and password matched correctly. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void loginCredentialValidation_isCorrect() {
    LoginValidation loginValidation = new LoginValidation(mMockContext, "armageddon@gmail.com","pass");
    String resultWithInvalidCredentials = loginValidation.validate();
    assertEquals(resultWithInvalidCredentials, LoginValidation.SUCCESS);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Although I didn't test everything, and certainly not on par with all testing principles, I did introduce myself nicely to the skill. If you're also new to unit testing, I would suggest postponing writing tests until you know the language and the framework really well. Although this doesn't comply with Test-Driven Development, writing code not only in a new framework (Mockito and JUnit), for a new framework (Android), for a new purpose (software testing) can be very overwhelming if you're already new to the technologies themselves. &lt;/p&gt;

&lt;h1&gt;
  
  
  Google Play Releases
&lt;/h1&gt;

&lt;p&gt;A Google Play Developer Account (which has a one-time $25 fee) gave me access to the Google Play Console, which let me upload my Android app as a &lt;code&gt;.aab&lt;/code&gt; file (Android App Bundle), which makes my code understandable by the Android operating system. I released for every feature that I added and utilized the different forms of testing. &lt;/p&gt;

&lt;h1&gt;
  
  
  Conclusion
&lt;/h1&gt;

&lt;p&gt;I hope this guide was helpful for anyone wanting to build their own mobile app. Even if you're using Kotlin instead of Java, or JSON instead of XML, most things mentioned stay the same. Have you made a mobile app before? Was your journey similar to mine? Leave a comment down below!&lt;/p&gt;

&lt;p&gt;The app is public and available for download: &lt;a href="https://play.google.com/store/apps/details?id=com.boruminc.borumjot.android" rel="noopener noreferrer"&gt;https://play.google.com/store/apps/details?id=com.boruminc.borumjot.android&lt;/a&gt;&lt;br&gt;
I would greatly appreciate if you checked my app out!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published on HashNode at &lt;a href="https://varuns.hashnode.dev/my-first-full-stack-android-app" rel="noopener noreferrer"&gt;https://varuns.hashnode.dev/my-first-full-stack-android-app&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>android</category>
      <category>java</category>
      <category>firstpost</category>
    </item>
  </channel>
</rss>
