<?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 prince donkor on Medium]]></title>
        <description><![CDATA[Stories by prince donkor on Medium]]></description>
        <link>https://medium.com/@prince.donkor74?source=rss-cb347ffb7f24------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*g75V2AWhoQXAc4VMuCYDxQ.png</url>
            <title>Stories by prince donkor on Medium</title>
            <link>https://medium.com/@prince.donkor74?source=rss-cb347ffb7f24------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:45:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prince.donkor74/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[Why You Should Create A Progressive Web App]]></title>
            <link>https://medium.com/@prince.donkor74/why-you-should-create-a-progressive-web-app-e85c46ccb24f?source=rss-cb347ffb7f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85c46ccb24f</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[prince donkor]]></dc:creator>
            <pubDate>Sun, 18 Aug 2019 21:12:58 GMT</pubDate>
            <atom:updated>2019-08-18T21:21:03.515Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building A Progressive Web App</h3><p>As a software engineer, I have been asked by many small business owners to build them a website but they also want to have an app for the same business, they, of course, would want an app for both android and IOS. Now if they just wanted an app, I would just code in React Native which according to <strong>Google</strong> is<em> ‘a JavaScript framework for writing real, natively rendering mobile applications for IOS and Android’</em>. But this does not fully solve my problem. I would still need to build a website as well along with React Native and I would have to maintain both applications. To solve this we can create Progressive web apps.</p><h3>What I will cover in this article</h3><ul><li>What are progressive web apps</li><li>Advantages of Progressive Web Apps</li><li>Drawbacks of Progressive Web Apps</li><li>Requirements to build a PWA</li><li>What is Lighthouse?</li><li>What is a Manifest</li><li>What is a Service Worker</li><li>What is IndexedDB</li><li>What is Firebase and why I use it?</li></ul><h3>What Are Progressive Web Apps?</h3><p>Progressive Web Apps (PWA) isn’t a new framework or technology, It is a set of best practices to make a website function like a desktop or mobile application.</p><p>To be considered a Progressive Web App, it must be:</p><ul><li>Progressive — Works for every user regardless of browser choice.</li><li>Responsive — Mobile-friendly web application</li><li>Connectivity Independent — Enhanced with service workers to work offline</li><li>Safe — Served via HTTPS</li><li>Can be installed — Allow users to keep the application on the home screen without the hassle of an app store</li></ul><h3>Advantages of Progressive Web Apps</h3><ul><li>Fast — Response quickly, Due to caching the pages, we do not have to hit the network again.</li><li>Integrated user experience — PWA feel and behave like native apps, they are on the home screen, can push notifications and have access to a device functionalities (ex. GPS and Camera)</li><li>Reliable experience — Can work offline with the help of service worker</li><li>Engaging — We can send notifications to users to keep them engaged with the app.</li><li>Affordable — There are many more developers that can code in HTML, CSS, and Javascript then react-native, so the rates significantly reduced.</li><li>No Installation Process — PWA quickly downloads directly on mobile devices, users do not have to wait like native apps.</li></ul><h3>What Are The Drawbacks of PWA?</h3><ul><li>Limited Browser Support — Not all PWA features are supported by all browsers, for example, google chrome on iOS mobile does not support notifications.</li><li>Limited Hardware and Software support — PWAs cannot access a device’s near-field communication which allows two devices that are within 4 centimeters to communicate. Users can transfer files, videos, etc. Can’t access a device Bluetooth, proximity sensors, advanced camera controls and more which could make the app less personal for users</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*FQyx7co9Yf03aQ0B2s5cug.png" /><figcaption>Limited Browser Support</figcaption></figure><ul><li>No Download Store Presence — Although it is a benefit that PWA is not in an app store, you will miss out on a large number of users who search for apps on the app store.</li><li>High Battery Usage — PWAs consume more battery compared to native apps because they are written in high-level web code so the phone has to work harder to interpret the code. Users who notice a drain in their battery power are more likely to not use the app if they need to prolong their battery life.</li></ul><h3>Requirements to build a PWA</h3><p>To create a progressive web app you would need:</p><ul><li>Lighthouse</li><li>Manifest</li><li>Service Worker</li><li>IndexedDB</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*8dX7NTMK51Xrj0HZnOmLMQ.png" /><figcaption>Lighthouse</figcaption></figure><p><strong>What is Lighthouse?</strong></p><ul><li>Lighthouse is an open-source, automated tool for improving the quality of web pages. It has audits for performance, accessibility, progressive web apps and more. You can run Lighthouse in Chrome DevTools, from the command line or as a node module.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*whtvdjjrdddV4vm05dvI8A.png" /><figcaption>Failed Progressive Web app</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*4k4Tt9Nx8zrY-vTqCFNcDQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*vI4NIuFzJlzCdJyXQLpBRQ.png" /></figure><p><strong>What is Manifest?</strong></p><ul><li>A web app manifest gives information about an app in a JSON text file. It tells the browser about how it should behave when installed on the user’s mobile device or desktop. A manifest file includes information about the app name, icons, the start URL it should start at when launched, background color, theme color and much more.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*4NOsV9lUDO7PwZ4hDVa3KA.png" /><figcaption>iOS icon settings</figcaption></figure><p><strong>What is a Service Worker?</strong></p><p>A service worker is a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages</p><ul><li>The service worker can receive push messages from a server when the app is not active. This lets your app show push notifications to the user, even when it is not open in the browser.</li><li>The service worker can’t access the DOM directly. To communicate with the page, the service worker uses the<a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage">postMessage()</a> method to send data and a &quot;message&quot; event listener to receive data.</li></ul><p><strong>The Service Worker life cycle</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*LNppG1THiym-ryje.png" /></figure><p><strong>Install Event</strong></p><p>When learning about service worker, life cycle seemed so complicated, but once you understand how it works you can deliver the best web and native patterns. The first life cycle is the install. To Install a service worker you need to register it in your javascript file. It may look like the following:</p><pre>if (&#39;serviceWorker&#39; in navigator) { <br>  navigator.serviceWorker.register(&#39;/service-worker.js&#39;);<br>}</pre><pre>According to javatpoint: &#39;The <strong>navigator object</strong> is used for browser detection. It can be used to get browser information such as appName, appCodeName, userAgent etc.&#39; In this cause we are checking if serviceWorker can be registered</pre><p>You may see a lot of boilerplate registering servicer worker like above but for best practice, you would want to do the following:</p><pre>Best Practice</pre><pre>if (&#39;serviceWorker&#39; in navigator) {<br>  window.addEventListener(&#39;load&#39;, function() {<br>    navigator.serviceWorker.register(&#39;/service-worker.js&#39;);<br>  });<br>}</pre><p>What the code above does is wait for the application to load before registering the service worker.</p><p>The Install event is the best place to cached the minimum assets your app will initially need to boot. This may include any pages and pictures. You don’t want to install everything on the other hand because if any of the assets fail your service worker will not install. It will keep retrying. Essentially the more assets you have the chances of failing will be higher. I would recommend no more than 15 assets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*qtIt8dAD-G836z_c1JBsmw.png" /></figure><p>In the code above I created a staticCacheName called ‘site-static-v8’, in the install event the ‘waitUntil’ waits for all promises to be resolved. The first thing we do is create a cache with a given name. ‘caches.open(name)’ returns a cache which we use to add all of our assets. According to Mozilla, ‘ The <strong>addAll()</strong> method of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Cache">Cache</a> the interface takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache’. This simply means the addAll method takes in an array of URLs as an argument and for each URL does a fetch request to your server and caches the response as a key-value.</p><h4>Activation Event</h4><p>Once the service worker is installed activation is the next event. Activation event is the best places to handle existing old caches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*AJHFoD3p2GbGHd7huHKmOQ.png" /></figure><p>In the code above in my activate event I again call the waitUntil method. The first thing I do is get all the cache names, filter through and delete any that is an older version. You will only want to do this when you are updating your service worker.</p><h4>Fetch Event</h4><p>So now the service worker is installed and activated, It is time to handle requests from our UI. The Fetch Event is where all the magic happens. This is where we can intercept any request that the UI is making to the server. For Example, if the user is trying to request the index.html page since we have that page already cached we can send a response back which makes the application run much faster since we are not making any network calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PC4a6oPMIHZhdD0HlysgmA.png" /><figcaption>Example of a fetch event</figcaption></figure><p>In my fetch event, the first thing I do is make sure the request is not to my database in firebase. Fetch event is listening to every request event including POST, Get, Patch, and Delete, We do not want to cache data, we only want to cache Html pages, pictures, icons, and any other library that the UI will need to display information. All Data are being stored in IndexedDB which we will go next.</p><p>Next is checking if we have event request cached already If so we simply return the value as a response. But if we don’t have the response cache we will continue the fetch request to the service. Once we get a response we open a cache. In this example, our cache name is ‘<strong><em>site-dynamic-v8</em></strong>’ saved as ‘<strong><em>dynamicCacheName</em></strong>’. When opening a cache with the method ‘<strong><em>caches.open(*cacheName*)</em></strong>’ we get a cache as a response. we will use the cache.put method to add the response we get back from the server to the cache. The ‘<strong><em>cache.put(key, value)</em></strong>’ will take in two arguments, the first argument will be the ‘<strong><em>evt.request.url’ , </em></strong>The<strong><em> </em></strong>reason is if the user was to make the same request later we can use the event request URL as a key<strong><em>,</em></strong><em> the </em>second argument will be a clone response we get from the server then we simply return the original response we get from the fetch request.</p><p>If an error accord while doing the fetch request, In our catch error function we check if the request that the user was trying to make was for an HTML page. If so we send our fallback page. The reason for this is the user might only request to get an icon or a picture. We don’t want to send a fallback page if an icon or a picture failed to load.</p><p>I like to do (and this is optional) is to limit cache size. This method simply takes the cache name and the size we want to limit it to. The size is how many items we have, It is not the size of memory space. The reason for doing this is because we only have a limit amount of memory space. According to Google developers ‘<em>In Chrome, apps can use up to 6% of free disk space.</em>’ We would want to remove cache items that the user has not used to make room. The least used cached item will be at the top of the list, anytime we add a new cache item and we hit our limit space, we can simply remove the first item and add the new item.</p><ul><li>Chrome&lt;6% of free space</li><li>Firefox&lt;10% of frees pace</li><li>Safari&lt;50MB</li><li>IE10&lt;250MB</li><li>Edge — <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/storage/IndexedDB/">Dependent on volume size</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*nZSmnTsgweUvADdAU4pbbw.png" /><figcaption>Limit cache size</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*X2wDGckRsvXzThEN5i4d_A.png" /></figure><h4>IndexedDB</h4><p>So far we have covered a lot of materials, we went over what a PWA is, Advantages and Drawback, Requirements to build a PWA, What a Lighthouse, Manifest, Service Worker, and Service Workers events. The last thing we need to know is IndexedDB.</p><p>According to MDN web docs ‘<em>IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs.</em>’ Cache and Web Storage is great for storing a smaller amount of data, it is very difficult to store a large amount of data due to the limited amount of memory. This is where IndexedDB comes into play.</p><p>IndexedDB is like a SQL database system but instead of a fixed-column table, IndexedDB is a JavaScript-base object-oriented database. ‘ <em>IndexedDB lets you store and retrieve objects that are indexed with a </em><strong><em>key</em></strong><em>; any objects supported by the structured clone algorithm can be stored. You need to specify the database schema, open a connection to your database, and then retrieve and update data within a series of transactions</em>.’</p><p>We will use indexedDB to store user’s data and any data we want the user having access to when offline. When the user is offline we would want to still be able to display data to the UI as well as handling requests, including the ability to <em>Write</em>, <em>Update</em> and <em>Delete </em>while being offline<em> </em>and the moment the user reconnects to the Internet sync up our database with indexedDB.</p><p>This is where Firebase comes into play. Firebase is built on Google infrastructure and scales automatically, It gives you functionality like analytics and databases, messaging and so much more but most importantly firebase works great with indexedDB.</p><p>According to Firebase Docs ‘<em>Data Persistencecaches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. You can write, read, listen to, and query the cached data. When the device comes back online, Cloud Firestore synchronizes any local changes made by your app to the Cloud Firestore backend</em>. ’. This feature makes building a PWA so much easier, it is just one method that you have to call and automatically syncs the indexedDB with the Cloud Firestore.</p><pre>firebase.firestore().enablePersistence()<br>  .catch(function(err) {<br>      if (err.code == &#39;failed-precondition&#39;) {<br>          // Multiple tabs open, persistence can only be enabled<br>          // in one tab at a a time.<br>          // ...<br>      } else if (err.code == &#39;unimplemented&#39;) {<br>          // The current browser does not support all of the<br>          // features required to enable persistence<br>          // ...<br>      }<br>  });</pre><ul><li>Get Offline data — If you get a document while the device is offline, Cloud Firestore returns data from the cache. If the cache does have data for that document then it will throw an error.</li><li>Query offline data — Query works offline, but will initially run only against the cached documents.</li><li>Disable and enable network access — While the network is disabled, all document request retrieves the result from cache.</li></ul><pre>firebase.firestore().disableNetwork()<br>    .then(function() {<br>        // Do offline actions<br>        // ...<br>    });</pre><pre>firebase.firestore().enableNetwork()<br>    .then(function() {<br>        // Do online actions<br>        // ...<br>    });</pre><p>Now I don’t mean to sound like a Firebase salesman, Firebase is great for building new applications but what about an existing application that is not using Firebase for a database. IndexedDB API is powerful but can seem very complicated. There are libraries to help simplify working with indexedDB:</p><ul><li><a href="https://localforage.github.io/localForage/">LocalForage</a></li><li><a href="https://dexie.org/">dexie.js</a></li><li><a href="https://github.com/erikolson186/zangodb">ZangoDB</a></li><li><a href="https://pouchdb.com/">PouchDB</a></li><li>IDB</li><li>IDB<a href="https://www.npmjs.com/package/idb-keyval">-keyval</a></li><li><a href="http://jsstore.net/">JsStore</a></li></ul><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85c46ccb24f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Regular Expression]]></title>
            <link>https://medium.com/@prince.donkor74/master-regular-expression-613f2cf9ea6b?source=rss-cb347ffb7f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/613f2cf9ea6b</guid>
            <dc:creator><![CDATA[prince donkor]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 23:58:14 GMT</pubDate>
            <atom:updated>2018-08-13T19:42:51.493Z</atom:updated>
            <content:encoded><![CDATA[<p>The first time I saw regular expression it look complicated, I had no idea what what any of the characters mean and I just avoided for a while till I had to write a form for my website to find out it is actually pretty easy.</p><p>In this Article I will cover what are Regular Expressions, Why you should learn it, How to Create a regular expression pattern, What are special characters and Flags. I will not cover every single detail about Regular Expression but after reading this article you will be able to write your own Expression and understand the code below:</p><pre>password: /^[\w@-]{8,20}$/,</pre><pre>firstName: /^[a-z]{1,20}$/i,</pre><pre>lastName: /^[a-z]{1,20}$/i,</pre><pre>email : /^([a-z\d-]+)@([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/,</pre><pre>Cpassword: /^[\w@-]{8,20}$/</pre><h4>What are Regular Expression?</h4><p>Regular Expression allows us to check characters for matches, it allows us to check a form field to try and match a valid input. For example for a valid email it must have an @ symbol at a certain position and must end in extension like .com .org or .company.us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*UbIJu6qw3sZRoqOZx2Zf4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*wYAQ0hYkmeJm7vrqvai0gw.png" /></figure><p>Both of the screenshots show invalid email due to a missing @ or .com</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*0cBD69yqGmAwqAuQR-8D_w.png" /><figcaption>A valid email</figcaption></figure><p><strong>Why should you learn regular expression ?</strong></p><p>Simple answer is learn once, write anywhere. Regular expressions can be used for any programming language. Not only is it good for validation but also interacting with Unix shell, searching/refactoring code, database search and lots more.</p><p><strong>How to Create a regular expression ?</strong></p><p>There are two ways to create a regular express.</p><pre>const example = /ab+c/;</pre><p>One is a pattern enclosed between slashes like above. Most people do write expression this way.</p><pre>const example = new RegExp(&#39;ab+c&#39;)</pre><p>Second is calling the constructor function of the Regex object. Personally I never wrote regular expression this way.</p><h4>Writing your first RegExp</h4><p>I will be using <a href="https://regex101.com/">https://regex101.com/</a> to write simple regex then I will show how to write regex in your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*cF466jwvR55jR-cvWvCXhA.png" /></figure><p>Can see we type “abc” and we have a match!, we can type anything between slashes. But this will only match the first match. But what if we want to match all abc in our test string ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*4sl70R8Lj_eyXpN5pgmt6A.png" /></figure><p>If we want to match all ‘abc’ in our given string we will use a flag. A flag is a global pattern, which will be used for all of our test string. In our case we are using ‘<strong>g</strong>’ which tells the engine not to stop after the first match has been found, but rather to continue until no more matches can be found.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*rPcMpyMThSGF6eJq5j-dkw.png" /><figcaption>Regex flags</figcaption></figure><p>We can have case insensitive flags, which is a simple ‘<strong>i</strong>’ outside of the slashes next to the ‘<strong>g</strong>’.</p><p>But this is not the full power of regex what if we want to match both ‘<strong>abc’</strong> and ‘<strong>ebc</strong>’ ? Both of these words have bc at the end, the only change is the first word. We can surround ‘e’ and ‘a’ character in a square bracket and have bc afterwards.The bracket is only going to cover the first position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*vbhcP8r7XruZi4UkuLO_RA.png" /></figure><p>what if we want to exclude any set of words that begin with ‘<strong>r</strong>’ and ‘<strong>l</strong>’, well from what we just went over we can type all of the letters we do want but that will be very long. Instead we can use ^ in our bracket which will not match any letter inside of our bracket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*yQXh1yIaKVdtYx6RxUljjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*1RkE9kR65YpoUgG--vQRow.png" /></figure><p>What if we want to match all the letters in the alphabet ? we can use [a-z]. You may have noticed ‘<strong>i</strong>’ next ‘<strong>g’</strong> outside of our latches, this will cause code to be case insensitive. Now we can match uppercase and lowercase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*_I1-pdWUHgX5t-R9dxPI6w.png" /></figure><p><strong>Repeating Characters</strong></p><p>We have mostly talked about and weights well what about numbers? Let’s say you have to match a 10 digit phone number? we could just write our range and repeat but this is likely to cause an error down the road.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*5Wor2aVkhIBYQOXue08Eag.png" /></figure><p>To solve this problem we can use a Quantifier which will match exactly 10 times [0–9] rather the repeating [0–9]. We can also apply this for letters and set a range in our Quantifier. The first number being the minimum and second is the maximum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*xkl7_9-AsURSCLuFIVPoUg.png" /></figure><p>You may look at the example and see it is match all os the letters in the long string. But what it is actually doing is starting all over again once it hit the maximum number. ‘somera’ has the length of 6 which is my max. ‘ndomst’ is also the length of 6. The shades of blue makes it easier to spot the different matches. Also a side note that the end of our long string ‘er’ was not match due to it not have the length of 4.</p><p><strong>Metacharacters</strong></p><p>Metacharacters are characters that have special meaning in regex, there is a lot of metacharacters, I will not cover all of them, instead check out mozilla docs <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions</a> which goes over all the metacharacters if you are interested. What i will go over is the common ones.</p><pre>\d - match any digit character(same as [0-9])</pre><pre>\w - match any word character (a-z, A-Z, 0-9 and _&#39;s)</pre><pre>\s - match a space or tab</pre><pre>\t match a tab character only</pre><pre>must be careful just using &#39;d&#39; will match character &#39;d&#39; </pre><pre>&#39;\d&#39; will change it to be a metacharacter </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ImRx1oSKsKsnwiNVLN2EtQ.png" /></figure><p>‘<strong>\d</strong>’ — matches a digit (equal to [0–9])</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*pe0lAedjWTlqdAaX75jX0w.png" /></figure><p>‘<strong>\w</strong>’ — matches any word character (equal to [a-zA-Z0–9_])</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Mi6ktSOgie_IKK7aUEHDpQ.png" /></figure><p>‘<strong>\s</strong>’ — matches any whitespace character</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*Y4zX8MHz1w6VRDoQSgDfzg.png" /></figure><p>Let&#39;s combine what we have learned to match a phone number.</p><pre>\d{3}</pre><pre>matches a digit (equal to [0–9])</pre><pre>{3} <strong>Quantifier</strong> — Matches exactly <strong>3</strong> times</pre><pre>\s matches any whitespace character </pre><pre>\d{3}</pre><pre>matches a digit (equal to [0–9])</pre><pre>{3} <strong>Quantifier</strong> — Matches exactly <strong>3</strong> times</pre><pre>\s matches any whitespace character</pre><pre>\d{4}</pre><pre>matches a digit (equal to [0–9])</pre><pre>{4} <strong>Quantifier</strong> — Matches exactly <strong>4</strong> times</pre><p><strong>Special Characters</strong></p><p>We have already used a few special characters like ‘\’ and ‘[]’</p><pre>[] - character set</pre><pre>\ -The escape character (used when creating a Metacharacters)</pre><pre>&#39;+&#39; - We have not used this yet but it simply means one or more. Much like a quantifier of {1}. You place it after a set and you want one or more to match.</pre><pre>[^] - Negate symbol, (what you do not want to match, this is also used in-front of the start of regex).</pre><pre>&#39;?&#39; - the zero or one quantifier(optional)</pre><pre>&#39;*&#39; - 0 or more quantifier </pre><pre>&#39;.&#39; - Any character (except the newline character)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*c-bPCZEKDgduyp8FC2_7MQ.png" /></figure><p>The question mark makes ‘<strong>\d</strong>’ which is [0–9] optional</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*YdhubiCQWBI1jp8jbWpljA.png" /></figure><p>example matches the characters example literally (case sensitive)</p><p>‘.’ matches any character, will not match if there is not last character</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=613f2cf9ea6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Week 3 Full Stack]]></title>
            <link>https://medium.com/@prince.donkor74/week-3-full-stack-51e63bc5477c?source=rss-cb347ffb7f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/51e63bc5477c</guid>
            <category><![CDATA[eventemitter]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[callback]]></category>
            <dc:creator><![CDATA[prince donkor]]></dc:creator>
            <pubDate>Sun, 01 Jul 2018 16:31:56 GMT</pubDate>
            <atom:updated>2018-07-01T16:31:56.132Z</atom:updated>
            <content:encoded><![CDATA[<p>For week 3 we learned about :</p><ul><li><strong><em>Callback and Event-Emitters, * Promises, *Express-Sequelize, *Front-end-Modules, * AJAX, *ES6-Modules, * React Component- Lifecycle, * FullStack-Data-Flow</em></strong></li></ul><h3><strong><em>CallBack and Event-Emitters</em></strong></h3><p>A CallBack is a function that is passed to another function</p><p>There are two types of CallBacks :</p><ul><li>Blocking</li></ul><pre>predicates - a function that determines whether something is true or false based on the arguments<br>arr.select(function predicate(elem) {...});</pre><pre>comparators - needs two arguments, the first and the second element it should compare<br>arr.sort(function comparator (elmA, elmB) {...})</pre><pre>iterator- described by a structure that contains a pointer to the next element in the iteration.<br>arr.map(function iterator(elem) {...})</pre><ul><li>Non-Blocking</li></ul><pre>event handlers- when a user clicks on the html element it will execute the function.<br>button.on(&#39;click&#39;, function handler(data) {..});</pre><pre>middleware - unctions that have access to the request object ( req ), the response object ( res ), and the next function in the application&#39;s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.<br>app.use(function middleware (req,res,next){...})</pre><pre>vanilla async callback - returns an asyncFunction object<br>fs.readFile(&#39;file.txt&#39;,function callback(err,data){...})</pre><p>Event Emitters is a code pattern of deferring certain functions to execute only in response to certain ‘events’, it acts exactly like DOM event but is not restricted to events that are emitted by the environment — we listen for emit any events we choose by writing our own event emitter.</p><pre>Example <br>const userMessage = new EventEmitter();</pre><pre>userMessage.on(&#39;newMessage&#39;,function (message){</pre><pre>console.log(message.text)<br>})</pre><pre>userMessage.emit(&#39;newMessage&#39;,{<br>text: &#39;this is a new message&#39;</pre><pre>})<br>An instance of the observer/observable<br>Objects that can emit specific events with a payload to any amount of registered listeners.</pre><h3><strong><em>Promises</em></strong></h3><p>A promise is a javascript object with two(hidden) properties : value and state</p><p>When a promise is created its state is pending and its value id null. Once an asynchronous operation completes, a promise can evaluate two ways: 1 — If the not error, it will internally resolve otherwise 2- it will internally reject.</p><pre>pg / Sequelize queries/ db actions, AJAX(axios, fetch) are all existing libraries that may return promises.</pre><pre>const fs = require(&#39;fs&#39;)<br>const {promisify} = require(&#39;util&#39;)</pre><pre>const readFileAsync = promisify(fs.readFile);</pre><pre>const exampleOfPromise = new Promise((resolve,reject)) =&gt; {...} //creating a promise </pre><p>A promise object acts as a placeholder for the eventual results of an asynchronous operation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErGhhFYESOstN8zNxtV1KQ.png" /></figure><p>Promises looks and acts much like a synchronous code but has error handling and can be portable</p><pre>let result = readFileAsync(&#39;/file.txt&#39;)</pre><pre>let num = await result</pre><pre>//note this will be in an async function</pre><p>Async Function — A function which can contain an await expression, that pauses the execution of the async function and waits for the passed Promise’s resolution.If the promise fulfills, you get the value back else the rejected value is thrown.</p><p>Async functions always return a promise even if you use await or not.</p><pre>async function anAsyncFunction() {</pre><pre>try{<br>const result = await promise </pre><pre>}catch(err){</pre><pre>console.log(err)<br>}<br>}<br>// we put this in a try catch which will be able to catch the error if the promise was not fulfill or make the result the value of the promise if it is.</pre><p><strong><em>Sequential vs Parallel</em></strong></p><p>Sequential will run all the promises in order, where Parallel will run all at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*gx3W2pFE4jiWx8Hxr0PH8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*rEATH9i6dmzwLALMQ2rjgw.png" /></figure><p>Promise .all([promise1, promise2]) — Returns a single promise that resolves when all of the promises in the argument have resolved. Reject if any of the passed promises are rejected.</p><p><strong><em>.then</em></strong></p><p>Accepts up to two arguments but are optional. for then you ca attach as many as you want. Every call to .then return a new promise!</p><p><strong><em>.catch</em></strong></p><p>Much like .then but .catch only accepts an error handler, and rejection will bubble down to the first error hander.</p><pre>Files.findByID(1)<br>.then(file ={<br>return file.update()</pre><pre>}).then(result =&gt; {</pre><pre>console.log(result)<br>}).catch(err =&gt;{<br>console.log(err)</pre><pre>})</pre><h3><strong><em>Express-Sequelize</em></strong></h3><p>Custom error handler — Express comes with a build-in error hander. Define error-handling middleware just like other middleware but instead function have four arguments instead of three : (err,req,res,next)</p><pre>app.use((err,req,res,next)=&gt;{</pre><pre>console.error(err.stack)<br>res.status(500).send(&#39; a picture stating page is not found&#39;)</pre><pre>})</pre><p>Sequelize : Class and instance methods- ways to add functionality to your sequelize</p><p>models.</p><pre>Const tableExample = db.define(&#39;example&#39;,{/* . etc */}) // after creating a table </pre><pre>tableExample.findFiles = function(){</pre><pre>return this.findAll({</pre><pre>//the this. findAll is the same as table.Example.findAll </pre><pre>{</pre><pre>where:{</pre><pre>version : {$lte : 1}<br>}<br>}<br>})<br>}</pre><pre>we can call the function findFiles on tableExample :<br>const result = await tableExample.findFile()</pre><p>Associations in Sequelize establish three things:</p><ol><li>For one-one or one-many associations, it establishes a foreign key relationship between two tables (though a table could be related to itself). For many-many associations, it establishes a join-table that contains pairs of foreign keys.</li><li>It creates several special instance methods (like “getAssociation”, “setAssociation”, and potentially others depending on the type of association) that an instance can use to search for the instances that they are related to</li><li>It creates the ability to use “include” in queries to include data about related rows (known as “eager loading”)</li></ol><p><strong><em>Types of Associations</em></strong></p><p>It is possible to specify the following associations in Sequelize:</p><ul><li>belongsTo</li><li>hasOne</li><li>hasMany</li><li>belongsToMany</li></ul><p>These relations can be combined to establish <em>one-one</em>, <em>one-many</em> and <em>many-many</em>relationships, like so:</p><ul><li>one-one</li><li>A.belongsTo(B)</li><li>B.hasOne(A)</li><li>one-many</li><li>A.belongsTo(B)</li><li>B.hasMany(A)</li><li>many-many</li><li>A.belongsToMany(B, {through: &#39;AB&#39;})</li><li>B.belongsToMany(A, {through: &#39;AB&#39;})</li></ul><p><strong><em>WebPack (a compiler )</em></strong></p><p>WebPack is A tool that bundles our frontend Javascript. So it allows us to use `require` and `module.exports` in frontend “source” code, which it then compiles into a single file.</p><pre>- Install it: `npm install --save-dev webpack webpack-cli`<br>- Define our webpack.config.js<br>- Run it: `./node_modules/.bin/webpack`</pre><pre>When you run webpack there are some things it knows:<br>- it knows how to find files<br>- it knows how to squish a bunch of files into one (&quot;bundling&quot;)<br>- ...other things about how to compile</pre><pre>But it doesn&#39;t know some things (project specific):<br>- where the &quot;root&quot; entry point of our frontend source is<br>- where we want the bundle to go<br>- what type of debugging we will want to do</pre><pre>The standard way is to make a `webpack.config.js` file that exports an object containing such options.</pre><pre>(For example see the file over in `./tripplanner-modular-frontend-solution/webpack.config.js`.)</pre><h3><strong><em>Front-end-Modules</em></strong></h3><p>A browser navigate and retrieve new documents from the server by:</p><ul><li>URL bar</li><li>Links</li><li>JavaScrip(window.location.href = ‘http://www.google.com’)</li><li>submitting forms (get/post)</li></ul><p>NOT a Single page applications vs Single-page application(spa)</p><p><strong><em>NOT a single page applications </em></strong>— views stored on the server, served up as html pages, when user goes to a new page, the browser navigates in totality, refreshing and retrieving a brand new html document and each page, since it is a new page, retrieves stylesheets, script, file and everything from the server.</p><p><strong><em>Single-page application</em></strong> is a web application or web site that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from a<br>server.”</p><h3><strong><em>AJAX</em></strong></h3><p><strong><em>AJAX</em></strong> stands for Asynchronous JavaScript and XML, it makes background http request using javascript, hands the response of those http requests with javascript and no page refresh is needed.</p><p><strong><em>Data Serialization formats</em></strong> — is how real data is transported or stored. Used for delivery of data over limited transports like http. examples are JSON, XML and Yaml.</p><p><strong><em>window.fetch() </em></strong>— The Fetch API provides an interface for fetching resources (including across the network). This method takes one argument, which is the path to the resource you want to fetch. It returns a Promise.</p><h3><strong><em>React Component- Lifecycle</em></strong></h3><p>React is a JavaScrip library for building user interfaces. it contain state which is a data that changes, when state update, React re-renders the view.</p><p><strong><em>Lifecycle </em></strong>is when we render a component, React components go through several different stages in addition to the render stage.</p><p><strong><em>Render</em></strong> is when React compares the JSX output of the render method with it’s internal “virtual DOM”, and makes a decision about how to update the actual DOM in a performant way.</p><p><strong><em>Virtual Dom</em></strong> is a JavaScript object representing the DOM tree, changing the DOM directly is expensive so react does a little bit of JavaScript first so it can do as little manipulation of the actual DOM as possible.</p><p><strong><em>Mounting</em></strong> — When the JSX your component represents gets turned into real, live DOM nodes by React, your component is said to be “mounted”.</p><p><strong><em>Component Did Mount </em></strong>— is a function that fires after the initial rendering, it is a good place to perform any AJAX request to get data from your server and adding event listeners.</p><pre>class example extends React.Component {</pre><pre>constructor(){<br>super()<br>this.state={<br>information : []<br>}<br>}</pre><pre>async componentDidMount(){<br>const res = await axios.get(&#39;/api/allFiles&#39;) // getting data from our //api, axios is another way to fetch information from our api <br>const information - res.data // we only want the data off our result<br>this.setState({information: information}) // now we are changing the //state of information<br>}</pre><pre>}</pre><p><strong><em>Map over list </em></strong>— can use map to turn list of data into JSX, great for tables and list. It is important that each set of JSX in the list needs to be given a special ‘key’ prop</p><pre>//example of using map to make a list of puppy name.<br>const DogList = (props) =&gt; {<br> // [{id: 1, name: &#39;Cody&#39;}, {id: 2, name: &#39;Lexie&#39;}]<br> const puppies = props.puppies<br> return (<br> &lt;ul&gt;<br> {<br> puppies.map(puppy =&gt; &lt;li key={puppy.id}&gt;{puppy.name}&lt;/li&gt;)<br> }<br> )<br>&lt;/ul&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51e63bc5477c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Week 2 Full Stack]]></title>
            <link>https://medium.com/@prince.donkor74/week-2-full-stack-2b49bf7f6c99?source=rss-cb347ffb7f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b49bf7f6c99</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[bubble-sorting]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[prince donkor]]></dc:creator>
            <pubDate>Sat, 30 Jun 2018 22:44:22 GMT</pubDate>
            <atom:updated>2018-06-30T22:44:22.703Z</atom:updated>
            <content:encoded><![CDATA[<p>Week 2 at full stack, we mainly focus on the back end.</p><p>Here is a list of all the topics we went over and I will give a brief explanation and examples for each topic.</p><ul><li><strong>Algorithms</strong>, *<strong> Bubble Sorting, * Merge Sorting, * Client-Server, * Node, * Express, * Database and Postgres, * SQL, * Async Await, * Node-Postgres, * Express Routers and Rest, and lastly * Sequelize.</strong></li></ul><h3><strong>Algorithms</strong></h3><p>An Algorithms is a set of instructions a computer follows, we can think of this as a recipe which tells your computer exactly what steps to take in order to solve a problem or reach a goal.</p><p>There are six types of Algorithms:</p><ul><li>Step by step instructions(deterministic)</li><li>Complete(gets you an answer)</li><li>Finite(doesn&#39;t waste time getting the correct answer but it gets close enough)</li><li>Correct(the exact answer)</li><li>Downside(when the problem is too hard or its taking too long to solve)</li></ul><p><strong>Comparing Algorithms Using Big O Notation</strong></p><p>Big O Notation took me a while to understand but after I took my time to understand it I can calculate how much time each of my function will take.<br>Big O notation is done by humans and used to explain the performance or complexity of an algorithm.<br>First ask: what is the resource we care about: time or space.</p><p><em>For time:</em></p><ul><li>“Count the steps” for each line of code.</li><li>Determine how many times each loop will cycle.</li><li>Multiply that by the steps inside the loop. (repeat if it contains loops)</li><li>Add up all the numbers.</li><li>For recursive algorithms we need a different approach. (diagram and reason about the call tree)</li><li>Drop the constants.</li><li>Drop the non-dominant terms.</li></ul><p><em>For space:</em></p><ul><li>“Count the memory” for each line of code.</li><li>Determine how many times each loop will cycle.</li><li>Multiply that by the steps inside the loop. (repeat if it contains loops)</li><li>Add up all the numbers.</li><li>For recursive algorithms we need a different approach. (diagram and reason about the call tree)</li><li>Drop the constants.</li><li>Drop the non-dominant terms.</li></ul><p>For more about Big O check out this article ‘A beginner’s guide to Big O notation’ which helped me when I was first trying to understand.</p><p><a href="https://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/">A beginner&#39;s guide to Big O notation</a></p><p>What is a comparator? <br>A comparator is callback that sort algorithms can use, it will work by comparing two elements at a time and determining whether they are in order or not.</p><p><strong>Bubble Sorting</strong></p><p>Bubble sorting is an algorithm that repeated steps through the list until if is sorted</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*fgpalmFEER_uCrxMduuqSA.png" /></figure><p>In my code above I started ‘end’ as the length of the array that is being passed in and I subtract one per loop. (the reason why I subtract one instead of making it infinity is once we loop through the first time we know that the largest number will be the last in our array, it will be a waste of time and memory if we keep going to the end of the array when we don’t need to)<br>In side of our end loop we have another loop that will loop to the length of end, it will pass the array and the index of j to in-order which is a Comparator, it simply returns a boolean if the current number and the number on next to it both are in order or not, if not we will pass it inside swap which will switch the position of the current index number and the number next to it.</p><p><strong>Merge Sorting</strong></p><p>Merge sort divides and array into half until each number is in its own array then merges the two sorted halves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*Gb5v_BbTZR-HHzU8SuCu0A.png" /></figure><p><strong>Client-Server</strong></p><p>Client-side is being able to run JavaScrip code on the client machine instead of sending request to the server side.</p><p>Server-side is when the JavaScrip code run on the server which servers web pages.</p><p>According to Joe Karlesson there are three different client server relationships.</p><ul><li><strong>XHR</strong> is optimized for “transactional” request-response communication: the client sends the full, well-formed HTTP request to the server, and the server responds with a full response. There is no support for request streaming, and until the Streams API is available, no reliable cross-browser response streaming API.</li><li><strong>SSE</strong> enables efficient, low-latency server-to-client streaming of text-based data: the client initiates the SSE connection, and the server uses the event source protocol to stream updates to the client. The client can’t send any data to the server after the initial handshake.</li><li><strong>WebSocket</strong> is the only transport that allows bidirectional communication over the same TCP connection the client and server can exchange messages at will. As a result, WebSocket provides low latency delivery of text and binary application data in both directions.</li></ul><p><strong>Node</strong></p><p>Node.js is an open source server environment, it is written in JavaScript.</p><p>Node.js eliminates the waiting, and simply continues with the next request.</p><p>Node.js runs single-threaded, non-blocking, asynchronously programming, which is very memory efficient.</p><p>Node.js can generate dynamic page content, create, open, read, write, delete, and close files on the server, collect form data and add, delete, modify data in your database.</p><p>Node.js handles a file request</p><ul><li>sends the task to the computer file system</li><li>ready to handle the next request</li><li>The file system has opened and read the file, the server returns the content to the client.</li></ul><p><strong>Express</strong></p><p>Express is a node.js web application framework that provides set of features for web and mobile applications.</p><p>To create a new express</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*hB1rDBhKSXOy7EsIcx_rNA.png" /></figure><p>For this example we first installed express( npm install express ), we then need to require it, create a new app by invoking express. We then set a listening port, in our case we are listening to port 3000, we created two local host path, to get to the main page users have to go to localhost:3000</p><p><strong>Database and Postgres</strong></p><p>PostgreSQL is an open source a database management system (DBMS) that uses and extends the SQL language combined with many features that safely store and scale the most complicated data workloads.</p><p><strong>SQL</strong></p><p>SQL stands for Structured Query Language, it lets you access and manipulate database.</p><p>According to w3 SQL can:</p><ul><li>execute queries against a database</li><li>retrieve data from a database</li><li>insert records in a database</li><li>update records in a database</li><li>delete records from a database</li><li>create new databases</li><li>create new tables in a database</li><li>create stored procedures in a database</li><li>create views in a database</li><li>set permissions on tables, procedures, and views</li></ul><pre>SELECT * FROM Customers;</pre><p>the code above will get all the data from customers</p><p><strong>Async Await</strong></p><p>Before we start to understand async we must understand what a promise is.</p><p>According to Sandeep Panda “A Promise object represents a value that may not be available yet, but will be resolved at some point in the future. It allows you to write asynchronous code in a more synchronous fashion.”</p><p>An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise’s resolution, and then resumes the async function’s execution and returns the resolved value.</p><p>example from developer mozilla</p><pre>function resolveAfter2Seconds() {<br>  return new Promise(resolve =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve(&#39;resolved&#39;);<br>    }, 2000);<br>  });<br>}</pre><pre>async function asyncCall() {<br>  console.log(&#39;calling&#39;);<br>  var result = await resolveAfter2Seconds();<br>  console.log(result);<br>  // expected output: &quot;resolved&quot;<br>}</pre><pre>asyncCall()</pre><pre>The resolveAfter2Seconds returns a promise which will simply wait 2 seconds,(you can imagine this as getting data from api which sometimes may delay)in the asyncCall function we will first console log calling, but we will not be able to console log result until the promise for resolveAfter2Seconds is resolved. In an async function everything will go in order, usually javascript will not wait, it will simply go to the next line of code and execute it but due to the function being an async it will execute in order. </pre><p><strong>Node Postgres</strong></p><p>Node-postgres is a collection of node.js modules for interfacing with your PostgreSQL database. It has support for callbacks, promises, async/await, connection pooling and so much more.</p><pre>npm install pg </pre><pre><strong>const</strong> { Client } = require(&#39;pg&#39;) <br><strong>const</strong> client = <strong>new</strong> Client()  </pre><pre>How to connect, query and disconnect with async/await </pre><pre>const init = async function() {<br><strong>await</strong> client.connect()<strong><br>}<br></strong></pre><p><strong>Express Routers</strong></p><pre>(app.js file)</pre><pre>const express = require(&#39;express&#39;)</pre><pre>const app = express()</pre><pre>//how to require routes<br>app.use(&#39;/&#39;,require(&#39;./router&#39;))</pre><pre>app.listen(3000, () =&gt; {</pre><pre>console.log(`Server running at port 3000`)</pre><pre>})</pre><p>Above is our main app.js, below is our router. We could put all of this in the same file but it will quickly add up, if we want different url that we can have different file for every different url. There is a routing method app.all() which is not derived from any HTTP method. This routing method gets loaded for functions at a specified path for all request methods.</p><pre>(router.js file)</pre><pre>const router = express.Router()<br>router.get(&#39;/&#39;,(req,res) =&gt;{<br>res.send(&#39;this is the router page&#39;)</pre><pre>})</pre><pre>module.export = router</pre><p><strong>Sequelize</strong></p><p>Sequelize interacts with databases. Maintaining relationships between tables, fetching related records and managing transactions. It is easy to use compare to queries, and very useful when creating api.</p><p>Creating a simple database with two columns firstName and lastName</p><pre>npm install sequelize<br>const Sequelize = require(&#39;sequelize&#39;)<br>const db = new Sequelize(&#39;postgres://localhost:5432/your-db&#39;)</pre><pre><br>const User = db.define(&#39;user&#39;, {<br>  firstName: {<br>    type: Sequelize.STRING<br>  },<br>  lastName: {<br>    type: Sequelize.STRING<br>  }<br>});<br>// we stated these table must be a string, if a user was to type in a number it will reject the input and throw an error.</pre><pre>// force: true will drop the table if it already exists<br>await User.sync({force: true})<br>// Table created</pre><pre>await User.create({<br>  firstName: &#39;John&#39;,<br>  lastName: &#39;Hancock&#39;<br>})</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b49bf7f6c99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Week 1 Full Stack]]></title>
            <link>https://medium.com/@prince.donkor74/full-stack-week-1-abstract-data-types-data-structures-6c229f1f931e?source=rss-cb347ffb7f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c229f1f931e</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[prince donkor]]></dc:creator>
            <pubDate>Sat, 30 Jun 2018 16:26:17 GMT</pubDate>
            <atom:updated>2018-07-01T18:54:03.971Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Abstract Data Type And </strong>Data Structures</h3><p>The day one of Fullstack Academy was a wake up call, usually the first day of school, you expect an easy day, meet everyone in your class, go over a couple of rules and where everything is, well in Fullstack Academy, we did all of that within 3 hours or so, after that we jumped right into learning the first topic which was shocking for me. ///adapted<br>We learned about abstract Data Types. There are four we learned that day.</p><p><strong>Stack</strong> — A Stack is defined by the following structure and operations, and it is an ordered collection of items in which are added and removed from the end, which is called the “top.” In Full Stack, we call this LIFO(last in, First Out) , must like a stack of pancake, the first pancake to be placed down will be the last to be eaten, due to us starting from the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKkC1S_KQ1anXIOgOc92Yw.png" /></figure><p><strong><em>Stack operations</em></strong><em>- </em>there are 5 different operations,.</p><p><strong><em>stack()</em> </strong>— which creates a new stack that empty.</p><p><strong><em>push(value)</em></strong>- which adds a new item to the top or in-front of the array.</p><p><strong><em>pop()</em> </strong>— which in an array it will remove value from the end, but in stack case it will remove value from the front.</p><p><strong><em>peek()</em></strong>- simply returns what value is at the top.</p><p><strong><em>isEmpty()</em></strong>- returns a Boolean determining if the stack is empty and the last one is <strong><em>size()-</em></strong>returns how many values we have in our stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dz1mX2KR9MQvzgnFgZKSxA.png" /></figure><p><strong>Queue</strong> — A Queue is stored like stack but follows the rule of first in, first out. As a value enters like stack the removal of a value is called “rear”, the end of the stack. I think of it like people in line, the first person that came first or is in-front of the line will go.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vmM4XUZMp2sgHOsRLmEJhw.png" /></figure><p><strong>Linked List</strong> — Uses nodes which have values and pointers(s) to other nodes, it does not require each node to be next to one another which makes it more flexible then array, it by far the easiest to resize and dynamic, can insert values anywhere including the middle.Where as stack and queue can only insert in the front or back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*sBer__pqGZ88azSErOmoSQ.png" /></figure><p><strong>Binary Tree</strong> — Binary Search tree allows us to search through root nodes by repeatedly cutting the array in half. It checks if the value is greater or less the root value, if less then, it will travel down the left node else the right node and repeats the step until the root value is the same as value or if that value is in the tree.</p><h3><strong>The DOM (</strong>“Document Object Model”)</h3><p>The DOM is a model for the elements currently on the page, it is dynamic and represents each element as an object we can interact with directly through JS.</p><p><strong>Higher-order function — </strong>takes in another function (or multiple functions) as an input or return a function.</p><p><strong>Events —</strong> Event listener at first seems to be complicated but over time you can image programming a full working web page without it. //wtf</p><p>Event Listener method is when you start a function when a user click a link, enters a form, move his or her mouse over an element, scrolls or does anything within the Dom.</p><pre>&lt;button id=’test’ onClick=’alert(‘Hello, World’);’&gt; &lt;/button&gt;</pre><p>For the example above if the user was to click the button, an alert will pop on their webpage stating ‘Hello World’</p><pre>In JavaScript we can do this by first getting the element we want.<br>let myElement = document.getElementById(‘test’)<br>We can add our on click listener :<br>myElement.onClick = function(){alert(‘Hello World’)}</pre><p>In Full Stack we used an event listener to build a game of life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c229f1f931e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fullstack Academy Foundations]]></title>
            <link>https://medium.com/@prince.donkor74/fullstack-academy-foundations-b079d190653f?source=rss-cb347ffb7f24------2</link>
            <guid isPermaLink="false">https://medium.com/p/b079d190653f</guid>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[prince donkor]]></dc:creator>
            <pubDate>Sat, 30 Jun 2018 16:00:33 GMT</pubDate>
            <atom:updated>2018-06-30T16:00:33.056Z</atom:updated>
            <content:encoded><![CDATA[<p>Before starting Fullstack Academy, a student must finish a program call foundations, which is a four week, part time, remote curriculum geared to solidify the fundamentals needed to succeed at Fullstack.</p><p>Foundations is required and crucial for your success at Fullstack and Grace Hopper. In the past, students that were successful in Foundations were also successful throughout the Immersive Curriculum.</p><p>On Fullstack website, they stated it will take roughly 80–100 hours and is divided into four different parts, but for me due to me working full time during the foundation, I would say took around 60 hours, I had the fear that i would not be able to finish the program in time due to me getting accepted a week late to the program and only having 3 weeks to finish foundation. Everyday after work (around 5pm) I would head to Clark University and stay until 12 to do as much of foundation as I can.</p><p>Foundations has an excellent support system which includes access to instructors, office hours, individual mentors, and more! Foundations support creates a remote learning environment to help students thrive and stay on pace to complete Foundations, which I used to my advantage when i get stuck.</p><p>First things students do in Foundation is the Command line. This selection takes around 2 hours to complete, its explains what a command line, keyboard shortcuts, Cursor Navigation, Directories and Filesystems, Navigating the FS, making Directories and much more. After completing the command line selection, I was able to navigate through my FS like I do in windows.</p><p>The second section on the first foundation focused on Exploring Git. This section was about Version Control System(VCS), using basic git commands like git add, git commit, git status and git log. Later down the selection is when we learn to make a local git repository using git init and using git push origin master to push our work to our remote GitHub.</p><p>Im not going to go in full details of the foundations for Full stack due to it just covering the basics of JavaScript like mapping and looping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b079d190653f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>