<?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 Joseph Harwood on Medium]]></title>
        <description><![CDATA[Stories by Joseph Harwood on Medium]]></description>
        <link>https://medium.com/@josephharwood-62087?source=rss-14af7d3eb6a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wYgkJiYxyvVA6yT08i1fQQ.jpeg</url>
            <title>Stories by Joseph Harwood on Medium</title>
            <link>https://medium.com/@josephharwood-62087?source=rss-14af7d3eb6a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:17:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@josephharwood-62087/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[PostgreSQL JSON]]></title>
            <link>https://josephharwood-62087.medium.com/postgresql-json-b89f895884db?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89f895884db</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 02:04:50 GMT</pubDate>
            <atom:updated>2019-11-08T05:26:55.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*s1RzllbHuy7WdNHq.jpg" /><figcaption>Hi JSON</figcaption></figure><p>My friend, JSON, is very popular these days. We will explore how to query JSON objects in this blog post.</p><p>Let’s create a table and populate it.</p><pre>CREATE TABLE purchases (<br>   ID serial NOT NULL PRIMARY KEY,<br>   <strong>purchase json NOT NULL</strong><br>);</pre><pre>INSERT INTO purchases (purchase)<br>VALUES<br>   (<br>      &#39;{ &quot;customer&quot;: &quot;Steve&quot;, &quot;items&quot;: {&quot;product&quot;: &quot;Beer&quot;,&quot;qty&quot;: 50}}&#39;<br>   ),<br>   (<br>      &#39;{ &quot;customer&quot;: &quot;Karen&quot;, &quot;items&quot;: {&quot;product&quot;: &quot;Lotion&quot;,&quot;qty&quot;: 5}}&#39;<br>   ),<br>   (<br>      &#39;{ &quot;customer&quot;: &quot;Kyle&quot;, &quot;items&quot;: {&quot;product&quot;: &quot;Monster Energy&quot;,&quot;qty&quot;: 9}}&#39;<br>   );</pre><p>Notice that we made a JSON type column called purchase and inserted JSON objects into the purchases table.</p><p>Let’s explore the different ways to query JSON objects.</p><pre>SELECT purchase FROM purchases;</pre><pre>purchase                                <br>--------------------------------------------------------------------<br> { &quot;customer&quot;: &quot;Steve&quot;, &quot;items&quot;: {&quot;product&quot;: &quot;Beer&quot;,&quot;qty&quot;: 50}}<br> { &quot;customer&quot;: &quot;Karen&quot;, &quot;items&quot;: {&quot;product&quot;: &quot;Lotion&quot;,&quot;qty&quot;: 5}}<br> { &quot;customer&quot;: &quot;Kyle&quot;, &quot;items&quot;: {&quot;product&quot;: &quot;Monster Energy&quot;,&quot;qty&quot;: 9}}<br>(3 rows)</pre><p>This gives us the JSON objects in the purchase column for each row.</p><pre>SELECT purchase <strong>-&gt;</strong> &#39;customer&#39; AS customer FROM purchases;</pre><pre> customer <br>----------<br> &quot;Steve&quot;<br> &quot;Karen&quot;<br> &quot;Kyle&quot;<br>(3 rows)</pre><p>The <strong>-&gt;</strong> operator returns all customers as JSON.</p><pre>SELECT purchase <strong>-&gt;&gt;</strong> &#39;customer&#39; AS customer FROM purchases;</pre><pre> customer <br>----------<br> Steve<br> Karen<br> Kyle<br>(3 rows)</pre><p>The <strong>-&gt;&gt;</strong> operator returns all customers as text.</p><pre>SELECT purchase -&gt; &#39;items&#39; -&gt;&gt; &#39;product&#39; AS product FROM purchases ORDER BY product;</pre><pre>    product     <br>----------------<br> Beer<br> Lotion<br> Monster Energy<br>(3 rows)</pre><p>You can chain <strong>-&gt;</strong> and <strong>-&gt;&gt; </strong>together to get this. First the <strong>-&gt;</strong> returns items as a JSON object, then <strong>-&gt;&gt;</strong> returns the items as text.</p><pre>SELECT purchase -&gt;&gt; &#39;customer&#39; AS customer                                         FROM purchases                                                                              WHERE purchase -&gt; &#39;items&#39; -&gt;&gt; &#39;product&#39; = &#39;Monster Energy&#39;;</pre><pre> customer <br>----------<br> Kyle<br>(1 row)</pre><p>You can also use <strong>-&gt;</strong> and <strong>-&gt;&gt;</strong> in the <strong>WHERE</strong> clause to select for specific values.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89f895884db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Recursive Queries]]></title>
            <link>https://josephharwood-62087.medium.com/postgresql-recursive-queries-610a16e772b8?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/610a16e772b8</guid>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Fri, 01 Nov 2019 15:23:32 GMT</pubDate>
            <atom:updated>2019-11-02T17:30:12.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jMNcMq17pcLZN3ol.png" /><figcaption>Not convoluted at all</figcaption></figure><p><strong>Common Table Expression (CTE)</strong> is a form of recursive SQL that makes a temporary result set of a query. It is an alternative to subqueries, views and user-defined functions that is useful for generating summary reports of a query. You can look at this <a href="https://medium.com/@josephharwood_62087/recursion-and-binary-search-trees-in-javascript-ae965b9ea01d">article</a> if you have any questions about what recursion is.</p><p>I just threw a lot of words at you. I think the best way to learn recursive queries is to look at an example. Let’s look at a <strong>CTE</strong> in PostgreSQL.</p><p>This is the structure of a recursive query:</p><pre>WITH RECURSIVE cte_name(</pre><pre>CTE_query_definition <em>-- non-recursive term</em></pre><pre>UNION [ALL]</pre><pre>CTE_query definition  <em>-- recursive term</em></pre><pre>) SELECT * FROM cte_name;</pre><p>A <strong>CTE</strong> consists of 3 elements:</p><ul><li><strong>Non-recursive term</strong>: the base result set of the <strong>CTE</strong> structure.</li><li><strong>Recursive term</strong>: one or more <strong>CTE</strong> query definitions joined with the non-recursive term using the <strong>UNION</strong> or <strong>UNION ALL</strong> operator. The recursive term references to the <strong>CTE</strong> name itself.</li><li><strong>Termination check</strong>: the recursion stops when no rows are returned from the previous iteration.</li></ul><p>Let’s build a test case:</p><pre>INSERT INTO employees (<br>   employee_id,<br>   full_name,<br>   manager_id<br>)<br>VALUES<br>   (1, &#39;Michael North&#39;, NULL),<br>   (2, &#39;Megan Berry&#39;, 1),<br>   (3, &#39;Sarah Berry&#39;, 1),<br>   (4, &#39;Zoe Black&#39;, 1),<br>   (5, &#39;Tim James&#39;, 1),<br>   (6, &#39;Bella Tucker&#39;, 2),<br>   (7, &#39;Ryan Metcalfe&#39;, 2),<br>   (8, &#39;Max Mills&#39;, 2),<br>   (9, &#39;Benjamin Glover&#39;, 2),<br>   (10, &#39;Carolyn Henderson&#39;, 3),<br>   (11, &#39;Nicola Kelly&#39;, 3),<br>   (12, &#39;Alexandra Climo&#39;, 3),<br>   (13, &#39;Dominic King&#39;, 3),<br>   (14, &#39;Leonard Gray&#39;, 4),<br>   (15, &#39;Eric Rampling&#39;, 4),<br>   (16, &#39;Piers Paige&#39;, 7),<br>   (17, &#39;Ryan Henderson&#39;, 7),<br>   (18, &#39;Frank Tucker&#39;, 8),<br>   (19, &#39;Nathan Ferguson&#39;, 8),<br>   (20, &#39;Kevin Rampling&#39;, 8);</pre><p>This is a recursive query that selects all subordinates of the manager with the id of 2:</p><pre>WITH RECURSIVE subordinates AS (<br>   SELECT<br>      employee_id,<br>      manager_id,<br>      full_name<br>   FROM<br>      employees<br>   WHERE<br>      employee_id = 2<br>   UNION<br>      SELECT<br>         e.employee_id,<br>         e.manager_id,<br>         e.full_name<br>      FROM<br>         employees e<br>      INNER JOIN subordinates s ON s.employee_id = e.manager_id<br>) SELECT<br>   *<br>FROM<br>   subordinates;</pre><p>Let’s break this down!</p><p>This is the <strong>non-recursive term</strong> that selects the employee id of 2.</p><pre>SELECT<br>      employee_id,<br>      manager_id,<br>      full_name<br>   FROM<br>      employees<br>   WHERE<br>      employee_id = 2</pre><p>This is the <strong>recursive term</strong> that selects the employees that are subordinates of the manager_id of 2 (meaning that they have a manager_id that is a child of the manager_id of 2)until the <strong>termination check</strong> is reached where nothing is returned (where there are no children of manager_id 2).</p><pre>UNION<br>      SELECT<br>         e.employee_id,<br>         e.manager_id,<br>         e.full_name<br>      FROM<br>         employees e<br>      INNER JOIN subordinates s ON s.employee_id = e.manager_id</pre><p>Lastly, this is where we display what is being returned in the <strong>CTE.</strong></p><pre>SELECT<br>   *<br>FROM<br>   subordinates;</pre><p>The results:</p><pre>employee_id | manager_id |    full_name<br>-------------+------------+-----------------<br>           2 |          1 | Megan Berry<br>           6 |          2 | Bella Tucker<br>           7 |          2 | Ryan Metcalfe<br>           8 |          2 | Max Mills<br>           9 |          2 | Benjamin Glover<br>          16 |          7 | Piers Paige<br>          17 |          7 | Ryan Henderson<br>          18 |          8 | Frank Tucker<br>          19 |          8 | Nathan Ferguson<br>          20 |          8 | Kevin Rampling</pre><p>Here we are displaying all of the subordinates of the manager_id 2.</p><p>The cool thing about <strong>CTE’s </strong>are that we can drill down to specific aggregate functions that we may find useful in a summary report.</p><p><strong>One example:</strong></p><pre>WITH RECURSIVE subordinates AS (<br>   SELECT<br>      employee_id,<br>      manager_id,<br>      full_name<br>   FROM<br>      employees<br>   WHERE<br>      employee_id = 2<br>   UNION<br>      SELECT<br>         e.employee_id,<br>         e.manager_id,<br>         e.full_name<br>      FROM<br>         employees e<br>      INNER JOIN subordinates s ON s.employee_id = e.manager_id<br>) <strong>SELECT<br>   manager_id, COUNT(employee_id)<br>FROM<br>   subordinates<br>GROUP BY manager_id;</strong></pre><p>This gives us a count of all of the employees that are under each manager that is under manager_id 2.</p><pre>manager_id | count <br>------------+-------<br>          2 |     4<br>          7 |     2<br>          1 |     1<br>          8 |     3</pre><p><strong>Second example:</strong></p><pre>WITH RECURSIVE subordinates AS (<br>   SELECT<br>      employee_id,<br>      manager_id,<br>      full_name<br>   FROM<br>      employees<br>   WHERE<br>      employee_id = 2<br>   UNION<br>      SELECT<br>         e.employee_id,<br>         e.manager_id,<br>         e.full_name<br>      FROM<br>         employees e<br>      INNER JOIN subordinates s ON s.employee_id = e.manager_id<br>) <strong>SELECT<br>   COUNT(employee_id) as &quot;subordinate count&quot;<br>FROM<br>   subordinates;</strong></pre><p>This gives us a count of all the employees under manager_id 2.</p><pre>subordinate count <br>------------------------<br>                     10</pre><p>I hope that you found this useful. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=610a16e772b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Javascript]]></title>
            <link>https://josephharwood-62087.medium.com/solid-javascript-6b9a481d8a72?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b9a481d8a72</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Sat, 26 Oct 2019 18:39:07 GMT</pubDate>
            <atom:updated>2019-10-26T20:21:21.120Z</atom:updated>
            <content:encoded><![CDATA[<p>This post will cover what the S.O.L.I.D. principle is and show examples of each in Javascript so that you will have a SOLID understanding of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*SQhiUj8hdr5Z7zrC.png" /></figure><p>Let’s break these down and show examples:</p><h3>Single Responsibility Principle</h3><p><em>A class should have one and only one reason to change, meaning that a class should only have one job.</em></p><p>Let’s say we have an app that has a login page that asks for a username and a password prompt. This is a way to write a function that accomplishes a login page, but it doesn’t follow the Single Responsibility Principle:</p><pre>const mainMenu = () =&gt; {<br>  console.log(&quot;Enter Username:&quot;);<br>  console.log(&quot;Enter Password:&quot;);<br>}</pre><p>Notice that <strong>mainMenu</strong> is doing 2 tasks. This isn’t good because it wouldn’t be possible to just give a prompt for just a username or password. We can accomplish this by splitting <strong>mainMenu</strong> into smaller functions for usernames and passwords:</p><pre>const login = () =&gt; {<br>  console.log(&quot;Enter Username:&quot;);<br>}</pre><pre>const password = () =&gt; {<br>  console.log(&quot;Enter Password:&quot;);<br>}</pre><pre>const mainMenu = () =&gt; {<br>  login()<br>  password()<br>}</pre><p>Splitting up the work into separate functions will make it easier to modify login and passwords in the future if we need to.</p><h3>Open Closed Principle</h3><p><em>Software components should be open for extension, but closed for modification</em></p><p>This means that if someone wants to extend a module’s behavior, they won’t need to modify existing code if they don’t want to. You’ve failed the Open Closed Principle if you have to your module and make a modification in order to extend it,. A bad example:</p><pre>const sandwiches = [&#39;turkey&#39;, &#39;ham&#39;];<br>const sandwichMaker = {<br>  makeSandwich(sandwich) {<br>    if (sandwiches.indexOf(sandwich) &gt; -1) {<br>      console.log(&#39;You made a sandwich!&#39;);<br>    } else {<br>      console.log(&#39;You don&#39;t get a sandwich!&#39;);<br>    }<br>  },<br>};<br>export default sandwichMaker;</pre><p>Notice that there is no way to add a sandwich to the sandwiches array without hard-coding the <strong>sandwiches</strong> array. Let’s modify this to make a good example:</p><pre>const sandwiches = [&#39;turkey&#39;, &#39;ham&#39;];<br>const sandwichMaker = {<br>  makeSandwich(sandwich) {<br>    if (sandwiches.indexOf(sandwich) &gt; -1) {<br>      console.log(&#39;You made a sandwich!&#39;);<br>    } else {<br>      console.log(`You don&#39;t get a sandwich!`);<br>    }<br>  },<br>  addSandwich(sandwich) {<br>    sandwiches.push(sandwich);<br>  },<br>};<br>export default sandwichMaker;</pre><p>Now we can add a new sandwich to the sandwiches array without having to modifying the <strong>sandwiches</strong> array directlyw.</p><h3>Liskov’s Substitution Principle</h3><p><em>Derived types must be completely substitutable for their base types. extended classes should be able to fit into out app without failure.</em></p><p>In Javascript terms, this principle means that functions that are derived from other functions shouldn’t break the parent function. A bad example:</p><pre>const sandwiches = [&#39;turkey&#39;, &#39;ham&#39;];<br>const sandwichMaker = {<br>  makeSandwich(sandwich) {<br>    if (sandwiches.indexOf(sandwich) &gt; -1) {<br>      console.log(&#39;You made a sandwich!&#39;);<br>    } else {<br>      console.log(`You don&#39;t get a sandwich!`);<br>    }<br>  },<br>  addSandwich(sandwich) {<br>    sandwiches.push(sandwich);<br>  },<br>};</pre><pre>const openDeli = () =&gt; {<br>  sandwiches.push(&quot;italian&quot;)<br>  sandwichMaker.makeSandwich(&quot;turkey&quot;)<br>  return sandwiches<br>}</pre><p><strong>openDeli </strong>breaks <strong>sandwichMaker</strong> because it doesn’t use <strong>addSandwich</strong> to add to the <strong>sandwiches </strong>array. An example that uses the principle:</p><pre>const sandwiches = [&#39;turkey&#39;, &#39;ham&#39;];<br>const sandwichMaker = {<br>  makeSandwich(sandwich) {<br>    if (sandwiches.indexOf(sandwich) &gt; -1) {<br>      console.log(&#39;You made a sandwich!&#39;);<br>    } else {<br>      console.log(`You don&#39;t get a sandwich!`);<br>    }<br>  },<br>  addSandwich(sandwich) {<br>    sandwiches.push(sandwich);<br>  },<br>};</pre><pre>const openDeli = () =&gt; {<br>  sandwichMaker.makeSandwich(&quot;turkey&quot;)<br>  sandwichMaker.addSandwich(&quot;roast beef&quot;)<br>  return sandwiches<br>}</pre><p><strong>openDeli</strong> now uses <strong>addSandwich</strong> and doesn’t contradict the <strong>sandwichMaker</strong> function.</p><h3>Interface Segregation Principle</h3><p><em>Clients should not be forced to implement unnecessary methods that they won’t use.</em></p><p>This principle is pretty self-explanatory. You shouldn’t implement methods that are unnecessary in your code. Say in our deli example, you wouldn’t need a function to make ice cream because it isn’t relevant to working in a deli. But say it was necessary, you could make a separate <strong>iceCreamMaker</strong> function to facilitate that need:</p><pre>const iceCreams = [&#39;vanilla&#39;, &#39;chocolate&#39;];<br>const iceCreamMaker = {<br>  makeIceCream(iceCream) {<br>    if (iceCreams.indexOf(iceCream) &gt; -1) {<br>      console.log(&#39;You made a iceCream!&#39;);<br>    } else {<br>      console.log(`You don&#39;t get a iceCream!`);<br>    }<br>  },<br>  addIceCream(iceCream) {<br>    iceCreams.push(iceCream);<br>  },<br>};<br>const openIceCreamStore = () =&gt; {<br>  iceCreams.addIceCream(&quot;rocky road&quot;)<br>  iceCreamMaker.makeIceCream(&quot;vanilla&quot;)<br>  return iceCreams<br>}</pre><h3>Dependency Inversion Principle</h3><p><em>Depend on abstractions, not on concretions.</em></p><ul><li>High Level Modules Should Not Depend On Low Level Modules</li><li>Abstraction Should Not Depend on Details, Details Should Depend on Abstractions</li></ul><p>Let’s look at what we have so far for <strong>sandwichMaker</strong> and <strong>iceCreamMaker</strong>:</p><pre>const sandwiches = [&#39;turkey&#39;, &#39;ham&#39;];<br>const sandwichMaker = {<br>  makeSandwich(sandwich) {<br>    if (sandwiches.indexOf(sandwich) &gt; -1) {<br>      console.log(&#39;You made a sandwich!&#39;);<br>    } else {<br>      console.log(`You don&#39;t get a sandwich!`);<br>    }<br>  },<br>  addSandwich(sandwich) {<br>    sandwiches.push(sandwich);<br>  },<br>};</pre><pre>const openDeli = () =&gt; {<br>  sandwichMaker.makeSandwich(&quot;turkey&quot;)<br>  sandwichMaker.addSandwich(&quot;roast beef&quot;)<br>  return sandwiches<br>}</pre><pre>const iceCreams = [&#39;vanilla&#39;, &#39;chocolate&#39;];<br>const iceCreamMaker = {<br>  makeIceCream(iceCream) {<br>    if (iceCreams.indexOf(iceCream) &gt; -1) {<br>      console.log(&#39;You made a iceCream!&#39;);<br>    } else {<br>      console.log(`You don&#39;t get a iceCream!`);<br>    }<br>  },<br>  addIceCream(iceCream) {<br>    iceCreams.push(iceCream);<br>  },<br>};<br>const openIceCreamStore = () =&gt; {<br>  iceCreams.addIceCream(&quot;rocky road&quot;)<br>  iceCreamMaker.makeIceCream(&quot;vanilla&quot;)<br>  return iceCreams<br>}</pre><p>This doesn’t seem like a very efficient way to make sandwiches and ice cream. Most of the functions are exactly same. Let’s make an abstraction of both of these functions:</p><pre>let stock = [];<br>const itemMaker = {<br>  makeItem(type, item) {<br>    if (stock.indexOf(item) &gt; -1) {<br>      console.log(`You made a ${type}!`);<br>    } else {<br>      console.log(`You don&#39;t get a ${type}!`);<br>    }<br>  },<br>  addItem(item) {<br>    stock.push(item);<br>  },<br>};</pre><pre>const openIceCreamStore = () =&gt; {<br>  stock = []<br>  itemMaker.addItem(&quot;vanilla&quot;)<br>  itemMaker.addItem(&quot;chocolate&quot;)<br>  itemMaker.addItem(&quot;rocky road&quot;)<br>  itemMaker.makeItem(&quot;ice cream&quot;, &quot;vanilla&quot;)<br>  return stock<br>}</pre><pre>const openDeli = () =&gt; {<br>  stock = []<br>  itemMaker.addItem(&quot;turkey&quot;)<br>  itemMaker.addItem(&quot;ham&quot;)<br>  itemMaker.addItem(&quot;roast beef&quot;)<br>  itemMaker.makeItem(&quot;sandwich&quot;, &quot;turkey&quot;)<br>  return stock<br>}</pre><p>I made an <strong>itemMaker </strong>function that can take in whatever type of items a user would want to use. Looking at the bullet points above, <strong>itemMaker</strong> doesn’t depend on <strong>openDeli</strong> or <strong>openIceCreamStore</strong> to work. Any input will work with <strong>itemMaker</strong>, plus we also have less repetitive code!</p><h3>Conclusion</h3><p>I hope that this breakdown of the S.O.L.I.D principle helps you apply it to your Javascript code. Thanks for reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*ONCLydgs57ynzN2y.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b9a481d8a72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Q: NoSQL? A: No Problem!]]></title>
            <link>https://josephharwood-62087.medium.com/q-nosql-a-no-problem-d006a78e8d55?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d006a78e8d55</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Fri, 11 Oct 2019 02:16:04 GMT</pubDate>
            <atom:updated>2019-10-11T02:45:16.750Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*O6MBPl-e5qeMnaKf.jpg" /><figcaption>Solid reference.</figcaption></figure><p>Most programmers are familiar with SQL (Structured Query Language) and <strong>Database Management Systems</strong> <strong>(DBMS)</strong> like PostgreSQL, SQL Server, Oracle, MongoDB, MariaDB, Redis, and MySQL. What you may not know is that these DBMS’s are either <strong>Relational</strong> or <strong>Non-Relational</strong>. This blog post will explore the differences between these 2 types with examples.</p><h3>Relational Databases</h3><p>Most databases in the past were relational databases, meaning they used a set data structure, which allowed them to link information from different tables, using indexes, that could then be linked through a relationship. A relationship example would be an Owner table that has many pets in a Pets table. <strong>SQL</strong> <strong>(Structured Query Language)</strong> is the language used to create, retrieve, update, and delete information stored in the tables. The popular examples are PostgreSQL, SQL Server, Oracle, and MariaDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/0*99p38PVtxg-ddpMQ.jpg" /></figure><h3>Non-Relational Databases</h3><p><strong>NoSQL</strong> is exactly how it sounds, it is “No Structured Query Language”. Meaning that is a non-relational database that doesn’t use any kind of relational enforcement. You decide whether or not any relationships are necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/0*wCnaVBADiyVweZzH.png" /></figure><h3>Real World Uses</h3><p>A <strong>SQL</strong> database is ideal for an application that requires complex, intensive queries between different databases and vertical scaling, like an online shopping system. <strong>Vertical scaling</strong> is adding more power to an existing table, like adding more owners to an Owners table and pets to a Pets table.</p><p>A <strong>NoSQL</strong> database is typically better for applications that require horizontal scaling and more flexible architecture, such as big data analytics and real-time web applications. <strong>Horizontal scaling </strong>is adding or removing more nodes to a system, such as adding a new computer to a distributed software application. An example would be scaling out from one web server to three, where a relationship might not be necessary.</p><h3>Architectural Differences</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*0UC3drqMRV939HDe.jpg" /></figure><p>Relational databases uses tables that have schemas that strictly define the structure of the tablespaces, tables, indexes, and table relationships. I feel like most programmers understand relational databases, so I want to focus on non-relational databases in this post. Non-relational databases don’t have schemas and data is kept in key-value pairs, columns, documents, or graphs. Let’s break down what some of these are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*nydJVl154pIaAfxL.png" /></figure><p>Inside the database, there is a collection. Inside of a collection, there a document, and inside the document, there are key-value pairs. From a relational database perspective, a <strong>collection</strong> is a table, the <strong>document</strong> is a row, and row consists of <strong>key-value pairs</strong>. Records are stored in JSON in a non-relational database.</p><pre>JSON/NoSQL  <br> {  <br>     &quot;Book id&quot;: &quot;1&quot;,  <br>     &quot;Book title&quot;: &quot;A Clockwork Orange&quot;,  <br>     &quot;Author id&quot;: &quot;23&quot;,  <br>     &quot;Author name&quot;: &quot;Anthony Burgess&quot;  <br>}</pre><p><strong>Key-value</strong> pairs should be familiar to everyone that has used Javascript and JSON. A <strong>key</strong> in the key-value pair must be unique, and it allows you to access the <strong>value</strong> associated with the key. <strong>Redis, Riak, and Oracle NoSQL </strong>are key-value databases.</p><p>A document database is a non-relational database used to store the semi-structured data as <strong>documents </strong>in JSON format. A document can have the same or a different data structure to other documents. Documents are grouped into <strong>collections </strong>(like tables in relational databases). This allows you to persist the data in a database by using the same model that you use in your application JSON code. <strong>Apache, CouchDB, and MongoDB</strong> are document databases.</p><p>Graph, in-memory, and search non-relational databases aren’t used in the most popular non-relational databases, like MongoDB and Redis, so I won’t discuss these today. Feel free to look these up if they interest you.</p><p>I hope that this introduction to NoSQL will inspire you to try it out in a project!</p><h3>Sources</h3><p><a href="https://ormuco.com/blog/most-popular-databases">https://ormuco.com/blog/most-popular-databases</a></p><p><a href="https://www.javatpoint.com/aws-non-relational-database">https://www.javatpoint.com/aws-non-relational-database</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d006a78e8d55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Worst Code Challenge Question]]></title>
            <link>https://josephharwood-62087.medium.com/the-worst-code-challenge-question-c6ed4150e9c7?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6ed4150e9c7</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Sat, 05 Oct 2019 18:32:52 GMT</pubDate>
            <atom:updated>2019-12-09T18:11:41.455Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a clickbaity title, but this was easily the most difficult code challenge problem that I have solved yet. This is in no way the most efficient solution to this problem, but it works. I am very interested if anyone reading this knows of a more elegant solution to this problem. Feel free to shoot me a message on any of the contact links on my <a href="https://jbharwood.github.io/#contact">site</a> if you have a better answer. I will detail my thought process in this post.</p><h3>The Premise</h3><p>Given an input of 3 integers, like 6, 1, 1, that are associated with numbers of the letters, a, b, c, make a string that places the letters without more than 2 letters repeating in a row. For 6, 1, 1, the desired output will be aabaacaa. Assume that the input will allow a straightforward answer and won’t make a valid answer impossible. For example, 0, 0, 3 wouldn’t work because ccc has 3 c’s in a row.</p><h3>First Try</h3><pre>function solution(A, B, C) {<br>  let str = &quot;&quot;<br>  let stackA = []<br>  let stackB = []<br>  let stackC = []<br>  let total = A + B + C</pre><pre>for(let i = 0; i &lt; A; i++){<br>    stackA.push(&quot;a&quot;)<br>  }</pre><pre>for(let i = 0; i &lt; B; i++){<br>    stackB.push(&quot;b&quot;)<br>  }</pre><pre>for(let i = 0; i &lt; C; i++){<br>    stackC.push(&quot;c&quot;)<br>  }</pre><pre>for (let i = 0; i &lt; total; i++) {<br>    if (stackA.length &gt; 0 &amp;&amp; str[i-2] !== &quot;a&quot;) {<br>      str += stackA[0]<br>      stackA.pop()<br>    } else if (stackB.length &gt; 0 &amp;&amp; str[i-2] !== &quot;b&quot;) {<br>      str += stackB[0]<br>      stackB.pop()<br>    } else if (stackC.length &gt; 0 &amp;&amp; str[i-2] !== &quot;c&quot;) {<br>      str += stackC[0]<br>      stackC.pop()<br>    } else {<br>      if (stackA.length &gt; 0) {<br>        str += stackA[0]<br>        stackA.pop()<br>      } else if (stackB.length &gt; 0) {<br>        str += stackB[0]<br>        stackB.pop()<br>      } else if (stackC.length &gt; 0) {<br>        str += stackC[0]<br>        stackC.pop()<br>      }<br>    }<br>  }</pre><pre>return str<br>}</pre><pre>console.log(solution(6, 1, 1)) //aabcaaaa<br>console.log(solution(6, 2, 2)) //aabbaaccaa<br>console.log(solution(2, 4, 2)) //aabbccbb</pre><p><strong>Analysis</strong></p><p>I had quite a bit of difficulty with thinking how to approach this problem until I thought about what kind of data structure would allow me to place letters when I needed them. I decided to go with a queue because it allowed me to track the number of letters and shift out a letter from each letter’s queue until they were empty. I added up the inputted numbers to get a total number to iterate through. I concatenated a letter to an outputted string and shifted out the letter from the queue once it was used. The else statement checks for edge cases. I checked to make sure that the letter wasn’t used in the output string 2 indexes back. This solution was incomplete because if there weren’t all even numbers in the input, like in 6, 1, 1, it wouldn’t work. It outputted aabcaaaa, with aaaa being invalid.</p><p>It was time to go back to the drawing board…</p><h3>Final Answer</h3><p>I know that this is a lot to take in, but I will break it down in detail below.</p><pre>let dubs = []<br>let singles = []</pre><pre>function solution(A, B, C) {<br>  let str = &quot;&quot;<br>  dubs = []<br>  singles = []<br>  let leftovers = []<br>  let strArr = []<br>  let total = A + B + C</pre><pre>let counts = {&quot;a&quot;: A, &quot;b&quot;: B, &quot;c&quot;: C}<br>  // avoids edge cases where multiple dubs can be added at the end of the string<br>  let sortedCounts = Object.keys(counts).sort((a,b) =&gt; counts[b] - counts[a])</pre><pre>for (let letter in sortedCounts) {<br>    placeLetters(counts[sortedCounts[letter]], sortedCounts[letter])<br>  }<br>  // placeLetters(A, &quot;a&quot;)<br>  // placeLetters(B, &quot;b&quot;)<br>  // placeLetters(C, &quot;c&quot;)</pre><pre>// str and strArr are used because it&#39;s easier for me to keep track // of what&#39;s valid and invalid in a string vs an arr<br>  for (let i = 0; i &lt; total; i++) {<br>    // keeps track of dubs that are valid to be in str<br>    if (dubs.length &gt; 0 &amp;&amp; dubs[0] !== str.slice(-2)) {<br>      str += dubs[0]<br>      strArr.push(dubs[0])<br>      dubs.shift()<br>    // pushes invalid dubs into leftovers<br>    } else if (dubs[0] === str.slice(-2)){<br>      leftovers.push(dubs[0])<br>      dubs.shift()<br>    }<br>    // pushes valid single letters into strArr<br>    if (singles.length &gt; 0 &amp;&amp; singles[0] !== str.slice(-1)) {<br>      str += singles[0]<br>      strArr.push(singles[0])<br>      singles.shift()<br>    }<br>  }</pre><pre>// places leftover dubs into strArr in valid places<br>  if (leftovers.length &gt; 0) {<br>    for (let i = 1; i &lt; strArr.length+1; i++) {<br>      if (strArr[i-1] !== leftovers[0] &amp;&amp; leftovers.length &gt; 0) {<br>        strArr.splice(i, 0, leftovers[0])<br>        leftovers.shift()<br>      }<br>    }<br>  }</pre><pre>str = strArr.join(&quot;&quot;)<br>  return str<br>}</pre><pre>function placeLetters(count, letter) {<br>  if (count === 0) {<br>    return<br>  }<br>  // handles even numbers<br>  if (count/2 &gt; 1 || count === 2) {<br>    for(let i = 0; i &lt; Math.floor(count/2); i++){<br>      dubs.push(letter + letter)<br>    }<br>    // handles 1 letter if there are even numbers existing<br>    if (count % 2 &gt; 0) {<br>      singles.push(letter)<br>    }<br>  // handles odd numbers if there are no even numbers<br>  } else {<br>    singles.push(letter)<br>  }<br>}</pre><pre>console.log(solution(6, 1, 1)) // aabaacaa<br>console.log(solution(1, 6, 1)) // bbabbcbb<br>console.log(solution(1, 1, 6)) // ccaccbcc<br>console.log(solution(6, 2, 2)) // aabbaaccaa<br>console.log(solution(2, 4, 2)) // bbaabbcc<br>console.log(solution(2, 3, 2)) // bbaabcc<br>console.log(solution(1, 3, 6)) // ccbccaccbb<br>console.log(solution(3, 4, 3)) // bbabbcaacc<br>console.log(solution(1, 1, 2)) // ccab<br>console.log(solution(0, 0, 2)) // cc</pre><p><strong>Analysis</strong></p><pre>let str = &quot;&quot;<br>  dubs = []<br>  singles = []<br>  let leftovers = []<br>  let strArr = []<br>  let total = A + B + C</pre><pre>let counts = {&quot;a&quot;: A, &quot;b&quot;: B, &quot;c&quot;: C}<br>  // avoids edge cases where multiple dubs can be added at the end of the string<br>  let sortedCounts = Object.keys(counts).sort((a,b) =&gt; counts[b] - counts[a])</pre><pre>for (let letter in sortedCounts) {<br>    placeLetters(counts[sortedCounts[letter]], sortedCounts[letter])<br>  }<br>  // placeLetters(A, &quot;a&quot;)<br>  // placeLetters(B, &quot;b&quot;)<br>  // placeLetters(C, &quot;c&quot;)</pre><p>I decided to go with a slightly different approach with this problem than the first try. Instead of putting each letter into their own queues, I made a queue for 2 letters called dubs and a queue for 1 letter called singles. I made a counts object with the letter counts and sorted them in descending order to avoid having to deal with edge cases where multiple double letters are added to the end of output string.</p><pre>function placeLetters(count, letter) {<br>  if (count === 0) {<br>    return<br>  }<br>  // handles even numbers<br>  if (count/2 &gt; 1 || count === 2) {<br>    for(let i = 0; i &lt; Math.floor(count/2); i++){<br>      dubs.push(letter + letter)<br>    }<br>    // handles 1 letter if there are even numbers existing<br>    if (count % 2 &gt; 0) {<br>      singles.push(letter)<br>    }<br>  // handles odd numbers if there are no even numbers<br>  } else {<br>    singles.push(letter)<br>  }<br>}</pre><p>I made this placeLetters function to place the letters into the dubs and singles queues (both are global variables) based on whether or not the counts for each letter were divisible by 2. The divisible by 2 counts are pushed into dubs and the odd numbers are pushed into singles. Anything with a 0 count returns null.</p><pre>// str and strArr are used because it&#39;s easier for me to keep track // of what&#39;s valid and invalid in a string vs an arr<br>  for (let i = 0; i &lt; total; i++) {<br>    // keeps track of dubs that are valid to be in str<br>    if (dubs.length &gt; 0 &amp;&amp; dubs[0] !== str.slice(-2)) {<br>      str += dubs[0]<br>      strArr.push(dubs[0])<br>      dubs.shift()<br>    // pushes invalid dubs into leftovers<br>    } else if (dubs[0] === str.slice(-2)){<br>      leftovers.push(dubs[0])<br>      dubs.shift()<br>    }<br>    // pushes valid single letters into strArr<br>    if (singles.length &gt; 0 &amp;&amp; singles[0] !== str.slice(-1)) {<br>      str += singles[0]<br>      strArr.push(singles[0])<br>      singles.shift()<br>    }<br>  }</pre><p>This part is a bit convoluted and could use some refactoring, but it works. I populate the str string and strArr array with valid letters from the dubs and singles queues. I used strings and arrays because I was having problems keeping track of valid and invalid string combinations with just an array, so I used strings for the conditional statements. Valid strings are pushed into strArr and the queues are shifted. Invalid dubs are pushed to a leftovers queue so that they can be placed later. This was the solution to the 6, 1, 1problem that I had on the first try, where it outputted aabcaaaa, with aaaa being invalid and thus leftovers. Everything up to this point works with just even numbers, like 6, 2, 2 that outputs aabbaaccaa.</p><pre>// places leftover dubs into strArr in valid places<br>  if (leftovers.length &gt; 0) {<br>    for (let i = 1; i &lt; strArr.length+1; i++) {<br>      if (strArr[i-1] !== leftovers[0] &amp;&amp; leftovers.length &gt; 0) {<br>        strArr.splice(i, 0, leftovers[0])<br>        leftovers.shift()<br>      }<br>    }<br>  }</pre><pre>str = strArr.join(&quot;&quot;)<br>  return str<br>}</pre><p>The leftover dubs are pushed into strArr when they are valid and not preceded by 2 of the same letters before it. The queue is shifted after each dub is placed. Lastly, strArr is joined and overwrites str to give us our output. This part makes 6, 1, 1 finally give us aabaacaa.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6ed4150e9c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Problems Part 2]]></title>
            <link>https://josephharwood-62087.medium.com/coding-problems-part-2-aa7f68dc1ad2?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa7f68dc1ad2</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 14:21:48 GMT</pubDate>
            <atom:updated>2019-10-02T13:31:35.854Z</atom:updated>
            <content:encoded><![CDATA[<p>This week I am going over some Javascript coding problems that I found rather challenging and learned a lot from working on.</p><h3>Shortest Substring</h3><p>Given a string input, find the shortest substring that has all of the unique letters of the string within it. For example, when given s = “dabbcabcd”, the 2 substrings would be “dabbc” and “abcd”. The shortest substring would be “abcd”.</p><pre>function shortestSubstring(s) {<br>  if (s.length === 1) return s<br>  let words = []<br>  let stringCopy = s<br>  let length = stringCopy.length<br>  let arr = s.split(&quot;&quot;)<br>  let uniqueLetters = arr.filter((item, i, ar) =&gt; ar.indexOf(item) === i);<br>  while (length &gt; 0) {<br>    let word = findStr(stringCopy, uniqueLetters)<br>    words.push(word)<br>    length -= word.length<br>    //removes substring from stringCopy<br>    stringCopy = s.replace(word, &#39;&#39;)<br>  }<br>  let noShortWords = words.filter(word =&gt; !word.includes(&quot;*&quot;))<br>  let shortestSubstring = noShortWords.reduce((a, b) =&gt; a.length &lt;= b.length ? a : b)<br>  return shortestSubstring<br>}</pre><pre>function findStr(s, uniqueLetters) {<br>  let count = 0<br>  let indexes = []<br>  for (let x = 0; x &lt; uniqueLetters.length; x++) {<br>    // checks for repeated characters at the end and makes sortedIndexes length smaller<br>    if (s.indexOf(uniqueLetters[x]) !== -1) {<br>      indexes.push(s.indexOf(uniqueLetters[x]))<br>    }<br>  }<br>  let sortedIndexes = indexes.sort( (a,b) =&gt; a - b)<br>  let last = sortedIndexes.length<br>  let substring = s.slice(sortedIndexes[0], sortedIndexes[last-1]+1)<br>  // invalid word check<br>  if (sortedIndexes.length &lt; uniqueLetters.length) {<br>    substring += &quot;*&quot;<br>  }<br><br>  return substring<br>}</pre><pre>console.log(shortestSubstring(&quot;dabbcabcd&quot;));<br>console.log(shortestSubstring(&quot;dabbbbbbcabc&quot;));<br>console.log(shortestSubstring(&quot;d&quot;));<br>console.log(shortestSubstring(&quot;dds&quot;));<br>console.log(shortestSubstring(&quot;dd&quot;));<br>console.log(shortestSubstring(&quot;ddadaxxxx&quot;));<br>console.log(shortestSubstring(&quot;xxcxxddadaxxxcx&quot;));</pre><p><strong>Output</strong></p><pre>abcd</pre><pre>dabbbbbbc</pre><pre>d</pre><pre>dds</pre><pre>d</pre><pre>ddadax</pre><pre>daxxxc</pre><p><strong>Analysis</strong></p><p>My strategy for solving this problem was to to first filter out all of the unique characters in the string and then loop through the string to cut out the substrings with all of unique characters in it. I used a while loop that terminates when the length of the copied input string length is equal to 0. Within the while loop, a findStr function checks for each unique letter in the input string and returns that string. I did a hacky thing where I added an “*” to the end of a substring if it was the end of the inputted string and was missing any of the unique letters. The length of the returned substring decrements the length of the copied input string length. I filter out any substring with “*” in it and find the shortest substring.</p><h3>Make Anagram</h3><p>An anagram is a word, phrase, or name formed by rearranging the letters of another, such as <em>cinema</em>, formed from <em>iceman</em>. This problem gives 2 input strings and finds the number of deletes that are needed to make the 2 input strings anagrams of each other.</p><pre>function makeAnagram(a, b) {<br>  let counter = {};<br>  let total = 0;<br>  let arrA = a.split(&#39;&#39;)<br>  let arrB = b.split(&#39;&#39;)</pre><pre>arrA.forEach(char =&gt; {<br>    if (counter[char]) {<br>      counter[char] = counter[char]<br>    } else {<br>      counter[char] = 0<br>    }<br>    counter[char]++;<br>  })</pre><pre>arrB.forEach(char =&gt; {<br>    if (counter[char]) {<br>      counter[char] = counter[char]<br>    } else {<br>      counter[char] = 0<br>    }<br>    counter[char]--;<br>  })</pre><pre>  Object.keys(counter).forEach(k =&gt; {<br>    if (counter[k] !== 0) {<br>        total += Math.abs(counter[k]);<br>    }<br>  })</pre><pre>return total;<br>}</pre><pre>console.log(makeAnagram(&quot;cdex&quot;, &quot;abcx&quot;));<br>console.log(makeAnagram(&quot;cde&quot;, &quot;abc&quot;));<br>console.log(makeAnagram(&quot;fcrxzwscanmligyxyvym&quot;, &quot;jxwtrhvujlmrpdoqbisbwhmgpmeoke&quot;));</pre><p><strong>Output</strong></p><pre>4</pre><pre>4</pre><pre>30</pre><p><strong>Analysis</strong></p><p>I split the 2 strings into arrays and iterate through each to get a count of occurrences of each letter. If the letters are found in both strings, string a increments in the count object and string b decrements it. In the end, it checks the count object to see if any of the keys have values that aren’t equal to 0 and adds their absolute value to the total number of deletes needed to make the two strings an anagram. An example of what the counter looks like for console.log(makeAnagram(“cdex”, “abcx”));:</p><pre>{ c: 0, d: 1, e: 1, x: 0, a: -1, b: -1 }</pre><h3>Sherlock and the Valid String</h3><p>Sherlock considers a string to be valid if all characters of the string appear the same number of times. It is also valid if he can remove just character at index in the string, and the remaining characters will occur the same number of times. Given a string , determine if it is valid. If so, return YES, otherwise return NO.</p><p><strong>Sample Input 1</strong></p><pre>aabbcd</pre><p><strong>Sample Output 1</strong></p><pre>NO</pre><p><strong>Explanation 1</strong></p><p>Given , we would need to remove two characters, both c and d aabb or a and b abcd, to make it valid. We are limited to removing only one character, so is invalid.</p><p><strong>Sample Input 2</strong></p><pre>abcdefghhgfedecba</pre><p><strong>Sample Output 2</strong></p><pre>YES</pre><p><strong>Explanation 2</strong></p><p>All characters occur twice except for which occurs times. We can delete one instance of to have a valid string.</p><pre>function isValid(s) {<br>  let arr = s.split(&#39;&#39;)<br>  let counter = {}<br>  for (let i = 0; i &lt; s.length; i++) {<br>    if (counter[s[i]]) {<br>      counter[s[i]]++<br>    } else {<br>      counter[s[i]] = 1<br>    }<br>  }</pre><pre>let prev = counter[Object.keys(counter)[0]]<br>  let removed = 0<br>  for (let i = 1; i &lt; Object.keys(counter).length; i++) {<br>    if (prev === counter[Object.keys(counter)[i]]) {<br>      prev = counter[Object.keys(counter)[i]]<br>    } else if (prev !== counter[Object.keys(counter)[i]] &amp;&amp;<br>        counter[Object.keys(counter)[i]]-1  === prev) {<br>          //check for if the count is equal to the normal count - 1<br>    }<br>    else if (prev !== counter[Object.keys(counter)[i]] &amp;&amp;<br>        counter[Object.keys(counter)[i]]-1  === 0) {<br>          removed++<br>    } else {<br>      return &quot;NO&quot;<br>    }<br>  }</pre><pre>if (removed &gt; 1) {<br>    return &quot;NO&quot;<br>  }</pre><pre>return &quot;YES&quot;<br>}</pre><pre>console.log(isValid(&quot;abc&quot;));<br>console.log(isValid(&quot;abcc&quot;));<br>console.log(isValid(&quot;aabbcd&quot;));<br>console.log(isValid(&#39;aabbccddeefghi&#39;));<br>console.log(isValid(&#39;abcdefghhgfedecba&#39;));<br>console.log(isValid(&#39;abcdefghhgfedecbaa&#39;));<br>console.log(isValid(&#39;aabbc&#39;));</pre><p><strong>Output</strong></p><pre>YES</pre><pre>YES</pre><pre>NO</pre><pre>NO</pre><pre>YES</pre><pre>NO</pre><pre>YES</pre><p><strong>Analysis</strong></p><p>Similar to the last problem, I make a counter object to count the number of occurrences of each letter. Each letter has to have the same count, except for one that be valid if its count can be decremented to equal the same count as the others. I do this by keeping track of the previous count of each iteration and doing checks for if the count of each element is equal to the others or if it is +1. There is also a check to see if the +1 is being removed more than once because if it happens more than once, it is invalid. If any of these checks don’t pass, it returns NO, otherwise it returns YES.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa7f68dc1ad2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion and Binary Search Trees in Javascript]]></title>
            <link>https://josephharwood-62087.medium.com/recursion-and-binary-search-trees-in-javascript-ae965b9ea01d?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae965b9ea01d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 02:38:08 GMT</pubDate>
            <atom:updated>2019-09-22T03:00:38.907Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recursion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*uHUmJWvltpF7WAnr.jpeg" /></figure><p><strong>Recursion </strong>is the process in which a function calls itself directly or indirectly. A <strong>recursive</strong> function is a function that calls itself during its execution.</p><p>A simple example of a recursive function:</p><pre>const factorial = (n) =&gt; {<br>    if (n === 1) {<br>      return 1<br>    }<br>    else {<br>      return n * factorial(n-1)<br>    }<br>}</pre><p>Every recursive function needs to have the simplest solution provided for the <strong>base case.</strong></p><pre>if (n === 1) {<br>      return 1<br>}</pre><p>The solution to the bigger problems are shown in smaller problems.</p><pre>else {<br>      return n * factorial(n-1)<br>}</pre><p>As you can see, the base case for getting the factorial of n would be 1 and the bigger problems have a recursive call of the factorial recursive method until n is equal to 1.</p><p>Let’s show what this recursive call looks like:</p><pre>const factorial = (n) =&gt; {<br>    if (n === 1) {<br>      console.log(&quot;n &quot; + n);<br>      return 1<br>    }<br>    else {<br>      console.log(&quot;n &quot; + n);<br>      return n * factorial(n-1)<br>    }<br>}</pre><pre>console.log(factorial(5));<br>console.log(factorial(1));</pre><p>Output:</p><pre>n: 5</pre><pre>n: 4</pre><pre>n: 3</pre><pre>n: 2</pre><pre>n: 1</pre><pre>120</pre><pre>n: 1</pre><pre>1</pre><p>factorial(5) recursively calls factorial(n-1) until it reaches 1 and factorial(1) hits the base case and immediately returns 1.</p><p>Now that we have completed a simple example, let’s look at practical applications used with the Binary Search Tree data structure.</p><h3>Binary Search Tree</h3><p>A <strong>Binary Search Tree</strong> is a node-based binary tree data structure which has the following properties:</p><ul><li>The left subtree of a node contains only nodes with keys lesser than the node’s key.</li><li>The right subtree of a node contains only nodes with keys greater than the node’s key.</li><li>The left and right subtree each must also be a binary search tree.</li></ul><p>BSTs get an average case of O(log n) on gets, adds, and deletes, but they can have a worst case of O(n) if you add a sorted list (like [1, 2, 3, 4, 5) to a BST.</p><pre>1<br> \<br>  2<br>   \<br>    3<br>     \<br>      4<br>       \<br>        5</pre><p>Let’s define a BST that looks like this graphic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*sJBKXPKIvpZGpl5d.png" /></figure><pre>const tree = {<br>    &quot;value&quot;: 8,<br>    &quot;left&quot;: {<br>        &quot;value&quot;: 3,<br>        &quot;left&quot;: {<br>            &quot;value&quot;: 1,<br>            &quot;left&quot;: null,<br>            &quot;right&quot;: null<br>        },<br>        &quot;right&quot;: {<br>            &quot;value&quot;: 6,<br>            &quot;left&quot;: {<br>                &quot;value&quot;: 4,<br>                &quot;left&quot;: null,<br>                &quot;right&quot;: null<br>            },<br>            &quot;right&quot;: {<br>                &quot;value&quot;: 7,<br>                &quot;left&quot;: null,<br>                &quot;right&quot;: null<br>            }<br>        }<br>    },<br>    &quot;right&quot;: {<br>        &quot;value&quot;: 10,<br>        &quot;left&quot;: null,<br>        &quot;right&quot;: {<br>            &quot;value&quot;: 14,<br>            &quot;left&quot;: {<br>                &quot;value&quot;: 13,<br>                &quot;left&quot;: null,<br>                &quot;right&quot;: null<br>            },<br>            &quot;right&quot;: null<br>        }<br>    }<br>}</pre><p><strong>Depth-first Traversal</strong></p><p>Depth-first traversal has the deepest node of the BST visited and then backtracks to its parent node if no sibling of that node exist. There are three types of depth-first traversal.</p><ul><li><strong>Preorder traversal —</strong> you process the node, then recursively call the method on the left subtree and then the right subtree.</li><li><strong>Inorder traversal —</strong> you first recursively call the method on the left tree, then process the node, and then call the method on the right tree.</li><li><strong>Postorder traversal —</strong> you recursively call the method on the left subtree, then the left subtree, then you process the node.</li></ul><p>How it looks in Javascript:</p><pre>const preorderTraverse = (node, array) =&gt; {<br>  if (!node) return array;<br>  array.push(node.value);<br>  array = preorderTraverse(node.left, array);<br>  array = preorderTraverse(node.right, array);<br>  return array;<br>};</pre><pre>const inorderTraverse = (node, array) =&gt; {<br>  if (!node) return array;<br>  array = inorderTraverse(node.left, array);<br>  array.push(node.value);<br>  array = inorderTraverse(node.right, array);<br>  return array;<br>};</pre><pre>const postorderTraverse = (node, array) =&gt; {<br>  if (!node) return array;<br>  array = postorderTraverse(node.left, array);<br>  array = postorderTraverse(node.right, array);<br>  array.push(node.value);<br>  return array;<br>};</pre><pre>console.log(preorderTraverse(tree, []));<br>console.log(inorderTraverse(tree, []));<br>console.log(postorderTraverse(tree, []));</pre><p>Output:</p><pre>// Preorder<br>[8, 3, 1, 6, 4, 7, 10, 14, 13]</pre><pre>// Inorder<br>[1, 3, 5, 6, 7, 8, 10, 13, 14]</pre><pre>// Postorder<br>[1, 4, 7, 6, 3, 13, 14, 10, 8]</pre><p>The base case in these recursive methods is if (!node) return array; and the left and right branches of each node are recursively called with array = inorderTraverse(node.left, array); and array = inorderTraverse(node.right, array);. Recursion makes traversing the BST much easier than doing it iteratively.</p><p><strong>Other Recursion Examples with BSTs:</strong></p><pre>const minNode = (node) =&gt; {<br>   if(!node){<br>      return 0;<br>   }<br>   if(node.left){<br>     return minNode(node.left)<br>  }<br>  return node.value<br>}</pre><pre>const maxNode = (node) =&gt; {<br>   if(!node){<br>     return 0;<br>  }<br>  if(node.right){<br>     return maxNode(node.right)<br>  }<br>  return node.value;<br>}</pre><pre>const contains = (node, value) =&gt; {<br>  if (!node) {<br>    return false<br>  }<br>  if (node.value === value) {<br>    return true<br>  }<br>  else if (value &lt; node.value) {<br>    return contains(node.left, value)<br>  }<br>  else {<br>    return contains(node.right, value)<br>  }<br>}</pre><pre>console.log(minNode(tree));<br>console.log(maxNode(tree));<br>console.log(contains(tree, 10));</pre><p>Output:</p><pre>1</pre><pre>14</pre><pre>true</pre><pre>false</pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae965b9ea01d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures Implementation in Javascript Part 2]]></title>
            <link>https://josephharwood-62087.medium.com/data-structures-implementation-in-javascript-part-2-b3eed4c3016b?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3eed4c3016b</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Fri, 13 Sep 2019 20:16:19 GMT</pubDate>
            <atom:updated>2019-09-15T14:46:08.468Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post will discuss how to implement Stacks and Queues in Javascript.</p><h3><strong>Stack</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*lge6FPgShS5upsFu.png" /></figure><p>A stack is a linear data structure represented by a real physical stack or pile, a structure where insertion and deletion of items takes place at one end called top of the stack. The basic implementation of a stack is <strong>LIFO</strong> (Last In First Out) to demonstrate the way it accesses data. A basic stack implementation has 2 actions: inserting an item into a stack and deleting an item from the stack.</p><p>All operations are O(1).</p><p><strong>Properties</strong></p><blockquote><strong>push</strong> — function — Accepts a value and adds a new item on top of the stack<br><strong>pop</strong> — function — Removes the top item from the stack<br><strong>isEmpty</strong> — function — Checks if the stack is empty<br><strong>size</strong> — function — Counts the number of items on the stack</blockquote><p><strong>Javascript Implementation</strong></p><pre>class Stack {</pre><pre>constructor() {<br>    this.stack = []<br>  }</pre><pre>push(value) {<br>    this.stack.push(value)<br>  }</pre><pre>pop() {<br>    this.stack.pop()<br>  }</pre><pre>isEmpty() {<br>    if (this.stack.length === 0) {<br>      return true<br>    } else {<br>      return false<br>    }<br>  }</pre><pre>size() {<br>    return this.stack.length<br>  }</pre><pre>serialize() {<br>    return this.stack<br>  }<br>}</pre><pre>let stack = new Stack()<br>stack.push(1)<br>stack.push(2)<br>console.log(stack.serialize());<br>stack.push(3)<br>console.log(stack.isEmpty());<br>console.log(stack.size());<br>console.log(stack.serialize());<br>stack.pop()<br>console.log(stack.serialize());<br>stack.pop()<br>stack.pop()<br>console.log(stack.serialize());<br>console.log(stack.isEmpty());</pre><p><strong>Output</strong></p><pre>[ 1, 2 ]</pre><pre>false</pre><pre>3</pre><pre>[ 1, 2, 3 ]</pre><pre>[ 1, 2 ]</pre><pre>[]</pre><pre>true</pre><h3>Queue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*jptuVokKCAzx8GoJ.png" /></figure><p>A queue is a linear data structure in which the first element is inserted from one end, called the rear (also called tail), and the removal of existing element takes place from the other end, called the front (also called head). A queue is a <strong>FIFO</strong>(First in First Out) data structure, which means that element inserted first will be removed first.</p><p>All operations are O(1).</p><p><strong>Properties</strong></p><blockquote><strong>enqueue</strong> — function — Accepts a value and adds an element to the queue<br><strong>dequeue</strong> — function — Removes an element from the front of the queue<br><strong>peek</strong> — function — Gets the front element in the queue<br><strong>empty</strong> — function — Checks if the queue is empty</blockquote><p><strong>Javascript Implementation</strong></p><pre>class Queue {</pre><pre>constructor() {<br>    this.queue = []<br>  }</pre><pre>enqueue(value) {<br>    this.queue.push(value)<br>  }</pre><pre>dequeue() {<br>    let removed = this.queue[0]<br>    this.queue.shift()<br>    return removed<br>  }</pre><pre>peek() {<br>    return this.queue[0]<br>  }</pre><pre>empty() {<br>    if (this.queue.length === 0) {<br>        return true<br>    } else {<br>        return false<br>    }<br>  }</pre><pre>serialize() {<br>    return this.queue<br>  }<br>}</pre><pre>let queue = new Queue()<br>queue.enqueue(1)<br>queue.enqueue(2)<br>queue.enqueue(3)<br>console.log(queue.serialize());<br>console.log(queue.peek());<br>console.log(queue.empty());<br>queue.dequeue()<br>console.log(queue.serialize());<br>queue.dequeue()<br>queue.dequeue()<br>console.log(queue.serialize());<br>console.log(queue.empty());</pre><p><strong>Output</strong></p><pre>[ 1, 2, 3 ]</pre><pre>1</pre><pre>false</pre><pre>[ 2, 3 ]</pre><pre>[]</pre><pre>true</pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3eed4c3016b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures Implementation in Javascript Part 1]]></title>
            <link>https://josephharwood-62087.medium.com/data-structures-implementation-in-javascript-part-1-3d67ef52ea19?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d67ef52ea19</guid>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Sun, 08 Sep 2019 02:47:10 GMT</pubDate>
            <atom:updated>2019-09-13T19:58:44.507Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post will discuss how to implement Array Lists and Hash Tables in Javascript.</p><h3>Array List</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*p4GqjPnOqVvgdyTq.png" /></figure><p>An Array List uses a dynamic array for storing elements. Array Lists are created with an initial size, when this size is exceeded, it gets enlarged automatically. The elements shift whenever an element is deleted. It can contain duplicate elements and the insertion order is maintained.</p><p>Array List’s adds and deletes are O(n) and the gets are O(1).</p><p><strong>Properties</strong></p><blockquote><strong>length</strong> — integer — How many elements in the array<br> <strong>push</strong> — function — Accepts a value and adds to the end of the list<br> <strong>pop</strong> — function — Removes the last value in the list and returns it<br> <strong>get</strong> — function — Accepts an index and returns the value at that position<br> <strong>delete</strong> — function — Accepts an index, removes value from list, collapses,<br> and returns removed value</blockquote><p><strong>Javascript Implementation</strong></p><pre>class ArrayList {</pre><pre>  constructor() {<br>    this.length = 0<br>    this.data = {}<br>  }</pre><pre>  push(value) {<br>    this.data[this.length] = value<br>    this.length++<br>  }</pre><pre>  pop() {<br>    const ans = this.data[this.length-1]<br>    delete this.data[this.length-1]<br>    this.length--<br>    return ans<br>  }</pre><pre>  get(index) {<br>    return this.data[index]<br>  }</pre><pre>  delete(index) {<br>    const ans = this.data[index]<br>    this._collapseTo(index)<br>    return ans<br>  }</pre><pre>  _collapseTo(index) {<br>    for (let i = index; i &lt; this.length; i++) {<br>      this.data[i] = this.data[i+1]<br>    }<br>    delete this.data[this.length-1]<br>    this.length--<br>  }</pre><pre>  serialize() {<br>    return this.data<br>  }<br>}</pre><pre>let list = new ArrayList()<br>list.push(1)<br>list.push(2)<br>list.push(3)<br>list.push(4)<br>console.log(list.get(1))<br>console.log(list.serialize())<br>list.pop()<br>console.log(list.serialize())<br>list.delete(0)<br>console.log(list.serialize())</pre><p><strong>Output</strong></p><pre>2</pre><pre>{ &#39;0&#39;: 1, &#39;1&#39;: 2, &#39;2&#39;: 3, &#39;3&#39;: 4 }</pre><pre>{ &#39;0&#39;: 1, &#39;1&#39;: 2, &#39;2&#39;: 3 }</pre><pre>{ &#39;0&#39;: 2, &#39;1&#39;: 3 }</pre><h3>Hash Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*olBxfKysLl7fIXfz.png" /></figure><p>A hash table is a data structure that allows you to keep a list of key-value pairs and provides a quick and efficient access to them. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found. Hash functions need to be idempotent, meaning a function given an input always outputs the same output. A good hashing algorithm has a good distribution of values spread out as evenly as possible in order to avoid collisions. Collisions are when something is hashed to an index that was already used in the hash table. The modulo operator (%) is used in the hash function to ensure that the numbers don’t exceed the max size of the hash table.</p><p>Hash tables have constant time (O(1)).</p><p><strong>Properties</strong></p><blockquote><strong>add</strong> — function — Takes a string as an input, hashes it, and puts in its table<br><strong>check</strong> — function — Takes a string and returns true if it exists in its table; otherwise returns false<br><strong>hash</strong> — function — Takes a string and a max number and return a number between 0 and the max number. function must be idempotent; the same string and max number will always yield the same output</blockquote><p><strong>Javascript Implementation</strong></p><pre>class HashTable {</pre><pre>  constructor() {<br>    this.table = new Array(255)<br>  }</pre><pre>  add(input) {<br>    this.table[this.hash(input, 255)] = input<br>  }</pre><pre>  check(input) {<br>    return !!this.table[this.hash(input, 255)]<br>  }</pre><pre>  hash(input, max) {<br>    let num = 0<br>    for (let i = 0; i &lt; input.length; i++) {<br>      num += input.charCodeAt(i) * i<br>    }<br>    return num % max<br>  }<br>}</pre><pre>let hash = new HashTable<br>hash.add(&quot;bob&quot;)<br>hash.add(&quot;susan&quot;)<br>hash.add(&quot;steve&quot;)<br>console.log(hash.check(&quot;bob&quot;))<br>console.log(hash.check(&quot;beth&quot;))</pre><p><strong>Output</strong></p><pre>true</pre><pre>false</pre><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d67ef52ea19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PostgreSQL Backup and Recovery]]></title>
            <link>https://josephharwood-62087.medium.com/postgresql-backup-and-recovery-a3511ef84eee?source=rss-14af7d3eb6a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3511ef84eee</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Joseph Harwood]]></dc:creator>
            <pubDate>Sat, 31 Aug 2019 16:32:33 GMT</pubDate>
            <atom:updated>2019-09-01T16:57:44.394Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most important principles of working with databases is that you always need a way to recover the database structures and data in case of an emergency. Some examples of an emergency could be that a table was loaded with bad data or a database structure was modified in a way that broke it. The best way to protect yourself is to frequently back up your databases. Ideally, you want the backups to be done in a scheduled job/program, so that you can recover to the point of time that you need. This blog post will show you how to backup and recover manually.</p><h3>SQL Dump</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*HjLvRnZwfpvsIMFJ.jpg" /><figcaption>Not that one</figcaption></figure><p>A SQL Dump is a file with SQL commands that will recreate the database in the same state as it was at the time of the dump.</p><p>The syntax of creating a dump:</p><pre>pg_dump <strong><em>dbname</em></strong> &gt; <strong><em>dumpfile</em></strong></pre><p>This will create a dumpfile in the folder that you are currently in.</p><p>An example with a timestamp (so you know when the backup was made):</p><pre>pg_dump idea &gt; idea-backup-$(date +%Y-%m-%d-%H.%M.%S).sql</pre><p>Creates:</p><pre>idea-backup-2019-08-31-12.13.50.sql</pre><p>Snippets of how the dump looks:</p><pre>CREATE TABLE public.&quot;Contents&quot; (</pre><pre>id integer NOT NULL,</pre><pre>idea_id integer,</pre><pre>post character varying(255),</pre><pre>audio character varying(255),</pre><pre>&quot;createdAt&quot; timestamp with time zone NOT NULL,</pre><pre>&quot;updatedAt&quot; timestamp with time zone NOT NULL,</pre><pre>html character varying(255)</pre><pre>);</pre><pre>CREATE TABLE public.&quot;Ideas&quot; (</pre><pre>id integer NOT NULL,</pre><pre>subject character varying(255),</pre><pre>category character varying(255),</pre><pre>&quot;createdAt&quot; timestamp with time zone NOT NULL,</pre><pre>&quot;updatedAt&quot; timestamp with time zone NOT NULL</pre><pre>);<br></pre><pre>COPY public.&quot;Contents&quot; (id, idea_id, post, audio, &quot;createdAt&quot;, &quot;updatedAt&quot;, html) FROM stdin;</pre><pre>28  10  Hello ddd !Paragraph 2  aaa 2019-08-22 11:25:16.63-04   2019-08-22 11:25:16.63-04   &lt;p&gt;Hello &lt;b&gt;ddd&lt;/b&gt; !&lt;/p&gt;&lt;p&gt;Paragraph 2&lt;/p&gt;</pre><pre>29  11  Hello dd !Paragraph 2   aaa 2019-08-22 11:45:17.628-04  2019-08-22 11:45:17.628-04  &lt;p&gt;Hello &lt;b&gt;dd&lt;/b&gt; !&lt;/p&gt;&lt;p&gt;Paragraph 2&lt;/p&gt;</pre><pre>30  12  Hellooooooo&amp;nbsp;!  bop 2019-08-23 11:36:47.964-04  2019-08-23 11:36:47.964-04  &lt;p&gt;Hellooooooo !&lt;/p&gt;<br></pre><pre>COPY public.&quot;Ideas&quot; (id, subject, category, &quot;createdAt&quot;, &quot;updatedAt&quot;) FROM stdin;</pre><pre>10  first song  music   2019-08-22 11:02:02.847-04  2019-08-22 11:02:02.847-04</pre><pre>11  second song music   2019-08-22 11:41:05.768-04  2019-08-22 11:41:05.768-04</pre><pre>12  third song  music   2019-08-23 11:36:32.717-04  2019-08-23 11:36:32.717-04</pre><pre>13  fourth song music   2019-08-24 10:32:15.107-04  2019-08-24 10:32:15.107-04</pre><pre>\.</pre><p>As you can see, the SQL commands for creating the tables and inserting the data are generated from the pg_dump command.</p><h3>Recovery</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*KyXz3knLk4dcTI7o.jpg" /><figcaption>Not that one</figcaption></figure><p>The syntax for recovering a database with a dumpfile:</p><pre>psql <strong><em>dbname</em></strong> &lt; <strong><em>dumpfile</em></strong></pre><p>An example:</p><pre>psql idea &lt; idea-backup-2019-08-31-12.13.50.sql</pre><p>You might get this error message after running this:</p><pre>SET</pre><pre>SET</pre><pre>SET</pre><pre>SET</pre><pre>SET</pre><pre>set_config</pre><pre>------------</pre><pre>(1 row)</pre><pre>SET</pre><pre>SET</pre><pre>SET</pre><pre>SET</pre><pre>SET</pre><pre>CREATE TABLE</pre><pre>ALTER TABLE</pre><pre>CREATE SEQUENCE</pre><pre>ALTER TABLE</pre><pre>ALTER SEQUENCE</pre><pre>CREATE TABLE</pre><pre>ALTER TABLE</pre><pre>CREATE SEQUENCE</pre><pre>ALTER TABLE</pre><pre>ALTER SEQUENCE</pre><pre>ERROR:  relation &quot;SequelizeMeta&quot; already exists</pre><pre>ALTER TABLE</pre><pre>ALTER TABLE</pre><pre>ALTER TABLE</pre><pre>COPY 3</pre><pre>COPY 4</pre><pre>ERROR:  duplicate key value violates unique constraint &quot;SequelizeMeta_pkey&quot;</pre><pre>DETAIL:  Key (name)=(20190803175505-create-idea.js) already exists.</pre><pre>CONTEXT:  COPY SequelizeMeta, line 1</pre><pre>setval</pre><pre>--------</pre><pre>30</pre><pre>(1 row)</pre><pre>setval</pre><pre>--------</pre><pre>13</pre><pre>(1 row)</pre><pre>ALTER TABLE</pre><pre>ALTER TABLE</pre><pre>ERROR:  multiple primary keys for table &quot;SequelizeMeta&quot; are not allowed</pre><p>Don’t worry about this. It is just metadata about the database that already exists on the SequelizeMeta table. It won’t break your database and its data.</p><p>You can check your data with a SQL query in PSQL to see that all your data is there. Your database is now fortified for whatever terrible things might happen to it. Make sure to do this often!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3511ef84eee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>