<?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>DEV Community: stuxnat</title>
    <description>The latest articles on DEV Community by stuxnat (@stuxnat).</description>
    <link>https://dev.to/stuxnat</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%2F684614%2Fffeaedba-a88e-4a46-8a83-f1da860a781f.png</url>
      <title>DEV Community: stuxnat</title>
      <link>https://dev.to/stuxnat</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/stuxnat"/>
    <language>en</language>
    <item>
      <title>P5 JS Audiovisualizer</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 11 Apr 2022 02:09:38 +0000</pubDate>
      <link>https://dev.to/stuxnat/p5-js-audiovisualizer-4a32</link>
      <guid>https://dev.to/stuxnat/p5-js-audiovisualizer-4a32</guid>
      <description>&lt;p&gt;One of my favorite things about coding is that I can make fun projects with it like building an audiovisualizer. Here is how to do it in p5! &lt;/p&gt;

&lt;p&gt;Before beginning, make sure to include the p5 sound library and reference it in your HTML file. Next: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1. Set up your canvas&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function setup() {
createCanvas(windowWidth, WindowHeight);
}

function draw(){
background(0);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2. Load the music&lt;/strong&gt;&lt;br&gt;
We will create a global variable for the song, and in this example, it will be a local file. We will also create a function that will play the song only when the mouse is clicked, because some browsers do not support autoplay.&lt;br&gt;
&lt;/p&gt;

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


function preload(){
song = loadSoung('example.mp3')
}

function setup() {
createCanvas(windowWidth, WindowHeight);
}

function draw(){
background(0);
}

function mouseClicked(){
if (song.isPlaying()) {
song.pause() 
} else {
song.play() 
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3. Capture the audio and analyze it&lt;/strong&gt;&lt;br&gt;
In this step, we will use Fast Fourier Transform (FFT). FFT will analyze the sound in every frame of the song and return an array with data about the sound.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const song 
const fft 

function preload(){
song = loadSoung('example.mp3')
}

function setup() {
createCanvas(windowWidth, WindowHeight);
fft = new p5.FFT()
}

function draw(){
background(0);
}

function mouseClicked(){
if (song.isPlaying()) {
song.pause() 
} else {
song.play() 
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4. Visualize the data&lt;/strong&gt;&lt;br&gt;
In this step, we will use Fast Fourier Transform (FFT). FFT will analyze the sound in every frame of the song and return an array with data about the sound. This should give you a waveform across the canvas which you can manipulate however you want (like changing colors, or creating a circle)!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const song 
const fft 

function preload(){
song = loadSoung('example.mp3')
}

function setup() {
createCanvas(windowWidth, WindowHeight);
fft = new p5.FFT()
}

function draw(){
background(0);
stroke(255); 
noFill()

const wave = fft.waveform()

beginShape()
for (let i = 0; i &amp;lt; width; i++{
const index = floor(map(i, 0, width, 0, wave.length))

const x = i 
const y = wave[index] * 200 + height / 2 

vertex(x, y)
}
endShape()
}

function mouseClicked(){
if (song.isPlaying()) {
song.pause() 
} else {
song.play() 
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
    <item>
      <title>SQL Injection Attacks</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 04 Apr 2022 03:28:20 +0000</pubDate>
      <link>https://dev.to/stuxnat/sql-injection-attacks-4ile</link>
      <guid>https://dev.to/stuxnat/sql-injection-attacks-4ile</guid>
      <description>&lt;p&gt;Injection attacks are one of the top three most common security breaches according to OWASP Top 10. Injection attacks pass a string of code as an input to a web app, which alters the operation of the application by executing certain commands. One of the most common injection attacks is SQL injection. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Why is SQL Injection Used?&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
SQL Injection can be used by attackers to: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bypass Authentication&lt;/strong&gt; - Attackers can pass a piece of code to the database that allows them to bypass the authentication process.  &lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT * FROM users WHERE username = '' OR 1=1-- ' AND password = 'foo'&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;What will happen here is 1=1 will return 'true', and everything after '--' will not be executed because '--' is used to comment out code in SQL, so the rest of the query will be ignored. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exfiltrate Data&lt;/strong&gt; - There are many areas that can be exploited to steal data from a targeted source. A common HTTP Server request could look like this: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT * FROM users INTO OUTFILE '/var/www/html/output.txt'&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;This will select all from users table and export that data as a text file. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Execute OS commands&lt;/strong&gt; - Beyond databases, attackers can gain access to an entire operating system and run system commands. SQL injection attacks are often used as a vector for gaining command of the shell. If an attacker has enough information about their target, they can pass something like this: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;' union select 1, '&amp;lt;?php system($_GET["cmd"]); ?&amp;gt;' into outfile '/var/www/dvwa/cmd.php' #&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This piece of PHP code will allow the attacker to execute os commands. They will have access to the shell via their browser. &lt;br&gt;
&lt;code&gt;&amp;lt;?php system($_GET["cmd"]); ?&amp;gt;&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vandalism/DoS&lt;/strong&gt; - Attackers can drop tables from a database and otherwise break things with SQL injection. Here is one of my favorite comics: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EgQ5sPDN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5usv2pwsolas5u5ada9w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EgQ5sPDN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5usv2pwsolas5u5ada9w.png" alt="Image description" width="666" height="205"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Prevent SQL Injection&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Here are some steps can be taken to prevent SQL injection attacks: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sanitize all inputs.&lt;/strong&gt; Basically, the client input cannot be trusted. Use whitelists and when possible, do not let user directly communicate with the database. Perform server-side validation. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do not expose native database errors.&lt;/strong&gt; Attackers can use database errors to learn more about your database and find vulnerabilities. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use Object Relational Mapping (ORM).&lt;/strong&gt;  ORM creates a layer between the language and the database. In Rails, ActiveRecord  translates between Ruby and SQL. This is mostly secure, but some things can still be exploited. &lt;/p&gt;

</description>
    </item>
    <item>
      <title>Starting a React App</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 28 Mar 2022 02:41:11 +0000</pubDate>
      <link>https://dev.to/stuxnat/starting-a-rails-app-5i9</link>
      <guid>https://dev.to/stuxnat/starting-a-rails-app-5i9</guid>
      <description>&lt;p&gt;How to start a React app:&lt;/p&gt;

&lt;p&gt;The first thing to do is make sure to have &lt;a href="https://nodejs.org/en/"&gt;Node.js&lt;/a&gt; and Node Packet Manager (NPM) installed on your system. &lt;/p&gt;

&lt;p&gt;Then, run:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npx create-react-app example-app&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, we can cd into the app directory. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;cd example-app&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Start the server by running &lt;code&gt;npm start&lt;/code&gt; &lt;/p&gt;

</description>
    </item>
    <item>
      <title>Devise Gem</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 21 Mar 2022 01:48:36 +0000</pubDate>
      <link>https://dev.to/stuxnat/devise-gem-4bmo</link>
      <guid>https://dev.to/stuxnat/devise-gem-4bmo</guid>
      <description>&lt;p&gt;In my previous post, I mentioned the &lt;a href="https://rubygems.org/gems/devise"&gt;Devise&lt;/a&gt; gem, which handles the user authentication process in Rails. It simplifies the process in several ways: it generates the necessary controllers for user login and sessions, creates forms for user sign up/log in, and handles the encryption process with bcrypt, eliminating the need to salt and hash passwords yourself. The Devise gem also provides compatibility with other user authentication methods like OAuth, so the user would have the option to log in through a third party. This gem is great for streamlining the user authentication process and ensuring app security. &lt;/p&gt;

&lt;p&gt;In this post, I want to go through set up with the gem! &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting up:&lt;/strong&gt;&lt;br&gt;
Add &lt;code&gt;gem devise&lt;/code&gt; to your Gemfile and run &lt;code&gt;bundle install&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Run &lt;code&gt;rails g devise:install&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Creating the User Model&lt;/strong&gt;&lt;br&gt;
Run &lt;code&gt;rails g devise user&lt;/code&gt; and &lt;code&gt;rake db:migrate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Voila! This gem will generate the controller for user log in. &lt;/p&gt;

&lt;p&gt;To generate views run &lt;code&gt;rails g devise:views&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;To work with Devise routes, add to routes.rb: &lt;code&gt;devise_for :MODELNAME&lt;/code&gt; where MODELNAME is the name of the model you want to create the route for. &lt;/p&gt;

</description>
      <category>ruby</category>
    </item>
    <item>
      <title>Rails App Security</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 14 Mar 2022 03:48:35 +0000</pubDate>
      <link>https://dev.to/stuxnat/api-security-2715</link>
      <guid>https://dev.to/stuxnat/api-security-2715</guid>
      <description>&lt;p&gt;Security is an important aspect to consider when building web applications. There are many layers to keep in mind when thinking about app security, such as the back-end storage, the web server, and the client-facing component.&lt;/p&gt;

&lt;p&gt;Below are some things you can do to ensure that you build a more secure Rail app:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Proper CORS configuration&lt;/strong&gt;&lt;br&gt;
One important thing to do with CORS to prevent unwanted access is to define access within your APIs correctly. The example below uses the wildcard '*' allows access from any origin and gives access to any resources - typically, this is not advisable (it depends on the purpose of your API). Instead, you can define which origins are allowed to access your API.&lt;/p&gt;

&lt;p&gt;This is an example of an unsecure CORS configuration:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: :any
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To define permitted origins and limit access, you can do something 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;Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3000'
    resource '*', headers: :any, methods: [:get]
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;2. Authentication and Access Controls&lt;/strong&gt;&lt;br&gt;
It is crucial to verify user identity to prevent unauthorized access. You can use the &lt;a href="https://rubygems.org/gems/devise"&gt;Devise gem&lt;/a&gt; for user management. &lt;/p&gt;

&lt;p&gt;Another important thing to do is maintain control to CREATE, READ, UPDATE, DESTROY actions. It is important to reinforce ownership of records made by users so that users can modify only permitted records. &lt;a href="https://github.com/varvet/pundit"&gt;Pundit&lt;/a&gt; is a great tool you can use to create user control policies. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Sessions Security&lt;/strong&gt;&lt;br&gt;
You can avoid common hijacking situations by managing sessions. Implementing &lt;code&gt;reset_session&lt;/code&gt; in your code prevents an attacker from using a fixed session to gain unauthorized access by issuing a new session identifier after a successful login.&lt;/p&gt;

&lt;p&gt;Other things to keep in mind when using sessions: use HTTPS to prevent session theft, and do not store permanent data in sessions - store permanent data in the database. &lt;/p&gt;

&lt;p&gt;A great resource to use is Open Web Application Security Project (OSWAP).  &lt;a href="https://owasp.org/www-project-top-ten/"&gt;OWASP Top Ten&lt;/a&gt; lists the ten most common security vulnerabilities and how to address them.  &lt;/p&gt;

</description>
      <category>cybersecurity</category>
      <category>api</category>
      <category>rails</category>
    </item>
    <item>
      <title>SQLZoo</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 07 Mar 2022 04:58:23 +0000</pubDate>
      <link>https://dev.to/stuxnat/sqlzoo-4o2j</link>
      <guid>https://dev.to/stuxnat/sqlzoo-4o2j</guid>
      <description>&lt;p&gt;I've been practicing SQL a lot recently. SQLZoo is a classic and great place to practice SQL. Today, I worked through the &lt;br&gt;
&lt;a href="https://sqlzoo.net/wiki/AdventureWorks"&gt;Adventure Works&lt;/a&gt; set of problems...I liked this one a lot because of the cycling related theme. Spring is around the corner and this problem set made me excited to be thinking about my bicycle. Anyway, below is some of the problem set:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- How many items with ListPrice more than $1000 have been sold?

SELECT COUNT(*) AS count
FROM SalesOrderDetail
JOIN Product
ON SalesOrderDetail.ProductID = Product.ProductID
WHERE Product.ListPrice &amp;gt; 1000;

-- Give the CompanyName of those customers with orders over $100000. Include the subtotal plus tax plus freight.

SELECT Customer.CompanyName
FROM SalesOrderHeader
JOIN Customer
ON SalesOrderHeader.CustomerID = Customer.CustomerID
WHERE SalesOrderHeader.SubTotal + SalesOrderHeader.TaxAmt + SalesOrderHeader.Freight &amp;gt; 100000;


 -- Find the number of left racing socks ('Racing Socks, L') ordered by CompanyName 'Riding Cycles'

SELECT SUM(SalesOrderDetail.OrderQty) 
FROM SalesOrderDetail
JOIN Product
ON SalesOrderDetail.ProductID = Product.ProductID
JOIN SalesOrderHeader
ON SalesOrderDetail.SalesOrderID = SalesOrderHeader.SalesOrderID
JOIN Customer
ON SalesOrderHeader.CustomerID = Customer.CustomerID
WHERE Product.Name = 'Racing Socks, L' AND Customer.CompanyName = 'Riding Cycles';```


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

&lt;/div&gt;

</description>
      <category>sql</category>
    </item>
    <item>
      <title>SQL 2ND Highest Salary</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 28 Feb 2022 04:57:31 +0000</pubDate>
      <link>https://dev.to/stuxnat/sql-2nd-highest-salary-57bn</link>
      <guid>https://dev.to/stuxnat/sql-2nd-highest-salary-57bn</guid>
      <description>&lt;p&gt;Here are several ways to find the second highest salary, given a table of employee salaries in SQL. &lt;/p&gt;

&lt;p&gt;Example table:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;employee table:&lt;br&gt;
+----+--------+&lt;br&gt;
| id | salary |&lt;br&gt;
+----+--------+&lt;br&gt;
| 1  | 100    |&lt;br&gt;
| 2  | 200    |&lt;br&gt;
| 3  | 300    |&lt;br&gt;
+----+--------+&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;POSSIBLE SOLUTIONS:&lt;/strong&gt; &lt;br&gt;
&lt;strong&gt;SOLUTION 1:&lt;/strong&gt; &lt;br&gt;
&lt;code&gt;SELECT MAX(salary) as SecondHighestSalary FROM employee WHERE salary NOT IN (SELECT MAX(salary) FROM employee);&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SOLUTION 2:&lt;/strong&gt; &lt;/p&gt;

&lt;p&gt;&lt;code&gt;SELECT * FROM employee &lt;br&gt;
GROUP BY salary &lt;br&gt;
ORDER BY  salary DESC LIMIT 1,1;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SOLUTION 3:&lt;/strong&gt; &lt;br&gt;
&lt;code&gt;SELECT DISTINCT salary AS SecondHighestSalary&lt;br&gt;
FROM employee&lt;br&gt;
ORDER BY salary DESC&lt;br&gt;
LIMIT 1 OFFSET 1&lt;/code&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>CTE in SQL</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 21 Feb 2022 01:17:30 +0000</pubDate>
      <link>https://dev.to/stuxnat/cte-in-sql-2h0n</link>
      <guid>https://dev.to/stuxnat/cte-in-sql-2h0n</guid>
      <description>&lt;p&gt;One thing I like about SQL are Common Table Expressions (CTE). CTE were introduced to simplify SQL queries. &lt;/p&gt;

&lt;p&gt;A CTE allows for the creation of a temporary result set, which can be treated just like a view. You can perform JOIN operations on them and the results can be filtered. This allows you to separately define queries instead of writing nested queries. This makes performing operations on datasets easier, especially when working with complex queries. This also helps to make the code more readable. &lt;/p&gt;

&lt;p&gt;The syntax is as follows: &lt;/p&gt;

&lt;p&gt;Define the CTE name and columns.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WITH cteName (column1, column2)  
AS 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Define the CTE query.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WITH cteName (column1, column2)  
AS (  
    SELECT 1, 2 
   )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Define the outer query, which will reference the CTE name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WITH cteName (column1, column2)  
AS (  
    SELECT 1, 2 
   ) 
SELECT * FROM cteName
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is an example of a sqlzoo &lt;a href="https://sqlzoo.net/wiki/Helpdesk_Medium_Questions"&gt;problem&lt;/a&gt; solved with CTE instead of nested queries. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;8. For each customer show: Company name, contact name, number of calls where the number of calls is fewer than 5&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with b as (
        SELECT  *
        FROM Caller
),


a as (
        SELECT
            Customer.Company_name,
            Customer.Contact_id,
            COUNT(*) AS nc
        FROM
            Customer
            JOIN
                Caller
                ON (Customer.Company_ref = Caller.Company_ref)
            JOIN
                Issue
                ON (Caller.Caller_id = Issue.Caller_id)
        GROUP BY
            Customer.Company_name,
            Customer.Contact_id
        HAVING
            COUNT(*) &amp;lt; 5
)

SELECT
    a.Company_name,
    b.first_name,
    b.last_name,
    a.nc
    from b join a ON (a.Contact_id = b.Caller_id);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the rest of the series on &lt;a href="https://github.com/naturalnat/sqlzoo/blob/main/helpdesk/medium.sql"&gt;GitHub&lt;/a&gt;. &lt;/p&gt;

</description>
      <category>sql</category>
    </item>
    <item>
      <title>Leetcode SQL: 175. Combine Two Tables</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 14 Feb 2022 02:16:40 +0000</pubDate>
      <link>https://dev.to/stuxnat/leetcode-sql-175-combine-two-tables-49k2</link>
      <guid>https://dev.to/stuxnat/leetcode-sql-175-combine-two-tables-49k2</guid>
      <description>&lt;p&gt;I decided to practice SQL today. This is a common question encountered during interviews. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The problem:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| personId    | int     |
| lastName    | varchar |
| firstName   | varchar |
+-------------+---------+
personId is the primary key column for this table.
This table contains information about the ID of some persons and their first and last names.


Table: Address

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| addressId   | int     |
| personId    | int     |
| city        | varchar |
| state       | varchar |
+-------------+---------+
addressId is the primary key column for this table.
Each row of this table contains information about the city and state of one person with ID = PersonId.


Write an SQL query to report the first name, last name, city, and state of each person in the Person table. If the address of a personId is not present in the Address table, report null instead.

Return the result table in any order.

The query result format is in the following example.



Example 1:

Input: 
Person table:
+----------+----------+-----------+
| personId | lastName | firstName |
+----------+----------+-----------+
| 1        | Wang     | Allen     |
| 2        | Alice    | Bob       |
+----------+----------+-----------+
Address table:
+-----------+----------+---------------+------------+
| addressId | personId | city          | state      |
+-----------+----------+---------------+------------+
| 1         | 2        | New York City | New York   |
| 2         | 3        | Leetcode      | California |
+-----------+----------+---------------+------------+
Output: 
+-----------+----------+---------------+----------+
| firstName | lastName | city          | state    |
+-----------+----------+---------------+----------+
| Allen     | Wang     | Null          | Null     |
| Bob       | Alice    | New York City | New York |
+-----------+----------+---------------+----------+
Explanation: 
There is no address in the address table for the personId = 1 so we return null in their city and state.
addressId = 1 contains information about the address of personId = 2.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The solution:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To solve this problem, we can use a LEFT JOIN. This will returns all rows from the left table, and the matching rows from the right table. NULL will be returned if there are no matches. &lt;/p&gt;

&lt;p&gt;The code:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;select FirstName, LastName, City, State from Person p left join Address a on p.PersonId = a.PersonId;&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

</description>
      <category>sql</category>
    </item>
    <item>
      <title>JavaScript: Binary Search</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Sun, 06 Feb 2022 22:02:42 +0000</pubDate>
      <link>https://dev.to/stuxnat/javascript-binary-search-2aej</link>
      <guid>https://dev.to/stuxnat/javascript-binary-search-2aej</guid>
      <description>&lt;p&gt;Today I will be writing about how to solve the Binary Search algorithm problem on Leetcode. &lt;/p&gt;

&lt;p&gt;The problem: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.&lt;/p&gt;

&lt;p&gt;You must write an algorithm with O(log n) runtime complexity.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var search = function(nums, target) { 
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 1. Create 2 pointers, left and right to point to the beginning and end of the array.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var search = function(nums, target) {
    let left = 0; 
    let right = nums.length - 1 
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Considering the given example array &lt;code&gt;[-1,0,3,5,9,12]&lt;/code&gt;, left would point to -1 and right would point to 12.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2. Create while loop.&lt;/strong&gt;&lt;br&gt;
We will set left = right because they will eventually meet. We also want to find a middle element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var search = function(nums, target) {
    //step 1. create 2 pointers, left and right to point to first and last elements. 
    let left = 0; 
    let right = nums.length - 1 

    while (left &amp;lt;= right){
        let middle = left + Math.floor((right - left) / 2)
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3. Write if-statement to calculate middle element.&lt;/strong&gt;&lt;br&gt;
If the middle element === target, return middle.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var search = function(nums, target) {
    let left = 0; 
    let right = nums.length - 1 

    while (left &amp;lt;= right){
        let middle = left + Math.floor((right - left) / 2)

            if(nums[middle] === target){
                return middle 
            } else if (middle &amp;lt; target) {
                left = middle + 1  
            } else { 
                right = middle - 1
            }
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 4. Return -1 if element does not match target.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

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

var search = function(nums, target) {
    let left = 0; 
    let right = nums.length - 1 

    while (left &amp;lt;= right){
        let middle = left + Math.floor((right - left) / 2)

            if(nums[middle] === target){
                return middle 
            } else if (middle &amp;lt; target) {
                left = middle + 1  
            } else { 
                right = middle - 1
            }
    }
return -1
};


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

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>algorithms</category>
    </item>
    <item>
      <title>JavaScript: Two Sum</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Mon, 31 Jan 2022 01:11:11 +0000</pubDate>
      <link>https://dev.to/stuxnat/javascript-two-sum-1j3l</link>
      <guid>https://dev.to/stuxnat/javascript-two-sum-1j3l</guid>
      <description>&lt;p&gt;Two Sum is another question frequently asked during interviews. There are two common ways to approach this problem. One way is considered "brute force" - it uses nested loops with a time complexity of O(n²). The second way is one of the preferred methods, because it has a time complexity of O(n). &lt;/p&gt;

&lt;p&gt;The problem asks: given an array of numbers and a target sum, find the sum of two numbers in the array that is equal to the target sum. This is how to solve it: &lt;/p&gt;

&lt;p&gt;Step 1. Start with an array of numbers and a target sum&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const sum = 15; 

const twoSum = (array, sum) =&amp;gt; {

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

&lt;/div&gt;



&lt;p&gt;Step 2. Write a for-loop to iterate through the array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const twoSum = (array, sum) =&amp;gt; {
    const past = []

    for(let i = 0; i &amp;lt; array.length; i++){
        let curr = array[i]
        let needed = sum - array[i]
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 3. Write if-statement to search through array of past numbers&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const twoSum = (array, sum) =&amp;gt; {
    const past = []

    for(let i = 0; i &amp;lt; array.length; i++){
        let curr = array[i]
        let needed = sum - array[i]
        if(!past.includes(needed)){
            past.push(curr)
        } else {
            return [needed, curr];
        }
    }
    return "Not found!"; 
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 4. Add counter that will increment by one each run &lt;br&gt;
This will show how many runs it takes to return "Not Found!"&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const sum = 20;

const twoSum = (array, sum) =&amp;gt; {
    const past = [];
    let count = 0;

    for (let i = 0; i &amp;lt; array.length; i++) {
        let curr = array[i]
        let needed = sum - array[i]
        if (!past.includes(needed)) {
            past.push(curr)
        } else {
            return [needed, curr];
        }
    count++; 
    }
    console.log(count)
    return "Not found!";
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;and that's it!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>JavaScript Algorithm: Roman Numeral Converter</title>
      <dc:creator>stuxnat</dc:creator>
      <pubDate>Sun, 23 Jan 2022 20:41:26 +0000</pubDate>
      <link>https://dev.to/stuxnat/javascript-algorithm-roman-numeral-converter-2ac7</link>
      <guid>https://dev.to/stuxnat/javascript-algorithm-roman-numeral-converter-2ac7</guid>
      <description>&lt;p&gt;Hello! Today I will be writing about how to solve the Roman numeral converter algorithm. &lt;/p&gt;

&lt;p&gt;When writing the solution, we have to remember key caveats in the Roman numeral system, like the number 4 being written as 5 minus 1, so IV. &lt;/p&gt;

&lt;p&gt;Instead of writing many if statements, we can use a dictionary to solve this problem. &lt;/p&gt;

&lt;p&gt;Step 1: Write dictionary.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dict = {
    1: 'I',
    4: 'IV',
    5: 'V',
    9: 'IX',
    10: 'X',
    40: 'XL',
    50: 'L',
    90: 'XL',
    100: 'C',
    400: 'CD', 
    500: 'D',
    900: 'CM',
    1000: 'M',
}
function toRoman(num) {

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

&lt;/div&gt;



&lt;p&gt;Step 2. Write an Array of Numbers &lt;br&gt;
Write an array containing the numbers in the dictionary - we will be looping through it. Because we will need to perform some calculations to convert the given number, we will be using subtraction to solve this problem. Starting from the largest value, we will subtract until we no longer can. For this reason, the numbers in the array are written from largest to smallest.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Step 3. Write a While-Loop &lt;br&gt;
For this, we will set a variable to an empty string because we will want to append the Roman numeral equivalent to the output string. &lt;br&gt;
If the number in the array is greater than num, then we will go to the following number (this is why the array is in reverse numerical order), compare that to num, and append to the output string whenever we were able to calculate a number.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function toRoman(num) {
    let output = '';
    let i = 0;

    while (num &amp;gt; 0) {
        const subtract = numbers[i];
        if (subtract &amp;gt; num) {
            i++;
        } else {
            num -= subtract;
            output += dict[subtract]

        }
    }
    return output
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your final code should look 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;const numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]

const dict = {
    1: 'I',
    4: 'IV',
    5: 'V',
    9: 'IX',
    10: 'X',
    40: 'XL',
    50: 'L',
    90: 'XL',
    100: 'C',
    400: 'CD',
    500: 'D',
    900: 'CM',
    1000: 'M',
}
function toRoman(num) {
    let output = '';
    let i = 0;

    while (num &amp;gt; 0) {
        const subtract = numbers[i];
        if (subtract &amp;gt; num) {
            i++;
        } else {
            num -= subtract;
            output += dict[subtract]

        }
    }
    return output
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
    </item>
  </channel>
</rss>
