1 sa 94

HackMIT 2020 Beginner Workshop

go.hackmit.org/beginner-slides

2 sa 94

A Few Important Announcements

  • Please join our q.hackmit.org!
    • We have several team members on call to help you
    • When submitting a ticket, please submit with the tag “Beginner Workshop”
  • If you have general questions, feel free to unmute, or send into the zoom chat
  • To submit to the Beginner Prize, your entire team must be composed of beginners, AND > 50% of your team attended one of the beginner workshop
    • We will be taking attendance near the end of the workshop
  • If you haven’t done setup, please hop over to go.hackmit.org/beginner-github
    • Do setup until Step 4!

3 sa 94

Welcome to Beginner Workshop!

  • Friday, 12:00 AM: Workshop 1
    • Intro to using Git
    • Creating a frontend with HTML/CSS
  • Saturday, 10:00 PM: Workshop 2
    • Creating a backend with Flask
    • Connecting it all with Javascript
  • Saturday, 11:15 PM: Workshop 3
    • Using databases
    • Intro to APIs

Important Links:

4 sa 94

Let’s Get Started!

We recommend you:

  • have your coding environment open
  • Have theses slides open
  • Take advantage of coding / question breaks!

If you fall behind:

  • Stay calm, submit a ticket
  • Some of us will stay after the workshop for some impromptu office hours!

5 sa 94

Workshop 1: Setup + Basics

6 sa 94

What is version control?

  • A system that keeps records of your changes
    • (Think Google Drive history but for your code)
  • Allows for collaborative development
  • Allows you to know who made what changes, when, and why
  • Can revert any change and go back to a previous state

7 sa 94

What is git?

  • A type of distributed version control
  • Users keep entire code and history on their local machines
    • Can make changes without internet access
    • (Need internet to interact with remote server)

8 sa 94

What is GitHub?

  • A code hosting platform for git
  • Basically a way to store your code on the internet to aid collaboration
    • Think Google Drive

9 sa 94

Install git

  • Linux (Debian)
    • Command: sudo apt-get install git
  • Linux (Fedora)
    • Command: sudo yum install git
  • Mac
  • Windows

10 sa 94

Create a GitHub account

  • https://www.github.com

11 sa 94

Key Concept: Snapshots

  • How git keeps track of code history
  • Records what all files look like at a given point in time
  • You choose when to take snapshot and which files are included
  • Can go back to look at old snapshots

12 sa 94

Key Concept: Commit

  • The act of creating a snapshot
  • Noun or verb
    • “I commited code”
    • “Take a look at the latest commit”
  • Project is made up of a bunch of commits
  • Have info about how files changed, reference to parent commit, and a hash code name

13 sa 94

Key Concept: Repository

  • Often shortened to repo
  • Collection of files and the history of those files
    • Consists of all your commits
  • Can live on local machine or remote server (GitHub!)
  • Copying a repository from a remote server to your machine is called cloning
    • Allows teams to work together
  • Pulling: the process of downloading commits that don’t exist on your machine
  • Pushing: the process of adding your local changes to the remote repository

14 sa 94

Key Concept: Branches

  • All commits live on a branch, which can be thought of as “versions” of your repository
  • There can be many different branches
  • The main branch in any project is the master branch

15 sa 94

What does a branch look like?

Time

  • HEAD is a reference to the most recent commit
  • master is the main branch in your project

16 sa 94

How do you branch from master?

  • The start of each branch points to a particular commit
  • When you want to make a new feature, make a new branch based on a commit
  • Feature-branch workflow

Time

17 sa 94

How do you branch from master?

  • Make a new (local) branch and switch to it: git checkout -b <branch>
  • Switch to existing branch: git checkout <branch>
  • Create new remote branch when pushing changes: git push -u origin <branch>

Time

18 sa 94

Key Concept: Merging

  • Once you’re done with your feature, you can merge your branch back into master
  • If someone else has made changes, will have to merge (can lead to merge conflicts)

Time

19 sa 94

How do you make a commit?

  • Different “stages” that a file can be in
  • Local files on your computer: “the working directory”
  • When a file is ready to be committed, you put it in the “staging area”
    • Stage a commit

20 sa 94

Adding a Commit

  • git add <filename> or git add .
    • Put file(s) in staging area
  • git commit -m “Your commit message here” or git commit
    • Message describing this commit
    • Without the -m flag, opens a text editor where you can write your commit message
      • Useful if you want to write a long description

21 sa 94

The Remote Repository

  • On GitHub (usually)
  • git pull
    • Pull changes from remote repository (e.g. from other users)
  • git push
    • Add your changes to the remote repository
    • Make sure you pull all changes before you try to push!

22 sa 94

Workshop 1, Part 2: HTML/CSS

23 sa 94

HackBook!

  • You will be making HackBook!
  • The only social network specifically for hackathon beginner workshop attendees

Features:

  • Display your name, picture, and facts about yourself
  • Update those facts at anytime
  • Make posts with whatever content you desire

24 sa 94

HTML / CSS

  • HTML (HyperText Markup Language) describes the structure of web pages using a series of nested “tags”
  • CSS (Cascading Style Sheets) adds styling to your web pages by using selectors to find specific HTML tags and change their graphical properties

25 sa 94

The HTML Tag

<div></div>

<div id=”this is unique” class=”not unique” blah=”random”></div>

<div id=”my-second-div” class=”not unique” blah=”random”></div>

<div blah=”random”></div>

  • Tags are opened and closed
  • Other tags are nested inside
  • Add text directly inside tags
  • Add “attributes” to tags

Important Attributes:

  • id - string that uniquely identifies a single tag
  • class - string that identifies a set of tags
  • href/src - a link or url

26 sa 94

Important Tags to Know

<p>A paragraph goes here</p>

<h1>Large header</h1>

<h2>Medium header</h2>

...

<h6>Smaller header</h3>

<a href=”link to smthn”></a>

<img src=”link to image”>

27 sa 94

HTML Structure

Definition - <html> </html>

It also identifies the beginning and end of the HTML document.

Header - <head> </head>

The header contains information about the document that will not appear on the actual page, such as the title of the document

Body - <body> </body>

The body tags contain all the information and other visible content on the page.

<!doctype html>

<html>

<head>

Metadata goes here

</head>

<body>

page content goes here

</body>

</html>

28 sa 94

Code: Creating our page structure

29 sa 94

Let’s make it pretty … CSS!

Selectors, basic styles

30 sa 94

CSS Selectors

Tag Selector

div { }

Class Selector

.class { }

Id selector

#id { }

Combining them:

.facts p { }

Common Properties/Values:

  • width:,50px, 50%
  • height: 50px, 50%
  • color: blue, green
  • background-color: red, yellow
  • text-align: center;
  • margin: 10px, auto

31 sa 94

Selectors Example

img { }

.some-text { }

#title { }

#second-text { }

<body>

<div id="container">

<h1 id="title">Justin</h1>

<img src="some image link">

<p class="some-text"></p>

<p id="second-text" class="some-text"></p>

<p class="some-text"></p>

</div>

</body>

32 sa 94

Code: Adding CSS

33 sa 94

Lowkey still kinda ugly tho?

34 sa 94

Extension: Using Frameworks

Bootstrap

Semantic UI

35 sa 94

Example: Semantic UI

https://semantic-ui.com/

Add this inside <head></head> before main.css

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">

Add this inside <body></body> after all your content

<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>

36 sa 94

Code: Making it even prettier

37 sa 94

Thanks for coming!

  • That’s the end of our workshop!
  • Next work: How to create a Flask Backend

Attendance Link: https://play.hackmit.org/attendance?id=8160

38 sa 94

Beginner Workshop Part 2: Flask + JS!

go.hackmit.org/beginner-slides

39 sa 94

A Few Important Announcements

  • Please join our q.hackmit.org!
    • We have several team members on call to help you
    • When submitting a ticket, please submit with the tag “Beginner Workshop”
  • If you have general questions, send into the zoom chat
  • To submit to the Beginner Prize, your entire team must be composed of beginners, AND > 50% of your team attended one of the beginner workshop
    • We will be taking attendance near the end of the workshop

40 sa 94

Code from Workshop 1

Has been pushed to the workshop1 branch on the beginner repo!

git pull

git add .

git commit -m “this is my commit message”

git checkout workshop1

Text Editors:

Sublime Text: https://www.sublimetext.com/

Visual Studio Code: https://code.visualstudio.com/

41 sa 94

The Language of the Internet

  • All HTTP messages are sent as requests
  • Types of requests:
    • GET
      • The most basic request
      • Only information sent is in URL
      • Browser sends GET request to server, server responds with HTML
      • I.e. https://www.facebook.com?myurlparameter=hello&other=bye
    • POST
      • Used for sending large quantity of data to server
      • Information sent using request body, stores many types of data (i.e. JSON)

42 sa 94

Using Postman

GET requests:

POST requests:

  • https://postman-echo.com/post
  • Make sure to set method to POST, body to raw and type to JSON

43 sa 94

What does the Backend Do?

Client ⇐⇒ Frontend, Server ⇐⇒ Backend

  • Listen for incoming requests on certain endpoints (urls) and reads them
  • Returns the appropriate response

44 sa 94

Directory Structure

  • my_app - folder containing flask app
    • __init__.py - Initializes flask app
    • static - folder containing all static files (css, js)
    • templates - folder for html templates
    • views.py - contains all endpoints for the app
  • run.py - python script to run flask app
  • config.py - store config variables for the app

45 sa 94

__init__.py

import os

from flask import Flask, session, request

app = Flask(__name__)

#load main config

app.config.from_pyfile('../config.py')

import my_app.views

46 sa 94

Hello World?

  • Try running `python run,py`
  • Go to localhost:5000
  • Syntax breakdown:

47 sa 94

Flask Templates

  • Flask receives request, responds with HTML, which your browser displays
  • Templates are html files found under the `templates` directory

Jinja Templating

  • Pass variables into the html file
  • {{ my_variable }} - renders as variable value

  • {% if condition %}
    • (Render specific HTML here)
  • {% endif %}
  • {% for x in loop %}
    • (Render specific HTML here)
  • {% endfor %}

48 sa 94

Code: Rendering Templates

  • Move `index.html` and `main.css` into `templates` and `static` respectively!
  • Change the <link> tag on `index.html` so it can still find the css

49 sa 94

Adding endpoints

50 sa 94

Testing with Postman

[GET] /change_name:

  • localhost:5000/change_name?name=my_name

[POST] /post :

  • localhost:5000/post
  • Body (raw, JSON):

{

"title":"Post title"

"description": "Post description"

}

51 sa 94

Exercise: Can you make a “change_fact” endpoint?

  • Endpoint: /change_fact
  • Method: Either POST or GET
  • Modifies the “facts” global variable, which stores a dictionary, and updates it with new facts about yourself

52 sa 94

Javascript & jQuery

53 sa 94

Intro to JavaScript (ft. jQuery)

  • JavaScript (not to be confused with Java) is a dynamically typed, event-driven scripting language
  • Client-side JavaScript is served through your browser and handled by your browser
  • Server-side JavaScript (i.e. Node.js) runs locally on your machine
  • jQuery is a JavaScript library that makes manipulating HTML using JavaScript much easier
    • We’ll be using it to make AJAX post requests

54 sa 94

Using Developer Tools in your browser

  • Chrome/Firefox on Windows/Linux: Ctrl + Shift + I
  • Chrome on MacOS: Option + ⌘ + J

55 sa 94

Console is a JavaScript shell

Basic language features:

  • let x; // declares a re-assignable variable
  • x = 5; // assigns the variable to a number
  • const y = ‘4’; // declares a constant variable string
  • x === y // compares two variables
    • == (double equals) is different from === (triple equals) in JavaScript, watch out!
    • x == y returns true, x === y returns false
    • try it in your browser!
    • false == 0 evaluates to true, but false === 0 does not
  • Other comparisons: x < y (less than), x > y (greater than), x != y (not equals)

56 sa 94

More useful language features!

  • Arrays:

let fruits = ['Apple', 'Banana'];

console.log(fruits.length);

console.log(fruits[0]);

  • For loops:

for (let i = 0; i < n; i++) {

// your code here

}

for (let x : fruits) {

}

57 sa 94

Interacting with HTML

document.getElementById("post1") -> selects and returns the element whose ID is “post1”

document.getElementsByTagName("p") -> selects and returns all elements that are a <p> type in an array

document.getElementsByClassName("className") -> select by class name

58 sa 94

Changing HTML through JavaScript

Use div ids where possible! Don’t do this :)

59 sa 94

jQuery?

  • Add <script src="jquery-3.5.1.min.js"></script> to your <head> to import jQuery
  • General jQuery selector syntax: $(selector).action();
    • ex: $(“.facts”).hide() -> hides all divs with class “facts”
  • Wrap all jQuery code with:

$(document).ready(function(){

// jQuery methods go here...

});

60 sa 94

Clicking things in jQuery

<head>

<title>Hack Book</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">

<link rel="stylesheet" href="../static/main.css">

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

<script src="../static/script.js"></script>

</head>

Create a new file in static/ called ‘script.js’ with the following contents. Add the post-button ID to the post button.

$(document).ready(function(){

$("#post-button").click(function(){

console.log("clicked!");

});

});

61 sa 94

Main use of jQuery: get/post requests

$(document).ready(function(){

$("#post-button").click(function(){

const url = "http://localhost:5000/post";

const postInfo = {

title: "New title",

description: "This is my new post description"

};

$.ajax({

url: url,

type: "POST",

data: JSON.stringify(postInfo),

processData: false,

contentType: "application/json; charset=UTF-8",

complete: function() {

console.log("request complete!");

}

});

});

});

62 sa 94

Adding dynamic input

In your HTML:

<input type="text" id="title"><br>

<input type="text" id="description">

<div class="ui button" id="post-button">Post</div>

In script.js:

const title = $("#title").val();

const description = $("#description").val();

const postInfo = {

title: title,

description: description

};

Refresh to see your page update!

63 sa 94

Break Time!

64 sa 94

Beginner Workshop 3: Databases and APIs

go.hackmit.org/beginner-slides

65 sa 94

Code from Workshop 2

Has been pushed to the workshop2 branch on the beginner repo!

git pull

git add .

git commit -m “this is my commit message”

git checkout workshop2

If you’re stuck, stay after the workshop for Office Hours!

66 sa 94

Why use a database?

67 sa 94

Relational Databases are made of tables of rows and columns

68 sa 94

id

name

value

0

“Birthday”

“Aug 29”

1

“Favorite Color”

“blue”

2

“Favorite hackathon”

“hackMIT”

Facts

69 sa 94

schema: the structure of the database

id

name

value

0

“Birthday”

“Aug 29”

1

“Favorite Color”

“blue”

2

“Favorite hackathon”

“hackMIT”

Facts

70 sa 94

SQL

  • most common language used to interact with relational databases
  • SQL queries used to get data from database

71 sa 94

SQLite

  • Simple implementation of SQL
  • We’ll be using this for our app

72 sa 94

Databases in Flask

  • flask-SQLAlchemy: allows you to manage the database using classes and function calls!
    • Allows us to switch SQL implementations

73 sa 94

Let’s add a database to our example app!

74 sa 94

import os��base = os.path.abspath(os.path.dirname(__file__))�SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(base, 'app.db')�SQLALCHEMY_TRACK_MODIFICATIONS = False

./config.py

75 sa 94

import os, config�from flask import Flask, session, request�from flask_sqlalchemy import SQLAlchemy���app = Flask(__name__)��app.config.from_pyfile('../config.py') �db = SQLAlchemy(app)��import my_app.views

./my_app/__init__.py

76 sa 94

How do we define the schema of our database?

id

name

value

Facts

77 sa 94

./my_app/models.py

from my_app import db��class Fact(db.Model):� id = db.Column(db.Integer, primary_key=True)� name = db.Column(db.String(100))� value = db.Column(db.String(100))�

78 sa 94

SQLAlchemy Query

  • Fact.query.all()
  • Fact.query.first()
  • Fact.query.filter(Fact.name == “birthday”)

79 sa 94

./my_app/views.py

@app.route("/")def index():� db_facts = Fact.query.all()� fact_dict = {fact.name: fact.value for fact in db_facts}� return render_template("index2.html", name=name, facts=fact_dict, posts=posts)

80 sa 94

./my_app/views.py

@app.route("/change_facts", methods=["POST"])def change_facts():� if request.method == "POST":� change_facts = request.get_json()� for key, value in change_facts.items():� if Fact.query.filter(Fact.name == key).first() is None:� new_fact = Fact(name=key, value=value)� db.session.add(new_fact)� db.session.commit()� return redirect("/")

81 sa 94

Exercise: implementing Posts!

82 sa 94

./my_app/models.py

class Post(db.Model):� id = db.Column(db.Integer, primary_key = True)� title = db.Column(db.String(100))� description = db.Column(db.String(300))

83 sa 94

@app.route("/")def index():� db_facts = Fact.query.all()� db_posts = Post.query.all()� fact_dict = {fact.name: fact.value for fact in db_facts}� post_list = [{'title': post.title, 'description': post.description} for post in db_posts]� return render_template("index2.html", name=name, facts=fact_dict, posts=post_list)���@app.route("/post", methods=["POST"])def post():� if request.method == "POST":� post_info = request.get_json()� new_post = Post(title=post_info['title'], description=post_info['description'])� db.session.add(new_post)� db.session.commit()� return redirect("/")

./my_app/views.py

84 sa 94

Adding a simple API

85 sa 94

What is an API?

  • Stands for “Application Programming Interface”
  • Essentially a way to interface with a website/service so that you can retrieve information from it and use it in your app
  • Examples
    • Get tweet info from Twitter API (number of likes, posts with certain hashtag, etc.)
    • Play YouTube videos in your web app with the YouTube API

86 sa 94

Let’s add the Cat API to our app!

  • Returns random pictures of cats :’)

87 sa 94

Add Javascript File

  • New directory: static/js
  • Include the script tag in the head of your document

88 sa 94

Add a button and div for the image

  • We will be dynamically adding the cat image to the “cat-div” using Javascript

89 sa 94

Get your API key

  • https://thecatapi.com/
  • Allows the maintainer of the API to monitor usage by certain users
    • For example, some Google APIs cost money to use, so Google tracks how many requests are made with a certain key
    • Also serves as a form of user authentication/authorization

90 sa 94

Create the getCat() function

91 sa 94

Connect our function to our button

92 sa 94

93 sa 94

94 sa 94