<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Learn | Think | Code</title>
	<atom:link href="https://johnyzaguirre.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://johnyzaguirre.com</link>
	<description>Projects i&#039;ve worked on, articles i&#039;ve written, and tutorials i&#039;ve recorded</description>
	<lastBuildDate>Fri, 08 May 2020 13:55:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.6.8</generator>

<image>
	<url>https://johnyzaguirre.com/wp-content/uploads/2020/04/cropped-kisspng-incandescent-light-bulb-emoji-led-lamp-symbol-5aff6eb3f3aaf8.7281496115266894599981-32x32.png</url>
	<title>Learn | Think | Code</title>
	<link>https://johnyzaguirre.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Learning React Part 1: A Gentle Introduction</title>
		<link>https://johnyzaguirre.com/2020/05/02/react-a-gentle-introduction-part-1/</link>
					<comments>https://johnyzaguirre.com/2020/05/02/react-a-gentle-introduction-part-1/#respond</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Sat, 02 May 2020 16:11:05 +0000</pubDate>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[react]]></category>
		<guid isPermaLink="false">https://johnyzaguirre.com/?p=1613</guid>

					<description><![CDATA[Here&#8217;s what you should be fairly comfortable with, before starting this tutorial: Setup First thing is to download the getting started files. I am going to pull down my own customized create-react-app setup from GitHub. Here are the terminal commands I use to get the hello world webpage: You should now see a browser window &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2020/05/02/react-a-gentle-introduction-part-1/" class="more-link">Continue reading<span class="screen-reader-text"> "Learning React Part 1: A Gentle Introduction"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p></p>



<div class="wp-block-image is-style-default"><figure class="aligncenter size-large"><img loading="lazy" width="1914" height="1010" src="https://johnyzaguirre.com/wp-content/uploads/2020/05/Screen-Shot-2020-05-02-at-11.32.35-AM.png" alt="" class="wp-image-1624" srcset="https://johnyzaguirre.com/wp-content/uploads/2020/05/Screen-Shot-2020-05-02-at-11.32.35-AM.png 1914w, https://johnyzaguirre.com/wp-content/uploads/2020/05/Screen-Shot-2020-05-02-at-11.32.35-AM-300x158.png 300w, https://johnyzaguirre.com/wp-content/uploads/2020/05/Screen-Shot-2020-05-02-at-11.32.35-AM-768x405.png 768w, https://johnyzaguirre.com/wp-content/uploads/2020/05/Screen-Shot-2020-05-02-at-11.32.35-AM-1536x811.png 1536w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<p>Here&#8217;s what you should be fairly comfortable with, before starting this tutorial:</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container">
<div class="wp-block-group"><div class="wp-block-group__inner-container">
<div class="wp-block-group"><div class="wp-block-group__inner-container">
<div class="wp-block-group"><div class="wp-block-group__inner-container">
<ul><li>HTML tags</li><li>Javascript and ES6 syntax</li><li>the built in Array.map() method</li><li>using the terminal to change directories</li><li>installing packages using npm or yarn</li></ul>
</div></div>
</div></div>
</div></div>
</div></div>



<h2>Setup</h2>



<p>First thing is to download the getting started files. I am going to pull down my own customized create-react-app setup from GitHub. Here are the terminal commands I use to get the hello world webpage:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">git clone https://github.com/sojohnnysaid/custom-create-react-app.git hello-world
cd hello-world
yarn install
yarn develop</pre></div>



<p>You should now see a browser window with some text. In your IDE you can use the hello-world folder as your root directory. Everything we code from this point on is in the src/index.js file.</p>



<h2>What is JSX? First example without JSX</h2>



<p>JSX stands for javascript XML and is a shorthand for the way React creates custom HTML elements. For example, In React, without JSX:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'


ReactDOM.render(React.createElement('App',{},'Hello! No JSX being used'), document.getElementById('root'))</pre></div>



<p>This will render the text to the browser, and if we inspect we can see it is wrapped in tags. We use uppercase in our javascript for elements to differentiate them from normal HTML elements.</p>



<h2>Adding a class based component</h2>



<p>So far we&#8217;ve added an element directly into the ReactDOM render method. Let&#8217;s create a class with it&#8217;s own render() method and insert that into the reactDOM method as a variable.</p>



<p>Instead of &#8216;App&#8217; as a string we will pass it directly as a class:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
    	return React.createElement('div', null, 'component class no JSX')
    }                                   
}

ReactDOM.render(React.createElement(App, null, null), document.getElementById('root'))</pre></div>



<p>This puts our string inside of div tags. We can also change it to h1 tags or any kind we want:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
        //wrapping our string in h1 tags instead
    	return React.createElement('h1', null, 'component class no JSX')
    }                                   
}

ReactDOM.render(React.createElement(App, null, null), document.getElementById('root'))</pre></div>



<p>The createElement method takes 3 arguments &#8211; component, props, and children. This method is flexible and allows you to pass a custom element name for the component or an entire class using the name like we&#8217;ve shown above. Props are properties and they allow us to manipulate data from outside of our class. Finally children as basically what is inside our component. Our component is like the parent. If we look at the example above our h1 tag is the parent and inside is the children, our string &#8216;component class no JSX.&#8217;</p>



<h2>More about props</h2>



<p>Not a huge fan of shortening things because it adds confusion. Props is short for properties, and it allows us to fill in data. What are we filling? A class is just a blueprint for an object instance. I&#8217;m going to change our tag to a custom tag called &#8216;App&#8217; instead of the standard h1 tag. In our class we can create placeholders when we add our string inside the parent like this:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
    	return React.createElement('App', null, `component class with a ${this.props.text} but no JSX`)
    }                                   
}

ReactDOM.render(React.createElement(App, {text: 'property'}, null), document.getElementById('root'))</pre></div>



<p>If you inspect the webpage, notice how was now have custom tags. Our class blueprint now has a property called &#8216;text&#8217; which we can access using the props argument in React&#8217;s createElement method. The second argument to the createElement is always an object and we include the property name and the value we want to pass in when our new object is created from our App class. We don&#8217;t have to pass a third argument when we use a class in the first argument, it will pass null by default if we left it out. This works the same:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
    	return React.createElement('App', null, `component class with a ${this.props.text} but no JSX`)
    }                                   
}
//removed null and completely left out the children argument
ReactDOM.render(React.createElement(App, {text: 'property'}), document.getElementById('root'))</pre></div>



<h2>One last thing before we add our JSX: What is Babel?</h2>



<p>Babel does 2 things, first it converts our code from the latest javascript syntax, to a version of javascript every major browser can render. So currently ES6 code gets transpiled to ES5 syntax. The second thing Babel does is convert JSX into javascript. It does this using rules setup by React in a special configuration that Babel reads in. This plugin is working behind the scenes so when we write any JSX it turns the code into similar code I&#8217;m writing in the examples above using the createElement method. So why do we even want to write JSX at all?</p>



<h2>Finally let&#8217;s use JSX</h2>



<p>I&#8217;m going to remove the text property for a moment and just pass a simple string again. Let&#8217;s take our App classes render method and return JSX instead of using React&#8217;s createElement method:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
		return &lt;h1&gt;Hello JSX!&lt;/h1&gt;
	}                                   
}

ReactDOM.render(React.createElement(App, null), document.getElementById('root'))</pre></div>



<p>On line 7 you can see we can pass in JSX without quotation marks, because JSX is not a string, it is a mix of JS and XML-like markup. Behind the scene the createElement is behind called, after some time learning the flow it will become clear JSX is easier to read and maintain. Notice the last line we are still using createElement for <strong>App</strong>, so let&#8217;s change that but just passing in a custom tag like this, because JSX allows us to write a single self closing tag to do the same thing:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
		return &lt;h1&gt;Hello JSX!&lt;/h1&gt;
	}                                   
}

ReactDOM.render(&lt;App /&gt;, document.getElementById('root'))</pre></div>



<h2>Passing props using JSX</h2>



<p>Now that we are using JSX, how do we pass a property from reactDOM.render to the App class so it can create an object that will become our component on the webpage.</p>



<p>We&#8217;ll pass in what looks like an html attribute like class or onclick, but this will be a custom attribute that matches the property in our App class &#8220;blueprint.&#8221; Here we&#8217;ll use text again as our property name:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
		return &lt;h1&gt;Hello JSX! {this.props.text}&lt;/h1&gt;
	}                                   
}
//removed null and completely left out the children argument
ReactDOM.render(&lt;App text='Hello props!'/&gt;, document.getElementById('root'))</pre></div>



<p>Anything we add in between JSX that is javascript like this.props.text has to be wrapped in curly braces. This is what tells Babel to stop interpreting JSX and run javascript code.</p>



<p>This does not mean we have to do this outside of the JSX. You can write normal Javascript everywhere else like this:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
        const text = this.props.text
		return &lt;h1&gt;Hello JSX! {text}&lt;/h1&gt;
	}                                   
}

ReactDOM.render(&lt;App text='Hello props!'/&gt;, document.getElementById('root'))</pre></div>



<p>I&#8217;ve created a text variable and am passing it inside the JSX. I use curly braces, which will interpret the variable based on what I pass to my JSX:</p>



<h2>Working with multiple properties and arrays</h2>



<p>Let&#8217;s add a second property called seasons and we&#8217;ll pass an array of the 4 seasons:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
        console.log(this.props.seasons)
        const text = this.props.text
		return &lt;h1&gt;Hello JSX! {text}&lt;/h1&gt;
	}                                   
}

const seasons = ['winter','spring','summer','fall']
ReactDOM.render(&lt;App text='Hello props!' seasons={seasons}/&gt;, document.getElementById('root'))</pre></div>



<p>notice the curly brackets around the seasons value inside of the JSX . Just remember anytime you introduce a javascript expression inside of JSX it has to be wrapped in {}brackets</p>



<p>So we&#8217;ve passed this to our class and it is now available in our App class this.props object. Let&#8217;s console.log and inspect the browser when the page loads:</p>



<figure class="wp-block-image"><img src="https://firebasestorage.googleapis.com/v0/b/firescript-577a2.appspot.com/o/imgs%2Fapp%2Fjohn-yzaguirre%2FL-dBmoK0st.png?alt=media&amp;token=ab451367-1b86-4a13-91ec-29c43287f0c7" alt="" title=""/></figure>



<p>So let&#8217;s display them on the page using a standard unordered list using these HTML elements:</p>



<p>Quick note! When you return something that requires multiple line breaks, remember to wrap your code in parenthesis:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
        const seasons = this.props.seasons
        const text = this.props.text
		return (
			&lt;ul&gt;
				&lt;li&gt;{seasons[0]}&lt;/li&gt;
				&lt;li&gt;{seasons[1]}&lt;/li&gt;
				&lt;li&gt;{seasons[2]}&lt;/li&gt;
				&lt;li&gt;{seasons[3]}&lt;/li&gt;
			&lt;/ul&gt;
		)
	}                                   
}

const seasons = ['winter','spring','summer','fall']
ReactDOM.render(&lt;App text=&quot;Hello text property!&quot; seasons={seasons}/&gt;, document.getElementById('root'))</pre></div>



<p>remember even though it looks like normal HTML it is in fact JSX so we need those brackets for any javascript code <strong>inside</strong> the JSX.</p>



<p>What if we pass the whole array like this: {seasons}</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
        const seasons = this.props.seasons
        const text = this.props.text
		return (
			&lt;ul&gt;
				&lt;li&gt;{seasons[0]}&lt;/li&gt;
				&lt;li&gt;{seasons[1]}&lt;/li&gt;
				&lt;li&gt;{seasons[2]}&lt;/li&gt;
				&lt;li&gt;{seasons[3]}&lt;/li&gt;
                &lt;li&gt;{seasons}&lt;/li&gt;
			&lt;/ul&gt;
		)
	}                                   
}

const seasons = ['winter','spring','summer','fall']
ReactDOM.render(&lt;App text=&quot;Hello text property!&quot; seasons={seasons}/&gt;, document.getElementById('root'))</pre></div>



<p>Running this gives us our list and the list item is each season bunched together with no spaces. So JSX will even evaluate an array into a string.</p>



<p>Now we can leverage this by creating a new array with our season names, but with the tags wrapped around each one.</p>



<p>Since we&#8217;re doing the exact same thing for each item in the array to create a new one we can use the <strong>map</strong> method which is a built in array method.</p>



<p>Remember we don&#8217;t need brackets outside of JSX only in between the tags. First let&#8217;s create our new array using map:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
        const seasons = this.props.seasons
        const seasonsList = seasons.map((name, index) =&gt; &lt;li&gt;{name}&lt;/li&gt;)
        const text = this.props.text
		return &lt;ul&gt;{seasonsList}&lt;/ul&gt;
	}                                   
}

const seasons = ['winter','spring','summer','fall']
ReactDOM.render(&lt;App text=&quot;Hello seasons!&quot; seasons={seasons}/&gt;, document.getElementById('root'))</pre></div>



<p>Let&#8217;s add back in our text property at the top to give our list a title:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}">// index.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {
	render() {
        const seasons = this.props.seasons
        const seasonsList = seasons.map((name, index) =&gt; &lt;li&gt;{name}&lt;/li&gt;)
        const text = this.props.text
		return (
        	&lt;div&gt;
            	&lt;h1&gt;{text}&lt;/h1&gt;
            	&lt;ul&gt;{seasonsList}&lt;/ul&gt;
            &lt;/div&gt;
        )
	}                                   
}

const seasons = ['winter','spring','summer','fall']
ReactDOM.render(&lt;App text=&quot;Hello seasons!&quot; seasons={seasons}/&gt;, document.getElementById('root'))</pre></div>



<p>Notice how I wrap everything in a signal parent tag? Whatever we return from our class has to be wrapped in one single tag. If we try to run this without the we get an error for trying to return two parent tags. Always one parent and as many children as we want inside.</p>



<p>That is our entire program! Hope all of that made sense. This is just the start but the more comfortable you feel now the better as things become more spread out and complicated. React is not a framework, it is a library that gives you access to methods. Also React has a plugin which works behind the scenes with Babel to change our code on the fly when we save. Webpack is what is serving our page to the browser when we are developing.</p>



<h2>What is Webpack?</h2>



<p>Webpack is a tool that takes your files and packages them into a folder that you can send to your server. This is the production ready version of your application is commonly known as a &#8220;build.&#8221; It also runs the development server when you run &#8216;npm start&#8217; or &#8216;yarn start.&#8217;</p>



<p>I use yarn so i&#8217;m going to create a &#8216;build&#8217; folder that is the production ready version of my web application. This folder can be sent to a server which users can request to use your web app. Everything is self contained and create to be as efficient and fast as possible.</p>



<p>I&#8217;ll run &#8216;yarn build&#8217; and in the terminal it will take about a minute to create my production build&#8230;</p>



<p>to run my build I will need to install the yarn serve package by typing:</p>



<p>&#8216;yarn global add serve&#8217;</p>



<p>I will then cd into the build directory</p>



<p>and finally run the command &#8216;serve&#8217;</p>



<p>now my webapp should appear in the browser again. You might notice also it is a little faster to load up. This code is not to be touched. If you need to make a change go back to our index.js and re-build again to have a production ready app!</p>



<h2>Conclusion</h2>



<p>React is confusing at first. I&#8217;ve found a lot of tutorials really try to cram too much into an introduction, when the code above is all you need to start learning. Learning and getting comfortable is the first step, trying to build an app and learn React at the same time is only going to lead to headaches 🤦‍♂️<br><br>Once you feel really comfortable with what we&#8217;ve written so far, check out the next tutorial. We&#8217;re going to build a simple input that updates some text in realtime, then a simple button to clear our text. This is the reactive part of react!</p>



<ul><li></li></ul>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2020/05/02/react-a-gentle-introduction-part-1/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Problem Set 7: CS50 Finance</title>
		<link>https://johnyzaguirre.com/2020/01/02/problem-set-7-cs50-finance/</link>
					<comments>https://johnyzaguirre.com/2020/01/02/problem-set-7-cs50-finance/#comments</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Thu, 02 Jan 2020 12:55:42 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">https://johnyzaguirre.com/?p=1523</guid>

					<description><![CDATA[Building an app is a process that needs structure I made an initial attempt that went very poorly. I read the CS50 assignment points and went through building the app page for page. Make all the code to register, then make all the code to get a quote, then buy, then sell. I started getting &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2020/01/02/problem-set-7-cs50-finance/" class="more-link">Continue reading<span class="screen-reader-text"> "Problem Set 7: CS50 Finance"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<h2>Building an app is a process that needs structure</h2>



<p>I made an initial attempt that went very poorly. I read the CS50 assignment points and went through building the app page for page. Make all the code to register, then make all the code to get a quote, then buy, then sell. I started getting very picky about how the user got feedback when something was posted. I wanted nice banners to show things were successful or unsuccessful. I wanted javascript on the front end to update values. Everything became a big mess.</p>



<p>So i deleted it all. And pulled out some post-it notes, and a pencil.</p>



<p>I made 3 stacks:</p>



<ul><li>Frontend</li><li>Database</li><li>Logic</li></ul>



<p>Then I started writing down all the tasks as I read them on the CS50 assignment page. Each post was very simple and specific. On the top left corner of each post-it I put the first letter of what stack it would go on. On the top right I put the first letter for the webpage (register, buy, sell, quote etc).</p>



<p>A post-it might be &#8220;create view template register.html,&#8221; which would be a F on the top left.</p>



<p>another might be &#8220;create model for users,&#8221; which would be a D.</p>



<p>&#8220;create get_balance method for users,&#8221; another D.</p>



<p>What I found was the Frontend stack could be done very quickly because I noticed there were similar tasks. They weren&#8217;t directly connected the way a user thinks when reading about the app. They were literally the same task just for a different page of the app.</p>



<p>So my advice would be to write out as many tasks as possible, sort them in this way, and try to develop frontend -&gt; database -&gt; logic.</p>



<p>For the database I highly recommend creating a new file called models.py and creating a class for each part of your app. I created <strong>users, transactions and portfolio</strong>. Here is what that looks like:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/3307cdb7bad663740e3204d2ac7f1f4a">Gist</a>.
</div></figure>



<p>During the database phase I recommend using the python terminal REPL. If you go into the directory that holds application.py for the flask app, you can actually test out any function, class or method right in the terminal. Here is an example of me using the terminal to test some of the user database methods:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1707" height="1087" src="https://johnyzaguirre.com/wp-content/uploads/2019/12/Screen-Shot-2019-12-28-at-7.28.53-PM.png" alt="" class="wp-image-1547" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/12/Screen-Shot-2019-12-28-at-7.28.53-PM.png 1707w, https://johnyzaguirre.com/wp-content/uploads/2019/12/Screen-Shot-2019-12-28-at-7.28.53-PM-300x191.png 300w, https://johnyzaguirre.com/wp-content/uploads/2019/12/Screen-Shot-2019-12-28-at-7.28.53-PM-768x489.png 768w, https://johnyzaguirre.com/wp-content/uploads/2019/12/Screen-Shot-2019-12-28-at-7.28.53-PM-1536x978.png 1536w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<p>type <strong>python -i application.py</strong><em>.</em> This is interactive mode and makes testing models easier so you don&#8217;t have to submit forms.</p>



<p>When you finish the database make sure to add some fake data to save time during the logic portion.</p>



<p>Logic is something like &#8220;if the user does not have enough cash to by stocks return apology.&#8221;</p>



<h2>API changes</h2>



<p>In the helpers file on line 42 I changed the url because the one given doesn&#8217;t work. Here is the actual api now <a href="https://iexcloud.io/docs/api/#quote">https://iexcloud.io/docs/api/#quote</a></p>



<p>change to this on line 42:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">        response = requests.get(f&quot;https://cloud.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token=YOUR_FREE_APITOKEN&quot;)
</pre></div>



<p>change your_free_api_token with your own token when you sign up.</p>



<h2>Other quick notes</h2>



<p>datetime: <a href="https://www.techonthenet.com/sqlite/functions/datetime.php">https://www.techonthenet.com/sqlite/functions/datetime.php</a></p>



<p>foreign keys: <a href="https://sqlite.org/foreignkeys.html">https://sqlite.org/foreignkeys.html</a></p>



<p>inner joins: <a href="https://www.sqlitetutorial.net/sqlite-inner-join/">https://www.sqlitetutorial.net/sqlite-inner-join/</a></p>



<h2>Using the with keyword for opening and closing sqlite3</h2>



<p>In python there is a way to open a sql connection and automatically close it using <strong>with</strong>.</p>



<p>Here would be the standard way of connecting to a database and closing it at the end.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()

c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')
c.execute(&quot;INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)&quot;)

# Save (commit) the changes
conn.commit()

# close the connection if we are done with it.
conn.close()</pre></div>



<p>Now using <strong>with</strong>:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">import sqlite3
  with sqlite3.connect('example.db') as conn:
    c = conn.cursor()

    c.execute('''CREATE TABLE stocks
                 (date text, trans text, symbol text, qty real, price real)''')
    c.execute(&quot;INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)&quot;)

    # Save (commit) the changes
    conn.commit()

    # connection automatically closed once we leave this indented section of code</pre></div>



<h2>Questions?</h2>



<p>This was a much bigger project, so if you have any questions please let me know and i&#8217;ll do my best to answer. My code will be up on github:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/46a9143472ef0c8eb906da159837b47b">Gist</a>.
</div></figure>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2020/01/02/problem-set-7-cs50-finance/feed/</wfw:commentRss>
			<slash:comments>14</slash:comments>
		
		
			</item>
		<item>
		<title>CS50 Week 8: Notes</title>
		<link>https://johnyzaguirre.com/2019/11/30/cs50-week-8-notes/</link>
					<comments>https://johnyzaguirre.com/2019/11/30/cs50-week-8-notes/#respond</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Sat, 30 Nov 2019 01:32:32 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">https://johnyzaguirre.com/?p=1499</guid>

					<description><![CDATA[CS50 store demo Cookies and sessions start off this weeks lecture notes. The important thing to remember is http protocol is a stateless protocol. This means traditionally you request a webpage, the server gives you the page data and nothing else happens. Similar to going to a store, buying an item and leaving. The cashier &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2019/11/30/cs50-week-8-notes/" class="more-link">Continue reading<span class="screen-reader-text"> "CS50 Week 8: Notes"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<h2>CS50 store demo</h2>



<p>Cookies and sessions start off this weeks lecture notes. The important thing to remember is http protocol is a <strong><em>stateless</em></strong> protocol. This means traditionally you request a webpage, the server gives you the page data and nothing else happens. Similar to going to a store, buying an item and leaving. The cashier doesn&#8217;t remember you next time. That is what stateless means. </p>



<p>Cookies and sessions allow the experience to be more <strong><em>stateful</em></strong>, meaning when you request a webpage, a cookie is inside that request header giving the server some <em>unique info about you</em>. This returns a webpage made only for you. Back to the store analogy, if every Monday you bought eggs, and the store had a way of knowing it was you right when you walked in, someone would just bring you eggs or even have them ready for you in advance at the register.</p>



<p>Here is the store demo code for application.py</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/b79424192a4acbcd21114ae1559c9e4f">Gist</a>.
</div></figure>



<p>On line 8 setting the SESSION_PERMANENT value to False means we do not store the session after the browser has been closed. If you quit the browser program and re-open it, the cart values will not be saved. However if the browser is still open and you close just the window, or tab, the cart values will persist. The SESSION_TYPE we are using is filesystem, which means our session values are stored on the server (in a folder called flask_session).</p>



<h2>MVC &#8211; Model View Controller</h2>



<p>MVC is a way of organizing pieces of a web application. The model is where all the database calls are made (variables being used in SQL statements most of the time). The View is for templating, like jinja2, the look of your pages. The controller is usually a main routes page like application.py, where decisions are made based on what the user is doing.</p>



<h2>A Simple Example</h2>



<p>I downloaded the lecture.db file from the notes and put it in the same directory as this script:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">from cs50 import SQL

db = SQL(&quot;sqlite:///lecture.db&quot;)

# Query database for all albums
rows = db.execute(&quot;SELECT * FROM Album&quot;)

# For each album in database
for row in rows:
	# Print title of album
	print(row[&quot;Title&quot;])</pre></div>



<p>In my terminal I got this result:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="890" height="1304" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.05.25-PM.png" alt="" class="wp-image-1513" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.05.25-PM.png 890w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.05.25-PM-205x300.png 205w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.05.25-PM-768x1125.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure>



<p>Using sys.argv[1] we can pass variables into the command line which get substituted.</p>



<p>like this:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">rows = db.execute(&quot;SELECT * FROM Album WHERE Title = :t&quot;, t=sys.argv[1])</pre></div>



<p>Its important to remember we don&#8217;t use the normal formatting syntax f&#8221;my string {variable}&#8221; in this case. Because the variables are <strong>sanitized</strong>, meaning the removal of potentially harmful characters. SQL injection is a thing attacks can use to get into our databases, so it&#8217;s important to just know we need this sanitization before running our sql statements.</p>



<h2>Adding Flask to the mix</h2>



<p>So with a flask application we will use the lecture.db file to show album titles on a webpage:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">from flask import Flask, render_template, request

from cs50 import SQL

app = Flask(__name__)

db = SQL(&quot;sqlite:///lecture.db&quot;)

@app.route(&quot;/&quot;)
def index():
    rows = db.execute(&quot;SELECT * FROM Album&quot;)
    return render_template(&quot;index.html&quot;, albums=rows)</pre></div>



<p>running this (I had to remove eprint) will show a block of text on the browser, which is all the album titles. But the cool thing is we&#8217;re using a database. So we have state, which means we can save things for later =).</p>



<h2>Query arguments</h2>



<p>We can also pass query arguments from the URL using a GET request type:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">@app.route(&quot;/&quot;)
def index():
    query = request.args.get(&quot;q&quot;)
    rows = db.execute(&quot;SELECT * FROM Album WHERE Title LIKE :q&quot;, q=query+&quot;%&quot;)
    return render_template(&quot;index.html&quot;, albums=rows)</pre></div>



<p>Above is a modified version of the example code. Using LIKE and a % symbol which is a wildcard, you can just use a single letter and it will return whatever starts with it.</p>



<p>So this URL: <a href="http://127.0.0.1:5000/?q=f">http://127.0.0.1:5000/?q=f</a></p>



<p>returns this:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1264" height="1449" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.30.27-PM.png" alt="" class="wp-image-1517" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.30.27-PM.png 1264w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.30.27-PM-262x300.png 262w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.30.27-PM-768x880.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure>



<p>So this is apparently enough for us poor online learning only souls to <strong>create an app for buying and selling stocks!</strong></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="398" height="222" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.32.05-PM.png" alt="" class="wp-image-1519" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.32.05-PM.png 398w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-29-at-8.32.05-PM-300x167.png 300w" sizes="(max-width: 398px) 100vw, 398px" /></figure></div>



<p>See you in the next one.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2019/11/30/cs50-week-8-notes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>CS50 Week 7: Walkthroughs</title>
		<link>https://johnyzaguirre.com/2019/11/23/cs50-week-7-walkthroughs/</link>
					<comments>https://johnyzaguirre.com/2019/11/23/cs50-week-7-walkthroughs/#respond</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Sat, 23 Nov 2019 21:54:38 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">https://johnyzaguirre.com/?p=1425</guid>

					<description><![CDATA[Hello name in python to start it off: Let&#8217;s quickly run through the &#8220;tougher&#8221; Déjà vu walkthroughs ( and then go deeper into the final similarities web app. Let&#8217;s start with the Mario challenge: mario.py So let&#8217;s build a pyramid shape in the terminal: 4 lines. Google range() and it&#8217;s arguments, then google rjust() and &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2019/11/23/cs50-week-7-walkthroughs/" class="more-link">Continue reading<span class="screen-reader-text"> "CS50 Week 7: Walkthroughs"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p>Hello name in python to start it off:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">print(f&quot;Hello {input('name: ')}&quot;)</pre></div>



<p>Let&#8217;s quickly run through the &#8220;tougher&#8221; Déjà vu walkthroughs ( and then go deeper into the final <em>similarities </em>web app. Let&#8217;s start with the <strong><em>Mario</em></strong> challenge:</p>



<h2>mario.py</h2>



<p>So let&#8217;s build a pyramid shape in the terminal:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">height = int(input(&quot;enter a number for your mario pyramid: &quot;))
for i in range(2, height+2):
    print(('#'*i).rjust(height+1), end=&quot; &quot;)
    print('#' * i)</pre></div>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="357" height="200" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/source.gif" alt="" class="wp-image-1428"/></figure></div>



<p>4 lines.</p>



<p>Google range() and it&#8217;s arguments, then google rjust() and it&#8217;s arguments. Use print statements to figure out what I did. If you have any questions try to say what this is doing out loud with a small number (like 2 for the user input). Comment below if you have any questions.</p>



<h2>cash.py</h2>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">cash = float(input(&quot;please enter cash amount to break down into coins (example 1.25): &quot;))
coins = {&quot;quarters&quot;: .25,&quot;dimes&quot;:.10,&quot;nickels&quot;:.05,&quot;pennies&quot;:.01}
for key, coin in coins.items():
	(coins[key], cash) = (divmod(cash,coin)[0], round(divmod(cash,coin)[1],2))
print(coins)</pre></div>



<p>Short but not impossible to read. Pull apart the packed variables and google divmod(), which is a very handy function in this case. <a href="https://johnyzaguirre.com/2018/11/13/cs50-week-6/">Go back to my python article that goes through packing and unpacking if you need a refresher.</a></p>



<h2>Caesar.py</h2>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">import sys

if len(sys.argv) != 2: 
  print(&quot;Usage: python3 caesar.py key&quot;)
  sys.exit(0)
key = int(sys.argv[1])

message = input(&quot;enter a secret message: &quot;)

def cipher(letter, key):
	if not letter.isalpha():
		return letter
	offset = 65 if letter.isupper() else 97
	return chr(((ord(letter) - offset) + key) % 26 + offset)

print(f&quot;userinput: {message}&quot;)
print(&quot;decoded_text: &quot; + ''.join([cipher(letter, key * -1) for letter in message]))
print(&quot;coded_text: &quot; + ''.join([cipher(letter, key) for letter in message]))</pre></div>



<h2>Similarities (from scratch)</h2>



<p>I&#8217;m going to do one from scratch then i&#8217;ll make it again using the CS50 instructions.</p>



<p>Here is the example image from the CS50 website:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><a href="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-16-at-7.04.16-AM.png"><img loading="lazy" width="1133" height="761" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-16-at-7.04.16-AM.png" alt="" class="wp-image-1447" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-16-at-7.04.16-AM.png 1133w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-16-at-7.04.16-AM-300x202.png 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-16-at-7.04.16-AM-768x516.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></a></figure></div>



<p>Here was my result. <a href="https://github.com/sojohnnysaid/cs50-similarities" target="_blank" rel="noreferrer noopener" aria-label="You can check out the github repo as well (opens in a new tab)">You can check out the github repo as well</a>. I styled the pages differently and added a number input for the substring page:</p>



<figure class="wp-block-gallery columns-3 is-cropped"><ul class="blocks-gallery-grid"><li class="blocks-gallery-item"><figure><a href="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.08.57-PM.png"><img loading="lazy" width="1290" height="1449" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.08.57-PM.png" alt="" data-id="1453" data-full-url="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.08.57-PM.png" data-link="https://johnyzaguirre.com/?attachment_id=1453" class="wp-image-1453" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.08.57-PM.png 1290w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.08.57-PM-267x300.png 267w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.08.57-PM-768x863.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></a></figure></li><li class="blocks-gallery-item"><figure><a href="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.09.55-PM.png"><img loading="lazy" width="1290" height="1449" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.09.55-PM.png" alt="" data-id="1452" data-full-url="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.09.55-PM.png" data-link="https://johnyzaguirre.com/?attachment_id=1452" class="wp-image-1452" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.09.55-PM.png 1290w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.09.55-PM-267x300.png 267w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.09.55-PM-768x863.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></a></figure></li><li class="blocks-gallery-item"><figure><a href="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.10.52-PM.png"><img loading="lazy" width="1290" height="1449" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.10.52-PM.png" alt="" data-id="1451" data-full-url="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.10.52-PM.png" data-link="https://johnyzaguirre.com/?attachment_id=1451" class="wp-image-1451" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.10.52-PM.png 1290w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.10.52-PM-267x300.png 267w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-17-at-2.10.52-PM-768x863.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></a></figure></li></ul></figure>



<p>application.py:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">from flask import Flask, render_template, redirect, request
from compare import compare_lines, compare_sentences, compare_substrings

app = Flask(__name__)

@app.route(&quot;/&quot;, methods=[&quot;GET&quot;,&quot;POST&quot;])
def index():
    if request.method == &quot;POST&quot;:
        file_one = request.files[&quot;file_one&quot;]
        file_two = request.files[&quot;file_two&quot;]
        return render_template(&quot;index.html&quot;, results=compare_lines(file_one,file_two))
    return render_template(&quot;index.html&quot;, results=None)



@app.route(&quot;/sentences&quot;, methods=[&quot;GET&quot;,&quot;POST&quot;])
def sentences():
    if request.method == &quot;POST&quot;:
        file_one = request.files[&quot;file_one&quot;]
        file_two = request.files[&quot;file_two&quot;]
        return render_template(&quot;sentences.html&quot;, results=compare_sentences(file_one,file_two))
    return render_template(&quot;sentences.html&quot;, results=None)



@app.route(&quot;/substrings&quot;, methods=[&quot;GET&quot;,&quot;POST&quot;])
def substrings():
    if request.method == &quot;POST&quot;:
        file_one = request.files[&quot;file_one&quot;]
        file_two = request.files[&quot;file_two&quot;]
        return render_template(&quot;substrings.html&quot;, results=compare_substrings(file_one,file_two, int(request.form.get('length'))))
    return render_template(&quot;substrings.html&quot;, results=None)


if __name__ == '__main__':
    app.run</pre></div>



<p>The index route goes straight to the matching lines page. All forms send a POST request to the same URL, so i&#8217;m checking for the request type using the IF statement. At the top i&#8217;ve imported my own file <strong>compare</strong>, which has the functions I need to process the files that are being uploaded. Also notice to get the files I use <strong>request.files</strong> and then pass in the form&#8217;s <strong>name</strong> value. This will return what flask calls a <strong><em>filestorage</em></strong><em> </em>object. This thin wrapper allows us to call <strong>read()</strong> which is still in a format that is not decoded because it doesn&#8217;t assume the file is text. </p>



<p>Here is the compare.py file so you can see the function I use to get the text from each file:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">from nltk.tokenize import sent_tokenize, word_tokenize

def get_file_data(file_one, file_two):
    #takes filestorage type of bytes and turns file data it into a string
    data = [file_one.read().decode('utf-8'), file_two.read().decode('utf-8')]
    data = [file.replace('&lt;', '&amp;lt;').replace('&gt;', '&amp;gt;') for file in data]
    return data


def get_similarities(file_one, file_two):
    return set(file_one).intersection(file_two)


def format_html(file_one, file_two, similarities):
    #adds span tags and \n re-added if identical lines otherwise just the line with \n re-added
    similarities = list(similarities)
    files = []
    for item in similarities:
        file_one = file_one.replace(item, f&quot;&lt;span&gt;{item}&lt;/span&gt;&quot;, 1)
        file_two = file_two.replace(item, f&quot;&lt;span&gt;{item}&lt;/span&gt;&quot;, 1)
    files.append(file_one)
    files.append(file_two)
    return files

def set_files_as_list_of_strings(formatted_files):
    return [''.join(formatted_files[0]), ''.join(formatted_files[1])]


def compare_lines(file_one, file_two):
    data = get_file_data(file_one, file_two)

    #split string into list of strings wherever a linebreak is found
    file_one = data[0].split('\n')
    file_two = data[1].split('\n')

    #set intersection returns a set of all identical lines between the lists
    similarities = get_similarities(file_one, file_two)

    #adds span tags and \n re-added if identical lines otherwise just the line with \n re-added
    formatted_files = format_html(data[0], data[1], similarities)

    #return as a list of 2 strings
    return set_files_as_list_of_strings(formatted_files)




def compare_sentences(file_one, file_two):
    data = get_file_data(file_one, file_two)

    #TO DO splits data up into sentences
    file_one = sent_tokenize(data[0])
    file_two = sent_tokenize(data[1])

    #set intersection returns a set of all identical sentences between the lists
    similarities = get_similarities(file_one, file_two)

    #adds span tags and \n re-added if identical sentence otherwise just the sentence with \n re-added
    formatted_files = format_html(data[0], data[1], similarities)

    #return as a list of 2 strings
    return set_files_as_list_of_strings(formatted_files)




def compare_substrings(file_one, file_two, length):
    data = get_file_data(file_one, file_two)

    #split string into list of substrings based on user input
    file_one = [char for item in word_tokenize(data[0]) for char in item]
    file_two = [char for item in word_tokenize(data[1]) for char in item]

    slices_one = []
    for i in range(0,len(file_one), length):
        if len(file_one[i:i+length]) == length and ''.join(file_one[i:i+length]).isalpha():
            slices_one.append(''.join(file_one[i:i+length]))

    slices_two = []
    for i in range(0,len(file_two), length):
        if len(file_two[i:i+length]) == length and ''.join(file_one[i:i+length]).isalpha():
            slices_two.append(''.join(file_two[i:i+length]))


    #set intersection returns a set of all identical substrings between the lists
    similarities = get_similarities(slices_one, slices_two)

    print(similarities)

    list_of_substrings = ['\n'.join(similarities), '\n'.join(similarities)]

    #return as a list of 2 strings
    return set_files_as_list_of_strings(list_of_substrings)</pre></div>



<p>On line 5 you can see where I call <strong>read()</strong> then <strong>decode(&#8216;utf-8&#8217;)</strong> to get the files actual text.</p>



<p>When the user posts the data we&#8217;re not able to immediately get to the text inside the submitted files. My goal is for our <strong>data</strong> variable to just hold the file text as a string.</p>



<p>Using <strong>read()</strong> with no argument, I save all the form data to memory until <strong>EOF</strong>. This goes back to the days we were messing with file handlers in C. That returns a <strong>byte </strong>object. In python a byte object represents sequences of integers which are usually ascii characters. We can use the decode method to get back a string. I&#8217;ve passed &#8216;utf-8&#8217; as an argument, <a rel="noreferrer noopener" aria-label="however it actually decodes to this by default too, so decode() would work just as well (opens in a new tab)" href="https://docs.python.org/3/library/stdtypes.html#bytes" target="_blank">however it actually decodes to this by default too, so <strong>decode()</strong> would work just as well</a>.</p>



<p>Once I get the files as strings I can start working on formatting the data. If you look at where it ends up in html you can see i&#8217;ve wrapped the text in <strong>&lt;pre&gt;&lt;/pre&gt;</strong> tags. Let&#8217;s look at <strong><em>templates/base.html</em></strong><em> on line 110:</em></p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;HTML&quot;,&quot;modeName&quot;:&quot;html&quot;}">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    {% block head %}
	&lt;title&gt;Similarities{% block title %}{% endblock %}&lt;/title&gt;
	&lt;style&gt;
	    {% block background %}
	    body{
            background: #606c88;  /* fallback for old browsers */
            background: -webkit-linear-gradient(to right, #3f4c6b, #606c88);  /* Chrome 10-25, Safari 5.1-6 */
            background: linear-gradient(to right, #3f4c6b, #606c88); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
        }
        {% endblock %}
        h1{
            line-height: 43px;
        }
        table, form{
            border-radius: 7px;
            box-shadow: 0px 12px 20px 1px;
            background: white;
            border-collapse: collapse;
            margin-left: auto;
            margin-right: auto;
            margin-top: 47px;
            font-size: 19px;
            line-height: 27px;
            width: 89%;
        }

        form{
            padding: 2px 0px 21px 39px;
        }

        input{
            font-size: 16px;
            margin: -14px;
        }


        table, th, td {
            border: 1px solid #191e2a;
        }

        th, td {
            padding: 15px;
            text-align: left;
        }

        span{
            background-color: yellow;
        }

        li a{
            text-decoration: none;
            padding: 16px;
            color: white;
            font-size: 27px;
        }

        li{
            flex: 3;
            text-align: center;
        }

        ul{
            display: flex;
            list-style-type: none;
            margin-top: 30px;
        }

        menu{
            padding-left: 0px;
        }

        pre{
            white-space: pre-wrap;
        }
        td{
            min-width: 45vw;
        }
	&lt;/style&gt;
    {% endblock %}
&lt;/head&gt;
&lt;body&gt;
    &lt;menu&gt;
    &lt;ul&gt;
        &lt;li&gt;&lt;a href=&quot;/&quot;&gt;Similar Lines&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/sentences&quot;&gt;Similar Sentences&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;/substrings&quot;&gt;Similar Substrings&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;/menu&gt;
    {% block content %}
    &lt;form action={{ request.path }} method=&quot;post&quot; enctype = &quot;multipart/form-data&quot;&gt;
      &lt;h1&gt;Upload two files to highlight similarities{% block h1 %}{% endblock %}&lt;/h1&gt;
      &lt;input type=&quot;file&quot; name=&quot;file_one&quot; id=&quot;file_one&quot;&gt;&lt;br&gt;
      &lt;input type=&quot;file&quot; name=&quot;file_two&quot; id=&quot;file_two&quot;&gt;&lt;br&gt;
      {% block numberInput %}{% endblock %}
      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
    &lt;/form&gt;
    &lt;table&gt;
        &lt;tr&gt;
            &lt;th&gt;
                Code Group One
            &lt;/th&gt;
            &lt;th&gt;
                Code Group Two
            &lt;/th&gt;
        &lt;tr&gt;
            &lt;td id=&quot;groupone&quot;&gt;
&lt;pre&gt;
{% block results_one %}{% endblock %}
&lt;/pre&gt;
            &lt;/td&gt;
            &lt;td id=&quot;grouptwo&quot;&gt;
&lt;pre&gt;
{% block results_two %}{% endblock %}
&lt;/pre&gt;
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/table&gt;
{% endblock %}
&lt;/body&gt;
&lt;/html&gt;</pre></div>



<p>Using jinja2 templating I can create a block that holds <strong>results_one</strong> and on line 116 I have another &lt;pre&gt; &lt;/pre&gt; with <strong>results_two</strong> inside. Now let&#8217;s look at <strong>index.html</strong> which is the first page of the website, where I compare lines:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text/x-objectivec&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Objective-C&quot;,&quot;modeName&quot;:&quot;objectivec&quot;}">{% extends &quot;base.html&quot; %}

    {% block title %} - Lines{% endblock %}
    {% block background %}
        body{
            background-image: linear-gradient(to right, #ab7272 0%, GRAY 280%);
        }
    {% endblock %}
{% block head %}
    {{ super() }}
{% endblock %}

    {% block h1 %} - matching lines{% endblock %}
    {% block results_one %}{{results[0]|safe}}{% endblock %}
    {% block results_two %}{{results[1]|safe}}{% endblock %}
{% block content %}
    {{ super() }}
{% endblock %}</pre></div>



<p>This is why jinja2 is so powerful.  My base.html is 123 lines of code. My index.html, sentences.html and substrings.html pages are less than 20! If I have to make a change on all the webpages, base.html will be the one place to make it.</p>



<p>Using  <strong>{% extends &#8220;base.html&#8221; %}</strong> allows me to reuse all the code and slip in custom variables by defining their values on each individual page. Look at line 14:</p>



<p><strong>{% block results_two %}{{results[1]|safe}}{% endblock %}</strong></p>



<p>I pass in the results from my compare function in application.py. Let me make a diagram so it&#8217;s easier to understand the flow:</p>



<figure class="wp-block-image size-large"><a href="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-2.jpg"><img loading="lazy" width="978" height="727" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-2.jpg" alt="" class="wp-image-1487" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-2.jpg 978w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-2-300x223.jpg 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-2-768x571.jpg 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></a></figure>



<p>This is generally what is happening. Things are being passed to do some processing work, but always end up back in application.py so the flask framework can do the rest for us.</p>



<p>I&#8217;m still learning as I go, and the tough part of this is all the different languages working together&#8230;the html, css, server calls, url requests and python code. Each is a journey on it&#8217;s own and don&#8217;t be discouraged if this made little sense. CS50 doesn&#8217;t cover html, or css very much so if you&#8217;re up to it check out teamtreehouse for video courses you can take on those topics.</p>



<h2>Finishing the actual challenges</h2>



<p>Back to similaries less, which is a much simpler challenge. We don&#8217;t have to make the flask app from scratch. Just update the helpers.py and index.html files with functions and a form. Here is what I ended up doing:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/602bbdf69d97f155ea0e293f2a3f3fc1">Gist</a>.
</div></figure>



<p>My drop down has a nifty javascript function inside it that will hide or show the numbers field if substring is selected. Also when the user hits the back button it resets the form using the script at the bottom.</p>



<p>So remember, a lot of these features i&#8217;ve added is not because i&#8217;m some all powerful genius. I am just not afraid to ask myself &#8220;what do I want this to do?&#8221; followed by googling it and not being too proud to use code from online. In these cases, if it works, great! The script at the bottom is straight from a stack overflow answer. I also forgot how to inline javascript in html so a quick google and you can see <strong>onchange</strong> on line 14 that goes into my javascript for changing the style of an element (which I also googled because I forgot for the 100th time, which is OK)</p>



<p>There is too much to remember, and too much changing in the world of programming, be a hunter of code examples and understand fundamentals to get things done and not get stuck with half finished projects.</p>



<p></p>



<p>Moving on to week 8!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2019/11/23/cs50-week-7-walkthroughs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>CS50 Week 7</title>
		<link>https://johnyzaguirre.com/2019/11/13/cs50-week-7/</link>
					<comments>https://johnyzaguirre.com/2019/11/13/cs50-week-7/#respond</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Wed, 13 Nov 2019 13:02:34 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">https://johnyzaguirre.com/?p=1278</guid>

					<description><![CDATA[Web Programming So with a brief overview of html, css and python it is time to put everything together. If you&#8217;ve never programmed something for the web just remember: THE INTERNET IS JUST A BUNCH OF COMPUTERS ALL TALKING TO EACH OTHER There is no special &#8220;cloud&#8221; machine or &#8220;server.&#8221; These are all just words &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2019/11/13/cs50-week-7/" class="more-link">Continue reading<span class="screen-reader-text"> "CS50 Week 7"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<h2>Web Programming</h2>



<p>So with a brief overview of html, css and python it is time to put everything together.</p>



<p>If you&#8217;ve never programmed something for the web just remember:</p>



<p><strong>THE INTERNET IS JUST A BUNCH OF COMPUTERS ALL TALKING TO EACH OTHER</strong></p>



<p>There is no special &#8220;cloud&#8221; machine or &#8220;server.&#8221; These are all just words that describe <strong>COMPUTERS</strong>. It&#8217;s not much different from sending a hand written letter from one house to another house. The mailman is just your internet cable and some electricity.</p>



<p>We have to command our computer to send information (think hand written letter) using a request called <strong>GET</strong>. So if you go inside your browser like safari, edge, chrome, firefox, whatever, that bar at the top for web addresses is where you send <strong>GET</strong> requests. You are saying &#8220;go GET me the information from google.com.&#8221; When you google cats the bar changes to some funky address that is saying &#8220;GET me cats.&#8221; (https://www.google.com/search?q=cats&amp;oq=cats&amp;aqs=chrome.0.69i59j0l4j69i61.3015j0j8&amp;sourceid=chrome&amp;ie=UTF-8)</p>



<p>On our computer we might have a word document locally. If we open it we get the information on the screen so we can read it. It is easy in our case to write more stuff onto the document and save it. How do we do this on the web?</p>



<p>There are a few different commands besides <strong>GET</strong> but the next one you should know is called <strong>POST</strong>. If I have data somewhere on the internet, meaning not on my computer but on the web, I can add data to it by using a <strong>POST</strong> type request. It is still a web address but it has some data tied to it that will be saved on the other end. You can also get a response from a <strong>POST </strong>request. Usually it will be a message that your data was either saved, or something went wrong.</p>



<p>Web requests have headers. I&#8217;m on Firefox so if I make a GET request, I can inspect by right clicking and choosing <strong>inspect</strong>. This is similar on a lot of browsers. Here is how I found the headers:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="547" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-04-at-7.44.06-AM-1024x547.png" alt="" class="wp-image-1279" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-04-at-7.44.06-AM-1024x547.png 1024w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-04-at-7.44.06-AM-300x160.png 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-04-at-7.44.06-AM-768x411.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /><figcaption><center>This took a while to find</center></figcaption></figure></div>



<p>So we can see in my case we&#8217;re using HTTP/2.0 the response code was 200 which means all is good and our content type is text/html; charset=UTF-8.</p>



<p>UTF stands for <strong>Unicode Transformation Format</strong> and after spending the past hour looking this up I think I get how it works. I&#8217;m probably not 100% but this is the gist. Please leave a comment if you have any additional info on the topic that would help others. Here is an image I put together to help visualize what is happening:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="768" height="1024" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/melinda-gimpel-0lrWg2ALPVw-unsplash-768x1024.jpg" alt="" class="wp-image-1281" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/melinda-gimpel-0lrWg2ALPVw-unsplash-768x1024.jpg 768w, https://johnyzaguirre.com/wp-content/uploads/2019/11/melinda-gimpel-0lrWg2ALPVw-unsplash-225x300.jpg 225w, https://johnyzaguirre.com/wp-content/uploads/2019/11/melinda-gimpel-0lrWg2ALPVw-unsplash.jpg 900w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /><figcaption>Photo by&nbsp;<a href="https://unsplash.com/@melindagimpel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Melinda Gimpel</a>&nbsp;on&nbsp;<a href="https://unsplash.com/s/photos/keyboard?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure></div>



<p><strong>utf-8</strong> is the encoding lookup table that turns a character code into binary for a computer to read or pass back out to Unicode. <strong>Unicode</strong> (a character set) takes the character code and maps it to a lookup table that has the actual character we display on the page using a typeface or font.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="348" height="72" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-7.41.52-AM.png" alt="" class="wp-image-1291" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-7.41.52-AM.png 348w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-7.41.52-AM-300x62.png 300w" sizes="(max-width: 348px) 100vw, 348px" /></figure></div>



<p>I hope that made sense. If it doesn&#8217;t please let me know in the comments.</p>



<h2>HTML</h2>



<p>HTML holds 2 types of info. Info we see and info we don&#8217;t see. Here is a sample from the CS50 lecture notes:</p>



<pre class="wp-block-code"><code>&lt;!DOCTYPE html>

&lt;html>
    &lt;head>
        &lt;title>hello, title&lt;/title>
    &lt;/head>
    &lt;body>
        hello, body
    &lt;/body>
&lt;/html></code></pre>



<p>The browser program is going to interpret this starting at the top. The first line lets the browser know we are dealing with HTML5, the current standard. Next we have <strong>&lt;html&gt;</strong> which starts and ends all the info we&#8217;re going to have on our page.</p>



<p><strong>&lt;head&gt;</strong> is where the browser gets info regarding the title of our page, scripts we want to run, and <strong>CSS</strong>.</p>



<p><strong>&lt;body&gt;</strong> is where we hold the material that can be viewed on the screen by our user. Inside the body we can have website titles, images, text, links and anything else you&#8217;ve ever seen on a webpage.</p>



<p>Notice how everything has a closing tag and has a nested structure.</p>



<h2>CSS</h2>



<p>CSS to style our page.  We can change the character font, color, add borders, background images and even animations. When you hover your mouse over a button, and the button on the page looks slightly different when you hover over it, that is CSS. Here is some example code:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/cc919a82e1297ca915b41069a3eb2449">Gist</a>.
</div></figure>



<p>You can put css in the &lt;head&gt; section of your html file, or reference a separate .css file.  The example file above can be opened using your browser without any other files. Try hovering over the button and last list item.</p>



<p>In CSS the first letter stands for cascading. It&#8217;s important you know that in css the rule closest to the bottom will always been the final say.</p>



<p>Notice on line 21 of my example I set the font to 1000000000px! Then on the following lines I change the font. So if a css rule is targeting the <strong>exact </strong>same element in the html, the last rule will win. Remember I wrote <strong>exact</strong>. If one rule is <strong>li</strong> and the next rule is <strong>li:first-child</strong> THEY ARE NOT EXACTLY THE SAME. So the cascading rule of last is not true. </p>



<p><a href="https://www.w3schools.com/css/" target="_blank" rel="noreferrer noopener" aria-label="To learn more I recommend W3Schools CSS tutorials, they are excellent. (opens in a new tab)">To learn more I recommend W3Schools CSS tutorials, they are excellent.</a></p>



<h2>Dynamic content with python</h2>



<p>This look complicated but lets try to break this down. I was stumped at first but after posting some questions on reddit I figured it out:</p>



<pre class="wp-block-code"><code># Implements a web server

from http.server import BaseHTTPRequestHandler, HTTPServer


# HTTPRequestHandler class
class HTTPServer_RequestHandler(BaseHTTPRequestHandler):

    # GET
    def do_GET(self):

        # send response status code
        self.send_response(200)

        # send headers
        self.send_header("Content-type", "text/html")
        self.end_headers()

        # write message
        self.wfile.write(bytes("hello, world", "utf8"))


# configure server
port = 8080
server_address = ("0.0.0.0", port)
httpd = HTTPServer(server_address, HTTPServer_RequestHandler)

# run server
httpd.serve_forever()</code></pre>



<p>Ok after going through the notes I understand what is happening. Seeing a class with a do_GET method and not finding it being called in the program was really confusing at first. </p>



<p><strong>do_GET</strong> gets called when the user goes to the browser and loads that webpage (makes a <strong>GET </strong>request).</p>



<p>wfile was confusing at first too, but it&#8217;s a file handler used by the HTTPServer class. It requires a <strong>bytes</strong> object so python has a helpful function that takes in a string and an <strong>encoding</strong> (utf-8). So we have above the example of &#8216;hello world&#8217; but we can also create our own file handler, insert it into the bytes function with the <strong>read()</strong> method and serve up our text file to the webpage.</p>



<p>Here is that version:</p>



<pre class="wp-block-code"><code># Implements a web server

from http.server import BaseHTTPRequestHandler, HTTPServer


# HTTPRequestHandler class
class HTTPServer_RequestHandler(BaseHTTPRequestHandler):

    # GET
    def do_GET(self):

        # send response status code
        self.send_response(200)

        # send headers
        self.send_header("Content-type", "text/html")
        self.end_headers()

        # write message
        # file handler gives us a stream. bytes turns it into a bytes object
        # we can pass the file handler, a string of text
        # just remember to pass the encoding type utf8!
        f = open("test.txt")
        self.wfile.write(bytes(f.read(), 'utf8'))
        f.close()


# configure server
port = 8080
server_address = ("0.0.0.0", port)
httpd = HTTPServer(server_address, HTTPServer_RequestHandler)

# run server
httpd.serve_forever()</code></pre>



<p>I created a file called test.txt in the same directory for this test. Next I&#8217;ll try an html file:</p>



<pre class="wp-block-code"><code># Implements a web server

from http.server import BaseHTTPRequestHandler, HTTPServer


# HTTPRequestHandler class
class HTTPServer_RequestHandler(BaseHTTPRequestHandler):

    # GET
    def do_GET(self):

        # send response status code
        self.send_response(200)

        # send headers
        self.send_header("Content-type", "text/html")
        self.end_headers()

        # write message
        # file handler gives us a stream. bytes turns it into a bytes object
        # we can pass the file handler, a string of text
        # just remember to pass the encoding type utf8!
        f = open("test.html")
        self.wfile.write(bytes(f.read(), 'utf8'))
        f.close()


# configure server
port = 8080
server_address = ("0.0.0.0", port)
httpd = HTTPServer(server_address, HTTPServer_RequestHandler)

# run server
httpd.serve_forever()</code></pre>



<p>Here is my html file:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;HTML&quot;,&quot;modeName&quot;:&quot;html&quot;}">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;title&gt;Wow CATS&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;h1&gt;CATS ARE AWESOME!!!&lt;/h1&gt;
	&lt;p&gt;Hello world this is my cats page please subscribe for lots of cats&lt;/p&gt;
	&lt;br&gt;
	&lt;img src=&quot;https://inteng-storage.s3.amazonaws.com/img/iea/4N610VqxGJ/sizes/cat-cloning_resize_md.jpg&quot;&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></div>



<p>The result:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="571" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-05-at-9.06.28-AM-1024x571.png" alt="" class="wp-image-1287" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-05-at-9.06.28-AM-1024x571.png 1024w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-05-at-9.06.28-AM-300x167.png 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-05-at-9.06.28-AM-768x428.png 768w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-05-at-9.06.28-AM.png 1173w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<p>So far we&#8217;ve created a static page but now we have to go even deeper and build <strong>dynamic pages</strong>. This is a pretty dense topic and we&#8217;ll soon see the differences. <a href="https://www.keycdn.com/support/difference-between-static-and-dynamic">Here is a quick read that explains the differences well</a>.</p>



<h2>Flask &#8211; a python web framework</h2>



<p>Make sure to type <strong>pip install flask</strong> in the terminal before getting started.</p>



<p>Let&#8217;s start with a simple example, straight from the Flask website, <a href="https://flask.palletsprojects.com/en/1.1.x/quickstart/">which you can find here</a>.</p>



<p>I&#8217;ve made a folder called flask_example, and inside a file called mysite.py. Inside that file are a few lines of code:</p>



<pre class="wp-block-code"><code>from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
	return 'Hello, CS50!'
</code></pre>



<p>If I tried to run this in the terminal by typing <strong>flask run</strong>, I will most likely get this message:</p>



<pre class="wp-block-code"><code> * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
Usage: flask run [OPTIONS]

Error: Could not locate a Flask application. You did not provide the "FLASK_APP" environment variable, and a "wsgi.py" or "app.py" module was not found in the current directory.</code></pre>



<p>It wants us to create an environment variable, which is a variable our operating system holds (not our program). Flask reaches to the OS for this variable to reference our file.</p>



<p>We can create environment variables by using the <strong>export</strong> command in the terminal.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="360" height="140" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.13.49-AM.png" alt="" class="wp-image-1296" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.13.49-AM.png 360w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.13.49-AM-300x117.png 300w" sizes="(max-width: 360px) 100vw, 360px" /></figure></div>



<p>So lets create the <strong>FLASK_APP</strong> environment variable that is the name of our program. In this example the file i&#8217;m working in is called <strong>mysite.py</strong></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="431" height="134" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.15.52-AM.png" alt="" class="wp-image-1297" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.15.52-AM.png 431w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.15.52-AM-300x93.png 300w" sizes="(max-width: 431px) 100vw, 431px" /></figure></div>



<p>Now when I run the command <strong>flask run</strong> I get this:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="799" height="124" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.16.33-AM.png" alt="" class="wp-image-1298" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.16.33-AM.png 799w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.16.33-AM-300x47.png 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.16.33-AM-768x119.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<p>If I hover of the website address and click open I get this:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="503" height="333" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.17.42-AM.png" alt="" class="wp-image-1300" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.17.42-AM.png 503w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.17.42-AM-300x199.png 300w" sizes="(max-width: 503px) 100vw, 503px" /></figure></div>



<p>Now that we&#8217;ve created this simple example lets follow the lecture notes.</p>



<h2>Flask continued (lecture notes)</h2>



<p>I&#8217;m going to rename mysite.py to <strong>application.py</strong> so it matches up with the notes. Then i&#8217;m going to create a folder called <strong>templates</strong>. The notes are a little confusing here but to clear it up here is the directory structure:</p>



<ul><li>flask_example<ul><li>application.py</li><li>templates</li></ul></li></ul>



<p>So flask_example is the main folder, which has application.py and the templates folder inside of it.</p>



<p><strong>first we have to make sure to reset our environment variable!!!!</strong></p>



<p>In the terminal type <strong>export FLASK_APP=application.py</strong></p>



<p>Next, inside the templates folder i&#8217;ll create a new file called index.html that has this html:</p>



<pre class="wp-block-code"><code>&lt;!DOCTYPE html>

&lt;html>
    &lt;head>
        &lt;title>hello, title&lt;/title>
    &lt;/head>
    &lt;body>
        hello, body
    &lt;/body>
&lt;/html></code></pre>



<p>I&#8217;m going to replace the code in application.py with this:</p>



<pre class="wp-block-code"><code>from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/zuck")
def zuck():
    return render_template("zuck.html")

@app.route("/login")
def login():
    return render_template("login.html")</code></pre>



<p>Next i&#8217;ll run the <strong>flask run </strong>command in the terminal:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="808" height="156" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.30.06-AM.png" alt="" class="wp-image-1304" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.30.06-AM.png 808w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.30.06-AM-300x58.png 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.30.06-AM-768x148.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="349" height="216" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.30.29-AM.png" alt="" class="wp-image-1305" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.30.29-AM.png 349w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-9.30.29-AM-300x186.png 300w" sizes="(max-width: 349px) 100vw, 349px" /></figure></div>



<p>Now inside of templates create a zuck.html file with this html:</p>



<pre class="wp-block-code"><code></code></pre>



<pre class="wp-block-code"><code>&lt;!DOCTYPE html>

&lt;html>
    &lt;head>
        &lt;title>hello, title&lt;/title>
    &lt;/head>
    &lt;body>
        hello, this is the zuck page!
    &lt;/body>
&lt;/html></code></pre>



<p>Enter <strong>flask run</strong> in the terminal again and open the website URL. Then add &#8220;/zuck&#8221; to the end of the url and you will get this result:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="379" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-6.18.03-PM-1024x379.png" alt="" class="wp-image-1308" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-6.18.03-PM-1024x379.png 1024w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-6.18.03-PM-300x111.png 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-6.18.03-PM-768x284.png 768w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-06-at-6.18.03-PM.png 1248w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<h2>Error handling and tracebacks with flask</h2>



<p>You can skip this and just run these commands:</p>



<pre class="wp-block-code"><code>touch ~/.bash_profile &amp;&amp; echo export FLASK_DEBUG=1 > .bash_profile</code></pre>



<p>Then restart the terminal for it to work. <a href="#frosh">Click here for the next section of text.</a></p>



<p>This was a huge pain to get working with CS50 IDE. I spent about an hour on this because I really wanted that nice traceback feature right in the browser. Turns out there is another environment variable that needs to be set similar to <strong>FLASK_APP.</strong> <a href="https://flask.palletsprojects.com/en/1.1.x/quickstart" target="_blank" rel="noreferrer noopener" aria-label="I found this in the flask documentation (opens in a new tab)">I found this in the flask documentation</a>:</p>



<p>To enable all development features (including debug mode) you can export the&nbsp;<code>FLASK_ENV</code>&nbsp;environment variable and set it to&nbsp;<code>development</code>&nbsp;before running the server:</p>



<pre class="wp-block-preformatted">$ export FLASK_ENV=development
$ flask run
</pre>



<p>(On Windows you need to use&nbsp;<code>set</code>&nbsp;instead of&nbsp;<code>export</code>.)</p>



<p>This does the following things:</p>



<ol><li>it activates the debugger</li><li>it activates the automatic reloader</li><li>it enables the debug mode on the Flask application.</li></ol>



<p>You can also control debug mode separately from the environment by exporting&nbsp;<code>FLASK_DEBUG=1</code>.</p>



<p>It turns out <strong>FLASK_ENV</strong> wasn&#8217;t the answer, I just needed that last little part <strong>FLASK_DEBUG=1</strong>. Or to be exact <strong>export FLASK_DEBUG=1</strong></p>



<p>To make it more frustrating I had to do this every time I opened a new terminal. To fix this I wrote this in the terminal:</p>



<pre class="wp-block-code"><code>touch ~/.bash_profile &amp;&amp; echo export FLASK_DEBUG=1 > .bash_profile</code></pre>



<p>I&#8217;ve run into .bash_profile in the past and I recommend doing a quick google how it works when you get a chance.</p>



<p>Now open a fresh new terminal, close the old one, and try to go to the login.html (make sure in the templates folder you delete login.html so it is not there since we&#8217;re trying to mock an error situation). You should get that awesome jinja2 traceback!</p>



<p><a id="frosh"></a></p>



<h2>Frosh IMs &#8211; what it means</h2>



<p>I have no idea what Frosh is let me look that up&#8230;</p>



<p>Ok google tells me it is a slang word for a first year student (like a freshman). </p>



<p>Ok&#8230; fine.</p>



<p>IM&#8217;s stands for intramurals which are sports organized within an institution. Fun fact, the word is derived from the Latin <em>intra muros</em> which means &#8220;within walls.&#8221; Now that i&#8217;ve unpacked the heading of this section let&#8217;s get down to the programming part:</p>



<p>File structure is similar to the previous example:</p>



<ul><li>froshims0/<ul><li>application.py</li><li>templates/<ul><li>failure.html</li><li>index.html</li><li>layout.html</li><li>success.html</li></ul></li></ul></li></ul>



<p>If we go through each file <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="http://cdn.cs50.net/2017/fall/lectures/9/src9/froshims0/" target="_blank">in the link provided here</a>, we can go into each file, copy the code and run it to get the form:</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-08-at-7.53.20-AM.png" alt="" class="wp-image-1325" width="272" height="177" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-08-at-7.53.20-AM.png 437w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-08-at-7.53.20-AM-300x195.png 300w" sizes="(max-width: 272px) 100vw, 272px" /></figure></div>



<p>Next I would like you to open the inspector in your browser by right clicking and choosing inspect. This is a little different for each browser. I&#8217;m using chrome in this case:</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="1024" height="447" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-08-at-7.55.35-AM-1024x447.png" alt="" class="wp-image-1326" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-08-at-7.55.35-AM-1024x447.png 1024w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-08-at-7.55.35-AM-300x131.png 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-08-at-7.55.35-AM-768x335.png 768w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-08-at-7.55.35-AM.png 1170w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<p>Next I want you to click on the &#8220;Network&#8221; tab:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="1666" height="1335" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/2019-11-08-08.17.55.gif" alt="" class="wp-image-1335"/></figure>



<p>A <strong>post request</strong> means the form values are sent in the HTTP body data. What does that mean? Even if we can&#8217;t see the body data doesn&#8217;t mean the other end doesn&#8217;t receive and read it. Lets think of it this way:</p>



<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img loading="lazy" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/sue-hughes-toQNPpuDuwI-unsplash-1-3000x2000.jpg" alt="" class="wp-image-1341" width="737" height="493"/><figcaption>Photo by&nbsp;<a href="https://unsplash.com/@suehughes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">sue hughes</a>&nbsp;on&nbsp;<a href="https://unsplash.com/s/photos/writing-envelope?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure></div>



<p>When I open my browser it&#8217;s like walking into a post office, where I get my mail. When I go to the counter, the clerk asks for information necessary to retrieve my mail. On my computer, when I type <strong>google.com</strong> it&#8217;s like asking the post office worker &#8220;please get me google.com.&#8221; Once that post office worker brings me an envelope let&#8217;s imagine it like this for google.com:</p>



<p></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="960" height="720" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing.jpg" alt="" class="wp-image-1346" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing.jpg 960w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-300x225.jpg 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-768x576.jpg 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<p>Now if I take this same idea and fill out a form on a webpage. I can use a GET request or a POST request. Using GET I pass in the form values right into the URL address. When filling out the frosh form using the method <strong>GET</strong>, and hitting submit the url will change to this:</p>



<pre class="wp-block-code"><code>https://792cdab9-edb1-4a25-a6df-87b8146cafcf-ide.cs50.xyz:8080/register?name=john+smith&amp;dorm=Canaday</code></pre>



<p>Notice the last part: <strong>?name=john+smith&amp;dorm=Apley+Court</strong></p>



<p>So if we look back at the envelope image it might look like this:</p>



<p></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="960" height="720" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1.jpg" alt="" class="wp-image-1350" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1.jpg 960w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-300x225.jpg 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-768x576.jpg 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<p>This is usually ok for quick and dirty apps that don&#8217;t need to be secure with data. A form about if you like cats or not might be ok for the <strong>GET </strong>method.</p>



<p>Otherwise we have to use <strong>POST</strong>. So if i change my code back so I use the <strong>POST</strong> method, which is how it was written by default, my url looks like this after submitting:</p>



<pre class="wp-block-code"><code>https://792cdab9-edb1-4a25-a6df-87b8146cafcf-ide.cs50.xyz:8080/register</code></pre>



<p>So where did my form values end up?</p>



<p><strong>THE SAME PLACE WHERE YOUR BROWSER STORES PAGE DATA.</strong> Like <strong>LITERALLY THE SAME PLACE.</strong> I had no idea for the longest time, because you can&#8217;t see what the computer (server) sees on the other side. It uses that space because you can store tons more data. Think about how many images, videos, text <strong>you view</strong> <strong>on the webpage body</strong>. That allows forms to take advantage of all that space to then store things to the computer on the other end of the form submission.</p>



<p>So here is what a post request looks like:</p>



<p></p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="960" height="720" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-1.jpg" alt="" class="wp-image-1351" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-1.jpg 960w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-1-300x225.jpg 300w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Untitled-drawing-1-1-768x576.jpg 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<h2>Flask routes and more</h2>



<p>Let&#8217;s look at the application.py file in our lecture notes:</p>



<pre class="wp-block-code"><code>from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def index():
	return render_template("index.html")

@app.route("/register", methods=["POST"])
def register():
	if not request.form.get("name") or not request.form.get("dorm"):
		return render_template("failure.html")
	return render_template("success.html")</code></pre>



<p>When we use <strong>from flask</strong> we&#8217;re saying <em>from the flask file, give me access to the Flask class. Python classes by convention </em>start with a capital letter. We are also importing the <strong>render_template</strong> function, and the <strong>request </strong>object, which has methods we can use to <strong>GET </strong>and <strong>POST</strong> things.</p>



<p>Next we have this funky <strong>@app.route(&#8220;/&#8221;)</strong>, followed by a function def. </p>



<pre class="wp-block-code"><code>@app.route("/")
def index():
	return render_template("index.html")</code></pre>



<p>This is called a <strong>decorator</strong>. Let&#8217;s break down what that means.</p>



<h3>A quick peak at decorators, factories and wrapping functions.</h3>



<p>Let&#8217;s jump right into this <em>magic</em>™</p>



<pre class="wp-block-code"><code>def returnPositiveNumber(number):
	if number > 0:
		return number
	else:
		return 1</code></pre>



<p>Here we have a simple function. It will always return a positive number. If it&#8217;s zero or a negative number it will return 1. Easy. <strong>Our function takes in one arguement <em>num</em> as it&#8217;s only argument.</strong></p>



<p>Python treats functions as first-class-objects, which means you can put them just about anywhere, <strong>including as arguments to other functions</strong>.</p>



<p>Check this next piece out:</p>



<pre class="wp-block-code"><code>def plusNineThousandDecorator(function):
	def wrapper(number):
		return function(number) + 9000
	return wrapper</code></pre>



<p>PlusNineThousand <strong>takes a function as its argument</strong>. So we&#8217;re going to pass our <strong>returnPositiveNumber</strong> function into it. How does this look if we try to print something out?</p>



<p><strong>SUPER IMPORTANT!</strong> When we use a function as an argument we are <strong>NOT</strong> calling the function, we reference it as an object which is super strange at first sight. <strong>NO () are used!</strong> </p>



<pre class="wp-block-code"><code>test = plusNineThousand(returnPositiveNumber)</code></pre>



<p>Look back to our plusNineThousand definition and check out the last line. <strong>It returns decorator</strong>. So what is decorator? It&#8217;s a function. <strong>So test is a function</strong>. What does it do? How does it work? <strong>Take a look at it&#8217;s definition:</strong></p>



<pre class="wp-block-code"><code>return function(number) + 9000</code></pre>



<p>It takes <strong>the same argument as our original function</strong>. So we need to run it as <strong>test(num)</strong>. But now <strong><em>it adds 9000 to the returned result.</em></strong></p>



<p>Let&#8217;s try it out:</p>



<pre class="wp-block-code"><code>print(test(42))
#result is 9042

print(test(-1))
#result is 9001</code></pre>



<p><strong>test</strong> is now a function that takes our original function which returned <strong>num</strong> and added a piece of new functionality, which is adding 9000 to it and returning it back.</p>



<p>When using decorators it is common to modify the original function like this:</p>



<pre class="wp-block-code"><code>returnPositiveNumber = plusNineThousandDecorator(returnPositiveNumber)</code></pre>



<p>Now our original function <strong>is what it used to be plus it adds 9000 to everything</strong>.</p>



<pre class="wp-block-code"><code>print(returnPositiveNumber(42))
#result is 9042</code></pre>



<p>We can use some syntax sugar to make our ugly: </p>



<pre class="wp-block-code"><code>returnPositiveNumber = plusNineThousandDecorator(returnPositiveNumber)</code></pre>



<p>Into this:</p>



<pre class="wp-block-code"><code>@plusNineThousandDecorator
def returnPositiveNumber(number):
	if number > 0:
		return number
	else:
		return 1</code></pre>



<p>Make sure the decorator function is before the function you modify. Also the decorator @ has to be placed on the line before the function like shown above.</p>



<p>Here is the entire program:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/6a70fe00b03c6ff34a0c0db328262341">Gist</a>.
</div></figure>



<p>Going deeper, we can assign arguments to our @plusNineThousandDecorator. We can only modify before and after our modified function so let&#8217;s try to add some html tags to the front and back of our number.</p>



<p>So we can not pass arbitrary arguments to our decorator. <strong>The decorator returns our original function wrapped in some other stuff</strong>.</p>



<p><strong>Now we need a &#8220;factory&#8221; that returns a decorator while passing some arguments in the process</strong>.</p>



<p>So let&#8217;s <strong>&#8220;wrap&#8221;</strong> our decorator function in a decorator factory:</p>



<pre class="wp-block-code"><code>def decoratorFactory(htmlTag):
	def plusNineThousandDecorator(function):
		def wrapper(number):
			return f"&lt;{htmlTag}>{function(number) + 9000}&lt;/{htmlTag}>"
		return wrapper
	return plusNineThousandDecorator


@decoratorFactory("h1")
def returnPositiveNumber(number):
	if number > 0:
		return number
	else:
		return 1


print(returnPositiveNumber(42))


# results
# &lt;h1>9042&lt;/h1></code></pre>



<p>Now we can modify our factory argument, get back a decorator, which then wraps our function, and finally modifies it&#8217;s behavior.</p>



<p>This keeps our program<em> dry</em>, or without repetitive code that is difficult to keep track of. If one thing changes in our program we only want to go fix it in <strong>one and only one</strong> place. <a href="https://blog.codinghorror.com/curlys-law-do-one-thing/">Here is a great article on this topic</a>. Decorators help us achieve this goal when creating software.</p>



<h2>Back to our flask app</h2>



<p>So now that we know a little bit about decorators let&#8217;s look again at a basic flask application:</p>



<pre class="wp-block-preformatted">app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"</pre>



<p><a href="https://ains.co/blog/things-which-arent-magic-flask-part-1.html">The example above is from ains.co, and I highly recommend coding through both part 1 and 2 articles here.</a></p>



<p>What is happening behind the scenes is this (basically):</p>



<pre class="wp-block-code"><code>#credit goes to ains.co 
#please read the article on his site it's fantastic
#https://ains.co/blog/things-which-arent-magic-flask-part-1.html

class Flask():
    def __init__(self):
        self.routes = {}

    def route(self, route_str):
        def decorator(f):
            self.routes[route_str] = f
            return f

        return decorator

    def serve(self, path):
        view_function = self.routes.get(path)
        if view_function:
            return view_function()
        else:
            raise ValueError('Route "{}"" has not been registered'.format(path))


app = Flask()

@app.route("/")
def hello():
    return "Hello World!"</code></pre>



<p>We haven&#8217;t used decorators in classes, but it&#8217;s basically the same except here we call a method inside of the Flask class.</p>



<p>The cool part is the <strong>self.routes{}</strong>. </p>



<p>Flask is storing each path (<strong>&#8220;/&#8221;)</strong> as a <strong>key</strong>, while the value is the decorator function itself.</p>



<p>It doesn&#8217;t go that final level deep to <strong>wrapper</strong>. In our example we used our modified function right away, but flask is saving this function to be used later in the <strong>serve</strong> method.</p>



<p>Once we make a request in our browser to the main domain (&#8220;/&#8221;), flask is going to check if that is in it&#8217;s <strong>self.routes</strong> dictionary. If it is it will return the function that is stored, which is <strong>hello()</strong>.</p>



<p>If this is confusing <strong>do not worry</strong>. It is ok to just understand the results of the code and get a <em>feel </em>for how flask operates. This is just a look under the hood of the flask <em>engine</em>. <a href="https://ains.co/blog/things-which-arent-magic-flask-part-1.html">Again here is the link if you want to learn (most of) the inner workings.</a></p>



<h2>Getting form values from flask</h2>



<p>Since our <em>form action</em> in the <strong>index.html</strong> &lt;form&gt; is <strong>&lt;form action=&#8221;/register&#8221;&#8230;</strong> we have to let flask know about this url, otherwise known to flask as a <em>route</em>, and what we should do when the user submits our form to it. So we are sending our form message to that url using the POST method as shown below:</p>



<pre class="wp-block-code"><code>@app.route("/register", methods=["POST"])
def register():
    if not request.form.get("name") or not request.form.get("dorm"):
        return render_template("failure.html")
    return render_template("success.html")</code></pre>



<p>Our function has some logic that guards against the user not submitting the correct values, and finally if the guard is passed we just return the success.html page found in our <strong>templates folder</strong>.</p>



<p>Some cool is the request object we have access to. This allows us to work with the form values that are specified in the index.html &lt;form&gt; element. These are </p>



<p><strong>&lt;input type=&#8221;text&#8221; name=&#8221;name&#8221;</strong>&#8230;</p>



<p>and</p>



<p><strong>&lt;select name=&#8221;dorm&#8221;&gt;</strong></p>



<p>using the <strong>name</strong> attribute we can use <strong>request.form.get(</strong><em>nameAttribute)</em> which gives us the value we specify.</p>



<p>Now let&#8217;s take a look at the failure.html file to pull apart what is happening.</p>



<h2>Flask templating</h2>



<p>Take a look at the templates/failure.html file in the froshim0 flask application:</p>



<pre class="wp-block-code"><code>{% extends "layout.html" %}
{% block body %} 
You must provide your name and dorm!
{% endblock %}</code></pre>



<p>The curly brace percent symbol syntax is <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://jinja.palletsprojects.com/en/2.10.x/" target="_blank">a templating language called jinja2</a>. This means we can write regular html, and when we need an expression like a variable we use the following syntax: <strong>{{ myVariable }}</strong>. When adding logic (for loops, conditionals etc), we wrap them in the curly brace percent symbol like this: <strong>{% <em>logic here %}</em></strong>.</p>



<p>Here is what the failure.html page looks like:</p>



<pre class="wp-block-code"><code>{% extends "layout.html" %}
{% block body %} 
You must provide your name and dorm!
{% endblock %}</code></pre>



<p>If we look into layout.html we only see this:</p>



<pre class="wp-block-code"><code>{% block body %}{% endblock %}</code></pre>



<p>Because there is nothing between block body and endblock, layout.html is not actually adding anything to our failure.html file.</p>



<p>If we erase the jinja2 lines and leave only the plain text:</p>



<pre class="wp-block-code"><code>You must provide your name and dorm!</code></pre>



<p>our webpage result is the same. Run the flask app in the terminal by typing <strong>flask run</strong>. Go to the webpage that has the form and leave it blank. Then click submit. We should get this.</p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img loading="lazy" width="300" height="153" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.00.19-AM.png" alt="" class="wp-image-1377"/></figure></div>



<p>Now let&#8217;s put the jinja2 lines back into failure.html.</p>



<p>Next go back to layout.html and add something like this:</p>



<pre class="wp-block-code"><code>{% block body %}
HELLO LAYOUT!
{% endblock %}</code></pre>



<p>Now when we test the webpage again we get this:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="300" height="153" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.00.19-AM-1.png" alt="" class="wp-image-1378"/></figure>



<p>So we don&#8217;t see HELLO LAYOUT!</p>



<p>This is because <strong>{% block body %}{% endblock%}</strong> is a placeholder for <strong>any file that extends layout.html</strong>. So if failure starts with the <strong>{% extends</strong> &#8230; <strong>%}</strong> expression that means anything within the <strong>{% block body %}{% endblock%}</strong> <strong>in the failure.html file will appear in the {% block body %}{% endblock%}</strong> <strong>inside the layout.html file</strong>.</p>



<p>Now let&#8217;s try adding some html to the outside of the expression in the layout.html file. Try this, save and re-run the flask app by canceling it in the terminal with ctrl-c, then re-running flask run.</p>



<p>Here is layout.html now:</p>



<pre class="wp-block-code"><code>HELLO START OF LAYOUT&lt;br>
---------------------&lt;br>
&lt;br>
&lt;br>
{% block body %} THIS WILL NOT RENDER {% endblock %}&lt;br>
&lt;br>
&lt;br>
-------------------&lt;br>
HELLO END OF LAYOUT</code></pre>



<p>Now things are getting interesting. Every page in our app now has this text we&#8217;ve added:</p>



<figure class="wp-block-gallery columns-3 is-cropped"><ul class="blocks-gallery-grid"><li class="blocks-gallery-item"><figure><img loading="lazy" width="336" height="350" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.12.35-AM-1.png" alt="" data-id="1382" data-full-url="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.12.35-AM-1.png" data-link="https://johnyzaguirre.com/?attachment_id=1382" class="wp-image-1382" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.12.35-AM-1.png 336w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.12.35-AM-1-288x300.png 288w" sizes="(max-width: 336px) 100vw, 336px" /></figure></li><li class="blocks-gallery-item"><figure><img loading="lazy" width="303" height="237" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.13.31-AM.png" alt="" data-id="1381" data-full-url="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.13.31-AM.png" data-link="https://johnyzaguirre.com/?attachment_id=1381" class="wp-image-1381" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.13.31-AM.png 303w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.13.31-AM-300x235.png 300w" sizes="(max-width: 303px) 100vw, 303px" /></figure></li><li class="blocks-gallery-item"><figure><img loading="lazy" width="309" height="248" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.13.40-AM.png" alt="" data-id="1380" data-full-url="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.13.40-AM.png" data-link="https://johnyzaguirre.com/?attachment_id=1380" class="wp-image-1380" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.13.40-AM.png 309w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-11-at-9.13.40-AM-300x241.png 300w" sizes="(max-width: 309px) 100vw, 309px" /></figure></li></ul></figure>



<p>Now we can put pieces of our webpage that repeat on many pages in one place, and extend them using the <strong>{% extends &#8230;%}</strong> method in jinja2.</p>



<h2>Storing form data with flask</h2>



<p>Flask allows us to access form fields when submitted by a user. Looking at application.py on line 1, we import <strong>request</strong>. Here is an updated version of our code:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">from flask import Flask, render_template, request, redirect

app = Flask(__name__)

# Registrants
students = []

@app.route(&quot;/&quot;)
def index():
	return render_template(&quot;index.html&quot;)


@app.route(&quot;/registrants&quot;)
def registrants():
	return render_template(&quot;registrants.html&quot;, students=students)



@app.route(&quot;/register&quot;, methods=[&quot;POST&quot;])
def register():
	name = request.form.get(&quot;name&quot;)
	dorm = request.form.get(&quot;dorm&quot;)
	
	if not name or not dorm:
		return render_template(&quot;failure.html&quot;)
	
	students.append(f&quot;{name} from {dorm}&quot;)
	return redirect(&quot;/registrants&quot;)</pre></div>



<p>Flask is instantiating the request object when the user goes to a webpage. So If I go to &#8220;/&#8221; or &#8220;/registrants&#8221; a new request object is made. This is because of <strong>threads </strong>and<strong> context</strong>.  Threading means the program is doing several things at once, a good example is one user going to our &#8220;/&#8221; webpage and another user at a different computer going to &#8220;/register.&#8221; Each thread has <strong>different stuff going on. The context of the request is not the same</strong>. So flask hands us back a unique object with values that are relevant to the user&#8217;s request.</p>



<p>on line 6 we create a list of<strong> </strong>&#8220;students.&#8221; because this lives outside of all our routes and functions it will be saved for as long as we run our flask app. It&#8217;s stored in memory.</p>



<p>on lines 21 and 22  we create variables &#8220;name&#8221; and &#8220;dorm&#8221; which store the user input from our form. Our request object has a form object inside of it with a get method. This is kind of confusing because it&#8217;s not like <strong>get and post</strong> kind of get, it&#8217;s just the &#8220;get me the value&#8221; kind of get. To clarify:</p>



<ul><li>get <strong>POST request values</strong><ul><li>use <em>request.</em>form.get(field name=&#8221;thisvalue&#8221;)</li></ul></li><li>get <strong>GET request values</strong><ul><li>use request.args.get(field name=&#8221;thisvalue&#8221;)</li></ul></li></ul>



<p>Finally on lines 24 through 28 we guard against the user not inputing values in our form by checking if either name or dorm return false. If one or both return false in our if statement, we return our failure.html page using the render_template function.</p>



<p>If the user submitted all the form values we use our &#8220;students&#8221; list and use the append method to add the formatted string to our list. Finally we redirect the user to the &#8220;/registrants&#8221; page. This confused me because I didn&#8217;t realize the app route is going to &#8220;/<strong>register</strong>&#8221; and the redirect is to &#8220;/regis<strong>trants</strong>.&#8221;</p>



<p>So normally we could pass a template using render_template. But I think it makes sense to use redirect to minimize code repetition. If the registrants template file ever had to change you would only have to change it in one place. The template should stay with the route!</p>



<p>Notice line 15 how we have students=students as an argument in the render_template fuction:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">@app.route(&quot;/registrants&quot;)
def registrants():
	return render_template(&quot;registrants.html&quot;, students=students)</pre></div>



<p>We&#8217;re creating a new variable for our render_template so it can access our <strong>students</strong> list. So the students on the right side is the one that has our name and dorms, while the one on the left is passed to our template. This is where <strong>jinja2</strong> comes into play.</p>



<p>Go to templates/registrants.html</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;HTML&quot;,&quot;modeName&quot;:&quot;html&quot;}">{% extends &quot;layout.html&quot; %}

{% block body %}

&lt;ul&gt;
    {% for student in students %}
    &lt;li&gt;{{ student }}&lt;/li&gt;
    {% endfor %}
&lt;/ul&gt;

{% endblock %}</pre></div>



<p>On line 6 we are using a <strong>for student in students</strong> <strong><em>loop</em></strong>. The <strong>students</strong> is the list of student data we passed from our application.py!</p>



<p>Just like any python loop we express a single item in our list but creating a temporary variable, in this case we call it <strong>student</strong> (singular). Now within the loop we add it to our html list with double curly braces <strong>{{ student }}</strong>.</p>



<p>We have to end our for loop when using html and jinja2 so on line 8 we use the <strong>{% endfor %}</strong>  statement.</p>



<p>Here is what happens after submitting the form two times:</p>



<figure class="wp-block-image size-large"><img loading="lazy" width="680" height="154" src="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-12-at-8.47.05-AM.png" alt="" class="wp-image-1410" srcset="https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-12-at-8.47.05-AM.png 680w, https://johnyzaguirre.com/wp-content/uploads/2019/11/Screen-Shot-2019-11-12-at-8.47.05-AM-300x68.png 300w" sizes="(max-width: 680px) 100vw, 680px" /></figure>



<p>Don&#8217;t forget using <strong>app.route</strong> doesn&#8217;t have to return a webpage! Notice how we don&#8217;t have a <strong>register.html</strong> file in our templates. This is because that route is only being used to process some values. Once we have them we can redirect them to an actual webpage. Each time the user goes to a different address it&#8217;s just running a function for us. That <em>might </em>be a webpage, other times it might just be doing some work behind the scenes.</p>



<h2>Adding more features to the froshim form</h2>



<p>Next up we add an email letting the user know they registered. Of course new features mean new import statements so let&#8217;s bring them in:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">import os
import smtplib
from flask import Flask, render_template, request</pre></div>



<p>We aren&#8217;t using the redirect method so we&#8217;ll leave it out this time.</p>



<p>Next we create our app object and the usual route to our root web address &#8220;/&#8221;:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">import os
import smtplib
from flask import Flask, render_template, request

# Configure app
app = Flask(__name__)

@app.route(&quot;/&quot;)
def index():
    return render_template(&quot;index.html&quot;)</pre></div>



<p>Then we configure the &#8220;/register&#8221; route to send a confirmation email to the user:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">import os
import smtplib
from flask import Flask, render_template, request

# Configure app
app = Flask(__name__)

@app.route(&quot;/&quot;)
def index():
    return render_template(&quot;index.html&quot;)


@app.route(&quot;/register&quot;, methods=[&quot;POST&quot;])
def register():
    name = request.form.get(&quot;name&quot;)
    email = request.form.get(&quot;email&quot;)
    dorm = request.form.get(&quot;dorm&quot;)
    if not name or not email or not dorm:
        return render_template(&quot;failure.html&quot;)
    message = &quot;You are registered!&quot;
    server = smtplib.SMTP(&quot;smtp.gmail.com&quot;, 587)
    server.starttls()
    server.login(&quot;jharvard@cs50.net&quot;, os.getenv(&quot;PASSWORD&quot;))
    server.sendmail(&quot;jharvard@cs50.net&quot;, email, message)
    return render_template(&quot;success.html&quot;)</pre></div>



<p>Using the smtblib (SMTP library &#8211; simple mail transfer protocol) we can log into an email account, and send emails to users through it. Just like you would from your own email account.</p>



<p>Using the os library allows us to use operating system variables and methods from within our program. We don&#8217;t want a plain text password in our program, so we can have the os library call it from an environment variable we set outside of the program. I&#8217;m using a mac, so in the terminal I would type <strong>export PASSWORD=<em>mypassword</em></strong>.</p>



<p>This script doesn&#8217;t work without a few changes. Can you try to use your email to send a success message back to the same email?</p>



<p>I had to add the email input in the index.html file, create an environment variable with my email password then update the script with my email address.</p>



<p>Finally google doesn&#8217;t allow apps like this to work by default. So do a quick search for <em>allowing less secure apps</em> <em>in gmail</em> to briefly allow the app to send the email to see it working.</p>



<h3>Using the csv library</h3>



<p>Here is another example where we save the registrants to a csv table file:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror cm-s-material" data-setting="{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}">from flask import Flask, render_template, request
import csv

app = Flask(__name__)

@app.route(&quot;/&quot;)
def index():
    return render_template(&quot;index.html&quot;)

@app.route(&quot;/register&quot;, methods=[&quot;POST&quot;])
def register():
    if not request.form.get(&quot;name&quot;) or not request.form.get(&quot;dorm&quot;):
        return render_template(&quot;failure.html&quot;)
    file = open(&quot;registrants.csv&quot;, &quot;a&quot;)
    writer = csv.writer(file)
    writer.writerow((request.form.get(&quot;name&quot;), request.form.get(&quot;dorm&quot;)))
    file.close()
    return render_template(&quot;success.html&quot;)</pre></div>



<p>Getting csv (comma separated values) data can be really handy to users who have to filter data later in a spreadsheet. Python3 comes with a great library for this called <strong>csv</strong>. </p>



<p>On line 14 we use the <strong>open</strong> function to create our csv file, and the <strong>&#8220;a&#8221;</strong> means we&#8217;re going to be writing to the file in <em>append</em> mode, since we are going to add info to the file over and over every time a user fills out the form. We don&#8217;t want to overwrite the previous data, which is what would happen if we used <strong>&#8220;w&#8221;</strong> or write mode.</p>



<p>The csv class has a writer class that takes in a file handler, and gives us back an object with methods for adding data to the csv. We name the object <strong>writer</strong> and use the writerow method, passing in the data the way we want it entered into the row. Imagine this is our csv spreadsheet:</p>



<figure class="wp-block-table"><table class=""><tbody><tr><td>John Smith</td><td>Apley Court</td></tr><tr><td>Jane Smith</td><td>Matthews</td></tr></tbody></table></figure>



<p>Our csv files can be open in a text editor and look like this:</p>



<p>John Smith, Apley Court<br>Jane Smith, Matthews</p>



<p>Each column is separated with a comma<br>and each row is separated with a line break.</p>



<p>Back to our program we see on line 18 this is exactly what the <strong>writer.writerow</strong> function is doing. Pushing in a row of data from the form.</p>



<p>Finally with use the <strong>file.close()</strong> method, and return our success.html page.</p>



<p>Our .csv file can be opened in Excel. Create a few entries and try it out!</p>



<p>That is it for week 7 lecture notes!!!</p>



<h2>Preview into problem set 6</h2>



<p>Coming up we&#8217;re going to use flask to create a web app that compares strings char by char, or the less comfortable version is uploading two text files and comparing them in different ways. See you in the next one!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2019/11/13/cs50-week-7/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>CS50 Week 6 &#038; Week 6 Continued</title>
		<link>https://johnyzaguirre.com/2018/11/13/cs50-week-6/</link>
					<comments>https://johnyzaguirre.com/2018/11/13/cs50-week-6/#respond</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Tue, 13 Nov 2018 01:16:57 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">https://johnyzaguirre.com/?p=1219</guid>

					<description><![CDATA[Using the cs50 library in Python and VENV I&#8217;m going to show you something I wish I knew sooner. Python has a program that allows you to setup a virtual environment that is completely walled off from your entire computer. This means you can make a huge mess, write horrible messy code and install a &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2018/11/13/cs50-week-6/" class="more-link">Continue reading<span class="screen-reader-text"> "CS50 Week 6 &#038; Week 6 Continued"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<h2>Using the cs50 library in Python and VENV</h2>



<p>I&#8217;m going to show you something I wish I knew sooner.</p>



<p>Python has a program that allows you to setup a virtual environment that is completely walled off from your entire computer. This means you can make a huge mess, write horrible messy code and install a ton of packages that break everything without worry of messing up your computer or other programs. Just exit the environment and delete the folder and you&#8217;re done. Keep in mind the folder only holds the environment data so you can write code even outside of your chosen directory.</p>



<p>To do this i&#8217;m going to go to my desktop and create a folder called <em>cs50</em> and then go to that folder in my terminal window.</p>



<p>Make sure you&#8217;ve installed python 3 (google download python 3 to get it).</p>



<p>When working with virtual environments with python 3 you have to remember three steps:</p>



<ul><li>create the env file using <em>p</em>ython3</li><li>startup the environment using <em>source</em></li><li>exit the environment with a single command <strong>deactivate</strong></li></ul>



<p>So i&#8217;m in my cs50 folder in the terminal and i&#8217;m ready to create my environment folder. I know it seems confusing, <em><strong>isn&#8217;t cs50 the environment folder???</strong></em> No, we are in cs50 to keep things nice and tidy. More on that in a second&#8230;</p>



<p>Let&#8217;s run our first command: <strong>python3 -m venv .env</strong></p>



<p>So what just happened?</p>



<p>We are using the -m flag which is the command-line flag, to run the venv module as a script. So we&#8217;re basically running the venv python program.</p>



<p>the last bit is our argument we pass which is whatever we want to name our folder. I&#8217;m going to name it .env to make it a hidden folder (env just stands for environment so I know what it is for).</p>



<p>Now that we have our environment folder ready I can activate it. Still in the cs50 directory i&#8217;ll type: <strong>source .env/bin/activate</strong></p>



<p>Now my terminal prompt changes so there is a <strong>(.env) </strong>at the beginning.</p>



<p>I can now install packages and run python3 without worrying about affecting other projects.<br></p>



<p>Finally if I want to save all my packages I can run this command: </p>



<p><strong>pip freeze &gt; requirements.txt</strong></p>



<p>This creates a text file that has all the packages my project is currently using which I can then install on any other machine by typing:</p>



<p><strong>pip install -r requirements.txt</strong></p>



<p>And that is the way to create a clean directory with a .env file and a requirements file. Run the freeze command anytime you are finished with a project so it is up to date.</p>



<p>If you were putting your whole project into the cs50 folder it&#8217;s very convenient to zip it up, send it to someone and have them spin up the same environment from their computer without any issue!</p>



<p></p>



<ul><li>So let’s save a file in the CS50 IDE,&nbsp;<code>hello.py</code>, with the following contents:<code>print("hello, world")</code></li><li>Then, we can run&nbsp;<code>python hello.py</code>&nbsp;and see this:<code>$ python hello.py hello, world</code><ul><li><code>python</code>&nbsp;is the name of the interpreter program that we’ve installed onto the CS50 IDE, and&nbsp;<code>hello.py</code>&nbsp;is the name of our file that we are passing in as an argument, for it to interpret.</li></ul></li></ul>



<h2>Lecture and Python</h2>



<p>The first lecture for the week was done at Yale university and is very hard to follow. It gave me flashbacks of all those days trying to figure out the C problem sets. </p>



<p>Moving on to the next lecture, we&#8217;re back at Harvard learning Python. Python is a &#8220;productivity&#8221; language. It&#8217;s easier to use than most other languages and has the added benefit of strict indentation. So your code looks just like my code (indent wise anyways). I have made some pretty basic programs in Python and get the gist of how it works. So this week was yet another breeze! Heading forward to week 7 in record time! </p>



<h2>Python Basics (explained in a python program)</h2>



<p>Here is a program I&#8217;ve written that goes through all the python basics in the lecture:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/f8b63f78ebe2199e6c93d79f151eee91">Gist</a>.
</div></figure>



<ul><li>If we were to just import cs50 without the from statement, we would have access to cs50 as an <strong>object</strong>. This means to get to the <strong>get_string</strong> function we would have to write it as <strong>cs50.get_string(</strong>&#8220;name: &#8220;<strong>)</strong>. By using the <strong>from</strong> statement we have direct access to that function in our program.<br></li><li>using f before a string allows special formatting, for example using variables by wrapping them in curly brackets. Because a string is an object with methods built in, we can also use &#8220;mystring {}&#8221;.format(myvariable). Using f&#8221;string {variable}&#8221; is a built in shortcut.</li><li><strong>__name__ </strong>is a &#8220;special variable&#8221; that holds the name of either the main program or the file name where a program is being run.  By default the program file I am working in will be &#8220;__main__&#8221; inside the <strong>__name__ </strong>variable. If I had a separate file I imported that would have it&#8217;s file name associated with the <strong>__name__ </strong>variable from within itself. Here is a quick example:<br><br><em>create a file called <strong>cow.py </strong>with the following code:<br></em></li></ul>



<pre class="wp-block-code"><code>print(f"I am a cow and the __name__ is = {__name__}")

if __name__ == "__main__":
    print("mooooo")
else:
    print("I must be running in the duck file!\n")</code></pre>



<p><em>Next create another file called <strong>duck.py</strong> with the following code:</em></p>



<pre class="wp-block-code"><code>import cow

print(f"I am a duck and the __name__ is = {__name__}")

if __name__ == "__main__":
    print("quaaaack")
else:
    print("I am not a duck")</code></pre>



<p>Running cow.py and then duck.py will show how <strong>__name__ </strong>is interpreted differently depending on the file being run.</p>



<h2>Python Operators</h2>



<p>My gist is slightly different from the cs50 notes. Better to re-write it in my own way to really learn more deeply.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/ae2f621e25374f5865ebff36ee8572a4">Gist</a>.
</div></figure>



<p>The floor division is interesting. It truncates everything after the decimal point. So if you give it 2 integers it returns an integer back. Normal division will return a float.</p>



<p>If at anytime you want to know the type of something, use the type() function which is a part of the standard library of python, which means it just works out of the box!</p>



<h2>Python Logic</h2>



<p>Logic is very clean in python. Not a lot of braces to deal with. Indentation is important and code will break if things are not indented correctly. Makes looking at code slightly easier (very slightly for me at this point).</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/2a2476d8f4f4e77943874898e738d145">Gist</a>.
</div></figure>



<p>Instead of using &amp;&amp; and || python uses the actual words <strong>or</strong>/<strong>and </strong>which is easier to read, in my opinion.</p>



<p>Using <strong>==</strong> also works with strings for comparison just like chars.</p>



<h2>Defining functions</h2>



<p>While looking at the notes on functions everything looked straightforward until I hit this &#8220;**&#8221; operator. It took a minute to realize python has another operator just for giving you the result of a number to the power of another number. So if I wrote <strong>4**8 </strong>I would be saying <strong>4</strong> <strong>to the power of 8</strong>.</p>



<p>When writing functions we don&#8217;t use the function keyword we use <strong>def</strong>. No curly braces required as long as we indent everything within the function after the colon.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/c7308fef412e685cecf9c376d9146923">Gist</a>.
</div></figure>



<p>When dealing with longer lines of strings you can break them up as shown above. Just keep in mind if there are variables in your string you have to start each new line with the <strong><em>f</em></strong> character so python knows it&#8217;s an &#8220;<strong>f-string</strong>.&#8221;</p>



<h2>Validate user input</h2>



<p>I learned a few things from this example. I always get sloppy when trying to validate user input. In short you have to:</p>



<ul><li>while true</li><li>if this meets my criteria (if the value is true)</li><li>break out</li><li>return the value</li></ul>



<p>So while true, if true break and return! Input validated.</p>



<p>Also you can create multiline comments in your code by using triple quotation marks like so: &#8221;&#8217;</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/9dbee060a630b2a39468e49416839a19">Gist</a>.
</div></figure>



<p>Remember that <strong>main()</strong> is run at the very end so we can define it at the top and add the other functions later.</p>



<h2>Integer overflow</h2>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/a47a6316a0fa41a7d085fe0cb252cf21">Gist</a>.
</div></figure>



<p>The sleep function is cool for creating a delay. It&#8217;s amazing how python has a library for just about everything.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/e57c28a9946ebc4dffdc3a68e1777d55">Gist</a>.
</div></figure>



<h2>Mario&#8230;again</h2>



<p>This took a good 30 minutes to sort out in my head. I found the <strong>end</strong> argument to be super helpful, but don&#8217;t forget to explicitly write a print() statement wherever you want an actual line break. By stating <strong>end=&#8221;&#8221;</strong> you are saying <em>print this to stdout but don&#8217;t include a line break at the end just put nothing at the end.</em> This is also helpful if for some reason every string in your loop needs to have something at the end that is repeated. Maybe a list of names and you just want to say <strong>{name}, end=&#8221; is awesome!&#8221; print()</strong>.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/390803432fa9e7b392f430240d2f106c">Gist</a>.
</div></figure>



<h2>Command line arguments</h2>



<p>If we want access to the program name and any command line arguments when the program is about to run we can<strong> </strong>import the <strong>sys</strong> library which is a part of the standard python library. Here is a quick example:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/2aa93c8b562373ad4ab3818002014dc2">Gist</a>.
</div></figure>



<p>As an added bonus there is a loop that goes through each string argument and then iterates through each character. It is the most readable loop in a loop ever.</p>



<h2>Extract a user&#8217;s initials</h2>



<p>In the cs50 notes for python lecture 8 there is an example for getting a user&#8217;s initials from their full name. It looks like this:</p>



<pre class="wp-block-code"><code># Extracts a user's initials

from cs50 import get_string

s = get_string("Name: ")
initials = ""
for c in s:
    if c.isupper():
        initials += c
print(initials)</code></pre>



<p>I wanted to see if I could figure out a way to get the users initials even if they didn&#8217;t capitalize the letters.</p>



<p>This is an opportunity to learn new things, jump into stackoverflow and overcome challenges. <strong>Do not feel bad for getting code off stackoverflow!</strong> It&#8217;s documentation of people spending hours figuring out edge case issues, and if you go there for something in particular over and over you will eventually memorize it. If it is an edge case you are better off leaving it out of your brain to focus on more important things! I did not copy and paste the entire script from someone else. If I got stuck on a small piece I worked through it with help from googling the question.</p>



<p>So I use regex every so often at my job, and it comes in super handy for getting the right bits of text, validating it so you only get what you want. It can be hard to visualize and figure out how to get the right groups.</p>



<p>Regex is a huge topic I won&#8217;t discuss here but, I will say check out <a rel="noreferrer noopener" aria-label=" (opens in a new tab)" href="https://regex101.com/" target="_blank">https://regex101.com/</a> if you want to learn more.</p>



<p>So here is my initial generator! No capitals required, plus you can have as many names as you want and you will get initials forever!</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/6ea1adeff0cf8299768fda722f86ac21">Gist</a>.
</div></figure>



<h2>Linear search in python</h2>



<p>We can find an item in either a list of dictionary by using the <strong>in</strong> operator. It is a straightforward process. I made a quick list and a dictionary to both confirm an item in a list and then bring up an associated price for the item.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/c97b8276518a87a22704d1d4147dfcbd">Gist</a>.
</div></figure>



<h2>Comparing two strings</h2>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/89dad8215fa498a31f297d0cf5d9acd5">Gist</a>.
</div></figure>



<p>I created a slightly different version here where I did not use an else branch. <strong>sys.exit(0)</strong> is a function that will exit out of the program with a code of zero which means program ran successfully. If the string is equal it will pass over that branch and continue to the final print function.</p>



<h2>Null and none</h2>



<p>get_string can return a value known in python as <strong>none</strong>. It&#8217;s basically null I think!</p>



<h2>Swapping values</h2>



<p>We touched upon this in my big python program at the top. Packing and unpacking allows us to swap values in one line like this:</p>



<pre class="wp-block-code"><code>x = 1
y = 2

print(f"x is {x}, y is {y}")
x, y = y, x
print(f"x is {x}, y is {y}")</code></pre>



<h2>Data structures (classes)</h2>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/ac852561203c8bea1237002add0e2614">Gist</a>.
</div></figure>



<p>Notice how this gist has 2 files. As long as they are in the same folder <strong>from student import Student</strong> should work just fine. Creating an object from a class is the same as a function call. We use the class name and the arguments from the <strong>__init__ </strong>method from inside the class. We don&#8217;t need to include <strong>self</strong> when we create the object because <strong>self is a reserved keyword used to bind each argument that it follows</strong>. So we&#8217;re creating the object and binding <strong>name and dorm </strong>to that particular instance. So a class is just a template, or a mold for an actual object. When create an instance of the class, we fill the mold and pop out an object.</p>



<p>After gathering the user input in a loop and pushing each one in our list using the <strong>append</strong> list method, we run a loop printing each <strong>student </strong>object within our <strong>students </strong>list.</p>



<h2>Saving data to a file in python</h2>



<p>This confused me at first because in the example I was under the impression the <strong>csv</strong> library we import included this weird <strong>with open </strong>statement. Check this out:</p>



<pre class="wp-block-code"><code># Demonstrates file I/O

import csv
from cs50 import get_string
from student import Student

# Space for students
students = &#91;]

# Prompt for students' names and dorms
for i in range(3):
    name = get_string("name: ")
    dorm = get_string("dorm: ")
    students.append(Student(name, dorm))

with open("students.csv", "w") as file:
    writer = csv.writer(file)
    for student in students:
        writer.writerow((student.name, student.dorm))</code></pre>



<p>So at the bottom we have this new section where we take out students and create a <strong>.csv </strong>file, which is just a simple spreadsheet table.</p>



<p><strong>with open (&#8220;students.csv&#8221;, &#8220;w&#8221;) as file: </strong>is all in the box standard python stuff. We are creating a file handler, <a rel="noreferrer noopener" aria-label="which I talk about in a previous post. (opens in a new tab)" href="https://johnyzaguirre.com/2018/10/06/cs50-week-3/" target="_blank">which I talk about in a previous post.</a></p>



<p>Without the <strong>with </strong>statement we have to remember to close our file handler like in C. Using <strong>with </strong>we can forget about it, python takes care of closing the file handler for us.</p>



<p>Our fancy csv library comes with a method called <strong>writer</strong> that takes in a file handler and gives us a writer object. That object has a method called <strong>writerow</strong> that takes in a tuple which we wrap in parenthesis and writes that data one row at a time into our file. In my example I push column headers into the first row before the loop starts.</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/97899d1640faa464465f5bd7a712dc8a">Gist</a>.
</div></figure>



<h2>What a dictionary class looks like in python</h2>



<p>Almost done with the week 6 notes and i&#8217;m hit with this dictionary class! So lets try to break this all down:</p>



<pre class="wp-block-code"><code>class Dictionary:
    """Implements a dictionary's functionality"""

    def __init__(self):
        self.words = set()

    def check(self, word):
        """Return true if word is in dictionary else false"""
        return word.lower() in self.words

    def load(self, dictionary):
        """Load dictionary into memory, returning true if successful else false"""
        file = open(dictionary, "r")
        for line in file:
            self.words.add(line.rstrip("\n"))
        file.close()
        return True

    def size(self):
        """Returns number of words in dictionary if loaded else 0 if not yet loaded"""
        return len(self.words)

    def unload(self):
        """Unloads dictionary from memory, returning true if successful else false"""
        return True</code></pre>



<p>I&#8217;m going to have to go back and get the list of dictionary words from that challenge way back when. I will create a gist with the file. Back in a few&#8230;</p>



<p>Week 4&#8217;s speller walkthrough! So I found the txt of words to load into our dictionary. So let&#8217;s see this in action:</p>



<pre class="wp-block-code"><code>from dictionary import Dictionary

dictionary = Dictionary()

print(dictionary.load('large'))

print(dictionary.size())

sample_text = &#91;]

with open('aca.txt', 'r') as file:
    for line in file:
        line = line.split()
        for word in line:
            if word&#91;0].isalpha():
                sample_text.append(word.strip())


with open('spell_check.txt', 'w') as file:
    for word in sample_text:
        if not dictionary.check(word):
            file.write(word + '\n')
            print(f'{word} not in dictionary!')</code></pre>



<p>So you need the week for files which i&#8217;ve <a rel="noreferrer noopener" aria-label="included a link to here (opens in a new tab)" href="http://cdn.cs50.net/2017/fall/psets/5/speller.zip" target="_blank">included a link to here</a>. This gives you a zip file with all the files from that challenge.</p>



<p>This is nothing special and barely does what it should do. BUT the actual &#8220;correct&#8221; program was barely doing a good job spell checking so i&#8217;m ready to move on!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2018/11/13/cs50-week-6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>CS50 Week 5</title>
		<link>https://johnyzaguirre.com/2018/11/12/cs50-week-5/</link>
					<comments>https://johnyzaguirre.com/2018/11/12/cs50-week-5/#comments</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Mon, 12 Nov 2018 19:32:12 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">https://johnyzaguirre.com/?p=1213</guid>

					<description><![CDATA[Week 5 takes a sharp turn, sending us straight into web development. It&#8217;s a welcome break from programming in C. Fortunately for me I have had prior experience in full stack web development, after taking a few classes over at teamtreehouse. I think that is probably why the open source degree program i&#8217;m taking suggests &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2018/11/12/cs50-week-5/" class="more-link">Continue reading<span class="screen-reader-text"> "CS50 Week 5"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p>Week 5 takes a sharp turn, sending us straight into web development. It&#8217;s a welcome break from programming in C.</p>



<p>Fortunately for me I have had prior experience in full stack web development, after taking a few classes over at <a href="https://teamtreehouse.com/johnyzaguirre">teamtreehouse.</a></p>



<p>I think that is probably why the open source degree program i&#8217;m taking suggests I should move onto the next course at this point.</p>



<p>Although I agree, I want the verified certificate once I&#8217;ve completed the course. Which I will add to my &#8220;badges&#8221; page (coming soon!).</p>



<h2>Questions?</h2>



<p>If you are taking this course and made it to week 5, you probably understand how the internet works. If you don&#8217;t that&#8217;s ok too, and I would like to help you understand if there was something in the lecture or the video shorts that did not make sense. Feel free to leave a comment with your question and I&#8217;ll update this post with a detailed answer.</p>



<p>On ward to week 6!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2018/11/12/cs50-week-5/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>CS50 Week 4</title>
		<link>https://johnyzaguirre.com/2018/11/07/cs50-week-4/</link>
					<comments>https://johnyzaguirre.com/2018/11/07/cs50-week-4/#comments</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Wed, 07 Nov 2018 18:31:56 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">https://johnyzaguirre.com/?p=1143</guid>

					<description><![CDATA[Speller problem set explained I&#8217;m going to do my best to explain the solution in small, manageable steps so you can follow along and not go through the pain and suffering I did! Maybe running a gauntlet is harsh, but some days were brutal, and at one point I even deleted tons of code after &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2018/11/07/cs50-week-4/" class="more-link">Continue reading<span class="screen-reader-text"> "CS50 Week 4"</span></a></p>]]></description>
										<content:encoded><![CDATA[
<h2>Speller problem set explained</h2>



<p>I&#8217;m going to do my best to explain the solution in small, manageable steps so you can follow along and not go through the pain and suffering I did!</p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="610" height="270" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/con-air-gif-c.gif" alt="" class="wp-image-1148"/></figure></div>



<p class="has-drop-cap">Maybe running a gauntlet is harsh, but some days were brutal, and at one point I even deleted tons of code after being completely fed up. </p>



<p>If this happens just&nbsp;<strong>take a</strong>&nbsp;<strong>break</strong>. Work 30min to 45 min at a time and go for walks or just stand up for 5 to 10 min in between. Make small pieces of programs that prove a belief about what you think the code is doing.</p>



<p>The last C problem set is called&nbsp;<strong>speller</strong> and is simple when you explain it at a&nbsp;<strong>super high level</strong>.</p>



<p>Main Goals:</p>



<ul><li><strong>load()</strong> the dictionary word by word into a data structure</li><li>Keep track of each word added and return the total number of words in our dictionary by implementing a&nbsp;<strong>size() </strong>function</li><li>We are&nbsp;<strong>given&nbsp;</strong>a single word from the passage in a loop&nbsp;<strong>we do not have to implement ourselves.</strong>&nbsp;Looping through each word in the passage and pulling it has been done for us already! We only have to take a single word and compare it against our data structure within the&nbsp;<strong>check()&nbsp;</strong>function</li><li>Finally we have to loop through each index of our data structure (it&#8217;s just an array folks) and free all the dynamically allocated memory (this is not as hard as it sounds). This happens within our&nbsp;<strong>unload() </strong>function</li></ul>



<p>It processes a piece of text, looks at each word against a dictionary of words and returns any words not found in the dictionary as &#8220;misspelled.&#8221;</p>



<p>Yeah&#8230;simple right?</p>



<h2>Implementations</h2>



<p>So before I show my implementations, let&#8217;s go through each function. Remember a lot of this program is already done for us! Also the program puts each function in alphabetical order instead of the order of when they are called within the program. I will explain each in the order they are called from speller.c.</p>



<p>We need to&nbsp;<strong>know&nbsp;</strong>what our functions are expected to do, and the only way to know is to check what is being passed to us by the main program!</p>



<p><strong><a href="https://johnyzaguirre.com/2018/07/31/cs50-week-2-shorts-part-2/">Use GDB! Printf is great for little things but when you&#8217;re really lost in a bigger program gdb is printf on steroids! (click on the text to go back to the article where I walk you through GDB)</a></strong></p>



<h3>bool load(const char* dictionary) part 1</h3>



<p>The argument passed is a char* (a &#8220;string&#8221;). The const part means the value can not be changed. If we tried to change the string we are passed we will get an error. We should return the value&nbsp;<em>true&nbsp;</em>o</p>



<p>Let&#8217;s use GDB to see what is going on in the main program speller. We&#8217;ll create a break point right on the line&nbsp;<strong>load()&nbsp;</strong>is called, and&nbsp;<em>step into</em> the function so see what is being passed. In my speller.c file the call to&nbsp;<strong>load()&nbsp;</strong>happens on line 45.</p>



<figure class="wp-block-image"><img loading="lazy" width="1388" height="366" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.45.59-PM.png" alt="" class="wp-image-1155" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.45.59-PM.png 1388w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.45.59-PM-300x79.png 300w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.45.59-PM-768x203.png 768w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.45.59-PM-1024x270.png 1024w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /><figcaption>first we cd into the pset5 directory, then run gdb on speller</figcaption></figure>



<p>Remember we start gdb by typing gdb and the filename without the .c part. Now GDB will startup and give us a prompt &#8220;(gdb).&#8221;</p>



<p>So this is all just preparation before we run the program. First we have to tell gdb where to&nbsp;<strong>pause&nbsp;</strong>in our program. I&#8217;ve typed in <em>b 45</em>, which means when I hit run go through the program and&nbsp;<strong>pause, or&nbsp;in other words&nbsp;<em>break&nbsp;</em></strong>at line 45.</p>



<p>Now we just have to type the letter&nbsp;<em>r</em> to run the program:</p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="1076" height="222" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.52.26-PM.png" alt="" class="wp-image-1156" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.52.26-PM.png 1076w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.52.26-PM-300x62.png 300w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.52.26-PM-768x158.png 768w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-2.52.26-PM-1024x211.png 1024w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /><figcaption>nope got an error. What happened?</figcaption></figure></div>



<p><strong>Usage: speller [dictionary] text</strong> gives us the hint we need. When we typed in&nbsp;<strong>r</strong>&nbsp;gdb ran the program as if we typed&nbsp;<strong>./speller</strong> but the program has 2 arguments we need to pass in the terminal. </p>



<p>The first&nbsp;<em>[dictionary]</em>&nbsp;is optional, which is why it&#8217;s surrounded by square brackets. The second argument&nbsp;<em>text</em> is mandatory, which is why we couldn&#8217;t run it.</p>



<p>Check out the folders that are within pset5 using the command&nbsp;<strong>ls</strong> once you <strong>cd</strong> into pset5 from the <strong>~/workspace/</strong> directory. </p>



<p>You will see&nbsp;<strong>texts/</strong> and&nbsp;<strong>dictionaries/</strong></p>



<p>[dictionary] is optional because our main program will automatically choose the&nbsp;<em>large</em>&nbsp;file within that folder.</p>



<p><em>text&nbsp;</em>has to be choosen. I did some exploring in the text folder and found a small piece of text called&nbsp;<em>quote.txt:</em></p>



<blockquote class="wp-block-quote is-style-default"><p>It is known that there are an infinite number of worlds, simply because there is an infinite amount of space for them to be in. However, not every one of them is inhabited. Therefore, there must be a finite number of inhabited worlds. Any finite number divided by infinity is as near to nothing as makes no odds, so the average population of all planets in the universe can be said to be zero. From this it follows that the population of the whole universe is zero, and that all people that you may meet from time to time are merely the products of a deranged imagination.<br><br></p><cite>-Douglas Adams &#8211; The Restaurant at the End of the Universe</cite></blockquote>



<p>So what we really need to type is&nbsp;<strong>r texts/quote.txt</strong>. Let&#8217;s try again:</p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="1362" height="258" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-3.08.15-PM.png" alt="" class="wp-image-1157" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-3.08.15-PM.png 1362w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-3.08.15-PM-300x57.png 300w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-3.08.15-PM-768x145.png 768w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-3.08.15-PM-1024x194.png 1024w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /><figcaption>bingo</figcaption></figure></div>



<p>So we&#8217;re in speller.c on line 45 (speller.c:45) and the program is loading in something called&nbsp;<em>dictionary.</em>&nbsp;So the question is what is dictionary? Before we step into the function let&#8217;s just check using the&nbsp;<strong>p</strong> command which is short for&nbsp;<strong>print</strong>.</p>



<p>So instead of typing printf and trying to guess the value we can just use the command&nbsp;<strong>p</strong> and <strong>any variable of any type&nbsp;</strong>a</p>



<p>So back to our output&nbsp;<strong>p dictionary:</strong></p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="674" height="158" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-3.13.58-PM.png" alt="" class="wp-image-1159" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-3.13.58-PM.png 674w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Screen-Shot-2018-11-03-at-3.13.58-PM-300x70.png 300w" sizes="(max-width: 674px) 100vw, 674px" /></figure></div>



<p>So it passes the string &#8220;dictionaries/large.&#8221;</p>



<p>From the lecture and shorts videos, we know that loading the dictionary means creating a&nbsp;<strong>data structure</strong>. This is a&nbsp;<strong>super fancy word</strong>. Don&#8217;t be fooled into thinking a data structure is some super complex thing only a genius can create. It&#8217;s just an array, that is all&#8230;</p>



<p>An array of structs&#8230;</p>



<p>connected to other structs known as a linked list&#8230;</p>



<p>which we insert using a hash function&#8230;</p>



<p>oh&#8230; and the array is a global variable so we can access it within other functions&#8230;</p>



<p>OKAY MAYBE IT&#8217;S A LITTLE COMPLICATED.</p>



<p>Let&#8217;s get out of GDB for a moment, open&nbsp;<strong>dictionary.c</strong> and start coding within the <strong>load()</strong> function.</p>



<p><em>(to quit out of GDB just type&nbsp;<strong>q</strong> for quit. It will ask if you are sure. Just type&nbsp;<strong>y</strong> for yes.)</em></p>



<p>First we need to use the filename we&#8217;re passed (<strong>const char* dictionary</strong>) and use it to open the file.</p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="1044" height="814" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/speller.c-load-3.png" alt="" class="wp-image-1171" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/speller.c-load-3.png 1044w, https://johnyzaguirre.com/wp-content/uploads/2018/11/speller.c-load-3-300x234.png 300w, https://johnyzaguirre.com/wp-content/uploads/2018/11/speller.c-load-3-768x599.png 768w, https://johnyzaguirre.com/wp-content/uploads/2018/11/speller.c-load-3-1024x798.png 1024w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<p>Now paste this code into the load() function and run the&nbsp;<strong>make&nbsp;</strong>command:</p>



<pre class="wp-block-code"><code>    // create a FILE pointer and fopen() to start the stream
    FILE * dictionary_stream = fopen(dictionary, "r");

    // print out the first character
    printf("first character of the file is: %c\n", fgetc(dictionary_stream));

    // use GDB to inspect the test_string variable after it is used each time.
    char test_string[LENGTH+1];

    // fgets will give us everything on the current line 
    // and put into test_string
    fgets(test_string, (LENGTH+1), dictionary_stream);

    // fscanf gives us whatever we say in the format argument (like %s)
    // and put into test_string
    fscanf(dictionary_stream, "%s", test_string);

    printf("end of example\n");</code></pre>



<p>run GDB again using the same commands we did before. Here is a quick list:</p>



<ul><li>gdb speller</li><li>b 45</li><li>r texts/quote.txt</li></ul>



<p>At this point when we run quote.txt we get:</p>



<pre class="wp-block-preformatted">45          bool loaded = load(dictionary);<br></pre>



<p>load(dictionary) is&nbsp;<strong>about to run</strong>. </p>



<p>It has not yet run, but if I type&nbsp;<strong>n&nbsp;</strong>and go to line 46 (the next line), load() will run. </p>



<p>Everything that load() needs to do will be over and passed to the variable <em>bool loaded</em>.</p>



<p><strong>I don&#8217;t want that</strong>.</p>



<p>What I want is to&nbsp;<strong>step</strong> </p>



<p>For this we have to type&nbsp;<strong>s&nbsp;</strong>for&nbsp;<strong>step-into</strong>.</p>



<p>now we&#8217;re inside the function and get this as our output in GDB:</p>



<pre class="wp-block-preformatted">FILE * dictionary_stream = fopen(dictionary, "r");</pre>



<p>We can now type the&nbsp;<strong>n (stands for &#8220;next&#8221;)</strong>&nbsp;command to see what our variables are doing in the next few lines.</p>



<p>type&nbsp;<strong>n enter</strong></p>



<p>then type&nbsp;<strong>n enter one more time.&nbsp;</strong></p>



<p>Your output should be something like this:</p>



<pre class="wp-block-preformatted">first character of the file is: a<br>158         fgets(test_string, (LENGTH+1), dictionary_stream);<br></pre>



<p>Ignore the&nbsp;<strong>fgets&nbsp;</strong>part for now&#8230;it won&#8217;t run that line until we hit the&nbsp;<strong>n&nbsp;</strong>key.</p>



<p>Here we can see our first output, which is the printf we added to our function. It reads &#8220;first character of the file is: a.&#8221;</p>



<p>So our dictionary_stream was at the beginning of the file, (think of a play head on a youtube video) we used fgetc() which collected the first character, which then in turn moved the FILE pointer dictionary_stream to the next character.</p>



<p>You don&#8217;t have to open dictionaries/large, I will tell you the first few lines are as follows:</p>



<pre class="wp-block-preformatted">a<br>aaa<br>aaas<br>aachen<br>aalborg</pre>



<p>So fget(dictionary_stream) grabbed the first&nbsp;<strong>a&nbsp;</strong>a</p>



<p><em><strong>But wait a minute&#8230;</strong></em></p>



<p><em><strong>Did it really move the pointer to the&nbsp;next newline?</strong></em></p>



<p><em><strong>Let&#8217;s move ahead and see&#8230;</strong></em></p>



<p>hit the&nbsp;<strong>n&nbsp;</strong>key again and press enter.</p>



<pre class="wp-block-preformatted">fgets(test_string, (LENGTH+1), dictionary_stream);<br>(gdb) n<br>161         fscanf(dictionary_stream, "%s", test_string);</pre>



<p>So the first line above is the same one I told you to ignore a moment ago. Once we hit&nbsp;<strong>n</strong>&nbsp;and the enter key it brought us to&nbsp;<strong>fscanf.&nbsp;</strong>Which has not yet run so we can&#8217;t look at it&#8217;s value yet. </p>



<p>So let&#8217;s see what&nbsp;<strong>test_string&nbsp;</strong>is holding after running the&nbsp;<strong>fgets</strong> function. If you did not know&nbsp;<strong>fgets()</strong> takes everything from a single line and puts it in the char* variable we specify, in this case&nbsp;<strong>test_string</strong>.</p>



<p>run&nbsp;<strong>p test_string</strong> </p>



<pre class="wp-block-preformatted">$1 = "\n\000@", '\000' , "\220\336\377\377\377\177\000\000\360\334\377\377\377\177\000\000\000\000\000\000\000\000\000\000\200N\335\367\377\177"</pre>



<p>Your garbage values may vary but the important part is near the beginning of the output. Disregard the <strong>$1 = &#8220;</strong>&nbsp;at the start.</p>



<p><strong>Why did our function grab \n first?</strong></p>



<p>Look at the text at the beginning of our dictionaries/large again and see if you get why:</p>



<pre class="wp-block-preformatted">a\n &lt;- this \n is on every line but is invisible in the text editor<br>aaa<br>aaas<br>aachen<br>aalborg</pre>



<p><strong>It&#8217;s because our first function</strong> <strong><em>fgetc()&nbsp;</em>only grabbed the letter, not the invisible character \n that represents a line-break.</strong></p>



<p>If we never ran the first function&nbsp;<strong>fgetc()</strong> and only ran&nbsp;<strong>fgets()</strong> we would have gotten this output instead:</p>



<pre class="wp-block-preformatted">$1 = "a\n\000@", '\000' , "\220\336\377\377\377\177\000\000\360\334\377\377\377\177\000\000\000\000\000\000\000\000\000\000\200N\335\367\377\177"</pre>



<p>So now we know running fgets() will grab everything from the current file pointer position up to and including the <strong>\n (line-break special character).</strong></p>



<p>Continue on by typing&nbsp;<strong>n&nbsp;</strong>a</p>



<pre class="wp-block-preformatted">161         fscanf(dictionary_stream, "%s", test_string);<br>(gdb) n<br>164         fscanf(dictionary_stream, "%s", test_string);<br></pre>



<p>So again the first line we already saw, but since we&#8217;ve move one more line ahead we can now see what&nbsp;<strong>test_string</strong> is holding after running&nbsp;<strong>fscanf</strong>.</p>



<p>type&nbsp;<strong>p test_string.</strong>&nbsp;The output should be something like this:</p>



<pre class="wp-block-preformatted">$1 = "aaa", '\000' , "\220\336\377\377\377\177\000\000\360\334\377\377\377\177\000\000\000\000\000\000\000\000\000\000\200N\335\367\377\177"</pre>



<p>Again the garbage values are not important and will most likely be different for you. But the first part is the most interesting:</p>



<pre class="wp-block-preformatted">"aaa", '\000'</pre>



<p>Since the previous function grabbed the line-break. The pointer moved to the start of the next line. If you scroll up and check the second line of dictionaries/large was in fact the string &#8220;aaa.&#8221;</p>



<p>Let&#8217;s run the next&nbsp;<strong>fscanf()</strong></p>



<p>type&nbsp;<strong>n</strong> </p>



<p>type&nbsp;<strong>p test_string</strong> </p>



<p>now the output should be something like this:</p>



<pre class="wp-block-preformatted">166         printf("end of example\n");<br>(gdb) p test_string <br>$2 = "aaas", '\000' , "\220\336\377\377\377\177\000\000\360\334\377\377\377\177\000\000\000\000\000\000\000\000\000\000\200N\335\367\377\177"</pre>



<p>BINGO. Ignoring all the garbage values and previous printf statement we can clearly see &#8220;aaas&#8221; followed by the null terminator and some more zeros.</p>



<h3>!IMPORTANT</h3>



<p>See all those weird garbage values? That&#8217;s because when we <em><strong>declared</strong></em> our variable&nbsp;<strong>test_string[LENGTH+1],</strong>&nbsp;We didn&#8217;t <em><strong>initialize</strong></em>&nbsp;it to anything. Here is a trick I learned after I couldn&#8217;t get my code to work and went on a google binge for a few hours:</p>



<p>Go to the line <strong>char test_string[LENGTH+1];</strong></p>



<p>and change it to&nbsp;<strong>char test_string[LENGTH+1] = {&#8216;\0&#8217;};</strong></p>



<p>Quit out of gdb, run&nbsp;<strong>make</strong> and then go back into GDB and step into the function and&nbsp;<strong>p</strong> the values by moving through our&nbsp;<strong>load()</strong> </p>



<p>Now you&#8217;ll get output similar to this:</p>



<pre class="wp-block-preformatted">$1 = "aaa", '\000' &lt;repeats 42 times&gt;<br></pre>



<p>When you initialize the first index,&nbsp;<strong>it automatically makes all other indicies a null terminator.</strong></p>



<p>This might not matter now, but when comparing strings we will have to worry about every index of our array (in my implementation anyways).</p>



<h3>bool load(const char* dictionary) part 2</h3>



<p>Now erase all the test code we&#8217;ve written in our&nbsp;<strong>load()</strong> function. </p>



<p>We know&nbsp;<strong>fscanf</strong> is the way to go for reading in each word, so let&#8217;s talk about it&#8217;s technical definition and how we can use it in a loop to get all our words and start creating our data structure.</p>



<hr class="wp-block-separator"/>



<p><a href="https://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm">From tutorials point:</a></p>



<h4>Description</h4>



<p>The C library function int fscanf(FILE *stream, const char *format, …) reads formatted input from a stream.</p>



<h4>Return Value</h4>



<p>This function returns <strong>the number of input items successfully matched</strong> and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.</p>



<hr class="wp-block-separator"/>



<p>So we&#8217;re given the filename from the main function. We still need that dictionary_stream pointer to the file so let&#8217;s put that back into the function:</p>



<pre class="wp-block-preformatted">// create a FILE pointer and fopen() to start the stream<br>    FILE * dictionary_stream = fopen(dictionary, "r");<br></pre>



<p>We know there is a #define in the main function where LENGTH is a constant for the longest word possible. Let&#8217;s also create a place to hold the current word in the loop:</p>



<pre class="wp-block-preformatted">char temp[LENGTH+1] = {'\0'};</pre>



<p>Remember we need that +1 for the &#8216;\0&#8217; null terminator if we ever come across a word that is the max length.</p>



<p>So now&nbsp;<strong>fscanf()&nbsp;</strong>will return the number of things we tell it to pull on success. So what are we asking it for? The second argument we pass it is the&nbsp;<strong>format specifier.</strong>&nbsp;</p>



<pre class="wp-block-preformatted">returns an int: fscanf(the file pointer, format you want, a place to store the thing you want)<br></pre>



<p>So if we say hey fscanf here is the&nbsp;<strong>dictionary_stream&nbsp;</strong>I want you to pull a&nbsp;<strong>%s&nbsp;</strong>which is a string, and store it in&nbsp;<strong>temp,</strong>&nbsp;</p>



<p>Because the file pointer&nbsp;<strong>dictionary_stream</strong> moves automatically everytime it&#8217;s called we just have to keep running fscanf() until it no longer returns the number we are expecting.</p>



<p>So each time we call fscanf it pulls in&nbsp;<strong>a single word</strong>. We know this because we specify &#8220;%s&#8221; which is a one string. So by that logic we can say&nbsp;<strong>while fscanf returns the number 1 keep calling the function.</strong> </p>



<p>Let&#8217;s create a small test to see if this is working. Here is the entire function as it stands to avoid confusion:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/49f6f80bcab1762295e4c233aef7e094">Gist</a>.
</div></figure>



<p>If we run&nbsp;./speller texts/quote.txt while in the pset5 directory we get this output:</p>



<pre class="wp-block-preformatted">143091<br>Could not load dictionaries/large.</pre>



<p>Since we&#8217;re returning false the main program returns early with the response &#8220;Could not load dictionaries/large. So hopefully you understand what the number 143091 represents.</p>



<p>We&#8217;ve successfully pulled in each word in our loop! We aren&#8217;t currently doing anything with that variable&nbsp;<strong>temp which holds the current word in that loop,</strong> but we now have the total number of words available within the&nbsp;<strong>counter</strong> variable.</p>



<h3>A Quick Detour</h3>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="214" height="235" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/images.jpg" alt="" class="wp-image-1185"/></figure></div>



<p>Before we continue loading each temp variable in the while loop into a data structure, let&#8217;s score any easy win by implementing another function using only a few lines of code. We have that&nbsp;<strong>counter&nbsp;</strong>v</p>



<p>Within dictionary.c we have another function just below the load() function called&nbsp;<strong>size().</strong></p>



<p>Above the function the comment reads: &#8220;<em><strong>Returns number of words in dictionary if loaded else 0 if not yet loaded</strong></em>.&#8221;</p>



<p>Now if you didn&#8217;t already know, variables declared within a function only exist in that function.</p>



<p>Go to&nbsp;<a href="https://repl.it/languages/c">https://repl.it</a> and spin up a quick C programming environment to run this code for a second:</p>



<pre class="wp-block-code"><code>#include &lt;stdio.h>

char *global_animal = "bears";

char *lions(void){
  printf("You can not escape the %s!\n", global_animal);
  char *animal = "lions";
  return animal;
}

char *tigers(void){
  // the variable animal is created
  // within lions but this function
  // has no idea.

  // try to run the code with the
  // line below uncommented and you
  // will get an error
  //printf("NOPE CITY %s\n", animal);


  printf("%s are everywhere!\n", global_animal);
  char *animal = "tigers";
  return animal;
}

int main(void){
  printf("%s, %s, %s, oh my!\n", lions(), tigers(), global_animal);
}</code></pre>



<p>So given this information we know we have a&nbsp;<strong>counter&nbsp;</strong>variable in the <strong>load()</strong> function where it is building up the final count of words. But we need to&nbsp;<strong>pass it along to the size() function.</strong></p>



<p>Let&#8217;s declare the variable&nbsp;<strong>outside of the load() function at the top near our #include directives.</strong></p>



<pre class="wp-block-code"><code>#include &lt;stdio.h>
#include &lt;stdbool.h>
#include &lt;stdlib.h>

// global variable
int dictionary_word_counter = 0;</code></pre>



<p>I&#8217;ve changed the name from&nbsp;<strong>counter</strong> to&nbsp;<strong>dictionary_word_counter.</strong> Go back to the function&nbsp;<strong>load() and remember to change the name there too!</strong></p>



<p>Now our&nbsp;<strong>load()&nbsp;</strong>f</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/c0d766be40653adc3a8c702c8afe45c5">Gist</a>.
</div></figure>



<p>All we have to do for&nbsp;<strong>size()&nbsp;</strong>n</p>



<pre class="wp-block-code"><code>/**
 * Returns number of words in dictionary if loaded else 0 if not yet loaded.
 */
unsigned int size(void)
{
    return dictionary_word_counter;
}</code></pre>



<h3>Some cats&#8230;</h3>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="148" height="116" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/download.jpg" alt="" class="wp-image-1187"/><figcaption>Here are some cats in a basket<br></figcaption></figure></div>



<h3>bool load(const char* dictionary) part 3: The Hashtable explained</h3>



<p>Getting values from an array is easy when you know the index. If I have an array called&nbsp;<strong>numbers[42, 18, 9001]</strong>&nbsp;and I want 42, it&#8217;s easy if I know to look in array location [0] right? But if I don&#8217;t know where my number is I need to run a loop and check each array location until I get a matching number and then return that index.</p>



<p>Running that loop on 3 items isn&#8217;t a big deal.</p>



<p>Running that loop on&nbsp;<strong>143,000+ words is a big deal.</strong></p>



<p>It will either take a very long time, or crash. <em><strong>So we have to find a way to place a word in the array quickly and get it back quickly and it has to work exactly the same.</strong></em></p>



<p>The good news is some smarty pants person already found a solution for this, we just have to implement the process.</p>



<p>This process of fast insertion and retrieval is called a&nbsp;<strong>hashtable</strong> and it involves taking </p>



<ul><li>a regular array </li></ul>



<ul><li>our regular char* text</li></ul>



<ul><li>a funky function we&#8217;ll called&nbsp;<strong>generate_hash</strong> </li></ul>



<p><strong>generate_hash()&nbsp;</strong>takes our text and calculates our index based on some math it will perform on the characters. Remember characters have ascii codes that are&nbsp;<strong>integers</strong> so we can do some clever mathematics like adding up each word and using the output to determine the index we will place it. DO NOT IMPLEMENT YOUR OWN HASH FUNCTION. It&#8217;s a big to do that this course doesn&#8217;t cover. Here is a link:&nbsp;</p>



<p><a href="https://stackoverflow.com/questions/628790/have-a-good-hash-function-for-a-c-hash-table">https://stackoverflow.com/questions/628790/have-a-good-hash-function-for-a-c-hash-table</a></p>



<p>Confused? Here is a drawing:</p>



<figure class="wp-block-image"><img loading="lazy" width="960" height="720" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/hashtable.png" alt="" class="wp-image-1188" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/hashtable.png 960w, https://johnyzaguirre.com/wp-content/uploads/2018/11/hashtable-300x225.png 300w, https://johnyzaguirre.com/wp-content/uploads/2018/11/hashtable-768x576.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure>



<p>So now that you understand how we can place words in our data structure we need to take things one step further, using something called a&nbsp;<strong>singly linked list or linked list for short.</strong> We can not hold 143,000 array indexes because our resources on the stack are limited. We have to hold a pointer to a linked list and search for our word. I&#8217;ll do my best to explain all this.</p>



<h4>The Stack and The Heap</h4>



<p>We put everything we declare in our program on&nbsp;<strong>the stack</strong>. Anything dynamically allocated at runtime using&nbsp;<strong>malloc()&nbsp;</strong>we put on&nbsp;<strong>the heap.</strong> Unfortunately for us the stack won&#8217;t hold 143,000 array indexes. We need to lower the number of indexes and somehow use&nbsp;<strong>the heap.</strong></p>



<p>Imagine the stack as this nice orderly piece of data like the array in the picture above, while the heap is a mess of chaos. We have to get clever to leverage the space the heap gives us without losing the stuff we throw in there. Try to use this image as a reference we&#8217;ll talk about later:</p>



<figure class="wp-block-image"><img loading="lazy" width="960" height="720" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/Stack-vs-Heap.png" alt="" class="wp-image-1193" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/Stack-vs-Heap.png 960w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Stack-vs-Heap-300x225.png 300w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Stack-vs-Heap-768x576.png 768w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure>



<p>The heap is massive in comparison to the stack but it&#8217;s complete chaos. Using&nbsp;<strong>malloc()&nbsp;</strong>we can utilize a portion of heap memory. When we run the&nbsp;<strong>m</strong>emory-<strong>alloc</strong>ation function it returns&nbsp;<strong>the address to the first</strong>&nbsp;<strong>block of memory since we can allocate multiple blocks</strong>.&nbsp; We can allocate 4 blocks of size(char) for example. </p>



<p>The biggest challenge when dealing with heap memory is that we only get an small address. Confused what that means?</p>



<p>The address to your house is a few words and numbers. That can lead a person to your actual house where you have your computer, toaster, clothes and other house hold items. If someone is 50 miles away and they have no idea where you live, and no address&nbsp;<strong>they won&#8217;t find you</strong>.</p>



<p>The address to a soccer stadium is&nbsp;<strong>still just a few words and numbers</strong> but can hold&nbsp;<strong>thousands of people</strong>. Lose this address, you will miss the soccer game.</p>



<p>Because we are given a pointer to the memory address, the stack can handle that tiny piece of information. We can leave the heap to deal with the actual values. We always have to keep track of the addresses. Keep this all in mind as we talk about building a&nbsp;<strong>linked list.</strong></p>



<h3>Singly Linked Lists</h3>



<p>Run this little c program:</p>



<pre class="wp-block-code"><code>#include &lt;stdio.h>
#include &lt;stdlib.h>

int main(void) {
  int *one_char = malloc(sizeof(char));
  int *two_char = malloc(sizeof(char)*2);

  *(one_char + 0) = 'a'; // same as *one_char = 'a';

  *(two_char + 0) = 'b'; // same as two_char = 'b';

  *(two_char+1) = 'c';

  printf("%c, %c, %c\n", *one_char, *two_char, *(two_char+1));

  return 0;
}</code></pre>



<p>Here is a diagram of what is happening in our little program:</p>



<figure class="wp-block-image"><img loading="lazy" width="1424" height="1167" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/singly-linked-lists-1.png" alt="" class="wp-image-1197" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/singly-linked-lists-1.png 1424w, https://johnyzaguirre.com/wp-content/uploads/2018/11/singly-linked-lists-1-300x246.png 300w, https://johnyzaguirre.com/wp-content/uploads/2018/11/singly-linked-lists-1-768x629.png 768w, https://johnyzaguirre.com/wp-content/uploads/2018/11/singly-linked-lists-1-1024x839.png 1024w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure>



<p>First we malloc enough space for one character. This creates the first red circle.</p>



<p>Then we create the second bigger red circle to hold 2 blocks, each the size of 1 character.</p>



<p>Then we assign a value to that block of memory. We can use pointer arithmetic to access different blocks of memory. I&#8217;ve put a number below each character to show the corresponding number you have to add to the <a href="https://stackoverflow.com/questions/14224831/meaning-of-referencing-and-dereferencing/14224990">dereferenced pointer.</a></p>



<p>Notice how our stack only has to hold a small memory address that points to the chunk of memory. Is it possible then to string along multiple chunks in one array index on the stack? Let&#8217;s make a struct in C and call it a&nbsp;<strong>node,</strong> then let&#8217;s make a tiny linked list:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/0a350ce24f7966039e8d67d8a76a9134">Gist</a>.
</div></figure>



<p>Check this diagram to visualize the code above and try to figure out what is happening:</p>



<div class="wp-block-image"><figure class="aligncenter"><img loading="lazy" width="1397" height="1215" src="https://johnyzaguirre.com/wp-content/uploads/2018/11/Untitled-drawing.png" alt="" class="wp-image-1199" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/11/Untitled-drawing.png 1397w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Untitled-drawing-300x261.png 300w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Untitled-drawing-768x668.png 768w, https://johnyzaguirre.com/wp-content/uploads/2018/11/Untitled-drawing-1024x891.png 1024w" sizes="(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px" /></figure></div>



<h3 id="mce_2">bool load(const char* dictionary) part 4: The finale</h3>



<p>So here are all the things our&nbsp;<strong>load()</strong> function should do: </p>



<ol><li>Access a <strong>global</strong> FILE * dictionary_stream and fopen() the filename passed in from the main speller program</li><li>Declare and initialize a char array of size length + 1 for the NULL terminator</li><li>Create a while loop while fscanf() returns the number 1<ol><li>within the loop create space on the heap for our struct node (<em>do not get confused with node_ptr we need room for a&nbsp;</em><strong><em>node</em></strong><em> but we are passed a </em><strong><em>node_ptr</em></strong><em> to store on the stack which points to our newly acquired space on the heap.</em>)</li><li>save the current word in the loop to the node&#8217;s word property</li><li>generate the correct index (generate a hash) to place the node_ptr</li><li>when inserting into the array make sure to check if there is an item at that array location, which means we have to do some singly list rearrangement techniques, for example placing the new item to the &#8220;head&#8221; of the list. Just keep in mind we need to create a temp node_ptr that knows the address of the old head of the list (the original array value on the stack). We update the array index value to the newest address to the newest node, Then we take the newest node&#8217;s&nbsp;<strong>next</strong> property and assign it to the temp node_ptr. Which means we&#8217;ve weaved another item to that array index. The diagram above is an example of what it should look like at the end.</li></ol></li></ol>



<p>Hopefully if you piece together all the ideas in these little programs i&#8217;ve shared, plus some creative programing you can come up with your own solution. Here is what I came up with:</p>



<figure class="wp-block-embed is-type-rich is-provider-embed-handler"><div class="wp-block-embed__wrapper">
View the code on <a href="https://gist.github.com/sojohnnysaid/02757c63b7a0a26eda9114c54cbeaae7">Gist</a>.
</div></figure>



<h2>Do you want more explanations?</h2>



<p><strong>unload() </strong>loops through each array location and free&#8217;s each node from the linked list. I created a function free_linked_list() to make it look cleaner.</p>



<p><strong>check()</strong> takes in a word from the passage text and after &#8220;cleaning&#8221; (all lower case) the data, generates a hash number (an index in the array to search), and loops through however many nodes exist at that location, comparing each dictionary word to the given passage word. We just have to return true or false.</p>



<p>You will see at the top of my solution I created functions for working with nodes and generating the hash. If you want me to go more in depth on any of those other functions please leave a comment and i&#8217;ll do my best to share some more diagrams and clarify what is happening. My goal in this article was to try and simplify the idea of data structures and sharing the solutions to some of the most frustrating moments I had while trying to write up a working program.</p>



<p>As always, </p>



<p>rest, but never quit.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2018/11/07/cs50-week-4/feed/</wfw:commentRss>
			<slash:comments>15</slash:comments>
		
		
			</item>
		<item>
		<title>CS50 Week 3</title>
		<link>https://johnyzaguirre.com/2018/10/06/cs50-week-3/</link>
					<comments>https://johnyzaguirre.com/2018/10/06/cs50-week-3/#comments</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Sat, 06 Oct 2018 22:32:40 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">http://johnyzaguirre.com/?p=652</guid>

					<description><![CDATA[Note: I&#8217;ve added a lot of code examples in this article towards the end that deal with the&#160;resize less comfortable&#160;problem that I found difficult to understand. Use a C repl online to copy and paste the github gists (code examples) i&#8217;ve included and by understanding how they work you&#8217;ll be one step closer to making &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2018/10/06/cs50-week-3/" class="more-link">Continue reading<span class="screen-reader-text"> "CS50 Week 3"</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>Note: I&#8217;ve added a lot of code examples in this article towards the end that deal with the&nbsp;<em><strong>resize less comfortable&nbsp;</strong></em>problem that I found difficult to understand. Use a C repl online to copy and paste the github gists (code examples) i&#8217;ve included and by understanding how they work you&#8217;ll be one step closer to making sense of resize.c!</p>
<h2>New format&#8230;</h2>
<p>Please comment if you have any questions and i&#8217;ll do my best to respond with a detailed answer to help clear anything up. I&#8217;m noticing these problems went from wow that was difficult, to wow what is the meaning of life how could anyone solve these problems in a week?!</p>
<h2>Padding question</h2>
<p>The readme had me stumped on this one:</p>
<blockquote>
<pre>What value does line 65 of `copy.c` assign to `padding` 
if `bi.biWidth` is `3`?</pre>
</blockquote>
<p>Here is the code in question:</p>
<pre>// determine padding for scanlines
int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4;</pre>
<p>So broken down:</p>
<pre>We're given 3 for the width and a rgb triple is 3 as well:

int padding = (4 - (3 * 3) % 4) % 4;

// 3 * 3 = 9

int padding = (4 - (9) % 4) % 4;

// 9 % 4 = 1

int padding = (4 - 1) % 4;

// 4 - 1 = 3

int padding = 3 % 4;

// 3 % 4 = 3

int padding = 3;

</pre>
<p>Does modulo still confuse you? Whenever I step away for a couple of days I lose my &#8220;modulo mojo.&#8221;</p>
<p>Why does 3 % 4 = 3</p>
<p><strong>because mod gives us the remainder of a division operation.</strong></p>
<p>Look at the expression 8 % 4 for example.</p>
<p>Imagine the 4 hits the 8 and gives 4 damage on the 8. So that 4 can hit 8 twice before there is nothing left.</p>
<p>If the first number was 9 there would be 1 left. That&#8217;s what mod gives us,&nbsp;<strong>whatever is left after the second number hits the first number.</strong></p>
<p>So what about 3 % 4?</p>
<p>Well 4 can&#8217;t even fight 3 because it can&#8217;t get at least 4 damage out of it. So the fight never happens and modulo gives us what is left in the first number which is the same as what we started with which is 3!</p>
<h2>Whodunit, struct and typedef explained</h2>
<p>Although it can be uncomfortable at first to wade through someone else&#8217;s file of code, this was a little easier to solve than last weeks helper functions. Remember the lecture speaks about file pointers and modeling our data using structs.</p>
<p>Here is a simple program to help demystify things:</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/094e1ba50da8374f11d3b80699975533">Gist</a>.</p>
<p>I&#8217;ll show my answer and explain what is going on (starts on line 80):</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/b786e84f4a13f8e41c241d4cc8b5536a">Gist</a>.</p>
<p>In our loop we&#8217;re streaming in one pixel of RGB at a time. To access the value of the current pixel we can dive into our struct&#8217;s properties. To access a property we take the struct, which in this care is&nbsp;<strong>triple</strong>, add a dot and then our property:</p>
<pre>triple.rgbtRed</pre>
<p>So we can print this value out or run a test. I wanted to remove all red pixels so I created a branch within the loop between the&nbsp;<strong>fread</strong> and&nbsp;<strong>fwrite</strong> functions. This is the perfect place to make modifications because it&#8217;s right before we write into the new file!</p>
<p>I decided my test would be if a pixel had any full red value. In hex thats&nbsp;<strong>0x0000ff</strong>.</p>
<p>If it did I would take that pixel and black it out on all channels. We can do that by taking each property and assigning it the value of&nbsp;<strong>0x000000</strong>, which is black.</p>
<h2>GDB to the rescue</h2>
<p>Working through resize <del>more</del>&nbsp;less comfortable right now. <del>Figured I would give the more challenging problem a try</del>. After watching the video i&#8217;m faced with resize.c and bmp.h feeling very confused as to where I should start.</p>
<p>Try this:</p>
<ol>
<li>make your copy of the file copy.c (I named mine resize.c) and use&nbsp;<strong>make</strong></li>
<li>run the command gdb resize</li>
<li>set a break point after the header variables are created and read into (this was around line 45) using the command&nbsp;<strong>b 45</strong></li>
<li>run the command&nbsp;<strong>r</strong> &lt;infile.bmp&gt; &lt;outfile.bmp&gt; (using your own bmp files)</li>
<li>now take a look at where you are in the code by using the command&nbsp;<strong>list</strong></li>
<li>finally print out either the&nbsp;<strong>bf</strong> or&nbsp;<strong>bi&nbsp;</strong>structs using the command&nbsp;<strong>print bf&nbsp;</strong>or <strong>print bi</strong></li>
</ol>
<p>Now you can see the insides of those variables and what they are made up of when read. Try printing bf.bfSize etc. It makes a huge difference in my comfort level and I didn&#8217;t have to write a single print statement!</p>
<h2>Understanding File I/O in C</h2>
<p>File I/O operations that occur in resize less comfortable. We have structs being created from a header file, some pointers getting thrown around and what the heck is that nested for loop monster doing at the bottom? Weren&#8217;t we support to write neat little functions for everything?</p>
<p><a href="https://johnyzaguirre.com/wp-content/uploads/2018/09/2i030u.jpg"><img loading="lazy" class="size-full wp-image-665 aligncenter" src="https://johnyzaguirre.com/wp-content/uploads/2018/09/2i030u.jpg" alt="" width="500" height="350"></a></p>
<p>Once you understand what is going on in each of these simple programs,&nbsp;<strong>write it from scratch yourself</strong>. Change the text, add a conditional if you want to be adventurous. Maybe if somewhere there is the character &#8216;s&#8217; switch it to &#8216;z&#8217;. Make it your own to really learn what is going on. Each time you run&nbsp;<strong>make</strong> and there is an error, solve it and be amazed at your growth as a programmer!</p>
<p>Creating a new file:</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/4152ad002ee8edc3c1dcd3c7eee7605e">Gist</a>.</p>
<p>Reading in a file:</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/e3785b177fb0bf20031593979922755c">Gist</a>.</p>
<h2>Visualize file I/O in C</h2>
<pre>FILE * fp = fopen("stuff.txt", "r");</pre>
<p>The FILE data type is known as an&nbsp;<strong>opaque data type&nbsp;</strong>so the details are hidden. You should also know FILE is a struct which means this creates an object. For now we need to know this is the data type when dealing with files. Simple enough for now&#8230;</p>
<p>Next we have the * fp. So we know that fp is a pointer which holds the address where our file lives. But what if we don&#8217;t have a file yet? Well we don&#8217;t quite have access to an address space but a &#8220;stream.&#8221; The fp becomes a &#8220;file handler.&#8221;<a href="https://johnyzaguirre.com/wp-content/uploads/2018/10/2i04p8.jpg"><img loading="lazy" class="aligncenter wp-image-960 size-medium" src="https://johnyzaguirre.com/wp-content/uploads/2018/10/2i04p8-300x243.jpg" alt="" width="300" height="243" srcset="https://johnyzaguirre.com/wp-content/uploads/2018/10/2i04p8-300x243.jpg 300w, https://johnyzaguirre.com/wp-content/uploads/2018/10/2i04p8.jpg 500w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<p>We take for granted how simple it is to&nbsp;<strong>save files</strong> on our computer. We don&#8217;t think for a second about it. Back in the day this was an issue. Programs store data to memory (RAM) while they&#8217;re running, and if there is enough memory, but once stopped (or shut off from power) programs lose everything stored on the computers memory. In order to save data after programs stopped they needed a completely different way of storing data. Files became the way, and needed a way to be&nbsp;<strong>HANDLED</strong>.</p>
<p>Memory (RAM) is usually a long chip with squares. File storage devices are not all alike. DVD&#8217;s, SD cards,HDD&#8217;s and SSD&#8217;s are all storage devices that you find in modern computers today. But it did not start out that way at all!</p>
<p>In the past, data was stored on giant spinning disk machines. There were programmers that had to implement code that could save data to these.</p>
<p>Let&#8217;s create a pseudo function for that:</p>
<pre>saveDataOnSpinningDisk(){
  // lots of programming
}</pre>
<p>It&#8217;s 1965 and your manager comes in and tells you &#8220;They have these new tape machines that store 100 times the data in the same amount of space! we have to write code to save data to these new data storage machines!&#8221;</p>
<p>All our programs (think thousands of lines of code) have a function called saveDataOnSpinningDisk().</p>
<p>So what do we do? Maybe we have an if statement like this:</p>
<pre>if(using old data storage method){
   saveDataOnSpinningDisk()
}else{
   saveDataOnNewTapeMachine()
}</pre>
<p>A few years later the HDD (Hard Drive Disk) is invented, and a basement full of tape machines can be stored in the palm of your hand. Management is telling you to write more code to&nbsp;<strong>HANDLE FILES</strong> using this new method of storage. Soon CD&#8217;s DVD&#8217;s Blue-ray discs, SD cards&#8230;you get the picture.</p>
<p>Eventually people figured out data storage could be abstracted out to their basic&nbsp;<strong>operations</strong>. All of these storage devices can be&nbsp;<strong>written, read, appended to, deleted, and created</strong>. By keeping the specific implementation behind the scenes, our programs only have to deal with an abstraction called a&nbsp;<strong>FILE HANDLER</strong>, that handles these I/O operations for us.</p>
<p>The C programming language is taking care of the file I/O specific to our system&nbsp;<strong>for us</strong>. It knows we&#8217;re on linux ubuntu, on the CS50 cloud server and does the file I/O needed for the system. Many digital cameras use C, which means the same functions you write to manipulate file I/O can be used to store data on an SD card. This keeps you focused on the program at hand, not the distracting details of file I/O.</p>
<h2>I finally got through week 3</h2>
<p><figure id="attachment_673" aria-describedby="caption-attachment-673" style="width: 620px" class="wp-caption aligncenter"><a href="https://johnyzaguirre.com/wp-content/uploads/2018/10/2jcv4g.jpg"><img loading="lazy" class="wp-image-673 size-full" src="https://johnyzaguirre.com/wp-content/uploads/2018/10/2jcv4g.jpg" alt="" width="620" height="335"></a><figcaption id="caption-attachment-673" class="wp-caption-text"></p>
<p><center>It really be like that though</center></figcaption></figure></p>
<p>Honestly,&nbsp; it didn&#8217;t take 8 weeks. It took probably a week of really focused time to complete this problem. Specifically &#8220;less comfortable.&#8221;</p>
<p>I&#8217;ve created a few simple programs that helped me understand each part of the program resize.c, so it wouldn&#8217;t feel so overwhelming when trying to tackle in one pass.</p>
<p>Not sure how to create a file or make a copy? This little program might help:</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/aaa57a64af068a470e87ee8a189881cf">Gist</a>.</p>
<p>Not sure what the original copy.c is doing in the problem set? Try going through my version and see if it makes more sense. I added a lot of helpful comments.</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/aa08cd766d94d0d847b7fa293e6aa281">Gist</a>.</p>
<h2>Things in less comfortable that sucked</h2>
<p>I made many attempts but ultimately went on GitHub to find other programers solutions. My end goal was to&nbsp;<strong>understand the code</strong>. Reading it line by line I was able to finally understand what had to be done to complete the challenge. I&#8217;ll put my solution below and we&#8217;ll go through each section:</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/b8d9b7fd6e2c8db26cf23f27f7b2bf43">Gist</a>.</p>
<h2>Validating inputs</h2>
<p>Up to line 59 we&#8217;re just assigning the user inputs to clearly named variables and making sure our file streams are valid and working. On line 22 we have to use the enlargement factor argument as an&nbsp;<em><strong>int</strong></em> data type so using&nbsp;<em><strong>atoi()</strong></em>.</p>
<p>The part on line 51 about&nbsp;making sure it&#8217;s a 24-bit uncompressed BMP 4.0 is a detail we don&#8217;t have to worry about and are just copying from copy.c.</p>
<h2>Update the headers</h2>
<p>This covers all the way to line 87. We&#8217;ve got 2 headers, the BITMAPFILEHEADER and the BITMAPINFOHEADER. Read and write in the correct order! I kept bmp.h open in another tab in the cs50 ide to use as a reference on how the structs are ordered and what data each is holding.</p>
<p>It&#8217;s best to keep the infile data and the outfile data separate so I created variables for the infile headers (bf and bi) and variables for the outfile headers (obf and obi).</p>
<p>So the video reading less comfortable tells us all the things we have to update which are:</p>
<ul>
<li>width &amp; height</li>
<li>biSizeImage</li>
<li>bfSize</li>
</ul>
<p>Getting the values in this order is key because each is dependent on the former being updated.</p>
<p>Once all the updates are complete we use fwrite() to push that information into our outfile.</p>
<p>After each read and write operation, the infile pointer and outfile pointer is moving forward. Imagine a youtube player and when we&nbsp;<strong>read</strong> or&nbsp;<strong>write</strong> the little playhead ball is moving ahead.</p>
<h2>The difficult part</h2>
<p>Starting from line 91 we get caught up in a lot of nested loops.</p>
<p>First we have to think (whiteboards are very helpful here) about what we&#8217;re doing to the RGBTRIPLE in the loop. Let&#8217;s draw it out:</p>
<p>before a resize with a resize factor of 2:</p>
<p>[] []~</p>
<p>[] []~</p>
<p>after a resize:</p>
<p>[] [] [] []~</p>
<p>[] [] [] []~</p>
<p>[] [] [] []~</p>
<p>[] [] [] []~</p>
<p>([] represents one RGBTRIPLE)</p>
<p>(~ is padding and the values can be different)</p>
<p>When we read in a single RGBTRIPLE, we have to write it out&nbsp;<em>n</em> times. Whatever factor the user gives us. The tough part comes into play when we try to duplicate the&nbsp;<strong>rows</strong>.</p>
<p>Notice how the <em><strong>after</strong></em> drawing has 4 rows instead of 2?</p>
<p>I&#8217;ve seen some solutions using fseek by factoring out the 54 bytes of the header and looping through, but it was confusing for me so I choose to use the malloc() solution.</p>
<p>We store the entire current row of RGBTRIPLE&#8217;s (pixels) into scanline AFTER we duplicate the number of pixels using a nested loop.</p>
<p>Then push them&nbsp;<strong>n</strong> times into our outfile.</p>
<p>So the inner loop collects what our new row looks like and the outer loop actually writes to the outfile an entire row at a time.</p>
<p>before:</p>
<p>[][]</p>
<p>after:</p>
<p>[][][][]</p>
<p>scanline takes in an entire row [][][][]</p>
<p>then pushes the row into the outfile in the nested loop plus padding&nbsp;<strong><em>factor&nbsp;</em></strong> times</p>
<p>Back up more to line 91. We have a data type RGBTRIPLE but it&#8217;s a pointer type and we&#8217;re using malloc(). I was hesitant to use this for about 2 weeks.</p>
<p>Best way to learn is to practice with little programs one without malloc() and one with malloc():</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/e8a50e5b724635246e5e30903bf3f17c">Gist</a>.</p>
<p>So the above program is without malloc. We declare an array of chars size 3. We know the file is 3Max, 3 being our version of a &#8220;header&#8221; telling us the &#8220;width&#8221; is 3, or 3 chars. If we change the file 3Max to 3JohnnyYzaguirre we aren&#8217;t going to get the result we want because our variable holds a static number of chars.</p>
<p>We need something&nbsp;<strong>dynamic</strong>, which means something that can size itself&nbsp; based on what is required.</p>
<p>Malloc() allocates memory by supplying it with a number of bytes. We assign this to a pointer of whatever data type we want to store.</p>
<p><strong>By having the pointer of a data type (int, char, RGBTRIPLE etc), we can use pointer arithmetic, which allows us to move around the blocks of &lt;datatype&gt; memory very easily that we have allocated</strong>. <em>*WARNING THIS IS NOT LIKE A FILE STREAM! THE POINTER DOES NOT MOVE ON TO THE NEXT AVAILABLE PIECE OF MEMORY WHEN YOU READ OR WRITE FROM IT!</em></p>
<p>Try out this program to see what I mean. Lots of helpful comments here:</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/d3088453555bc6350d9e4fe8437d5297">Gist</a>.</p>
<p>resize less comfortable throws a lot at you so i&#8217;ll give you a few hints that I don&#8217;t feel I completely covered in the article.</p>
<ul>
<li>learn to use fseek() by looking up the function arguments. It&#8217;s like a functional way of taking the playhead backwards or forwards. You only need to push it forwards in this challenge. Once you have the correct outpadding you are going to manually add it&nbsp;<strong>after</strong> you&#8217;ve pushed a scanline into the outfile.</li>
<li>More on the loop section: The main loop represents the rows of the infile and has 2 inner for loops. the first inner loop represents the individual pixels in a row. Just like in our example with Max, we take that temp pixel variable and write it over and over&nbsp;<strong>factor</strong> times using a nested for loop. the second inner loop is where we actual write the scanline to the outptr followed by another nested loop where the padding is manually added.</li>
<li>The scanline pointer_counter lives inside of the main loop. This is because we actually need it to reset to zero since we&#8217;re re-using the scanline for the next row from the infile.</li>
</ul>
<p><img loading="lazy" class="size-full wp-image-962 aligncenter" src="http://159.65.235.173/wp-content/uploads/2018/10/6ad.gif" alt="" width="200" height="113"></p>
<p>Happy coding everyone! Until next time =)</p>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2018/10/06/cs50-week-3/feed/</wfw:commentRss>
			<slash:comments>8</slash:comments>
		
		
			</item>
		<item>
		<title>CS50 Week 2: Walkthroughs</title>
		<link>https://johnyzaguirre.com/2018/08/14/cs50-week-2-walkthroughs/</link>
					<comments>https://johnyzaguirre.com/2018/08/14/cs50-week-2-walkthroughs/#comments</comments>
		
		<dc:creator><![CDATA[Johnny]]></dc:creator>
		<pubDate>Tue, 14 Aug 2018 19:18:19 +0000</pubDate>
				<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[CS50]]></category>
		<guid isPermaLink="false">http://johnyzaguirre.com/?p=654</guid>

					<description><![CDATA[Any Questions? I&#8217;m going to be working on my blog posts while doing the walkthroughs next time around. It&#8217;s hard to remember what exactly stumped me and how I got around it otherwise. Here are my solutions for the Week 2 walkthroughs. This project was difficult and frustrating for me. I found using the CS50 &#8230; <p class="link-more"><a href="https://johnyzaguirre.com/2018/08/14/cs50-week-2-walkthroughs/" class="more-link">Continue reading<span class="screen-reader-text"> "CS50 Week 2: Walkthroughs"</span></a></p>]]></description>
										<content:encoded><![CDATA[<h2>Any Questions?</h2>
<p>I&#8217;m going to be working on my blog posts while doing the walkthroughs next time around. It&#8217;s hard to remember what exactly stumped me and how I got around it otherwise. Here are my solutions for the Week 2 walkthroughs. This project was difficult and frustrating for me. I found using the CS50 debugger was super super helpful in figuring out where I was going wrong. Use it to follow the values of variables throughout the program.</p>
<p>View the code on <a href="https://gist.github.com/sojohnnysaid/97930b7159aa58ccfa6207d8ff60ebe1">Gist</a>.</p>
<p>Leave a comment if you have any questions and i&#8217;ll do my best to answer them!</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://johnyzaguirre.com/2018/08/14/cs50-week-2-walkthroughs/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
