#100DaysOfCode

đŸ’« CS50x Certificate of Completion đŸ’« - Thanks to Flowy for the help and encouragement throughout this course :)

HarvardX’s CS50x

Final

CS50x final project using Flask

Raise virtual pets while improving your language skills! The site is setup using Python, Flask with Jinja templates, and a custom CSS stylesheet. View Distant Life website

Week 10 Ethics

Principles:

Ethic principles of democracy:

Week 9 Flask

Framework - a way of organizing your code

Flask:

Running locally (Mac) assuming application.py is entry:

python3 -m venv venv
. venv/bin/activate
pip install Flask
export FLASK_APP=application
flask run

Basic application.py:

# Greets user
from flask import Flask, render_template, request

# turn the current file into a web application
# __name__ refers to current file
app = Flask(__name__)

# define paths
# @ is a python decorator
@app.route("/")

# template pages go in the /templates/ folder
# request libraries allows us to pass ?name=arg in the URL
# arg defaults to None if not set
# passes variable name into function with name value
def index():
    return render_template("index.html", name=request.args.get("name", "world"))

Pass into index.html template:

hello, 

In cs50 IDE: flask run

Week 8 HTML, CSS, JavaScript

TCP/IP governs what goes outside the envelopes. HTTP governs what goes inside of the envelopes.

curl - connect to URL

Week 7 SQL

We can nest queries:

SELECT title FROM shows WHERE id IN (SELECT show_id FROM genres WHERE genre = "Musical");

Week 6 🐍 Python

Loosely-typed language:

print("hello, " + answer)

# or new print format syntax
print(f"hello, {answer}")

Simple for loop

for i in [0, 1, 2]:
    print("mew")

# or use range
for i in range(0,3):
    print("mew")    

Using library imports

from cs50 import get_int
x = get_int("x: ")
y = get_int("y: ")

# or use namespace
import cs50
x = cs50.get_int("x: ")
y = cs50.get_int("y: ")

Function hoisting

def main():
    for i in range(3):
        meow()

def meow():
    print("meow")

main()

Scope

print("I'll print with a newline")

# You can use an end argument to specify end of line
print("I'll print on the same line", end="")

Errors

import sys

# error (1)
sys.exit(1)

# all good (0)
sys.exit(0)

Files


Week 5 Data Structures

Helpful terms:

Arrays

Linked Lists

Example of LL as custom struct, where next is a pointer to the next node

typedef struct
{
    int number;
    node *next; // What is a node here?
}
node;

But since node doesn’t exist to refer to the pointer for a type node, we also add the name node to the top of the struct def and struct to the pointer variable def:

typedef struct node
{
    int number;
    struct node *next;
}
node;

More on Linked Lists

(*n).number = 1; 

// or equivalent:
n->number = 1;
n->node = NULL;

Reallocate

Example for loop for linked list items:

for (node *tmp = list; tmp != NULL; tmp = tmp->next)
    {
        printf("%i\n", tmp->number);
    }

How to allocate more nodes in the middle (sorted)

n->next = list;
list = n;

Linked lists are 1-dimensional

Trees

typedef struct node
{
    int number;
    struct node *left;
    struct node *right;
}
node;

Hash table

Essentially an array of linked lists; allows you to “bucketize” data to let you get data more quickly

More “buckets”

Tries (Retrievals)

AKA Prefix tree

Abstract data structures


Week 4 🍌 Memory

Hex

Addresses

int n = 50;
printf("%i", n);   // 50 - value of n
printf("%p", &n);  // 0x123 - address
printf("%i", *&n); // 50 - print value at 0x123 (address)

Pointers

Mailbox example

Strings

How would you copy a string?

Libraries

Defining a string variable w/ allocation:

char *s = malloc(4);
// uses heap, needs to also use free()
char s[4];
// uses stack, doens't need free()

Memory layout

File Input/Output

File I/O - taking input and output from files

FILE *file = fopen("phonebook.csv", "a"); 
// a - append
// w - write
// r - read

Full example of reading input and printing to a file:

// Saves names and numbers to a CSV file

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    // Open CSV file
    // FILE is a native C type
    FILE *file = fopen("phonebook.csv", "a");
    
    // Check if file is not null
    if (!file)
    {
        return 1;
    }

    // Get name and number
    string name = get_string("Name: ");
    string number = get_string("Number: ");

    // Print to file
    fprintf(file, "%s,%s\n", name, number);

    // Close file
    fclose(file);
}

For iterating thru bytes, we need to define a custom typedef:

typedef uint8_t BYTE;

Then we can copy, using buffer as a temporary value

// Copy source to destination, one BYTE at a time
BYTE buffer;
while (fread(&buffer, sizeof(BYTE), 1, source))
{
    fwrite(&buffer, sizeof(BYTE), 1, destination);
}

Images

Many file types have “magic numbers” the first N bytes in a file that establish what type of file it is; for example, every JPG will start with 0xff 0xd8 0xff


Week 3 🍍 Algorithms

Common formulas:

Search types

Comparing string values

Hertz defs

Creating custom types / data structures–allows you to keep related data tied together

typedef struct
{
	string name;
	string number;
}
person;

int main(void) 
{
	person people[2]; // Init person structure of size 2
	people[0].name = "Brian";
	people[0].number = "555-555-5555";
	
	...
}

Sorting

Comparison Sorting Examples

Selection Sort

For i from 0 to n-1
  Find smallest item between i'th item and last item
  Swap smallest item with i'th item

Bubble Sort

Repeat n-1 times
  For i from 0 to n-2
   If i'th and i+1'th elements out of order
   Swap them
  If no swaps
    Quit

Merge Sort

If only one number // Needs recursive base case
  Quit
Else
  Sort left half of numbers
  Sort right half of numbers
  Merge sorted halves

Recursion


Week 2 🧁 Arrays

Clang

Compiling

  1. Preprocessing–looks for any lines that start with a hash symbol, like #include cs50.h, and copies the contents of the file into the program; implements prototypes
  2. Compiling–changes source code to assembly code (xorl %ebx, %ebx would be like i = 0)
  3. Assembling–coverts assembly code to machine code (0s and 1s)
  4. Linking–takes the machine code from the given file and any included libraries and combines

Debugging

Size of C Types

“code smell” - when something is off with the code, but you can’t quite pinpoint it

C Notes:

For loop to get chars from string, check for null character:

string s = get_string("Input: "); 
printf("Output: "); 

for (int i = 0; s[i] != '\0'; i++) { 
  printf("%c", s[i])
}


for (int i = 0, n = strlen(s); s[i] < n; i++) { 
  printf("%c", s[i])
}

Or use string.h and strlen()

ctype.h

Manual pages for the C standard library, C POSIX library, and the CS50 Library.

int main(int argc, string argv[]) {
  # argv[0] will be the file name
  # argv[1] would be the command line argument
  # argc automatically saves how many words typed in (including filename, so 2 here)
}

Successful c functions return 0 for normal or return 1 for errors

đŸ„„ Shorts

#include <studio.h>
#include <cs50.h>

bool main(void) {
	int side1 = get_int("Side 1: ");
	int side2 = get_int("Side 2: ");
	int side3 = get_int("Side 3: ");
	return valid_triangle(side1, side2, side3);
}

bool valid_triangle(int side1, int side2, int side3) {

	if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
		return false;
	}

	if (side1 + side2 > side3) {
		if (side2 + side3 > side1) {
			if (side3 + side1 > side 2) {
				return true;
			}
		}
	}
	return false;
}

Arrays in C

Command line args


Week 1 C

#include <cs50.h>
#include <stdio.h>

// Prototype
void meow(void);

int main(void)
{
   meow();
}
void meow(void)
{
    string answer = get_string("what's your name? ");
    printf("meow, %s\n", answer);
}

5 Types built-in to C:

Types not built-in to C available in CS50 library:

You can init two variables in one line, for example: int height, width;


Week 0