arrow-left
Only this pageAll pages
gitbookPowered by GitBook
triangle-exclamation
Couldn't generate the PDF for 177 pages, generation stopped at 100.
Extend with 50 more pages.
1 of 100

Computer Science

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Our Curriculum and Department

This page will introduce you to the course material we're building and how the Computer Science Department at Gilmour Academy operates.

Intro to Programming

A review of the basics of computing, programming and robotics. We'll build simple Python apps and play with Raspberry Pi's.

We program little turtles to dance on the screen then we play with real robot cars. Learning how to program is an awesome time. I love my job.

hashtag
Acceptable Layer of Abstraction

hashtag
For the people that say "I'm not good with computers"

Computer Science may be intimidating but like any other field of study, you don't have to learn it all at once. We're skipping so much in this class. Don't worry about it. You'll have enough tools to figure out if you want to invest the time to learn the deeper, more challenging (and more powerful) stuff.

circle-info

In any line of questioning, you can keep asking "Why?" Eventually, you just stop when you think you've learned enough. For example, you can legitimately claim you know how a car works (you put gas in, turn a key, etc) even if you're hopeless as a mechanic. You've got a different acceptable layer of abstraction than a mechanic claiming too that she knows how a car works. The inner-workings of a car engine may just be an abstract idea that you only broadly understand (something about spark plugs). The point: You can start learning really cool tech without having to shift your acceptable layer of abstraction too much. It'll be fun.

hashtag
You need to know about the pieces, even if you don't know exactly how they work.

In order to understand basic computer programming, you will need to understand some of the components in your computer. If you understand the basic shape of the environment, the behavior of programming languages will have better context. You won't need to understand exactly how a processor works, but you'll need to know roughly how it fits into the picture so you can solve some common problems.

hashtag
Links and Resources

hashtag
Software

hashtag
Free Code Training

  • Best intro: (Python, git, Command Line)

  • Fun:

  • Solid: https://sololearn.com

Hard, smart: https://app.codesignal.com/arrow-up-right
Visual Studio Codearrow-up-right
Google Drive File Streamarrow-up-right
https://www.codecademy.com/arrow-up-right
https://codecombat.com/arrow-up-right

2D Game Design

Developing games using GameMaker Studio 2 and drag and drop programming

3D Game Design

Developing games using the Unity framework and the C# programming language

3D Modeling & Fabrication

This course focuses on what it means to make art in the modern world. Students will use the latest technology to explore digital painting, sculpting using computer controlled wood cutters and 3D printers, and interactive works using programmable electronics motors and sensors.

1: Parts of a Computer

What are the parts that make up a typical computer? Let's take one apart, label its components and talk about what each does.

hashtag
Expectations

hashtag
Learning Targets

  • I can disassemble and reassemble a computer.

  • I can describe the function of basic PC components.

hashtag
Assessments

  • You will be asked comprehension questions to identify parts of a computer from their images, what their primary purpose is, and what their common problems are

  • You will be observed disassembling and reassembling a computer and checked that you can identify all the components and that you can reassemble the machine correctly

hashtag
Components

Imagine a person juggling while singing an old song from their childhood. Part of the juggler's brain is tracking the motion of each ball and the timing of each throw. Another part of the juggler's brain is recalling the song. His stomach is fueling his muscles. His nervous system is communicating controls from his brain to his arms. His eyes are taking in information. His voice is outputting the song. We'll use this as a reference as we go over hardware.

hashtag
Central Processing Unit

hashtag
Description

CPUs or processors do math. They are a super complex series of logic gates made unbelievably small. What are logic gates? Imagine a wire with two light switches in a row. Since both switches are on the same wire, both need to be flipped to the ON position in order for power to flow through the line. That's an AND gate. If the wire split into two instead and each fork had its own switch, that would be an OR gate as only one or the other has to be enabled for power to flow. Processors have millions and millions of these complex arrangements made in microscopic sizes.

According to our analogy, the CPU is the part of the juggler's brain that's calculating the path of each ball while also managing all the other signals through his brain. It doesn't cover all the functions of the brain in our analogy, but it is at the center of the comparison.

hashtag
Problems with CPUs

CPUs use a lot of power and generate heat. Metal wires create a little resistance as electricity flows through them and that energy turns into heat. You must manage the heat that gets created by your CPU using a fan or other cooling system. If your computer collects a lot of dust, it will insolate

If a CPU is older it means it could be generating more heat while executing fewer commands. And if the CPU is slow, that means it must be connected to a whole bunch of other parts that are older and slower too.

hashtag
Extra Information

In case you're curious and don't mind a little challenge, learn about the and how computer engineers have gotten around it.

hashtag
Random Access Memory

hashtag
Motherboard

hashtag
Hard Disk Drive

hashtag
Power Supply and Case

hashtag
Peripheral Devices

hashtag
Additional Practice

  • Look through and read how the experts recommend you shop for components

  • Create a Quizlet set and practice these terms

hashtag
APIs Make Life Easier

No one writes code totally from scratch. All programmers use a variety of preexisting systems that allow for easier development. We write code that interacts with other layers. That's an API or Application Program Interface. We can interact with our operating system, helpful resources or other apps.

hashtag
BIOS

The BIOS or Basic Input/Output System is firmware. It's something built right into your motherboard. It helps boot your computer up and gives something for the operating system to run off of.

hashtag
Operating System

The OS is a big deal. It serves as a vital intermediary between software and hardware. Instead of having to program every little operation for each device in our computer, we can just use the commands provided by the operating system.

hashtag
Interpreter

The interpreter allows us to execute our written Python code. It's our interface with the Operating System which is in turn interfacing with our hardware.

hashtag
Libraries and Packages

Part of what makes Python so great are all the tools and frameworks available. Want to build a web application? Use Flask or Django and you'll be up and running in minutes. Do you want tools for data analysis? Machine learning? Robotics? There's an ocean of open-source tools ready to give your app superpowers.

2: Parts of Python

hashtag
Expectations

We're going to take a tour of Python. You are expected to know generally what these things are, you're not yet expected to know how to use them. So no freaking out. We'll play around with some fun projects after a quick look around.

hashtag

4: Turtle Design App

hashtag
Class Videos

hashtag
2/1

Class Overview

hashtag
Expectations

We will be learning programming concepts using GameMaker Studio 2's drag and drop interface as well as some simple GML code. All the concepts will be taught through the creation of games. Through PowerPoint instructions, you will be able to work at your own pace and return to concepts which might be confusing.

Mr. Vanek will be available to help if you have bugs that crop up in your programming and to clarify points in the tutorials.

In each unit, you will be responsible for completing an assignment which builds on the concepts you have learned. Feel free to flex your creative design muscles, especially in the assignment portion of the game. Adding extra features or finding new ways to accomplish them will help your game and your learning.

Gamemaker Studio 2 and Github Setup

Game 1: Bouncing Ball

The bouncing ball game will provide the basics of using sprites, sounds, objects and rooms.

hashtag
Game 1: Instructions

hashtag

Turning in your games

Game 3: Ping Pong

With Ping Pong students learn to deal with multiple player inputs as well as create a simple scoring system.

hashtag
Ping Pong Instructions

hashtag

DO NOT DO:

hashtag

Publish to Opera

1: Class Overview

hashtag
Expectations

We will be learning C# programming and Unity development during this course. All the concepts will be taught through the creation of games. Through tutorials, you will be able to work at your own pace and return to concepts which might be confusing. Mr. Vanek will be available to help if you have bugs that crop up in your programming and to clarify points in the tutorials.

In each unit, you will be responsible for completing an assignment which builds on the concepts you have learned. Feel free to flex your creative design muscles, especially in the assignment portion of the game. Adding extra features or finding new ways to accomplish them will help your game and your learning.

2: Installation

We will be installing Unity Game Development Engine to develop your games.

hashtag
Expectations

Students should set up their personal computers to work with Unity and to share their save files between computers.

hashtag

OLD: GIT

This video will show you how to prepare your video for version control and turning in projects.

hashtag
Syncing your project

Installation

Download the fusion 360 software from the link below and install it on your computer. You will have to create an Autodesk account. Please use your Gilmour email.

Patterns

Appearances and Rendering

Assemblies and Mechanical Design

Sculpt Tools

hashtag
Final Assignment

Find a image of a cartoon character and create a sculpt based on that character. Simpler is better for this project. You should include the entire body of the character.

For the final project of the semester, you will be developing your own game. If you have good ideas for the form the game may take during the course of the semester, be sure to write them down.

For the final project of the semester, you will be developing your own game. If you have good ideas for the form the game may take during the course of the semester, be sure to write them down.
https://gamemaker.io/en/tutorials/publish-to-gxgames-tutorial#_ga=2.75440849.2104760815.1662492576-1508294388.1639755424arrow-up-right

Robotics 7

Robotics 8

Introduction to App Development, Kivy, and Intermediate Python.

Milling Concerns

Elevators

CAD Examples

Setting up for clarity

#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                 InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import Port, Stop, Direction, Button, Color
from pybricks.tools import wait, StopWatch, DataLog
from pybricks.robotics import DriveBase
from pybricks.media.ev3dev import SoundFile, ImageFile
from movementfunctions import line_follow

class MyRobot():
    def __init__(self):
        pass

    def new_function(parameters):
        pass
 
Learning Targets
  • I can make a hello world app in Python.

  • I can differentiate between compile-time, run-time, and logic errors.

  • I can describe the basic constructs of programming languages such as variables, conditionals, loops, and flow control.

hashtag
Assessments

  • You will be answering comprehension questions about the layers supporting software execution.

  • You will be creating and submitting your several small Python apps using trinket.io

Let's go to trinket.io and build some simple stuff, starting with print("Hello, world")

We'll go over each of these concepts in greater detail. For now, let's skim over all the big topics.

hashtag
Class Videos

The first video deals with the following concepts: Functions, Variables, Operators and Conditionals

Class 1/4

Class 1/11

Class 1 / 20: User defined functions

class 1/24: for / while loops

hashtag
Key Concepts

hashtag
Data Types

The first thing we'll tinker with is declaring variables and storing information. Variables in Python are dynamically typed, meaning you can store one type of information in a variable and then switch it without any fuss. Other languages are more strict and don't allow such shenanigans.

hashtag
Operators

We use math symbols for most common operations. But Python has some cool operators. Read!

hashtag
Conditionals

Conditionals control how the program flows based on input from the user (in an app) or sensors (on a robot.

hashtag
2/2

hashtag
2/7 assignment PT 2

hashtag

hashtag
2/7

hashtag
2/9 -- Extending the SuperTurtle APP Assignment

To finish off the superturtle app, we are going to add the following to our program:

  • Move the printing of the menu options to the helper function, but run it in main.py (2 points)

  • Add four_square to the menu options (you should have 1. add turtle, 2. star, 3. four square at this point) and make them execute when called. (2 points)

  • Add at least 3 new methods to the SuperTurtle class (whatever you want, but they should be obviously different than the things we wrote together.) Add the methods to the main menu and make sure they execute when called. (9 points)

  • Make sure you have a creative display! (2 points)

hashtag

Bounce Code

hashtag
Game 1: sprites and sound resourcesarrow-up-right

///Bounce against walls

move_bounce_all(true);
move_outside_all(direction, 100);

hashtag
HINTS for assignment!

///Bounce against walls

move_bounce_all(true);
move_outside_all(direction, 100);
Ping Pong Sprite and Sound Resourcesarrow-up-right
Learning Targets
  • I can set up a computer to be ready for work outside of class.

hashtag
Assignments

Download and install:

  • Unity Hub

  • The most recent version of Unity

  • Github Desktop

Von Neumann Bottleneckarrow-up-right
Tom's Hardwarearrow-up-right
We'll reference the idea of a person juggling as an analogy to PC components
This CPU doesn't have pins or a big metal heat sink on top of it
Mario Resourcesarrow-up-right

Game 2: Maze

The maze game increases user control with directional inputs as well as creating a game progression through multiple rooms.

hashtag
Maze Instructions.

hashtag

hashtag
Note: Maze reuses the resources from the first game. If you need to download the assets again, they can be found .

Game 7: Final Project

file-pdf
59KB
Computer Game Design Final Project.pdf
PDF
arrow-up-right-from-squareOpen

Please turn in the planning sheet answers by filling them out in a google doc and sharing it with me or by handing a printed sheet to me at the start of class.

hashtag
Places to find sprite and tile assets

hashtag
Assignment

hashtag
All games need to:

  • Have a strong theme or genre. (2 points)

  • Run smoothly and as intended. (8 points)

  • Have at least three animated multi-frame sprites. (3 points)

3: Exploring the Unity UI

We will be looking at the user interface for Unity, how to navigate, where to find different aspects of our programs.

Building a game is a huge task. Unity organizes the many elements in our game, connecting objects with scripted actions. We must learn how a user interfaces with all Unity's powerful capabilities. \

hashtag
Tutorial

triangle-exclamation

Unity has changed

The software has been updated frequently since the recording of this video. Be patient and attentive to the new layout as well as changes in class procedures

Learning Targets

  • I can find and create primitive shapes in the hierarchy

  • I can find components of my objects

  • I can find my game asset folder

hashtag
Assignments

  • Create and manipulate at least 5 objects.

FAQs

This page will be updated with videos to offer greater clarity or detail about Unity concepts. This is also the repository for student requested videos which are outside the classroom content.

hashtag
EXTRA DETAIL

hashtag
INPUTS

hashtag
CLASSES

hashtag
GITHUB

hashtag
STUDENT REQUESTED TUTORIALS

hashtag
Lerping The Camera

hashtag
Nav Meshes

hashtag
Procedural Levels

hashtag
Terrain

hashtag
VR

hashtag
First Person Controller

hashtag

Fusion 360 Interface and Sketch Modeling

hashtag
Keychain requirements (1 point each)

hashtag
Your keychain should:

  • Visually tell me something about you (include some image).

  • Be sized appropriately for purpose (60mm x 60mm max)

  • Include your name with the text tool.

  • Have a hole to support keychain rings (6mm).

  • Be a single body.

  • Have a flat, printable bottom.

Primitive Modeling

hashtag
Assignment:

In your group, you will create a community of buildings which should relate to each other and a theme of your choosing.

Your building should:

  • serve a different purpose in your group's community. (1 points)

  • be integrated into the community via the chosen theme. (2 points)

  • be in scale to the rest of your group's models (10mm = 1ft, for example). (2 points)

  • be modeled from primitives as well as sketch shapes. (4 points)

  • use several of the modify tools. (2 points)

  • include details that are unique to different sides of the building (as a person walks around it, it changes / has unique features). (3 points)

  • have appropriate textures for final renderings. (2 points)

  • include 4 finished renders of the building, each communicating a different detail. (4 points)

Parametric Modeling

hashtag
Assignment:

Design and create an invention using parametric modeling.

Your design should:

  • Be parametric (add parameters first, make sure your design doesn't break when you change them) (3 points)

  • Have at least three pieces that come together to function. (6 points)

  • be 3D printable (no overhangs, flat base for printing) (2 points)

  • have no piece greater than 200mm in a direction. (2 points)

  • Include final renders (2 points)

You will be turning in 3 things for this project, the fusion file, the printable STL files, and multiple angle renders of the finished design.

Replit

Laser Cutting

Python Turtle

hashtag

hashtag
Turtle assignment

Wordle with Turtles

hashtag
Daily Lessons

hashtag
Wordle with Turtles Assignment

7: Kivy

hashtag
Kivy App 2 Rubric

Create an interactive program using the kivy framework. The app should be useful to you (i.e.; not a game or a tech demo).

The program will be graded as follows:

  • Usefulness - 2pts

Intro to Web Design

Build web pages using HTML/CSS and WordPress all according to modern design principles.

hashtag
This is so awesome!

The Internet is the largest idea exchange ever built or conceived. Learning HTML, the language of the web, gives you incredible power to represent yourself or your work, or your clients. Let's start first by gathering our resources.

hashtag

8. Publish to Netlify

Move from a development environment to production

    • Create an account on the site and verify your email address

2-A: Selection and Iteration

hashtag
Conditions

A fundamental element of flow control is whether or not you want to execute a block of code. We use a conditional or if statement to test something. That test will result in a true or false value. If it's true, we'll execute the block of code. If it's false, we'll skip to the end of the block of code.

Review

Acing your AP test is about testing for bugs in your understanding, studying the fix, then practicing the solution.

hashtag
Review the concepts:

Game 5: Tank Battle

hashtag
Tank Battle Instructions Part

hashtag
Tank Battle Instructions Part II

OLD: Distance Learning Setup

This page describes how to get setup for distance learning, spring 2020.

Python basics (trinket.io)

hashtag
Video 1

hashtag
Terms:

Variables: Words that can store data. A variable might store a number, a word, a sentence or a list of things.

Programming for the Ev3

hashtag
Basic Drivetrain Setup:

hashtag
Defining our own functions:

Python review

hashtag
Functions, Variables, Comments and Simple Data Types

Competitive Robotics

The guide to getting involved in our school's FIRST Technology Challenge team.

Whether you're joining or a different FIRST Technology Challenge (FTC) team, we hope this guide will ease the process.

hashtag
Getting Started

  • Jump In Early: Don't wait! Attend team meetings, observe our workshops, and get a feel for different roles. Identify areas that ignite your interest and offer your help.

3D Printing Concerns

Software Team

Our team uses Java to program our robots. Many of the coding skills can be learned from our AP Computer Science course.

Take a look at our code:

Our software team is usually made up of students that have taken APCS:

Hardware Team

Much of the CAD work discussed in this section uses skills built in our 3D Modeling & Fabrication class.

Game 4: Final project

hashtag
Assignment

For the final project, you will be designing and executing a game of your own design. This will be a proof of concept game. The importance is placed on the game's design and programming, not on how it looks. Make sure that levels are playable before working too much on art assets.

The final project needs to fulfill the following requirements:

  • The program runs with no bugs that break the game.

  • The game should be FUN. This is a game, after all.

  • The project should have a minimum of two workings animation with transitions between them.

  • The project should have a minimum of three levels or be procedurally generated. Levels should have transitions between them.

  • The project should use some aspect of user interface (text) either via instructions or heads up display.

  • The project should have a good use of materials and / or material assets from the asset store.

Use 5 rooms (or utilize a procedurally generated room.) (5 points)
  • Get progressively more difficult. (2 points)

  • Be winnable and losable by the player. (2 points)

  • Use variables to control aspects of dynamic game play (i.e.; parts of your game should change in some way throughout the game. Power-ups, Getting new inventory/ materials, or level gain are examples of this.) (3 points)

  • I can navigate the game space
    file-pdf
    138KB
    Unity_HotKeys_Win.pdf
    PDF
    arrow-up-right-from-squareOpen
    Shortcut reference sheet
    file-pdf
    142KB
    Unity_HotKeys_Mac.pdf
    PDF
    arrow-up-right-from-squareOpen

    In order to complete the Wordle program, there are a few things you need to add:

    • Make a new method in GamePlay.py which can be called during process_input() with different colors in the different letter situations. Keep your code D.R.Y. (4 points)

    • Complete the check_game_end() method in Gameplay.py and implement checks throughout your game. Make sure the game actually ends -- remember we have a boolean which controls the end of the game in main.py. (4 points)

    • Make sure your settings variables are all implemented within your program (for example: when you change background value to a different color, it actually makes the change in your program). (2 points)

    • Add a minimum of twenty 5 letter words to your word list. (1 point)

    • Clean up your code. Get rid of methods or imports you didn't use. (1 point)

  • Uses a minimum of six total widgets - 3pts

  • Uses at least one widget that is not from the following list (Label, BoxLayout, Button, TextInput, Spinner) - 2pts

  • Program works as intended with no crashes- 3pts

  • main.py is commented for clarity - 1pt

  • unneeded code should be cleaned up - 1pt


  • hashtag
    Kivy API Call App

    Create a useful, interactive program using the kivy framework and an database API of your choice.

    The program will be graded as follows:

    • Usefulness - 2pts

    • Includes at least two distinct API calls - 3pts

    • Kivy widgets are used for user interactivity- 2pts

    • Program works as intended with no crashes- 3pts

    • all files are commented and cleaned up for clarity - 2pts


    hashtag
    How do I...

    hashtag
    ...make multiple pages in a kivy app.

    Links and Resources

    hashtag
    Required Software (install these)

    • Visual Studio Codearrow-up-right

    • Google Drivearrow-up-right

    hashtag
    Required Practice (create accounts)

    • Codecademyarrow-up-right

    • SoloLearnarrow-up-right

    hashtag
    Design Assets (bookmark these)

    • Google Fontsarrow-up-right

    • AllTheFreeStockarrow-up-right

    • ThemeForestarrow-up-right

    hashtag
    Colors

    • https://coolors.coarrow-up-right

    • https://colorhunt.co/arrow-up-right

    • Color wheelarrow-up-right

    hashtag
    Extra Training for Extra Cool Kids

    We won't study much JavaScript in this class but it's one of the best ways to take web design to the next level.

    • Hard, smart: https://app.codesignal.com/arrow-up-right (select JavaScript)

    • Fun: https://codecombat.com/arrow-up-right (select JavaScript)

    Once logged in, you'll see an area indicated by a dotted line where you can drop a folder

    • If your folder isn't uploading, you may images or other files that are too large. Downsize your images or move unneeded files outside of the bootstrap_project folder

  • Edit your site details so you can change the URL from its randomly-issued name

  • Submit the URL so it can be graded. Remember, if you make further changes, you need to re-publish your site using the following instructions:

  • hashtag
    Updating your page

    You've been seeing your page update on your local machine. That's not on the Internet and the link in your browser won't work on anyone else's machine as it refers to a file on your computer. But we can deploy the website to free host using Netlify.

    And then select your site
    Go the page that will allow us to update the root folder

    hashtag
    Requirements

    • All stock content replaced

    • A color palette implemented uniformly throughout the page and corresponds with the subject of the site

    • Custom header and body fonts that corresponds

    • CSS file formatted into sections with color palette written in a comment at the top

    • CSS rules overwriting theme styles like btn and bg

    • A new section added to the navbar and the body with smooth scroll working to that location

    • A new Bootstrap component taken from the documentation

    • A new CSS class and ID implemented in the CSS and HTML

    • Images (not in conflict with copyright law) successfully added to img folder and added to site

    https://app.netlify.com/droparrow-up-right

    hashtag
    Loops

    Loops are how we repeat commands or loop through items in a collection.

    hashtag
    for loops

    hashtag
    standard for loop

    Most for loops look something like this:

    The for statement has a declaration, condition and increment. But you can skip the declaration if you'd like. Let's say you want the counter to have a wider scope (so it can be accessed outside of the loop) like this:

    hashtag
    foreach loop

    Let's say I have an array or collection of numbers like this: int[] numberArray = [5, 10, 15, 20, 25];

    Each number in that group has an address or index (that starts at 0). If I wanted to print the number 10 for example, I could write System.out.println(numberArray[1]);

    So if I wanted to loop through (called iterating or traversing) all the items in this array, I could use a normal for loop like this:

    But there's an easier form of the for loop that's meant to easily traverse through a collection. We'll go over some of the pros and cons of this method later.

    hashtag
    while loops

    hashtag
    Infinite loop

    hashtag
    do-while loop

    The do-while is rarely used but it's handy if you want to make sure the steps run the first time before the loop condition is tested. Read more.arrow-up-right

    This is a silly joke, not an actual way to resolve problems with your loops.

    This comes up all the time in problems. It's a useful trick to avoid crashing your apps, too.

    hashtag

    Go over the AP Classroom problemsarrow-up-right
  • Fill in any gaps in your skillsarrow-up-right

  • hashtag
    Get your speed up:

    • https://www.varsitytutors.com/ap_computer_science_a-practice-testsarrow-up-right

    • http://www.danshuster.com/apcs/java_tests.htmarrow-up-right

    You got this.

    hashtag
    Watch Videos:

    • https://www.youtube.com/playlist?list=PL-ZKvhIgD8x0Dgl2_rnNAv1lhJoRsIfLgarrow-up-right

    • https://www.youtube.com/playlist?list=PL_JS5ztwk2L9EhSQysP2tiQ_k5g_fAajiarrow-up-right

    hashtag
    Going Pro:

    Crush all the Codingbat Problemsarrow-up-right

    Operators: Basic math symbols for addition, subtraction, multiplication and division (+, -, *, /)

    Functions: Commands which let us do things within the programs. Some functions are built in and some will be created by us!

    hashtag
    Video 2

    hashtag
    Terms:

    Input: Getting information from outside the program. This might come from someone using your program in the case of an app, or from sensor data in the case of a robot.

    Changing Variable Types: Sometimes we have to change variable types to allow them to interact. We do this with functions int() and str(). Remember that variables need to be alike if we want them to be able to interact!

    hashtag
    Video 3

    hashtag
    Terms:

    Conditionals: Conditionals let us check for when something happens or when something is true. The most common of these is an if statement (which can be expanded to an if/else or and if / elif / else statement).

    Boolean: A boolean is a specific type of variable, a True or False variable.

    hashtag
    Assignment!

    hashtag
    Basic Sensor Setup:

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
                                     InfraredSensor, UltrasonicSensor, GyroSensor)
    from pybricks.parameters import Port, Stop, Direction, Button, Color
    from pybricks.tools import wait, StopWatch, DataLog
    from pybricks.robotics import DriveBase
    from pybricks.media.ev3dev import SoundFile, ImageFile
    
    
    # This program requires LEGO EV3 MicroPython v2.0 or higher.
    # Click "Open user guide" on the EV3 extension tab for more information.
    
    
    # Create your objects here.
    ev3 = EV3Brick()
    
    
    # Write your program here.
    ev3.speaker.beep()
    
    hashtag
    Conditionals: if / elif / else

    hashtag
    Loops: for / while

    hashtag
    Defined Functions

  • Choose Your Path: Our team operates through various sub-groups, each playing a crucial role in our robot's success:

    • Marketing Team: Be the face of the team, recruit new members, manage logistics, and prepare presentations for judges. Hone your communication and organizational skills.

    • Software Team: Dive into the world of coding, working alongside hardware engineers and the drive team. Maintain our codebase, troubleshoot issues, and post questions on online forums to expand your knowledge.

    • Hardware Team: Design and build robot components using CAD software, 3D printing, and various hand tools. Develop hands-on engineering skills and fix technical issues during competitions.

    • Drive Team: Take the spotlight by operating the robot during competitions. Strategize gameplays, execute maneuvers based on calls, and practice extensively to become a well-coordinated unit

  • hashtag
    Additional Resources:

    • Moonshots' website: https://ga-moonshots.netlify.app/arrow-up-right

    • FTC official website: https://www.firstinspires.org/robotics/ftcarrow-up-right

    • FTCLib documentation: https://docs.ftclib.org/ftclib/arrow-up-right

    • FTCSim:

    • Programming Resources:

    Gilmour's Moonshotsarrow-up-right
    //Put this code in the update
    
            for (int i = 0; i < 20; i++)
            {
                if (Input.GetKeyDown("joystick 1 button " + i))
                {
                    print("joystick 1 button " + i);
                }
            }
    
    
            if (Input.GetAxis("TestInput") != 0 )
            {
                print(Input.GetAxis("TestInput"));
            }
    HEREarrow-up-right
    AP Computer Sciencechevron-right
    3D Modeling & Fabricationchevron-right

    FAQ

    // Pac Man Ghost Movement Code
    if (place_snapped(64,64)){
    	var changed = false;
    	var randomDir = irandom_range(1,4);
    	
    	if (hspeed == 0){
    		if (randomDir == 1){
    			if (!place_meeting(x - ghostSpeed, y, obj_wall)){
    				speed = ghostSpeed
    				direction = 180;
    				changed = true;
    			}
    		} else if (randomDir == 2){
    			if (!place_meeting(x + ghostSpeed, y, obj_wall)){
    				speed = ghostSpeed
    				direction = 0;
    				changed = true;
    			}
    		}
    	}
    	if (vspeed == 0 and changed == false){
    		if (randomDir == 1){
    			if (!place_meeting(x, y - ghostSpeed, obj_wall)){
    				speed = ghostSpeed
    				direction = 90; 
    			}
    		} else if (randomDir == 2){
    			if (!place_meeting(x, y + ghostSpeed, obj_wall)){
    				speed = ghostSpeed
    				direction = 270;
    			}
    		}
    	}
    }

    Kivy Basics

    hashtag
    Kivy Video Overviews

    hashtag

    hashtag

    hashtag
    Widgets

    Kivy uses widgets as the basic building block for GUIs (Graphical User Interfaces). Widgets are objects which can be layed out on your screen and which perform specific tasks. Some examples are input fields, buttons and drop down menus. In this section, you will find an example of widgets we will use in the class as well as specific parameters which can control individual widgets. If you feel like digging deeper into your options,

    hashtag
    Label

    The label widget is used to create text on your screen.

    • text: "Hello World"

      • Displays "Hello World" on the interface

    • color: 1, 0, 0, 1


    hashtag
    Button


    hashtag
    TextInput

    Software Installation

    #!/usr/bin/env pybricks-micropython
    from pybricks.hubs import EV3Brick
    from pybricks.parameters import Color
    
    # setup section
    ev3 = EV3Brick()
    screen = ev3.screen
    screen.clear()
    
    # Main Program
    screen.draw_text(10, 10, "Everything", text_color=Color.BLACK, background_color=None)
    screen.draw_text(10, 30, "is", text_color=Color.BLACK, background_color=None)
    screen.draw_text(10, 50, "Awesome!", text_color=Color.BLACK, background_color=None)
    
    ev3.speaker.beep()
    
    while (True):
        wait = 0
        

    6: Project Management

    Use project management software to be accountable for professional-caliber design work.

    hashtag
    Learning Targets

    • I can build a professional-caliber file system.

    Game 1: Rolling Ball

    hashtag
    Finished Game Overview

    hashtag

    Calculator

    for(int x = 0; x < 20; x++) {
        // code goes in here
    }
    int x = 0;  // declared outside the loop so it can remain afterwards
    for(; x < 20; x++){
        // code goes here for the loop
    }
    System.out.println(x);  // will print 20
    for (int x = 0; x < numberArray.length; x++){
        System.out.println(numberArray[x]);
    }
    for (int x : numberArray){
        // x isn't looping through the addresses this time
        // rather, it's pretending to be each number in the collection
        System.out.println(x); 
    }
    while(true){
        // will never stop looping unless I use the break command
    }
    do {
        // code will run at least one
    } while(x > 10);
    // Make sure that only the active player is able to fire the gun.
    // Also, no players should be able to fire if we are between turns 
    // (transitioning from player to player)
    
    if (obj_controller.WhoseTurn == myName) and (obj_controller.Transitioning == false){
        
        // Check to see if the the spacebar is released.
        if (keyboard_check_released(vk_space)){
       	 
    
       	 // The xdistance and ydistance is the difference between the origin 
     // position of the cannon and the end of the barrel at any given rotation.  
    
     // This value is basic trigonometry for a right triangle if you know the   
     // hypotenuse (the barrel sprite width -- in this case 64) and the angle.
       	 ydistance = 64 * (sin(degtorad(Barrel_Rotation)));
       	 xdistance = 64 * (cos(degtorad(Barrel_Rotation)));
       
       
             // instance_create_depth will create an object at a specific depth.  (100 is generally the
       	 // background.  We are creating obj_bullet at the x and y of the firing turret and shifting the
       	 // bullet based on the angle of the barrel.  
       	 
       	 // Because we are using "with" the things within the { } will apply to the thing being created.
       	 // In this case, we are giving the bullet the barrel rotation value of the turret which is
       	 // shooting it off.  We have to use other. because we are actually doing this from within the
       	 // bullet object, not the turret.
    
       	 with instance_create_depth(x+xdistance,y-ydistance,50,obj_bullet)
       		 {
       			 direction = other.Barrel_Rotation;
       		 }
       		 
       	 // We are adding an alarm in obj_controller and setting letting the game know we are between turns
       	 // so that players can't fire off multiple bullets and can't accidently fire off their opponent's
       	 // shot.  
    
       	 // We use room_speed for the alarm because we can multiply our Frames per second by a time in 
       	 // seconds for a more intuitive control.  At 30 FPS, we could have also put in a value of 30.
       	 obj_controller.alarm[1]= room_speed * 1 //seconds;
       	 obj_controller.Transitioning = true;
        }
    }
    
    // We will finish off our step event by turning the gravity back on if the turret
    // is not moving and there is nothing under it (a box just got destroyed for
    // instance) OR if there is fire directly under the turret.  We want the turret
    // to fall into the fire.
    
    if ((speed == 0 and place_empty(x,y+1)) or place_meeting(x,y+1,obj_fire))
    {
        gravity = 1;
    }
    
    
    https://color.hailpixel.comarrow-up-right
    https://ftcsim.org/arrow-up-right
    https://ftc-docs.firstinspires.org/en/latest/programming_resources/index.html#programming-tutorialsarrow-up-right

    Color takes 4 numbers from 0 - 1. These correspond to RGB and Alpha

  • font_size: 32

    • Sets the font to 32 pt

  • markup: True

    • Allows you to add markups such as bold, italics, font in your text

    • [b] Bold [/b], [i] italics[/i], [font=times] Change the font to times [/font]

    • [s] strikethrough [/s], [u] underline [/u], [color=#hexcolor] change color [/color]

  • size_hint: 0.5, 0.5

    • changes the size of the text box in relation to horizontal width of the window and vertical height of the window.

  • size: 200, 200

    • Changes the size of the text BOX, not the text.

  • the kivy documentation can be found here.arrow-up-right
    I can collaborate with my team through a KANBAN board.

    hashtag
    Google Drive

    While often used for online storage, Google Drive's offline functionality unlocks its potential for design projects. You and your team can work on Adobe AI and Photoshop files without an internet connection by enabling offline access. Shared folders within Drive serve as central hubs for exchanging design files and planning materials like Google Docs. This seamless collaboration ensures everyone stays on the same page, regardless of location or internet availability. This technique is crucial for delivering professional-caliber design work in a collaborative environment.

    • ProjectName

      • Loose in the folder can be branding documents, collections of text in Google Doc and other guides.

      • STOCK

        • Collect images from allthefreestock.com and other sources. These are raw images that will need to be resized and possibly color-treated.

      • HTML

        • Any coding elements get stored in this folder

      • IMG

        • Edited images ready for the web.

      • LOGO

        • Adobe files and your logo package

      • RESEARCH

        • Collect relevant articles, screenshots of other websites for comparison, etc.

    hashtag
    KANBAN

    Initially developed by Toyota to optimize manufacturing, KANBAN boards have become a popular project management tool across various industries, including design. Their simplicity lies in their visual, three-columned structure: Backlog, In Progress, and Done. This straightforward visualization aids communication and transparency, allowing every team member to grasp the project's status at a glance. KANBAN's power lies in its ability to manage project flow. Tasks move from Backlog to In Progress, signifying active work. Once completed, they shift to Done, signifying progress and freeing up space for new tasks. This system prevents overloading team members and keeps complex projects manageable, even for large-scale design endeavors. Whether collaborating remotely or in person, KANBAN boards ensure transparency, focus, and continuous project flow, propelling your design project toward successful completion.

    Pretty simple idea, right?

    Every Trello card is a vital piece in our project puzzle. Here's what makes a great one:

    Title: Keep it simple and descriptive. Focus on the problem, not the solution ("Broken Link on Homepage" versus "Update Header Navigation").

    Description: Explain the issue itself, avoiding descriptions of actions taken. Let the details flow freely so others can understand the scope of the problem.

    Visuals: Paint a picture! Paste screenshots directly onto the card to clearly illustrate the issue and where it occurs.

    Teamwork: Ensure the right team is aware. Tag the appropriate team members who can tackle this specific problem.

    Backlog to In Progress: When the card is ready for action, drag it to the "In Progress" column. Now's the time to assign ownership! Choose the individual(s) directly responsible for working on the issue, not the entire team.

    Progress Tracking: Before marking the card "Done," log your activity in the comments section. Share screenshots, code snippets, or any relevant updates to document your progress.

    Time Transparency: Be kind to your future self (and colleagues)! Track your work in 15-minute increments. This detailed time log will prove invaluable when creating project invoices.

    Remember, clear and concise Trello cards are the key to smooth communication, effective collaboration, and, ultimately, project success. Let's build clear cards and conquer those sprints!

    hashtag
    Example Cards

    You'll have to make your own cards, but here's some starting ideas:

    We'll be using Trello to track your progress and to coordinate a team project. Each task or card must be a specific task that can be achieved preferably within a class period or at least within a week. The measurement or proof of that task's completion should be described in the activity log entry of that Trello card.

    hashtag
    Building The Game

    hashtag
    1. Building the Scene

    hashtag
    2. Pickups: Scripts - Rotation.

    hashtag
    3: Player Movement: Part 1

    hashtag
    3b: Player Movement: Part 2

    hashtag
    4: Camera Control and Extra Levels

    hashtag
    5: Switching Between Levels: Part 1

    hashtag
    5b: Switching Between Levels: Part 2

    hashtag
    6: Text and User Interface Basics: Part 1

    hashtag
    6b: Text and User Interface Basics: Part 2

    hashtag
    6c: Text and User Interface Basics: Part 3

    hashtag
    Assignment

    For your assignment, you will need to build on the ball roller game in the following ways:

    1. Create at least three extra levels (for a total of five).

    2. Make your game say "You Win" when you beat the final level.

    3. Different colored power up with different point value from the ones we built.

    4. Stop the timer and disable game controls if the game is over. (Hint: You will need a boolean (bool) type variable to control whether the game has ended and link those to if - statements within your game)

    5. Create an death box or script under your level that will restart your level if the player falls off our hits it. If you are creating a death box, you will need at box collider, but not necessarily a renderer or material You can create invisible collisions.

    6. Make a sharable build of your game using the instructions below.

    hashtag
    Making a Sharable Build

    hashtag
    Booleans

    hashtag
    Learning Targets

    • I can create and use int, float and bool variables.

    • I can correctly change the value of a variable through code.

    • I understand when to use public and private variables.

    • I can access inputs and apply them to player movement.

    • I can implement if statements in C#.

    • I can write and call my own methods in C#

    • I understand and correctly use Start, Update, FixedUpdate and LateUpdate functions.

    • I can link components to variables.

    • I can determine how many of a GameObject exist in a scene.

    • I can organize and program based on my build index.

    • I can change scenes within my game through code.

    • I can create and manipulate several different 3D primatives.

    • I understand and can use several different components.

    • I can add text elements to the game screen.

    • I understand when to add RigidBody components and when not to.

    • I can use RigidBody components to interact with Unity’s physics system.

    • I can create and apply materials to objects.

    5: Interactive Turtles

    hashtag
    Expectations

    hashtag
    Learning Targets

    • I can interpret an unfamiliar code base.

    • I can extend the code to my own project.

    hashtag
    Assessments

    • You will create an interactive program or game based on existing turtle classes

    • You will be asked regular comprehension questions about Python.

    hashtag
    First Class Assignment (CodeHS.com)

    hashtag
    Adding Moving Turtle

    hashtag
    Assignment and Rubric

    Create an interactive turtle application of your own design. This can be a game or other interactive program, but it must use at least two of the three types of turtle classes we have outlined (moving turtle, keyboard turtle, clickable turtle).

    • 3 pts - Program works without errors

    • 3pts - Program uses two classes of turtle

    • 3pts - Program is interactive. Users can DO something with the program beyond what we set up in class. Make sure your theme is cohesive!

    hashtag

    hashtag
    How do I...

    hashtag
    ...make multiple things move?

    hashtag
    ...write text on the screen?

    hashtag
    ...stop movement with walls?

    hashtag
    ...make a ball move diagonally and bounce off multiple sides of the room?

    hashtag
    ... create a background image and have it change later?

    hashtag
    ...set up and check a timer

    hashtag
    ...add a start screen

    hashtag
    ...Save a High Score in a File?

    hashtag
    ... add points from different objects to a single score?

    hashtag
    ... get objects to check each other for different properties?

    hashtag
    ...find the x and y position of my mouse on the screen?

    hashtag
    ...create a custom shaped turtle?

    hashtag
    ...create a multi-colored turtle?

    1: What's the Internet?

    What is the Internet? We need to understand some of the basics to the underlying tech so we can understand why websites work the way they do.

    hashtag
    Expectations

    hashtag
    Learning Targets

    • I can describe a brief history of the Internet's origin and impact.

    • I can write a professionally formatted email.

    hashtag
    Assessments

    • You will receive comprehension questions about why the Internet was made, the very basics of its technology, how the technology grew, and its significance to society.

    • You will send a professional email () taking a position on whether the Internet is a basic human right.

    • (Codecademy) Get started on the

    hashtag
    The Idea

    The Internet is mankind's greatest achievement. Mr. Adiletta takes a dramatic position on the Internet as a basic human right. The evolution of human intelligence goes beyond the growth of our brain. and into the development of communal stories, into libraries, and then into the Internet. The Internet is a product of human evolution and is the birthright to all people.

    The Internet is a part of your mind and you have the right to use your brain.

    hashtag
    Why was the Internet created?

    During the height of the Cold War, the threat of a Soviet attack motivated the funding of a research project to build a web of communications lines. In such a network, if one line was cut by an attack, communications would proceed uninterrupted through alternate lines in the network. The beginnings of our was produced.

    hashtag
    Did Al Gore create the Internet?

    In his 2000 Presidential campaign, Al Gore rightly took some credit in the creation of the Internet. No, he did not help develop the TCP/IP network. However, after the ARPANET project was complete, the ownership of the underlying technology was in question. It was offered for sale to at least one telecommunications company but they passed on buying the Internet not knowing what it would be good for. Al Gore was a part of a congressional effort to make TCP/IP a public resource. No one owns the Internet because of that. He also helped establish support to connect people--something we have a moral obligation to continue.

    hashtag
    Significance of the Internet

    hashtag
    Why is this video funny?

    After watching this video, take a moment to think about why this video seems silly. It's not just her rockin' hair and vest or the British perspective of the American president. It may be the many, giant screens. But more specifically it's how the changing technology has changed our impressions. She talks about shopping on the internet as a future possibility and not something that everyone does like it's no big deal. Again, take a moment to understand that the Internet is a big deal.

    hashtag
    The Internet has a physical component that must be appreciated, too.

    hashtag
    Vocabulary

    • OSI model: The basis of the Internet. This describes how the TCP/IP network started by the Defense Department has evolved.

    • Internet Protocol (IP): A system for addressing and routing communication over a network. You can make up all the addresses you want on a private network, but the is the authority of the public's IPs and domains.

    • Domain Name System (DNS): A sort of phone book that changes or resolves domain names into IP addresses

    hashtag
    Further Exploration

    There are many free tools that help you learn about domains. These are very helpful for web designers as you may want to check on the current host of a client interested in a site redesign. Try looking up the record of a few domains using one of these tools:

    2: What are Websites?

    What's happening under the surface of a web page?

    hashtag
    Expectations

    hashtag
    Learning Targets

    • I can describe how web pages are displayed on my browser using HTTP and HTML.

    • I can create a basic HTML page.

    hashtag
    Assignments

    • You will construct an HTML page from scratch in a guided class activity.

    • You will complete HTML and CSS courses on codecademy.com

    hashtag
    World Wide Web

    hashtag
    Tim Berners-Lee

    If one person had to be named as the creator of the Internet, it might be in 1989. More specifically, he created the World Wide Web while working at . It was a way of transferring information over the TCP/IP network talked about in last chapter.

    hashtag
    No more

    The "Internet" we think of is primarily the contents of our web browser. Trying to find information by tediously scanning film after film was not fun. People like Tim Berners-Lee wanted to link text together. So touching one word might connect you to relevant information without having to manually search for hours.

    The most important part of a website remains the .

    hashtag
    HTTP sends HTML

    HyperText Transfer Protocol is a set of rules to pass information (like the HTML layout of a web page) over a network. HTML is a markup language. It describes the structure and content of a page. So when you type in an web address like google.com into your browser, you're sending a GET request to the Google server. It responds with an HTML package that your browser renders into a familiar display.

    hashtag
    Structure of HTML

    hashtag
    Tags and Elements

    A tag looks like this: <tag> </tag> The stuff that's between the opening <tag> and the closing </tag> is what's inside that element. The first and most important element in a web page is a hypertext link. If I wanted to make a link that went to Google.com, it would look like this: <a href="google.com">this is my link</a>

    The term tag describes the structure of the <opening> and </closing>. The element is what type of object is being built by the tag, (an a is a hyperlink). The contents of an element is whatever is between the open and closing tag of an element. The property="value" pair that goes inside of an HTML tag is called an attribute.

    hashtag
    Page Structure

    Every web page has to have a <!DOCTYPE html> at the very start to tell your browser that yes, this block of text is HTML and it should render it into a display. The <html> element does something very similar. Every page you've ever seen online has been the contents of an HTML tag.

    The <head> element isn't seen by the user. The contents of the head allow you to connect other resources to the page, such as fonts or CSS.

    hashtag
    CSS is HTML's Sidekick

    CSS has its own style rules. But you drop it into an HTML head like any other HTML, <style> css goes here </style>. You can put the CSS in the HTML file, but the better way is to keep your CSS in a separate file. In that case, you use a <link> element instead to connect the .css file.

    hashtag
    Practice

    hashtag
    Additional Training

    3: Hello Flask

    hashtag
    Expectations

    Where are you going to do your coding? If you try to run your app, what other software is required? How are you going to save or publish your work? Configuring your IDEarrow-up-right, dependenciesarrow-up-right, and VCSarrow-up-right is essentially your workspace.

    hashtag
    Learning Targets

    • I can create and view a blank Flask app.

    Before we get into the structure and mechanics of our code, let’s build the most basic of Flask apps. It’ll help set some context as we then start to learn particular skills. It’s important that you start from scratch as it builds confidence knowing you can start from the ground-up.

    hashtag
    Hello Flask

    Let's look at the most simple possible Flask app.

    hashtag
    Alternative

    In case Repl.it isn't cooperating with your browser, here's a simple view of a basic "Hello Flask" app.

    hashtag
    Challenge

    hashtag
    Variables from a route

    If I go to /hello/george, can you make the screen say, "Hello, George?" How do we pull a variable from the URL on that GET request?

    hashtag
    Link to another page

    Build another route and switch between two pages.

    hashtag
    Basic templating

    Use render_template

    hashtag
    What's Missing?

    If you can understand some of the elements that are missing from this simple example, you’ll have a greater appreciation for the core of our Flask app and the many components that we’re about to study.

    hashtag
    No Templates and Few Routes

    Our initial application, hello flask, had one singular route @app.route('/') which is very basic. Just a homepage, that’s it. On the other side, “Flaskinni” includes numerous routes so you see blog and account pages just to name a few. Each route in Flaskinni calls templates with method calls like render_template('index.html'). These are just as their name suggests, templates or outlines of the final HTML page a user sees. Templates are a big deal (⅓ of our whole MVT structure).

    Want to know the difference between ‘GET’ and ‘POST’? You see them mentioned as a on line 16 in the picture below? Well, you should know the name Tim Berners Lee. GET and POST are two of the HTTP requests that travel over our network and provide us the Internet. Simply put, GET is a request for a page and POST is when the user is submitting a form. Knowing the types of HTTP requests gets really important if you ever decide to use to use this web app to power mobile apps, too.

    hashtag
    No Models or Database

    In the Hello Flask application, there is no database or model schema being used. There are no objects like user, admin, blog post in the app. Also in the Hello Flask app, we had no database, but in Flaskinni there is a database, and a schema that shows how the database will be set up. Also in Flaskinni there is code that creates database tables and is able to send the data to the database in the format laid out by the schema.

    hashtag
    No Interactivity

    Our initial Hello Flask application had no interactivity whatsoever as illustrated by the one simple message that is sent to the user. Our app only responds to GET requests, never a POST request. In other words, the user is only getting static information and is never sending information back to the server or requesting more specific information. For example in the Flaskinni application a user can post a blog post or can request or a certain blog post.

    hashtag
    Few Libraries

    Libraries are expansion packs, they're files containing compiled code that allow the app to reference them later in other files. Libraries allow the app the run faster and have more capabilities. Instead of calling methods over and over while writing the app, the user can call the library file. The linking of libraries allows a file to gain the capabilities of the library module without having to define those methods again.

    Game 4: Breakout

    hashtag
    Breakout Instructions

    hashtag
    Bounce Code

    hashtag
    Pause Code - in obj_pause (create event)

    hashtag
    Pause Code - In obj_pause (Draw GUI event)

    hashtag
    Pause Code - In obj_pause (Key Press - Space)

    hashtag

    GitHub Desktop | Simple collaboration from your desktopGitHubchevron-right
    Guide to setting up the software needed for class
    GameMaker | Make 2D Games With The Free Enginewww.yoyogames.comchevron-right
    Setup and Initial Commit

    OLD 5: Replit, GitHub, and repositories (Oh my!)

    hashtag
    Expectations

    hashtag
    Learning Targets

    7: Advanced Editing

    hashtag
    Learning Targets

    • I can configure a project folder in a cloud-based file system.

    AP Computer Science

    A deep dive into Java programming in preparation for the College Board's Advanced Placement test.

    hashtag
    About the Test

    Check out the description from including the . For the technical folks (it'll be more useful later in the year), about the features of Java that the test uses. As of the time of this writing, there are two sections:

    1-A: Logic & Instances

    We start with the fundamentals of logic gates and logical expressions using De Morgan's Law. By looking at transistors, the most granular aspect of CS, we can steadily add layers of abstraction.

    hashtag
    Learning Targets

    • I can explain the connection between electricity and logic.

    3-B: Monster Project

    hashtag
    Monster Battle Game - Project Assignment

    hashtag
    Overview

    Enhance your game by implementing monster special abilities and customizing the 4th action button. Make your game feel complete and polished!

    Web App Dev

    Produce a full-stack web application in Python's Flask framework. While this is difficult and complex, it'll be a rewarding challenge.

    This section of 's Computer Science Department's GitBook is also the official documentation of the . If you would like to skip the background information about web applications, you can proceed straight to .

    hashtag
    Why web development?

    Web Development is my favorite area of Computer Science to study. Programming at the hub of all information gives you a bird’s eye view of how business operations fit together. If an organization has mobile apps, websites, and some sort of critical information for their business, then web developers are the people holding systems together. There's so much happening in this field, too. In fact, we've got to be careful that all this cool tech doesn't overwhelm you.

    Game 2: Tanks

    hashtag
    Game Overview

    hashtag
    Building The Game

    Command Pattern

    Conceptual overview of the "what" and "why" of Command pattern

    The Command pattern is the overall design that SolversLib uses. It's how we keep the code from becoming any more of a confusing mess than it already is — a pattern we can follow. This page delves into the "what" and "why" behind this pattern, equipping you to write efficient and maintainable robot code—the kind where Future You doesn't curse Past You's organizational choices.

    hashtag
    What is Command Pattern?

    The Command pattern boasts a rich history dating back to the late 1970s and early 1980s. The concept emerged within the Smalltalk and Xerox PARC communities, documented in publications like Anneliese Schürr's 1992 paper "Separation of Concerns and the Command Pattern." Initially focused on graphical user interfaces (GUIs), the pattern's flexibility was adopted in various software development domains.

    Python Material, Class 2
    Python - Operatorswww.tutorialspoint.comchevron-right
    Python Material, Class 1
    https://youtu.be/PTyR4Os8JfYyoutu.bechevron-right
    Free 2D Game Assets - CraftPix.netCraftPix.netchevron-right
    Royalty Free 2D Game AssetsGame Art 2Dchevron-right
    // Basic Kivy Code (main.py)
    from kivy.app import App
    from kivy.uix.boxlayout import BoxLayout
    
    class Interface(BoxLayout):
        pass
        
    class LayoutApp(App):
        pass
        
    LayoutApp().run()
    ///Bounce against walls
    
    move_bounce_all(true);
    move_outside_all(direction, 100);
    
    
    Pulling from existing repositories
    Design Analysis of a Level
    https://www.youtube.com/watch?v=WyJbFk67D-wwww.youtube.comchevron-right
    https://youtu.be/tSq4vOMSse8youtu.bechevron-right
    https://youtu.be/mdWm-L_n8Tgyoutu.bechevron-right
    https://youtu.be/UVbvs0BCiTEyoutu.bechevron-right
    https://youtu.be/3QXN3PUrBSIyoutu.bechevron-right
    https://youtu.be/leyeSeezHj8youtu.bechevron-right
    https://youtu.be/dw0ECuxhSOcyoutu.bechevron-right
    https://youtu.be/-LRr-bXTHZ0youtu.bechevron-right
    https://youtu.be/Z9EuIs8dZ9Eyoutu.bechevron-right
    https://youtu.be/-DKbg24fx3Eyoutu.bechevron-right
    https://youtu.be/SDFR2WOMGBIyoutu.bechevron-right

    hashtag
    Part 1: Monster Special Abilities (Required)

    Goal: When monsters attack, check if they have special abilities and trigger unique effects.

    Where to work: In the monsterAttack() method, after damage is dealt.

    Steps:

    1. Check each attacking monster's special() ability (it returns a String)

    2. If the ability is not empty, add custom behavior based on the ability name

    3. Display appropriate messages for each special ability

    Example Pattern:

    Possible Special Abilities to Implement:

    • Vampire: Heals for 50% of damage dealt

    • Poison: Deals 5 extra damage for the next 2 turns

    • Rage: Increases damage by 25% when below 50% health

    • Thorns: Player takes 10 damage back when attacking this monster

    • Regeneration: Heals 10 HP at the end of each turn

    • Stun: Player misses their next turn (skip next action)

    Tips:

    • You may need instance variables to track ongoing effects (like poison duration)

    • Update the setupGame() to create monsters with different special abilities

    • Test each ability one at a time

    hashtag
    Part 2: Customize the 4th Button (Choose One)

    hashtag
    Option A: Implement Use Item System

    Make the 4th button use consumable items from your inventory.

    Tasks:

    1. Create health potions in setupGame() (see GameDemo.java for examples)

    2. The useItem() method already works - just add items!

    3. Create 2-3 different item types:

      • Health Potion: Heals 30 HP

      • Bomb: Damages all monsters for 20 HP

      • Shield Potion: Adds temporary shield

      • Your own creative item!

    hashtag
    Option B: Implement Player Special Abilities

    Replace "Use Item" with a unique special ability for each character class.

    Tasks:

    1. Change button label in setupGame() to "Special"

    2. Add a useSpecial() method with unique abilities per class:

      • Fighter: Berserker Rage - Double damage for 2 turns

      • Tank: Iron Wall - Block all damage next turn

      • Healer: Group Heal - Heal 50 HP (cooldown: 3 turns)

      • Ninja: Shadow Strike - Attack all monsters for half damage

    3. Track cooldowns to prevent spam (add instance variable)

    4. Update handlePlayerAction(3) to call your new method

    Cooldown Pattern:

    hashtag
    Part 3: Polish Your Game (Required)

    Make your game feel professional and complete!

    Required Improvements:

    1. Victory Conditions: Display final stats when game ends (turns survived, damage dealt, etc.)

    2. Better Targeting: Let player choose which monster to attack (hint: show monster numbers in message)

    3. Status Display: Show active effects in messages (poison status, shield amount, cooldowns)

    4. Balance Testing: Adjust character stats so all classes are viable

    5. Bug Fixes: Ensure health can't go above max, shield doesn't go negative, etc.

    Optional Enhancements:

    • Add more monster types with different stat ranges

    • Create boss monsters with multiple special abilities

    • Add difficulty scaling (monsters get stronger each wave)

    • Implement combo attacks (bonus damage for consecutive attacks)

    • Add critical hit chances

    • Create a scoring system

    • Add sound descriptions in messages ("💥 CRASH!", "✨ SPARKLE!")

    hashtag
    Submission Checklist

    hashtag
    Tips for Success

    1. Test frequently: Run your game after each small change

    2. Start simple: Get one special ability working perfectly before adding more

    3. Use print statements: Add System.out.println() to debug issues

    4. Study GameDemo.java: It shows many useful patterns

    5. Ask for help: If stuck for 10+ minutes, ask a classmate or teacher

    6. Be creative: Add your own unique abilities and features!

    hashtag
    Example Monster Creation with Specials

    // After monster deals damage...
    if (!monster.special().isEmpty()) {
        if (monster.special().equals("Vampire")) {
            // TODO: Monster heals itself for some of the damage dealt
            // Hint: Use a variable to track damage before dealing it
        }
        else if (monster.special().equals("Poison")) {
            // TODO: Add poison effect that damages over time
        }
        // Add more special abilities!
    }
    private int specialCooldown = 0;  // Instance variable
    
    private void useSpecial() {
        if (specialCooldown > 0) {
            gui.displayMessage("Special ability on cooldown! (" + specialCooldown + " turns)");
            return;
        }
        
        // Do special ability...
        specialCooldown = 3;  // Set cooldown
    }
    
    // In gameLoop(), reduce cooldown each turn:
    if (specialCooldown > 0) specialCooldown--;
    // In setupGame(), create diverse monsters:
    monsters.add(new Monster("Vampire"));
    monsters.add(new Monster("Poison"));
    monsters.add(new Monster("Rage"));
    monsters.add(new Monster());  // Normal monster
    monsters.add(new Monster());  // Normal monster

    1pts - Program is cleaned up (unused imports have been deleted, for example)

    A Record
    : routes primary domains like google.com
  • C Record: routes subdomains like mail.google.com

  • MX Record: routes email addresses. That's why emails @gilmour.org go to a different server than what's hosting the website at gilmour.org

  • check against this guidearrow-up-right
    first HTML unitarrow-up-right
    TCP/IP networkarrow-up-right
    IANAarrow-up-right
    https://intodns.com/arrow-up-right
    http://whois.domaintools.com/arrow-up-right
    https://www.whatsmydns.net/arrow-up-right
    Afraid of phone lines disrupted in a nuclear war, the military funded research of a decentralized network
    Pretty complicated, right? You don't need to memorize any of this for this class.

    I can connect replit to my github repositories

  • I can clone an existing repository, fork it, and extend the code to my own project.

  • hashtag
    Assessments

    • You will submit a link to your GitHub repo.

    • You will create a game based on existing turtle classes

    • You will be asked regular comprehension questions about Python and Github.

    hashtag
    Setup your github account.

    hashtag
    Setup your replit account and connect your github.

    hashtag
    Join Replit I2P team with the link below.

    hashtag
    Fork github.com/MrVanek/Interactive-Turtles and clone repository into replit.

    hashtag
    Adding Moving Turtle

    hashtag
    Assignment and Rubric

    Create an interactive turtle application of your own design. This can be a game or other interactive program, but it must use at least two of the three types of turtle classes we have outlined (moving turtle, keyboard turtle, clickable turtle).

    • 3 pts - Program works without errors

    • 3pts - Program uses two classes of turtle

    • 3pts - Program is interactive. Users can DO something with the program.

    • 1pts - Program is cleaned up (unused imports have been deleted, for example)

    hashtag

    hashtag
    How do I...

    hashtag
    ...make multiple things move?

    hashtag
    ...write text on the screen?

    hashtag
    ...stop movement with walls?

    hashtag
    ...make a ball move diagonally and bounce off multiple sides of the room?

    hashtag
    ... create a background image and have it change later?

    hashtag
    ...set up and check a timer

    hashtag
    ...add a start screen

    hashtag
    ...Save a High Score in a File?

    hashtag
    ... add points from different objects to a single score?

    hashtag
    ... get objects to check each other for different properties?

    hashtag
    ...find the x and y position of my mouse on the screen?

    hashtag
    ...create a custom shaped turtle?

    I can customize the elements of an HTML template.
  • I can publish a completed webpage and share the link with my friends.

  • I can take feedback on my website and publish an improved draft.

  • hashtag

    • https://startbootstrap.com/arrow-up-right

    • https://code.visualstudio.comarrow-up-right

    • Google Fontsarrow-up-right​

    • ​​

    Colors

    • ​https://coolors.coarrow-up-right​

    • ​https://colorhunt.co/arrow-up-right​

    • ​Color wheelarrow-up-right​

    • ​ ​

    • ​

    hashtag
    Inspect and Overwrite

    Let's identify a rule that's being used by our theme and overwrite it.

    hashtag
    New Bootstrap Component

    Let's get back to the Bootstrap documentationarrow-up-right and shop for a new component to add to our site.

    hashtag
    Revisions

    We all have to edit our work. We need to collect feedback, review, make a list, and add improvements to our project. The more you repeat this process, the better your end product (as well as first draft on your next project).

    hashtag
    Responsive refinement

    This comes from a great blog post about "breakpoints"

    If you're not frequently having to look things up (and finding W3Schools) you're not trying out enough new things. @media is one I have to repeatedly look up.arrow-up-right

    hashtag
    Fine Tuning

    hashtag
    Extra Addons

    hashtag
    Load Screen

    hashtag
    We're going to use jQuery

    Our Bootstrap template uses jQueryarrow-up-right, which is a really handy JavaScript library. JavaScript is a programming language that runs right inside your browser. Most of what you do with jQuery can be done in plain-old vanilla JavaScript. We use jQuery to make life a little easier.

    Add a <div id="cover"></div> on the first line of your <body>. Then at the very bottom, add the following script:

    And we'll add the following code to our custom.css.

    hashtag
    Replacing Images

    hashtag
    JavaScript

    Multiple choice: 40 questions, 90 minutes, 50% of your score
  • Free response: 4 questions, 90 minutes, 50% of your score

  • hashtag
    Links and Resources

    hashtag
    Software

    • Visual Studio Codearrow-up-right (install latest JDK, then install the VS Code Java Extension Pack)

    • Google Drivearrow-up-right

    hashtag
    Great Books

    • Be Prepared for the AP Computer Science Exam in Javaarrow-up-right

    • Barron's AP Computer Science Aarrow-up-right

    hashtag
    Online Courses

    • Bill Barnum's YouTube collectionarrow-up-right

    • MistaPotta's YouTube collectionarrow-up-right

    • https://www.albert.io/ap-computer-science-aarrow-up-right

    hashtag
    Practice Problems

    • Official APCS walk-throughs and reviewsarrow-up-right

    • http://codingbat.com/java/AP-1arrow-up-right (learn by doing. Loads of mini problems)

    • Runestone Academyarrow-up-right best break-down of skills)

    hashtag
    Java Tutorials and References

    • https://www.khanacademy.org/computing/computer-programmingarrow-up-right

    • https://codesignal.com/arcadearrow-up-right

    • https://www.sololearn.com/Course/Java/arrow-up-right

    College Boardarrow-up-right
    description of the testarrow-up-right
    this is also a handy documentarrow-up-right

    I can interpret logical statements with all common operators, (i.e. and, or, nor, xor, if, iff).

  • I can describe the purpose of instantiation.

  • I can decide when to instantiate an object or when to use a static class.

  • I can simplify a logical expression according to De Morgan's Laws.

  • I can convert numbers from decimal to binary and to hexadecimal.

  • hashtag
    Logic Gates

    I'm absolutely fascinated in how people build logic, systems that react to conditions, into physical devices.

    We start with two tricks with circuits: 1) and && 2) or ||

    With tiny transistors and these building blocks, we can assemble our modern technological era. Let's just take a peak:

    hashtag
    De Morgan's Law

    You'll need to know how to distribute the ! when simplifying logical expressions. This will make more sense as we get into more practical examples.

    De Morgan's Laws essentially describes the distributive property of "not" or !

    A "promise" or an "if" within logic is something like:

    It's only false if the condition was met (you studied) but you did not get the promised result.
    iff means they both have to be the same for <-> to be true

    hashtag
    Practicing Boolean Logic

    Let's simplify these statements. Reduce them down to just true or false

    • true != true || (true || false)

    • false && true || true && false || true && false || true

    • !(true && false)

    • !(5 > 5)

    • !(5 <= 5)

    • 5 == 5 && true

    hashtag
    Binary

    Can you see how false and true could also be considered to be 0 and 1? All the sudden, we can make these logic gates, these electrical transistors, store binary data. Computers are pretty cool.

    hashtag
    Instantiation

    This is an important concept that's most easily introduced when we're not thinking about the code. If you have a recipe to make a cake, that's similar to a class definition. Each time you bake a cake, you're creating a new instance of that cake.

    One cake recipe produced many objects

    A whiteboard has functions but is not replicable. It's a static resource

    hashtag
    Another example of instance VS static classes

    This is by no means a perfect example as things are more complicated... but let's consider Fortnite for a moment. There's just one map. Programmers might refer to this map by its class. If I wanted to call a tornado, at Coney Crossroads, I might type something like, Map.createTornado("Coney Crossroads");

    One map and globally accessible resources. An potential example of a static class

    Now let's imagine a programmer wanted to provide a player with some individual powers. I wouldn't want to be so broad as to call the whole Player class as each player is an individual. I'd want to specify which individual player, something like lancerGuy99.upgradeWeapon();

    Each person controls an instance of the Player class. Each copy of stores the user's skin, current health, etc.

    hashtag
    Mixing Static and Instances

    Now that we understand the difference between static (class-level) and instance (object-level) methods, let's see what happens when we try to mix them inappropriately.

    Going back to our Fortnite example: remember that the map is static—there's only one map for everyone, so we use Map.createTornado(). But each player is their own individual instance, so we use lancerGuy99.upgradeWeapon().

    What would happen if we tried to put instance-specific things inside our static Map class? Imagine if we tried to write Map.upgradeWeapon()?

    This doesn't make sense because the Map doesn't know which specific player we're talking about. The map is shared by everyone, but each player has their own individual weapon that needs upgrading.

    Think of it like a school's PA system (static) versus individual student lockers (instances). The PA system can make announcements to everyone: "School will dismiss early today." But the PA system can't say "Please clean out your locker" because it doesn't know whose specific locker needs cleaning—that's something each individual student (instance) needs to handle for their own locker.

    In programming terms: static methods can't directly access instance variables or call instance methods because they don't know which specific object (which student, which player) they should be working with. Static belongs to the whole class, while instances belong to individual objects.

    circle-info

    Pro-level challenge

    Want to jump in with both feet and go hard on the research? See if you can get your head around the growing change from REST APIarrow-up-right to GraphQLarrow-up-right. What are those and why is there a change happening? Don't sweat it if YouTube videos and articles go right over your head. It's good to start dabbling and exposing yourself to top-level discussion.

    hashtag
    Acceptable Level of Abstraction

    Little kids like to keep asking, “Why?”

    A thread of inquiry can always get more detailed. It never stops. You can keep digging deeper. Sooner or later we just accept the idea of something and stop asking questions. For example, I know hardly any of the electrical engineering involved to build a stick of RAM but I would still claim I know what RAM is. I’ve just accepted that there’s a thing called RAM and it works like so and I’m okay not knowing any more details than that for right now.

    We are going to narrow our focus to building a Python Flask app using templates and a pre-built starting point. We can build really cool things but it means that we’re going to brush over big concepts that are totally worth studying. Sometimes it’s hard to feel like you understand something if you can’t take the time to closely examine all of the pieces and principles involved. Write down questions, don’t stifle your curiosity, but be patient as we setup lots of abstract ideas that we won’t be able to satisfactorily investigate for a while. TLDR: Be patient and keep a running list of concepts and questions to research later.

    hashtag
    Resources

    • Guided Training: Do your homework! Actually grind out the projects in tutorials. Learn the rules of new languages.

      • Pretty Printedarrow-up-right

      • The Flask Mega-Tutorial by (the great) Miguel Grinbergarrow-up-right

    • Publishing: How do we get our Flask app online?

    hashtag
    Extra Resources for the Try-Hards:

    • Official Flask Documentationarrow-up-right

    • JavaScript on Udemyarrow-up-right

    • Code Combatarrow-up-right (Python)

    • Books at give superpowers

    Gilmour Academyarrow-up-right
    Flaskinni open-source projectarrow-up-right
    4: Install Flaskinni
    hashtag
    1: Tank Design

    hashtag
    2: Movement

    hashtag
    Movement Part 2

    hashtag
    3: Turret Rotation

    hashtag
    Turret Rotation Part 2

    hashtag
    Turret Rotation - A Quick Fix

    hashtag
    4: Controller Diagram

    hashtag
    5: Camera Control

    hashtag

    hashtag
    6: Particle Effects

    The above file is for the Tank Particles 1 video if you don't have access to Photoshop or Illustrator.

    hashtag
    7: Materials

    hashtag
    8: Destructible Environment

    hashtag
    9: Audio

    hashtag
    10: Split Screen View

    hashtag
    11: Tank Targeting and Hit Points

    hashtag
    Assignment

    Make sure all tutorial sections have been completed and all features are implemented correctly.

    Add the following to your game:

    1: Make the tanks a target with appropriate health. (Video was added above for this assignment) 2: Add a non-destructible wall with metallic material.

    3: Create one extra piece of destructible terrain. 4: Add a secondary fire weapon (missile, artillery, machine gun, laser, mine, etc) with it's own particle system. 5: Make a power up that lasts for a limited amount of time and affects some aspect of the game (speed, fire rate, damage, etc). 6: Create three separate arenas with realistic materials for everything. 7: Create a start screen for your game. When a player hits Start, randomize the arenas and begin the game. 8: Add a win screen to the game and prompt players to restart once they both hit X.

    9: Turn in the game through GitHub (make sure you set it up with a Unity GitIgnore).

    hashtag
    Learning Targets

    file-image
    16KB
    Particle.png
    image
    arrow-up-right-from-squareOpen
    Particle File

    Its popularity soared with the rise of design patterns in the 1990s, solidified by Erich Gamma et al.'s influential book "Design Patterns: Elements of Reusable Object-Oriented Software." This widespread recognition cemented the Command pattern as a valuable tool for promoting loose coupling, reusability, and maintainability in object-oriented programming.

    Gamma, Helm, Johnson and Vlissides are sometimes referred to as the Gang of Four or GoF

    The Command pattern originates from software design principles and offers a structured way to manage robot actions. Instead of writing long, blocking code sections, you create independent classes called Commands. Each Command encapsulates your robot's specific task, like driving forward, turning, or activating a mechanism.

    hashtag
    Why Command Pattern?

    hashtag
    Farewell, Blocking Code

    Traditional robot programming often involves lengthy, sequential code blocks, potentially hindering responsiveness and multitasking. If your robot is stuck inside of a loop that gradually moves a motor, it's not doing other things. It's blocked until you move on.

    Non-blocking commands eliminate the need to do one thing at a time by repeatedly calling execute functions that run until their isFinished condition is reached. This allows the robot to perform multiple actions simultaneously. This means smoother operation and the ability to react to real-time events effectively.

    hashtag
    Reusable Gems

    Commands are designed for reusability. You can create a generic RotateCommandand adapt it for different distances or speeds across various parts of your code. This reduces code duplication and simplifies maintenance.

    hashtag
    Collaborative Codebase

    SolversLib encourages modularity with separate Command files. This translates to clear ownership and promotes a collaborative development environment. Team members can work on their specific Commands without worrying about conflicts in common code sections. Version control systems like Git become even more valuable as team members push their Command commits independently.

    hashtag
    Utilities in SolversLib

    This toolkit is packed with stuff — way more than just commands (though they're still a big deal and I'm going to keep writing about them). Check out all the things:

    Command Management:

    • Subsystem Framework: Organize your robot's hardware into logical subsystems that own their resources and prevent conflicts.

    • Command Scheduling: The scheduler handles command lifecycle, requirements, and interruptions automatically.

    • Command Composition: Chain commands together, run them in parallel, or create complex sequences without callback chaos.

    Hardware Wrappers:

    • Motor & Servo Control: Simplified classes with built-in caching to reduce unnecessary hardware writes. Special support for Axon servos with absolute encoders.

    • Sensor Interfaces: Wrappers for gyros, distance sensors, color sensors, and more.

    • Gamepad Extensions: Enhanced button and trigger handling with intuitive methods like wasJustPressed() and wasJustReleased().

    Movement & Navigation:

    • Drivebase Classes: Pre-built support for differential, mecanum, kiwi, and X-drive configurations with both robot-centric and field-centric control.

    • Kinematics & Odometry: WPILib-style classes for tracking robot position using encoders and gyros across different drivetrain types.

    • Controllers: PID, feedforward, and SquID control for precise mechanism movements.

    Utilities:

    • Geometry Classes: Pose2d, Translation2d, Rotation2d for coordinate math.

    • Look-Up Tables: Store and retrieve tuned values (velocities, angles) based on distance or other inputs.

    • Timers & Math Helpers: Built-in timing functions and utilities like clamp for value constraining.

    Pedro Pathing Integration:

    • Built-in support module for seamless integration with Pedro Pathing autonomous navigation.

    hashtag
    Video Overview

    https://docs.seattlesolvers.com/arrow-up-right
    Tim Berners-Leearrow-up-right
    CERNarrow-up-right
    Microfichearrow-up-right
    hyperlinkarrow-up-right
    Nobel Prize winner Tim Berners-Lee
    Microfiche was text printed on tiny films. Searching through many films was a pain
    HTML is Batman and CSS is Robin. CSS doesn't ever work alone--it's there to support HTML
    It can often be very frustrating to find the right CSS rule to fix your display
    kwargarrow-up-right
    Flask-RESTfularrow-up-right
    Breakout Resource Folderarrow-up-right
    OpenGameArt.orgOpenGameArt.orgchevron-right
    Logo
    Logo
    Sprite Game Assets | GraphicRiverGraphicRiverchevron-right

    3: DRY Turtle

    hashtag
    Expectations

    hashtag
    Learning Targets

    3: Bootstrap

    Use a Bootstrap template to produce a stunning webpage.

    hashtag
    Learning Targets

    • I can build a hero with a call to action.

    4-A: Data Structures

    We will build our own photo editing tools as we study more complex nested loops to traverse and mutate 2D arrays.

    hashtag
    Learning Targets

    • I can remove a column from a 2D array in Java.

    Building Community Gallery Page 2023

    hashtag
    Famous Buildings

    hashtag
    Bruno

    Game 3: Third Person Platformer

    hashtag
    Finished Game Overview

    hashtag
    Building The Game

    Autodesk Student Access to Education Downloadswww.autodesk.comchevron-right
    CodeSignal | The AI-Native Skills PlatformCodeSignalchevron-right
    psst... start with the arcade
    Object Following a Mouse
    from turtle import Turtle
    
    
    class ClassName (Turtle):
        def __init__(self, starting_x, starting_y):
            Turtle.__init__(self)
            self.starting_x = starting_x
            self.starting_y = starting_y
            
            # General setup
            # self.color("black")
            # self.penup()
            # self.shape("turtle")
            # self.goto(self.starting_x, self.starting_y)
            
        def method_example(self):
            pass
            ## change the name and make the method work
    from turtle import Turtle
    
    
    class ClassName (Turtle):
        def __init__(self, starting_x, starting_y):
            Turtle.__init__(self)
            self.starting_x = starting_x
            self.starting_y = starting_y
            
            # General setup
            # self.color("black")
            # self.penup()
            # self.shape("turtle")
            # self.goto(self.starting_x, self.starting_y)
            
        def method_example(self):
            pass
            ## change the name and make the method work
    @media only screen and (max-width: 600px) {
      body {
        background-color: lightblue;
      }
    }
      <script>
        $(window).on('load', function(){
          $('#cover').fadeOut(1000);
        });
      </script>
    #cover {
        /* save a file called loading.gif to your img folder */
        background: url("../img/loading.gif") no-repeat scroll center center #FFF;
        position: absolute;
        height: 100%;
        width: 100%;
        z-index: 9999;
    }
    BlankPage
    <!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
    
    </body>
    </html>
    hello.py
    
    import os  # connects the OS library so we can lookup our own IP address
    from flask import Flask   # this connects our framework of tools we'll need
    
    app = Flask(__name__)  # here we create our app in memory. It's maybe the most important line of code
    
    @app.route('/') # if anyone tries to go to the homepage, their request will be routed to the method below
    def index():
        return 'Hello from Flask'
    
    if __name__ == '__main__':
        host = os.getenv('IP', '0.0.0.0')
        port = int(os.getenv('PORT', 5000))
        app.debug = True 
        app.run (host=host, port=port)
      // Create surface, draw everything to it, deactivate all other objects
     
    surf = surface_create(room_width, room_height); 
        // creates a surface which is the same height and width as the room.
        // A surface is basically a clear drawing surface on the screen.
      
    surface_set_target(surf);   
        // Sets aside room in memory for surface and begins drawing on it
    
    draw_clear_alpha (c_red, .5); 
        // Clears surface of buffer noise and sets color and alpha 
        // (0= fully transparent, 1 = fully opaque, .5=50% transparent)
    
    surface_reset_target();
        // Tells GM to stop drawing on the surface and 
        // allows drawing directly on the screen again (and thus the draw GUI below)
     
    instance_deactivate_object (obj_ball);
        // Deactivates the ball without destroying it.
    
    visible = true; 		
        //This object is visible.  
        //Adding the command is not strictly necessary since we already set the object to visible.
    
    draw_set_font(fnt_pause);
    	// GML commands, also called functions,  are set up in categories.
    	// Draw_ gives you access to draw functions.
    	// Instance_ functions give you access to things dealing with instances of objects.
    	// Draw_set_ commands establish parameters for your draw actions.
    	// This one changes your draw font to your pause font (set it up, if you haven’t).
    
    draw_set_color(c_black);
    	// This one sets the color.
    	// typing c_ will give you a list of different color options.
    
    draw_set_halign(fa_center);
    	// Sets the horizontal alignment of the font to center.
    
    draw_surface(surf, 0, 0);
    	// This function draws the surface over the room.  
    	// The surface that it draws is called surf (which is what we called it in the create event).
    	// It draws it starting at 0x and 0y in the room.
    
    draw_text(room_width/2, room_height/2, "Game Paused:  Press Space to Continue");
    	// This draws text.  It looks for (x,y,string) which means the programmer 
    	// decides where the it goes.  room_width / 2 is right in the center of the room.
    	// A string is a series of text in “”. The text is in black and centered because of the above 
    	// draw_set_ functions.
    
    draw_set_halign(fa_left);
    	// Since the text of the scoreboard is aligned to the left, we need to reset the alignment.
    
    /// Unpause, clear surface, re-activate all objects.
    
    surface_free(surf); 
    	// Free up the memory from the surface.
    	// Essentially this deletes the surface.
    	// By the way, we are starting code now because there are no commands in 
    	// drag and drop programming that deal with surfaces.
    
    instance_activate_all(); 
    	// Activate all the objects again
    	// We could have also used instance_activate_object (obj_ball); 
    	// since that is the only thing we deactivated in the create event.
    
    instance_destroy(self);  
    	// Destroy the pause object.
    	
    	// As you look at this code, remember that instance_ functions are used
    	// to control instances of objects in the room.  As we get further along, we 
    	// will use more code blocks,  so it is important to be aware of the general 
    	// language rules because you won’t always know what the exact command 
    	// will be for an operation. 
    	
    	// In the code block autocomplete will help you find the right one.  If you know
    	// you are dealing with an instance, you can start typing “instance_” and will be
    	// given a list of possible things which could finish that command.  
    
    https://code.visualstudio.com/code.visualstudio.comchevron-right
    Logo

    I can implement the basic constructs of programming languages such as variables, conditionals, loops, and flow control.

  • I can make a class wrapper that inherits from a library's class.

  • I can call a method from a library.

  • hashtag
    Assessments

    • You will be submitting Trinket.ioarrow-up-right scripts demonstrating the following skills.

    hashtag
    Class Videos

    Class 1/24 Turtle drawing assignment:

    hashtag
    What is DRY code?

    Avoid having to copy and paste lines of code to repeat a command

    Loops and functions allow skilled programmers to make more efficient code that's easier to maintain.

    hashtag
    Parts of a for loop

    A for loop has an iterator and a collection that it traverses.

    hashtag
    Parts of a function

    A function has a definition that lists any parameters and has a code block underneath that gets activated when called.

    In the example above, the magic_spell function isn't a part of a Class. It's on its own. If that ability was a part of a player in a game, we'd call it a method instead of function.

    hashtag
    Code Along

    We're going to jump into work with a lot of advanced concepts. This is intentional. New programmers are very often intimidated by code they don't understand. I want you to get used to that early on. Enjoy tinkering with a few lines here and there and see how things change. Get comfortable swimming in the deep end.

    This class (inherits) from the Turtle class which is available since we imported the turtle library. Instead of writing from turtle import Turtle I could have also written just import turtle in which case every time I wanted to use the Turtle class, I would have had to specify the library, such as turtle.Turtle()

    The only thing that our SuperTurtle does that the regular Turtle doesn't is the way it gets constructed. When a new Turtle is created or instantiated, we initialize or __init__ with some default properties.

    Follow along as we go over a couple of skills. You aren't expected to be able to do this stuff yourself quite yet.

    1. Make a loop and create a bunch of turtles

    2. Add a new method to the turtle to make it go to a random location and call that method in the constructor

    3. Make a list of colors and make each turtle randomly select a color

    4. Make an empty list and add each turtle to the collection as it's being instantiated

    5. Loop through the turtle collection and modify each

    We'll spend some time experimenting with this code, learning by modifying existing code.

    hashtag
    Building Methods

    Experimenting with code given to you is fun and can be very helpful, but let's slow things down now and build some basic skills. Your Trinket.io arrow-up-rightapp should look something like this:

    A method or function is a group of commands that can be called. If I tell you to please clap, that's me activating or calling the command that's already defined in your head. I may give you additional parameters or arguments like, "clap 5 times loudly". In Python that may input("What's your name?") but that doesn't save the variable, so we write it as:

    name = input("What's your name?") written as joe.clap(5, "loudly")

    hashtag
    What's the difference between a function and a method?

    They both start with def and will execute their pre-programmed commands when called. However, we'll refer to a function as something floating outside of a class and a method as an ability built within an object. For example, a method would be if an instance of the Human class, let's call him Joe, had to sneeze: joe.sneeze(). But a function would be an anonymous helper like therancolor() function programmed above that just returns a random string in a list of colors.

    hashtag
    Novel Design

    Look at the documentation, other student examples, and Google searches to modify open-source code and customize your own design. You can use one or many turtles but the end result has to have multiple colors over a fun design.

    hashtag
    Taking Controls

    Let's make our app more interactive. Just like the print("message") function we've been using, there's another one that takes a string input called input()

    input("What's your name?") will work but that doesn't save the user's response anywhere. So let's create a variable that will store the answer in this example:

    name = input("What's your name?")

    hashtag
    Testing the input

    To make sure we are asked the question over again, we'll put the input within a while True: loop.

    I can implement a color palette via CSS.
  • I can build a responsive Bootstrap website.

  • I can implement Bootstrap classes and components into a website.

  • hashtag
    What is Bootstrap?

    Bootstrap has tons of helpful styles and tools built in, but most importantly, it makes your page responsive

    Read about itarrow-up-right. Twitter publishes a front-end framework that has significantly impacted web designers. It's great, and you'll spend a lot of time with its documentationarrow-up-right.

    hashtag
    What is responsive?

    Responsive design isn't just about websites looking good on different screens; it's about delivering an optimal user experience on any device. Imagine navigating a complex website on a tiny phone instead of a spacious desktop – the frustration is real! Responsive design solves this by adapting the website's layout, content, and functionality to various screen sizes, ensuring a seamless user journey.

    Bootstrap's Grid System:

    Bootstrap, a popular framework, makes responsive design accessible. Based on 12 columns, its grid system provides a flexible layout structure. In your example, <div class="col-md-6"> and <div class="col-lg-6"> define elements that occupy 6 columns on medium and large screens, respectively.

    Breakpoints and Device Adaptation:

    The magic happens with breakpoints and specific screen widths where the layout adjusts. Bootstrap uses predefined breakpoints for @media queries, essentially saying, "When the screen size reaches X, apply these styles." Your task with the inspector window is to find these breakpoints! Look for @media rules defining styles for lg, md, and sm (small) screens. Notice how Bootstrap adjusts the number of columns these classes occupy at each breakpoint.

    Exploring Device-Specific Adjustments:

    While Bootstrap offers a solid foundation, sometimes device-specific tweaks are necessary. For example, on smaller screens, you might:

    • Collapse content sections by default and use buttons or icons to reveal them.

    • Increase font sizes for better readability.

    • Simplify navigation menus or switch to hamburger menus for better accessibility.

    • Optimize images for faster loading times.

    Beyond Bootstrap:

    Remember, Bootstrap is a tool, not a silver bullet. You might need to go beyond its base styles as your projects evolve. This is where understanding CSS media queries and flexbox becomes crucial for more granular control over responsive layouts.

    Beyond Screen Size:

    While the screen size is the primary factor, a responsive design also considers other aspects:

    • Device orientation: Portrait and landscape modes on phones and tablets require different layouts.

    • Resolution: High-resolution displays might necessitate adjustments for image quality and text sizes.

    • Network speed: Consider loading optimizations for users with slower connections.

    The Importance of Testing:

    Responsive design isn't a one-and-done task. Rigorous testing on various devices and screen sizes is crucial. Use browser emulators and real devices to identify and fix any layout issues and ensure a consistent user experience across platforms.

    hashtag
    Container - Row - Column

    Every Bootstrap page starts with the same fundamental building blocks: Container, Row, and Column (C-R-C). Think of this as the skeleton that holds your entire layout together. Just like a house needs a foundation, walls, and rooms, Bootstrap needs containers, rows, and columns to create organized, responsive layouts.

    hashtag
    The Container: Your Layout's Foundation

    The container is the outermost wrapper that holds all your content. Bootstrap offers two types of containers:

    .container - Creates a responsive fixed-width container that adjusts at breakpoints .container-fluid - Creates a full-width container that spans the entire viewport

    The container provides proper margins and ensures your content doesn't stretch awkwardly on very wide screens. It's like setting boundaries for your design – everything stays contained and centered.

    hashtag
    The Row: Horizontal Organization

    Inside every container, you need rows to create horizontal groups of columns. Rows use negative margins to offset the padding that columns add, creating perfect alignment.

    Important rules for rows:

    • Rows must be placed inside containers

    • Only columns should be immediate children of rows

    • Rows create horizontal groups of columns using flexbox

    hashtag
    The Column: Where Content Lives

    Columns are where your actual content lives. Bootstrap's grid system is based on 12 columns, and you can combine them in various ways to create different layouts.

    Column class breakdown:

    • col- - The base column class

    • md - The breakpoint (xs, sm, md, lg, xl)

    • 6 - The number of columns to span (1-12)

    hashtag
    The Magic of 12 Columns

    Bootstrap's 12-column system is incredibly flexible. Here are some common combinations:

    • Two equal columns: col-md-6 + col-md-6 = 6 + 6 = 12 ✓

    • Three equal columns: col-md-4 + col-md-4 + col-md-4 = 4 + 4 + 4 = 12 ✓

    • Sidebar layout: col-md-8 + col-md-4 = 8 + 4 = 12 ✓

    • Four equal columns: col-md-3 + col-md-3 + col-md-3 + col-md-3 = 12 ✓

    hashtag
    Putting It All Together: A Complete Example

    Here's a basic Bootstrap page structure that you'll be building in CodePen:

    hashtag
    Key Takeaways for Your CodePen Assignment

    When building your C-R-C structure, remember:

    1. Rows go inside containers: They give you readable margins. We typically avoid putting rows directly in the body

    2. Columns go inside rows: And content goes inside columns

    3. The numbers must add up to 12 - Or less if you want some columns to not fill the full width

    4. Use breakpoints thoughtfully - col-md-6 means "6 columns wide on medium screens and up"

    This structure is the foundation of every Bootstrap layout. Once you master Container-Row-Column, you'll be able to create complex, responsive layouts with confidence.

    hashtag

    I can write 2D array methods for the PicLab.

    hashtag
    PicLab

    hashtag
    Activity 1 & 2: Color Code

    hashtag
    Eight Bits for 0 - 255

    1. Convert 128 to binary

    2. Covert 225 to binary

    3. Convert 11010111 from base 2 to base 10

    This is a byte.

    hashtag
    3 Bytes to RGB

    Max red, green and blue (255, 255, 255) is white. No red, green and blue (0, 0, 0) is black. Sometimes we add a fourth byte to control alpha layer (transparency). rgba(255, 255, 255, 255) is opaque black.

    hashtag
    Compress to Hex

    Two digits in base 16, hexadecimal, can describe 0 - 255. Eight digits can contain rgba. #FF0000FF is opaque black.

    hashtag
    Activity 3: Exploring a Picture

    1. What is the row index for the top left corner of the picture?

    2. What is the column index for the top left corner of the picture?

    3. The width of the picture is 640. What is the right most column index?

    4. The height of the picture is 480. What is the bottom most row index?

    hashtag
    Activity 4: Picture Arrays

    Okay, so you know how a regular array works
    Now a 2D arrays has a whole array in each spot
    You don't have to just use dumb old ints. Instantiated objects are cool too

    We use row-major to define the 2D array of pixels that makes a picture
    2D traversals go row by row and each column between each row

    hashtag
    Activity 5: Get working

    hashtag
    Review

    hashtag
    NumGrid Practice

    hashtag
    Exercises

    1. Imagine a circumstance where you might use an interface and an abstract class. Create and implement the interface and abstract class. Instantiate objects that extend these. Create a polymorphic container or method.

    2. Calculate the sum of an indicated column from an extremely rare occurrence of a 2D ArrayList: public static int sumColumn(int col, List<List<Integer>> grid){

    3. Remove a row from a 2D array: public static String[][] removeRow(int row, String[][] names){

    4. Calculate the sum of an entire 2D array: public static double sum(double[][] grid){

    5. Count the number of occurrences of a given number in a 2D array public static int count(int[][] grid, int target){

    6. Add a new column to a 2D array of Pixels with the average color at the end of the image public static Pixel[][] addAverageColumn(Pixel[][] picture){ // each Pixel has .getColor() which gives a single int // return an array that's one column wider, containing the average of every color in that row // you can set the color of a pixel by using .setColor() and passing the method the average of that row's .getColor() }

    7. Convert an RGB value like 220, 175, 205 to a hex value

    8. We have an array of Friends, Friends[] friends, and we want to make sure that each of our friends has the items they requested from the store. Friend.getItems() returns an array of Item objects (Item implements the Comparable interface so you can use .equals() to compare two items). If the Item is not on the shopping list, we'll add it to an ArrayList<Item> called requests. The Item class also has a publicly accessible boolean that marks if the Item has been claimed: Item.claimed.

      public ArrayList<Item> checkShoppingList(Friends[] friends, ArrayList<Item> list){

    hashtag
    Gino

    hashtag
    Nate


    hashtag
    COVID-19 Pandemic Inspired Buildings

    hashtag
    Evie

    hashtag
    Sam


    hashtag
    Cartoon Community

    hashtag
    Jesse

    hashtag
    Alex

    hashtag
    Jonas

    hashtag
    Dominic


    hashtag
    Fallout Community

    hashtag
    Matthew

    hashtag
    John

    hashtag
    Zane

    hashtag
    0: Setup

    hashtag
    1: Camera Relative Controls

    hashtag
    2. Jumping

    hashtag
    3: Physics materials

    hashtag
    4: Intro to Animations

    hashtag
    5: Building Assets: Probuilder and MagicaVoxel

    hashtag
    MagicaVoxel: http://www.voxelmade.com/magicavoxel/arrow-up-right

    hashtag

    hashtag

    hashtag
    6: Enemy AI

    hashtag
    Assignment

    1) Create five levels in which the player needs to explore in a controlled way. The level should have a start point and an end point. Think about how far / high characters can jump to keep parts blocked off.

    Make sure you control how the players can progress through the level with terrain. You should use Probuilder, MagicaVoxel, or both to design your level. You can also use other resources such as physics materials.

    2) Add at least one "hidden area" to your level.

    3) Add at least one area which requires an item to progress.

    4) Create one power up for your character (different than the progression item).

    5) Use slime enemies in the environment. If your player touches a slime, restart the level (or if you are feeling like a bit of a challenge, make checkpoints and move the player to the last touched checkpoint).

    6) Create at least one additional "humanoid" enemy complete with animations. Make sure the player can interact with the enemies in some way (attack, avoid, etc)

    hashtag
    Learning Targets

    AllTheFreeStockarrow-up-right
    CSS cheatsheetarrow-up-right
    https://color.hailpixel.comarrow-up-right
    https://courses.edx.org/courses/CooperUnion/CS.1x/1T2015/course/arrow-up-right
    http://www.whs.wwusd.org/page/3154arrow-up-right
    https://codehs.com/info/curriculum/apjavaarrow-up-right
    https://www.udemy.com/ap-computer-science-a-java-programming-essentials/arrow-up-right
    https://www.varsitytutors.com/ap_computer_science_a-practice-testsarrow-up-right
    http://www.danshuster.com/apcs/java_tests.htmarrow-up-right
    https://www.codestepbystep.com/arrow-up-right
    https://practiceit.cs.washington.edu/arrow-up-right
    https://www.codecademy.com/learn/learn-javaarrow-up-right
    Codecademyarrow-up-right
    SoloLearnarrow-up-right
    Digital Oceanarrow-up-right
    Herokuarrow-up-right
    CodeSignalarrow-up-right
    Flask by Miguel Grinberg arrow-up-right
    Fluent Pythonarrow-up-right
    Logo

    6: Raspberry Pi / GoPiGo

    hashtag
    Expectations

    hashtag
    Learning Targets

    • I can connect to my Raspberry Pi via SSH.

    • I can deploy an app to a Raspberry Pi.

    • I can compose a higher-ordered algorithm.

    • I can update code on my Raspberry Pi.

    • I can make short, descriptive commit messages.

    hashtag
    Assessments

    • You will submit a link to your GitHub repo.

    • You will demonstrate your capacity to control your robot.

    • You will be asked regular comprehension questions about Raspberry Pis.

    hashtag
    Terms

    hashtag
    Printed Circuit Board (PCB)

    ​

    hashtag
    Single Board Computer (SBC)

    This is a PCB with all the basic components found in a personal computer (PC)

    hashtag
    Getting Started

    hashtag
    Fork code

    1. Visit the and fork it

    2. Open Replit and start a new project from github

    3. Use your forked github project. You should now see your code on your editor. Explore student.py and teacher.py

    hashtag
    Push code to GitHub

    Whenyou make changes to your app and want to update the code on your robot, we first need to send the code from our computers to GitHub. This happens in the version control tab by typing in "What did you change" and hitting Commit & Push.

    hashtag
    Pull code on robot

    Now we'll remote control our robots using SSH. We'll use Linux commands to pull the updated code down from GitHub.

    Open putty and enter the ip address of your robot. Click open.

    • login: pi

    • password: robots1234

    Note: You will not see the password when typing. This is a security feature!

    1. Make sure you're in the right folder: cd Piggy

    2. Pull your updated code: git pull origin master

    3. Run your app: python3 student.py

    hashtag
    Calibrate

    We'll need to configure your class variables.

    hashtag
    Midpoint

    If the servo wasn't mounted perfectly, the midpoint won't be 1500. But that's rarely the case. We should adjust this to fit your particular robot.

    hashtag
    Motor Speeds

    Sometimes one motor will perform faster than the other, giving the robot a noticeable veer. We can try to correct for this drift by adjusting the motor power.

    hashtag
    Moving Your Robot

    hashtag
    Dance Project

    Check out what commands are available from the API that's provided for you. These are the commands you're inheriting.

    hashtag
    Higher-Ordered Logic

    Your dance method should read as close to regular English as possible. The nitty-gritty commands are all kept in the particular methods being called in your dance algorithm. So your dance method should just call a handful of moves. Within those moves, you'll use the specific motor commands below and get into the nitty-gritty of robot control.

    • deg_fwd(angle) - how many degrees do you want your wheels to rotate? You need to pass the angle

    • turn_to_deg(angle) - rotates to the given angle as calculated by the piggy's gyroscope

    • turn_by_deg(angle)

    hashtag
    Shutting down the robot

    To shut down your robot, type: sudo shutdown now in the putty window.

    hashtag
    Basic Movement Methods

    • Square

    • Dance

    • Add safe_to_dance() method which checks surroundings and only dances if it has enough space.

    hashtag
    Intermediate Movement Methods

    • Write a move method which scans slightly to the left and right of the robot as it moves forward.

    • If it senses a wall straight ahead, it goes around to the closest side as above (put that move in it's own method)

    • If it senses a wall at the edges of the robot, swerve slightly to miss the wall (this swerve should again be in it's own method).

    hashtag
    Maze Navigation

    • Coming soon.

    5: Graphics and Branding

    Let's talk about the design in web design.

    hashtag
    Learning Targets

    • I can describe the difference between raster and vector.

    • I can describe the difference between serif and sans serif.

    • I can iterate on my design.

    • I can use Photoshop's masking layers and quick select tool.

    • I can create a logo in Adobe Illustrator.

    hashtag
    Serif vs Sans Serif

    One of the first decisions to make when starting a new project is your font selection. It helps set a lot of the tone for your site. Typically, I select a header font and a body font--something fun for titles and something easy to read for my paragraphs.

    hashtag
    Color Palette

    Another key mood-setting decision to make is the type of colors you'll use around your site.

    Once you've selected your colors, we're going to add a note to your custom CSS like so:

    circle-info

    Adjust your colors!

    Choosing a hero image isn't just about visual impact; it sets the color palette for your entire website. Remember that initial color inspiration you had? Time to revisit it! Once your hero image is finalized, re-evaluate your chosen color scheme. Does it complement the image's tones and moods? Can you pull color accents directly from the image itself? Aligning your color scheme with your hero image fosters visual cohesion, ensuring a seamless and aesthetically pleasing browsing experience for your visitors. Don't let your hero stand alone; let its colors sing throughout your website's design.

    hashtag
    Call to Action

    Webpages have agendas. The author wants the reader to do something, read something, buy something. Especially on a , you need to make the key action item into an exciting call to action button.

    hashtag
    Raster VS Vector

    If your image has been zoomed in or stretched too far, and it's a rasterized image, you'll notice the pixels that make up the image. That's a problem. But the solution is not to use a super high-resolution image with a big file size. That'll just make your webpage take forever to load. We need the right resolution each time.

    Use vector where you can. Raster, if the image is the right resolution, looks great. The image below can confuse students into thinking raster is always blurry.

    hashtag
    Design Principles

    hashtag
    Common Mistakes

    Check out about the top five mistakes most common in small companys' websites.

    1. Navigation that isn't simple, logical and explanitory

    2. No clear calls to action

    3. Insufficient contrast between text and background or clashing colors

    hashtag
    Mostly Boring

    Backgrounds and most colors should NOT try to grab your attention. Most of it should be steady, comfortable patterns. Subtly is hard for students eager to splash bright colors on the page. That's why we study examples of great pages. Look how chill most of their decisions are... it makes the touches of bright color really exciting.

    hashtag
    Parallelism

    Brains love patterns and it can hurt when they're broken. Patterns exist in grammar, color, lines and all sorts of other things too.

    hashtag
    Keep Room to Digest

    Less is more.

    hashtag
    When something is considered "clean" design

    Lots of clear space with well-organized boundaries can create a "clean" feel. .

    hashtag
    Metro, Material and Flat Trends

    There is a constant variation in what's trending in web design styles. Here are three of the most popular. The last, flat, is more related to colors and icons and less known as a style.

    hashtag
    Photoshop

    Photoshop works with rasterized images (as opposed to vector images). Let's discuss the difference first.

    We're going to learn about three basic skills:

    hashtag
    Layer Masks

    Let's learn a little about . Now we'll practice masks.

    hashtag
    Resizing

    Our themes typically come with images perfectly formatted for the area. Instead of taking a new image and trying to crop and adjust it into the right size, I simply edit the original image in Photoshop. Once it's open, I'll drag and drop the new one on top of that.

    hashtag
    Color Correction

    We add in new adjustment layers to tweak colors. Turning down the brightness on a hero image so that it lets your CTA stand out more is a common technique.

    hashtag
    Logo Design in Illustrator

    Consistency in colors, branding across all your emails and publications (attention to things like ).

    hashtag
    Requirements of a Logo Package

    • PNG and JPG images

    • Wide but thin logos (banner format)

    • Square shaped logos

    hashtag
    Find a Tutorial

    Find a tutorial that gets close to the effect you want. Follow along and then try to tweak and customize it.

    circle-info

    If I can't hire a graphic designer for my client, I start with a template purchased from .

    1-C: Data Types & Operations

    We will learn to solve simple problems with Java programming. We will create all sorts of variables, test their limitations and exercise basic control flow.

    hashtag
    Learning Targets

    • I can declare variables of common Java data types and assign values.

    • I can control the flow of my app with loops, conditionals and method calls.

    • I can write efficient conditionals and return comparisons in my methods.

    • I can describe the difference between logic, run time and compile time errors.

    hashtag
    Declaring Variables

    Primitives are objects that live entirely in stack memory (they're lowercase like int and not like String) . We'll go over the difference between stack and heap memory later. For now, just think of stack memory as the lightweight stuff that's really fast-access. Take a look at the .

    hashtag
    Naming Conventions

    CompoundCapitalize name of classes

    camelCase variables and methods

    ALLCAPS variables marked as final, meaning they can't change

    snake_case is typically used only in Python and I miss it every time I work in Java or C#

    hashtag
    Operators

    hashtag
    Arithmetic

    hashtag
    Integer Math

    What's 9 / 4? In Java, it's just2, but if you wrote it like 9.0 / 2, then the answer would be 2.5. If you don't introduce a decimal to the operation, if you only give Java literal ints , it'll match that format and ignore decimals.

    hashtag
    Comparison

    We evaluate / test data and produce a true or false value.

    hashtag
    Short-Circuit Evaluation

    hashtag
    Arrays

    You can declare and initialize an int like int x = 5; Similarly, you can create an array that contains three ints like this: int[] x = {5, 10, 15};

    circle-info

    Arrays are immutable. They don't change in size. Java uses a fancier object called an ArrayList that is more flexible. So if one of your friends is trying to convince you to increase the size of an array, just say no.

    hashtag
    Array Tricks

    hashtag
    How long is that array?

    x.length; // note: this isn't a method like it is in the String class.

    hashtag
    What's the first element in the array?

    x[0]; // this will print "5" in my example

    hashtag
    What's the last element in the array?

    x[x.length-1]; // this will print "15" in my example

    hashtag
    What other skills do you need to know?

    • Loop through every element in the array

    • Check if an element is found in an array

    • Make an array of other types of objects

    hashtag
    Method Calls

    This is a part of control flow. The thread, the computer's train of thought, is being sent over to work through a set of commands called a method or function (either name works in this class).

    2: MVT Pattern

    hashtag
    Expectations

    In the last section, you learned there's a lot of layers to a stack. But even within our stack's application layer, there's a lot of complexity. If you don't keep organized, your code quickly gets overwhelming and difficult for other people to understand if you need help. But we find that we can sort-of split our code into three areas, 1) code that stores stuff like user data, 2) "logic" code, or rather the stuff that loads data executes actions like making a sale, and 3) the HTML visuals we see when we interact with the app. This pattern was originally called MVC. We use a slight twist on that called MVT.

    hashtag
    Learning Targets

    • I can describe the rationale for the MVT design pattern.

    hashtag
    Background

    There are countless ways to organize the files and code used in an application. How does one choose? How do you plan out the parts of your app? There’s big advantages to following best practices, using a pattern that others can recognize. You may hear people references the Gang of Four (GoF) when referring to . MVC is one such pattern, but for reasons I'm still figuring out, Flask uses a conflicting acronym for remarkably similar pattern.

    • Model: Database schema or rather, what gets stored in memory. But we won't have to learn a database language like SQL just yet. We'll have a tool called an ORM to convert Python into SQL for us. We'll use that to setup our SQL database tables for each object

    • View: Routes internet traffic. Here's where we connect the /url/someone/typed/ to the Python thinking that will respond to request for that certain webpage. The view is our controller. It's our application logic--our central brain.

    (We will be using a modification of this pattern called MVT)

    The model (M) is a model or representation of your data. It’s not the actual data, but an interface to the data. The model allows you to pull data from your database without knowing the intricacies of the underlying database. The model usually also provides an abstraction layer with your database, so that you can use the same model with multiple databases.

    The view (V) is what you see. It’s the presentation layer for your model. On your computer,the view is what you see in the browser for a Web app, or the UI for a desktop app. The view also provides an interface to collect user input. In our MVT pattern, this becomes T. So MVT and MVC both use the term "view" but for different parents of the same triangle. This seems needlessly cruel to those studying this stuff.

    The controller (C) controls the flow of information between the model and the view. It uses programmed logic to decide what information is pulled from the database via the model and what information is passed to the view. It also gets information from the user via the view and implements business logic: either by changing the view, or modifying data through the model, or both. In our MVT pattern, this is the V and will be found in our views.py file.

    hashtag
    Model

    hashtag
    Schema

    If I launched flask shell I could talk with Python while flask is running app and I could ask app.models for all the objects we use around our code. Like app.models.User. That would be the schema. It's not an actual user that I'm referring to when I say app.models.User. That's the definition, the skeleton or the schema. The individual records in the User table will used for the instantiated objects in my code.

    Schema is more than just the list of properties (like first_name and such) and functions of an object in your app. It also describes how objects are connected in your database.

    hashtag
    Relationships

    : Communication diagrams model the interactions between objects in sequence. They describe both the static structure and the dynamic behavior of a system.

    : table that associates two other tables in a many-to-many relationship. Let's say you make a website to manage school clubs. Students can be in many different clubs and clubs can have many different students. Somewhere in our database we need to write down a connection between each Student.id and each Club.id. It's the list of connections between two objects. You want to leave the club? Remove the record that links the two id's.

    There's more: Instead of just connecting two objects, what if we wanted to qualify that relationship? Not only do you want to say "this user belongs to this club," but you also want to mark down that she's the president of the club. So now we have a Membership object that can have all sorts of properties that describe your role on the club and what you're allowed to do or not do. Association objects are super cool.

    hashtag
    Queries

    : a technique that lets you query and manipulate data from a database using an object-oriented paradigm. When talking about ORM, most people are referring to a library that implements the Object-Relational Mapping technique, hence the phrase "an ORM". An ORM library is a completely ordinary library written in your language of choice that encapsulates the code needed to manipulate the data, so you don't use SQL anymore; you interact directly with an object in the same language you're using. For example, here is a completely imaginary case with a pseudo language: You have a book class, you want to retrieve all the books of which the author is "Linus". Manually, you would do something like that:

    book_list = new List(); sql = "SELECT book FROM library WHERE author = 'Linus'"; data = query(sql); while (row = data.next()) { book = new Book(); book.setAuthor(row.get('author'); book_list.add(book); }

    With an ORM library, it would look like this:

    book_list = BookTable.query(author="Linus");

    The mechanical part is taken care of automatically via the ORM library.

    Questions

    • So object-relational mapping is a programming technique for manipulating data?

      • Yes, it’s the tool (ours is called SQLALchemy) that keeps us from having to write many SQL commands of our own.

    : a method of associating user-defined Python classes with database tables, and instances of those classes (objects) with rows in their corresponding tables.

    : the process of transferring data between computer storage types or file formats. If we ever want to change our SQL tables to add new information to every record, we’ll need to migrate the data from the old table to the new table. We’ll use a tool called Alembic to do this.

    hashtag
    View

    hashtag
    Routes

    : moving data from source to destination. Our Flask controller will take requests to, for example, yourwebsite/home and match it to the code that builds the home page

    hashtag

    : Session is the time interval when a client logs into a server and logs out of it. The data, which is needed to be held across this session, is stored in a temporary directory on the server.

    hashtag
    Decorators

    hashtag
    Template

    : generating HTML code from a mix of Python and HTML, this is done in Flask using Jinja2.

    : a template engine for the Python programming language. It’s the software that takes the mix of HTML and Python and renders it down to just HTML which is then sent to the user.

    hashtag
    Inheritance

    There's no reason to write every page used in your app on separate html files. Templating allows us to extend or start from a base file that has all the nav bar and footer stuff we need. This is a type of inheritance and it's pretty neat.

    hashtag
    Static Assets

    Static assets are your images and CSS files and other stuff that doesn't get run like code and have to get served up to your users. We'll find ways of making this process go fast.

    Changing Background Colors in Code.
    Logo

    4-B: 2048

    Learning Targets

    • I can create and initialize 2D arrays of primitives.

    • I can traverse 2D arrays using nested loops in both row-major and column-major order.

    • I can implement algorithms that operate on entire rows or columns.

    6: Visualize Your App

    hashtag
    Expectations

    If you don't start visualizing things before you're knee-deep in code, your product will lack a cohesive visual style and an intuitive workflow. Building an app starts with colors, logos and most importantly, .

    hashtag

    10: Deployment

    Publish your Flask app to a web server. This is a challenging process often with unique challenges for every app. We'll get there.

    We’re going to use Digital Ocean to host our app. I also considered Heroku. If we were better with Docker, I’d also consider using Azure or Google Cloud. So don’t be afraid to look around at other options besides the stuff I spell out here. You really can figure this stuff on your own and chart a different path if you're willing to grind it out

    hashtag
    Initial Server Setup

    Game 6 Highlights

    hashtag
    Due to time, we will cover the following:

    • Platformer Movement (Video 1)

    # the range command will build a list you can traverse
    for x in range(5):
        print(x)
        
    # you could also write it using a literal list:
    for x in [0, 1, 2, 3, 4]:
        print(x) 
    def magic_spell(target):
        target.sneeze()
    
    # let's make Steve sneeze
    magic_spell(steve)
    class Player(object):
        
        def magic_spell(self, target):
            target.sneeze()
            
    lucy = Player()
    steve = Player()
    lucy.magic_spell(steve)
    
    # fun fact: you could also write line 8 like so:
    Player.magic_spell(lucy, steve)
    from turtle import Turtle
    
    class SuperTurtle(Turtle):
      
      def __init__(self, x, y, color='blue', shape='turtle'):
        Turtle.__init__(self) # run the normal Turtle constructor
        self.color(color)
        self.shape(shape)
        self.penup()
        self.goto(x,y)
    # here's where we imported the Turtle class from the turtle package
    from turtle import Turtle
    # now from the random package, we imported to helpful functions
    from random import randint, choice
    
    def rancolor():
      """ This method returns a string from a list of colors available to Turtle's .color() method """
      colors = ["brown", "darkorange", "maroon", "crimson", "navy", "salmon", "tomato", "khaki", "gold", "hotpink", "springgreen", "blue", "cyan", "purple", "green", "red", "pink", "yellow", "teal"]
      return choice(colors)
    
    
    class SuperTurtle(Turtle):
      # our own constructor that makes Turtles more convenient
      def __init__(self, shape='turtle'):
        Turtle.__init__(self)
        self.color(rancolor())
        self.shape(shape)
        self.penup()
        self.speed(9999)
        self.goto_random()
      
      def goto_random(self):
        self.goto(randint(-200,200), randint(-200,200))
        
      # HERE'S WHERE WE WILL ADD MORE METHODS
      def triangle(self):
        pass # replace pass with real code
    
      def square(self):
        pass # replace pass with real code
        
      def star(self):
        pass # replace pass with real code
      
    
    # create a collection for our turtles
    gang = []
    
    # loop through a set range of 20 and 
    # add a Turtle to our collection during each iteration   
    for x in range(20):
      gang.append(SuperTurtle())
      
    # loop through my gang and change each one
    for x in gang:
      x.shape("triangle")
    if "circle" in user_input:
        tina.circle()
    elif "triangle" in user_input:
        tina.triangle()
    <div class="container">
      <!-- Your content goes here -->
    </div>
    <div class="container">
      <div class="row">
        <!-- Columns go here -->
      </div>
    </div>
    <div class="container">
      <div class="row">
        <div class="col-md-6">
          <p>This takes up half the row (6 out of 12 columns)</p>
        </div>
        <div class="col-md-6">
          <p>This takes up the other half (6 out of 12 columns)</p>
        </div>
      </div>
    </div>
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Bootstrap C-R-C Example</title>
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
      <!-- Container -->
      <div class="container">
        
        <!-- Row 1: Header -->
        <div class="row">
          <div class="col-12">
            <h1>My Website Header</h1>
          </div>
        </div>
        
        <!-- Row 2: Main content and sidebar -->
        <div class="row">
          <div class="col-md-8">
            <h2>Main Content Area</h2>
            <p>This is where your main content would go.</p>
          </div>
          <div class="col-md-4">
            <h3>Sidebar</h3>
            <p>This is a sidebar with additional information.</p>
          </div>
        </div>
        
        <!-- Row 3: Footer -->
        <div class="row">
          <div class="col-12">
            <footer>© 2024 My Website</footer>
          </div>
        </div>
        
      </div>
    </body>
    </html>
    PictureTester.java
            //A5
            testKeepOnlyBlue();
            testKeepOnlyRed();
            testNegate();
            testGrayscale();
            testFixUnderwater();
            //A6
            testMirrorVertical();
            testMirrorVerticalRightToLeft();
            testMirrorHorizontal();
            testMirrorHorizontalBotToTop();
            testMirrorDiagonal();
            //A7
            testMirrorArms();
            testMirrorGull();
            //A8
            testCollage();
            //A9
            testEdgeDetection2();
    NumGroup.java
    public interface NumGroup {
        
        /**
         * Provides a total sum of its contained numbers
         * @return accumulated total
         */
        int sum();
    
        /**
         * Organizes its contained numbers to be sorted from least to great
         * using the selection sort algorithm
         */
        void sort();
    
        /**
         * Rearranges its contained numbers using the selection shuffle algorithm
         */
        void shuffle();
    
        /**
         * Displays the contained numbers in a returned string
         * @return formatted String display
         */
        String toString();
        
    }
  • I can manipulate array contents by shifting, merging, or transforming values.

  • hashtag
    From Pictures to Grids

    In the PicLab project, you worked with 2D arrays of Pixel objects to manipulate images. Each pixel had a location (row, column) and properties like color. Now we're going to work with 2D arrays of primitives—specifically integers—to represent game boards, data tables, and other grid-based structures.

    The concepts are similar:

    • PicLab: A 2D array where each cell holds a Pixel object

    • Grid games: A 2D array where each cell holds an integer representing game state

    The difference? Instead of calling methods on Pixel objects, we'll be performing calculations and comparisons directly on integer values.

    hashtag
    Understanding 2D Arrays

    A 2D array is like a table with rows and columns. Think of a classroom seating chart, a chess board, or a spreadsheet—any time you have data organized in a grid, a 2D array is a natural fit.

    hashtag
    Declaration and Initialization

    Here's how you create a 2D array:

    Important terminology:

    • grid.length gives you the number of rows (3 in the scores example)

    • grid[0].length gives you the number of columns (4 in the scores example)

    • grid[row][col] accesses the element at that position

    hashtag
    Visualizing 2D Arrays

    Let's say you have this array:

    To access the value 30, you'd use numbers[2][3].

    Think of it this way: The first index is "which row?" and the second index is "which seat in that row?"

    hashtag
    Traversing 2D Arrays

    The most fundamental skill with 2D arrays is visiting every cell. You do this with nested loops.

    hashtag
    Row-Major Traversal

    This is the most common pattern—go through each row, and for each row, visit every column:

    Pattern: Outer loop controls rows, inner loop controls columns.

    hashtag
    Column-Major Traversal

    Sometimes you need to process by columns instead. For example, finding the highest score in each subject:

    Pattern: Outer loop controls columns, inner loop controls rows.

    This is crucial: Notice how the indices swap. When traversing by column, scores[row][col] still uses row first, but your outer loop is the column counter.

    hashtag
    Common 2D Array Patterns

    hashtag
    Finding Values

    Let's say you want to find if a specific value exists in the grid:

    Or find the location of the maximum value:

    hashtag
    Collecting Matching Cells

    Sometimes you need to find all cells that meet certain criteria. For example, finding all empty cells in a game board:

    Pattern: Use an ArrayList to accumulate results, storing coordinates as int[] arrays.

    hashtag
    Operating on Rows vs Columns

    Many grid-based algorithms need to process entire rows or columns as units. This is where things get interesting.

    hashtag
    Processing a Single Row

    Let's say you want to shift all non-zero values in a row to the left:

    Example: [0, 3, 0, 5, 0, 2] becomes [3, 5, 2, 0, 0, 0]

    hashtag
    Processing a Single Column

    The same operation on a column requires careful index management:

    Notice the difference: When working with rows, col changes but row is fixed. When working with columns, row changes but col is fixed.

    hashtag
    Processing All Rows or Columns

    Once you can process a single row or column, you can loop through all of them:

    hashtag
    Advanced Pattern: Merging Adjacent Values

    A common requirement in grid games is merging adjacent equal values. Here's how you might merge adjacent matching numbers in a row:

    Example: [2, 2, 4, 4, 0, 0] becomes [4, 8, 0, 0, 0, 0]

    This pattern of compress → process → compress is very common in grid manipulation algorithms.

    hashtag
    Putting It All Together

    When working with 2D arrays in games or simulations, you typically:

    1. Initialize the grid with starting values

    2. Implement row/column operations as helper methods

    3. Apply operations based on user input or game rules

    4. Check win/loss conditions by traversing the grid

    5. Update display by traversing and rendering

    The key skills are:

    • Traversing correctly (row-major vs column-major)

    • Keeping indices straight (row first, then column)

    • Operating on rows vs columns (which index is fixed?)

    • Using helper methods to break complex operations into steps

    hashtag
    2048 Project

    You're now ready to build a fully functional 2048 game! In this project, you'll:

    • Manage a 4x4 grid of integers representing tiles

    • Implement sliding and merging logic for all four directions (up, down, left, right)

    • Add random tiles after each move

    • Check for win conditions (reaching 2048) and game over (no valid moves)

    • Handle complex array manipulation with multiple passes

    The game combines everything you've learned about 2D arrays:

    • Creating and initializing grids

    • Traversing by rows and columns

    • Operating on entire rows or columns

    • Checking conditions across the board

    • Modifying arrays in place

    You'll get a GitHub Classroom link to set up the project. The repository includes a complete game GUI, and your job is to implement the core game logic. The README provides detailed guidance on each method you need to write, along with the algorithms and patterns to use.

    This is one of the most satisfying projects in the course—when your move methods work correctly and you see the tiles sliding and merging on screen, you'll have built a real, playable game using fundamental CS concepts!

    Good luck! 🎮

    // Create a 4x4 grid of integers, all initialized to 0
    int[][] grid = new int[4][4];
    
    // You can also initialize with values
    int[][] scores = {
        {90, 85, 88, 92},
        {78, 91, 84, 87},
        {95, 89, 93, 90}
    };
    int[][] numbers = {
        {2, 4, 6, 8},
        {1, 3, 5, 7},
        {10, 20, 30, 40}
    };
    ```
    
    You can visualize it as:
    ```
         col0  col1  col2  col3
    row0:  2    4     6     8
    row1:  1    3     5     7
    row2:  10   20    30    40
    public void printGrid(int[][] grid) {
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                System.out.print(grid[row][col] + " ");
            }
            System.out.println();  // New line after each row
        }
    }
    public void printColumnTotals(int[][] scores) {
        for (int col = 0; col < scores[0].length; col++) {
            int total = 0;
            for (int row = 0; row < scores.length; row++) {
                total += scores[row][col];
            }
            System.out.println("Column " + col + " total: " + total);
        }
    }
    public boolean contains(int[][] grid, int target) {
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == target) {
                    return true;
                }
            }
        }
        return false;
    }
    public int[] findMax(int[][] grid) {
        int maxRow = 0;
        int maxCol = 0;
        int maxValue = grid[0][0];
        
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] > maxValue) {
                    maxValue = grid[row][col];
                    maxRow = row;
                    maxCol = col;
                }
            }
        }
        
        return new int[]{maxRow, maxCol};  // Return coordinates
    }
    public ArrayList<int[]> findEmptyCells(int[][] board) {
        ArrayList<int[]> empty = new ArrayList<>();
        
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[row].length; col++) {
                if (board[row][col] == 0) {
                    // Store coordinates as an array
                    empty.add(new int[]{row, col});
                }
            }
        }
        
        return empty;
    }
    public void compressRow(int[][] grid, int row) {
        int writePos = 0;  // Where to write the next non-zero value
        
        // Collect all non-zero values
        for (int col = 0; col < grid[row].length; col++) {
            if (grid[row][col] != 0) {
                grid[row][writePos] = grid[row][col];
                writePos++;
            }
        }
        
        // Fill remaining positions with zeros
        while (writePos < grid[row].length) {
            grid[row][writePos] = 0;
            writePos++;
        }
    }
    public void compressColumn(int[][] grid, int col) {
        int writePos = 0;
        
        // Collect all non-zero values
        for (int row = 0; row < grid.length; row++) {
            if (grid[row][col] != 0) {
                grid[writePos][col] = grid[row][col];
                writePos++;
            }
        }
        
        // Fill remaining positions with zeros
        while (writePos < grid.length) {
            grid[writePos][col] = 0;
            writePos++;
        }
    }
    // Compress all rows to the left
    public void compressAllRowsLeft(int[][] grid) {
        for (int row = 0; row < grid.length; row++) {
            compressRow(grid, row);
        }
    }
    
    // Compress all columns upward
    public void compressAllColumnsUp(int[][] grid) {
        for (int col = 0; col < grid[0].length; col++) {
            compressColumn(grid, col);
        }
    }
    public void mergeRow(int[][] grid, int row) {
        // First compress to remove gaps
        compressRow(grid, row);
        
        // Then merge adjacent equal values
        for (int col = 0; col < grid[row].length - 1; col++) {
            if (grid[row][col] != 0 && grid[row][col] == grid[row][col + 1]) {
                grid[row][col] *= 2;      // Double the value
                grid[row][col + 1] = 0;   // Clear the merged cell
            }
        }
        
        // Compress again to remove new gaps
        compressRow(grid, row);
    }
    .
  • Use SSH (on Mac) or PuTTyarrow-up-right (on Windows) to connect to your robot. Install PuTTy if it is not on your computer.

  • Open putty and enter the ip address of your robot. Click open.

    • login: pi

    • password: robots1234

  • Remove the Piggy folder if it's already there: rm -rf Piggy

  • Now we'll clone your project on the robot too with git clone https://github.com/YOURUSERNAME/Piggy

  • Change to your project folder: cd Piggy

  • Run the app: python3 student.py

  • If it doesn't run, study the error.

  • - turns relative to it's current heading. Positive values rotate right and negative rotate left
  • fwd - powers on your robot to drive forward. You'll need to use self.stop() to power off the motors

  • right - by default, self.right() will give the left motor 90% power and the right 0% which rotates right. You can use kwargs to adjust the power such as self.right(primary=90, counter=-90), which will spin the robot in place

  • left - same as right but reversed.

  • back - same as fwd but in reverse.

  • servo - moves the servo (plugged into servo1) to the given value (use 1000 - 2000)

  • stop - sets motor power to zero

  • read_distance - returns the distance from the distance sensor (plugged into I2C port) in millimeters

  • get_heading - returns the gyroscope's value

  • Move to wall and stop
  • Move to wall and turn around. Move forward again and repeat endlessly.

  • Move to box and go around it

  • Before moving around box, figure out which side of closer. If you are closer to the left end of the box, go around left. If you are closer to the right end of the box, go around to the right.

  • project arrow-up-right
    magic numberarrow-up-right
    Jumbled, unengaging, or unorganized content
  • Clutter

  • Large, medium and small file types
  • Original .ai files as well as exported versions

  • Reversed colors for dark backgrounds as well as light backgrounds

  • heroarrow-up-right
    this articlearrow-up-right
    Examplearrow-up-right
    types of imagesarrow-up-right
    faviconarrow-up-right
    GraphicRiverarrow-up-right
    Serifs helped printers stamp ink onto the page
    Let's start by picking colors that match our intended mood
    There's an irony here
    Is this a happy or a sad picture? There are more frowns than smiles but it still feels happy
    Notice this picture has a thick border around it unlike any other?
    Metro style is angular, often monochromatic

    b / a will give 2

    % (Modulus)

    Divides left-hand operand by right-hand operand and returns the remainder.

    b % a will give 0

    ++ (Increment)

    Increases the value of operand by 1.

    b++ gives 21

    -- (Decrement)

    Decreases the value of operand by 1.

    b-- gives 19

    a>b

    false

    <

    Less than

    a<b

    true

    >=

    Greater than or equal to

    a>=b

    false

    <=

    Less than or equal to

    a<=b

    true

    Operator

    Description

    Example (a=10, b=20)

    + (Addition)

    Adds values on either side of the operator.

    a + b will give 30

    - (Subtraction)

    Subtracts right-hand operand from left-hand operand.

    a - b will give -10

    * (Multiplication)

    Multiplies values on either side of the operator.

    a * b will give 200

    / (Division)

    Operator

    Description

    Example (a=10, b=15)

    Result

    ==

    Equality operator

    a==b

    false

    !=

    Not Equal to operator

    a!=b

    true

    >

    types of Java primitivesarrow-up-right
    The main function is calling max(), passing it a few numbers and saving the result
    The variable declared in the header is scoped to that function

    Divides left-hand operand by right-hand operand.

    Greater than

    Template: HTML with bits of {{ python }}. It's not just a regular HTML page. Python will render this so we can respond to different conditions. For example, if a user is logged in we can so the "Logout" button but if not, we show the "Login" button. Careful though, avoid putting too much logic here.
    their design patternsarrow-up-right
    Model-View-Controller:arrow-up-right
    ER Diagrams/UMLarrow-up-right
    Association Tablearrow-up-right
    ORMarrow-up-right
    SQL Alchemyarrow-up-right
    Migrationarrow-up-right
    Routearrow-up-right
    Flask Sessionarrow-up-right
    Renderarrow-up-right
    Jinja2 Templatearrow-up-right
    (image taken from djangobook.com)
    Learning Targets
    • I can develop a brand identify for my product including logos, color pallets, fonts, and tone of voice.

    • I can outline the workflow of my app in a wireframe.

    Setup a local folder using something like Google Drive to collaborate with your team. Download a theme. Start a PowerPoint or Google Slides document to take notes, build a scrapbook of visual designs that can help you shape the message you’re trying to send.

    hashtag
    Select a Theme

    Rather than design our own HTML layout and polish the finer details and effects, we’re going to use a theme. We’ll look at paid themesarrow-up-right and free themesarrow-up-right. You must make sure your theme is based on Bootstraparrow-up-right, preferably the most recent version. You want to make sure that the theme has a variety of elements and layouts that will allow you to mockup pages quickly.

    circle-info

    For rapid prototyping, don't be afraid of using Flaskinni's default theme. Proving your app concept with a pleasant, neutral design is smart.

    hashtag
    Custom layer

    Never make changes to theme.css, style.css or whatever your file is called that governs the primary rules of your theme. We will override the rules using different files. That way we can more easily upgrade the theme in the future. The custom.css file (that hopefully you're using Sassarrow-up-right to produce) in our <head> after the theme’s CSS. That way, our rules will overwrite the theme’s. We’ll have the final say.

    hashtag
    Change base.html

    Implementing a new theme is tricky business. You'll have to rebuild your static assets and modify all the templates. The base.html file will need the most amount of work as it will need to reflect We talk about that more next chapter.

    hashtag
    The Brand

    Building your app, your team, and your company requires a lot of drive. A brand identity is a flag on a battlefield for your soldiers to rally.

    Bajirao Mastani is a metaphor for the rallying effect of a brand

    hashtag
    Colors

    Go to the websites of some major brand names you know and look at the colors used. If you did deep enough, you'll find a variety of button colors, but most things follow a pretty consistent pattern. It's time to set up such a pattern inside our CSS.

    • http://coolors.coarrow-up-right These palettes can help you color your logo

    • https://color.adobe.com/create/color-wheel/arrow-up-right expand the 5 colors you get from coolors

    • https://colors.eva.design/arrow-up-right Eva will help you fill in any gaps on the standard Bootstrap colors (primary, success, info, warning, danger)

    • When in doubt, use Flat design

    hashtag
    Sass

    Hopefully you have a _variables.scss file where you can drop all your color palette. Many themes include these assets. Flaskinni's default theme comes from startbootstraparrow-up-right so you can take advantage of the Sass structurearrow-up-right to quickly implement your colors.

    circle-exclamation

    If you're using SourceLair, you may need to upgrade Sass so it can handle recent Bootstrap templates. So first run npm install -g sass so you can then run: sass app/static/scss/custom.scss:app/static/css/custom.min.css

    The code below are example MacOS settings for the Live Sass Compiler extension for VS Code.

    hashtag
    Fonts

    You'll need a header and a body font at least. Sometimes a logo font is used as the headers, sometimes not. You may want to pick out your logo first and then find complementary fonts afterwards.

    http://fonts.google.comarrow-up-right

    hashtag
    Logo

    Start sketching ideas on your branding document. It can be very powerful to have a logo designed early in project development as it sets styles, colors and gives you something to reference when discussing your project.

    http://graphicriver.netarrow-up-right

    hashtag
    Stock Images

    http://allthefreestock.com/arrow-up-right

    Shutterstock.com -- start building collections of images you might want to use

    Add images to your branding document. Scrapbook images that you don’t intend or are unable to buy and use but speak to the type of look and feel you want (or want to avoid). Have a different section for images that you may want to purchase and use later on. Free images you can start to download and organize into your team’s project folder. Paid images you can start to save in bookmarks, links on your slides, or in other ways.

    hashtag
    Wireframes

    The wire-framing that needs to be added to your branding document is essentially just shapes illustrating what your app can do. You could use Google Slides in a real hurry. Ideally though, you should use the wire-framing process not only to determine all the steps your users will need to take, but also how you'll organize the interface. You're making UI decisions as well as UX.

    I try to start by first looking through the pages that come with my HTML theme and see what sort of layout, widgets and objects are readily accessible. Keep them in mind when designing your wire-frames. After this early phase, we will be building full HTML mockups to illustrate these wire-frames.

    hashtag
    HTML mockups

    Building HTML mockups is much, much slower than Adobe XD. You ought to sketch out your apps before you code HTML elements. But designing the HTML elements using the theme assets you'll have in production takes you from planning the outline of the user experience (UX) to the mechanics of the actual interface (UI).

    Before you advance, be sure you’re making steady progress through the Flask Udemy course (and getting help when stuck)

    arrow-up-right

    wireframesarrow-up-right
    Register a domain and point your domain’s to DigitalOcean’s nameservers: https://www.digitalocean.com/community/tutorials/how-to-point-to-digitalocean-nameservers-from-common-domain-registrars arrow-up-righthttps://www.digitalocean.com/community/tutorials/an-introduction-to-digitalocean-dnsarrow-up-right
  • Setup your server’s basic settings: https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-18-04arrow-up-right This includes our ufw firewall: https://www.digitalocean.com/community/tutorials/how-to-setup-a-firewall-with-ufw-on-an-ubuntu-and-debian-cloud-serverarrow-up-right. Don't forget to disable root ssh login.

    1. Setup python (check on your version of ubuntu). You're not trying to get a demo app online, we're mostly using commands like sudo apt install python3.7-dev: https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-programming-environment-on-ubuntu-18-04-quickstartarrow-up-right Make sure we have the basics for our database (install, install, install!): https://stackoverflow.com/questions/28253681/you-need-to-install-postgresql-server-dev-x-y-for-building-a-server-side-extensiarrow-up-right

    2. Once you get your venv activated, don't forget pip install --upgrade pip wheel

  • Install and configure nginx, your webserver (remember the overview from the beginning of classarrow-up-right): https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-16-04 arrow-up-right-[ at this point you should be able to go to http://your-domain and see a blank, nginx page ]-

  • hashtag
    Deploying Your App

    Update your git repository and your requirements.txtarrow-up-right (video guidearrow-up-right). We’ve got to package your app ready to ship. Calling the deployment of software “shipping” is really cool and people think you’re cool when you say it. So instead of "setting up my app on a remote server" we can say, "shipping a new version." Nice.

    Pull your app’s repo and setup your dependencies before serving up your app: https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04arrow-up-right Notes to complement the Digital Ocean guide:

    • If admin rights are needed, you may need a command like this: sudo -H /home/myuser/venv/bin/python -m pip install -r requirements.txt

    • My wsgi.py file:

      from myapp import app if __name__ == "__main__":

      app.run(host='0.0.0.0')

    • There are many critical files in this process, but the one that ties them all together is: sudo nano /etc/systemd/system/flaskinni.service

    hashtag
    App deployment is tricky. You'll need some help tracking down problems:

    Helpful articles if you’re running into some trouble: https://stackoverflow.com/questions/39937071/uwsgi-configuration-with-flaskapparrow-up-right

    I use sudo cat /var/log/syslog frequently to see the errors being reported by the uWSGI service and use sudo less /var/log/nginx/error.log to see the errors just from nginx (they'll otherwise be mixed in with the syslog)

    If everything is working up to this point, your project will load a 500 error. Track down the error and it should be reporting that the connection to the database has failed.

    hashtag
    Service

    sudo nano /etc/nginx/sites-available/myproject

    sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

    hashtag
    Database

    Setup postresql on your serverarrow-up-right (adjust to the version of Ubuntu you're using)

    Postgres starts with a super user with the somewhat unoriginal name of postgres. You can use your admin powers to switch to that user by typing sudo -iu postgres and now you can use psql and you'll have full control to setup a new user. Read up on how to add a new user in psql. The lazy, slightly dangerous way is to createuser -P -s -e user_name Once you've created your user in psql, update your .env file with the user and password.

    We've got to test to make sure your database user can log into the database you've created. If your database user also exists in Linux, you can do the same sudo -iu trick we did before and then open up psql. This command will allow you to be more specific: psql user_name -h 127.0.0.1 -d db_name

    You may end up using ALTER USER user_name WITH PASSWORD 'new_password'; from the postgres user.

    hashtag
    Security

    Change the passwords and hash codes used in .env and remember that changes to secret keys or salt could break passwords currently saved in your database. For random strings to use as secret keys for apps, use a line of code like this to make one:

    1. Secure your HTTP connection: https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04 arrow-up-rightsudo apt install python-certbot-nginx sudo certbot --nginx -d mysite.net

    2. Practice deploying updates. Add, commit, and push from your development environment and pulling over SSH. Make a change to the database and use migrations to update your models without losing data.

      1. Making changes to your application

        1. After building a cool new feature on Cloud9

          1. git add .

          2. git commit -m “fixed the thing”

      2. If you modified any db.Column then, you need to track that migration on . Reading the is how you can best safeguard your users’ data.

    3. Get ready to handle errors:

      1. is an awesome tool to get notifications of any error happening on your server

    hashtag
    Error Reporting

    Importing Sprite Sheets (Video 1)
  • Enemy Movement & Paths (Video 2)

  • Tile Sets (class and video 3)

  • Big Room with a follow view (class and video 3)

  • hashtag
    Platformer Movement Script

    hashtag
    Animation Control

    hashtag
    Enemy Move

    hashtag
    Jump Attack

    hashtag
    Resources

    Mario Sprite Sheetarrow-up-right

    Enemy Sprite Sheetarrow-up-right Flying Enemy Sprite Sheetarrow-up-right

    Mario Tilesetarrow-up-right

    CodePencodepen.iochevron-right
    We'll build a practice page together in class using CodePen
    Flexbox Froggyflexboxfroggy.comchevron-right
    Replit – Build apps and sites with AIreplitchevron-right
    GitHub · Change is constant. GitHub keeps you ahead.GitHubchevron-right
    https://replit.com/teams/join/hgeffnguajivskqklikdnrmvtzpeffxb-intro-to-programming-2023replit.comchevron-right
    This is probably woefully out of date by now.
    Logo
    You may have different things to fix than shown in this video, but I hope it shows the process to follow
    loading.io - Your SVG + GIF + PNG Ajax Loading Icons and Animation Generatorloadingiochevron-right
    Don't have a loading GIF? Use this and give them credit in your code!

    1-B: How Java Works

    We will review the basics of object-oriented programming and how Java is configured. This is primarily a build-up of vocabulary. This unit moves quickly as there are limited practical applications.

    hashtag
    Learning Targets

    • I can describe the benefits of using the JRE.

    3-C: Data Science

    Using custom objects to bring life to each row in a spreadsheet

    hashtag
    Learning Targets

    • I can create a class to represent a row of real-world data.

    X: Inheritence

    We introduce our first complex algorithms and start to pull back the scaffolding a bit. Students will get their first real experience designing aggregate objects with encapsulated properties.

    hashtag
    Learning Targets

    • I can secure my class variables with encapsulation.

    1: Core Concepts

    hashtag
    Expectations

    Slow down. Get your head around these ideas before we lean into the code. Being able to come back and reference these terms as they come up will help you put the whole puzzle together.

    7: Theme & Blueprint

    hashtag
    Expectations

    During this phase of your project, you can implement a new cosmetic layer. This will help setup the visual tone of your project while buying us some more time while we learn fundamentals. We will also add a new folder inside app/ that will store your routes

    The great Richard Feynman addresses acceptable levels of abstraction, though he doesn't call it such
    /**
    
    COLORS
    https://coolors.co/05a8aa-b8d5b8-d7b49e-dc602e-bc412b
    Blue: 05a8aa
    Green: b8d5b8
    Red: bc412b
    Orange: dc602e
    
    **/
    // Let's demonstrate some array skills!
    
    // Here's a blank array that's got spots for five ints
    int[] arr = new int[5]; 
    
    // You can also create an array with initial values
    int[] x = {5, 10, 15}; 
        // add to your settings.json file in VSCode if you choose to liveSassCompile
        "liveSassCompile.settings.includeItems": [
            "/app/static/scss/custom.scss"
        ],
        "liveSassCompile.settings.generateMap": false,
        "liveSassCompile.settings.formats":[
            {
                "format": "compressed",
                "extensionName": ".min.css",
                "savePath": "/app/static/css/"
            }
        ]
    /etc/nginx/sites-available/myproject
    server {
        server_name flaskinni.org www.flaskinni.org;
    
        location / {
            include uwsgi_params;
            uwsgi_pass unix:/home/yourname/myproject/flaskinni.sock;
        }
    
        location /static {
            alias /home/yourname/myproject/app/static;
            expires 2d;
        }
    
        gzip on;
        gzip_vary on;
        gzip_min_length 10240;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css text/xml text/javascript application/x-javascript a$
        
    }
    import random, string
    ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(40))
    // Run This Function in END STEP event
    /*
     INSTRUCTIONS: 
     This function requires passing in arguments playerSpeed (not hspeed or speed) 
     and a gravity value.
     
     You should also make an optional argument maxFall with a value of 15
     
     In addition, you need to have two variables in the create event
     of your object:
     
         jumpSpeed = 0
         canJump = true
    	 
    optional:  Jumping variable (needed in create if you are going to have
    		   a jumping animation (controlled in step).
    
    */
    
    
    
    /*********************/
    /*Horizontal Movement*/
    /*********************/
    
    var move = -keyboard_check(vk_left) + keyboard_check(vk_right);
    var collision = instance_place(x+playerSpeed, y+vspeed, all);
    
    // You are moving right
    if (move == 1){
    	
    	if (collision < 0 or !object_get_solid(collision.object_index)){
    		x += playerSpeed;
    	}
    	
    	// Move to wall, if there is a SOLID wall to your right
    	else{  
    		move_contact_solid(0, playerSpeed);
    	}
    }
    
    // You are moving left
    else if (move == -1){
    	collision = instance_place(x-playerSpeed, y+vspeed, all)
    	if ( collision < 0 or !object_get_solid(collision.object_index)){
    		x -= playerSpeed;
    	}
    	
    	// Move to wall, if there is a solid wall to your left
    	else{
    		move_contact_solid(180, playerSpeed);		
    	}
    }
    
    
    
    /*******************/
    /*Vertical Movement*/
    /*******************/
    
    jumping = false;
    collision = instance_place(x, y - jumpSpeed, all);
    // Check to see if you are in the air or are about to jump.
    if (place_empty(x, y + 1) or jumpSpeed > 0 or (collision > 0 and !object_get_solid(collision.object_index))){
    	jumping = true;
    }
    
    // if you are jumping...
    if (jumping){
    	
    	
    	// Move up or down if there is no collision this frame.
    	if (collision < 0 or !object_get_solid(collision.object_index)){
    		y -= jumpSpeed;
    	}
    	
    	// Check for a SOLID object below you
    	else if (jumpSpeed < 0  and  object_get_solid(collision.object_index)){
    		move_contact_solid(270, jumpSpeed)
    		jumpSpeed = 0
    	}
    	
    	// Check for a SOLID object above you
    	else if (jumpSpeed > 0  and  object_get_solid(collision.object_index)){
    		move_contact_solid(90, jumpSpeed)
    		jumpSpeed = -0.1
    	}
    	jumpSpeed -= grav;
    	if (jumpSpeed < -maxFall){
    		jumpSpeed = -maxFall;
    	}
    }
    
    // If you are on SOLID ground, allow the player to jump again.
    if (!place_empty(x, y+1) and instance_place(x, y + 1, all) > 0 and object_get_solid( instance_place(x, y + 1, all).object_index)){
    	canJump = true;
    }
    var dir = -keyboard_check(vk_left) + keyboard_check(vk_right)
    
    //put your sprite names here:
    var jump_right = sMario_jumpR
    var walk_right = sMario_right
    var jump_left = sMario_jumpL
    var walk_left = sMario_left
    
    image_speed = 3
    if (dir == 1){
    	if (jumping){
    		sprite_index = jump_right;
    	}
    	else {
    		sprite_index = walk_right;
    	}
    }
    else if (dir == -1){
    	if (jumping){
    		sprite_index = jump_left;
    	}
    	else {
    		sprite_index = walk_left;
    	}
    }
    else {
    	if (!jumping and sprite_index = jump_right){
    		sprite_index = walk_right;
    	} else if (!jumping and sprite_index = jump_left){
    		sprite_index = walk_left;
    	} else if (jumping and sprite_index = walk_right) {
    		sprite_index = jump_right;
    	} else if (jumping and sprite_index = walk_left) {
    		sprite_index = jump_left;
    	}
    	image_speed = 0;
    	image_index = 0;
    }
    	
    var collision = instance_place(x+hspeed, y+vspeed, all);
    var collisionBelowRight = instance_place(x+hspeed+sprite_width, y+1, all)
    var collisionBelowLeft = instance_place(x+hspeed-sprite_width, y+1, all)
    
    if (hspeed > 0){
    	if (place_empty(x+hspeed+sprite_width, y+1) or
    	   (collision >-0 and object_get_solid(collision.object_index)) or
    	   (!place_empty(x+hspeed+sprite_width, y+1) and collisionBelowRight > 0 and object_get_solid(collisionBelowRight.object_index) == false )){
    		hspeed = -hspeed;
    	}
    }
    else if (hspeed < 0){
    	if (place_empty(x+hspeed-sprite_width, y+1) or 
    	   (collision >-0 and object_get_solid(collision.object_index)) or
    	   (!place_empty(x+hspeed-sprite_width, y+1) and collisionBelowLeft > 0 and object_get_solid(collisionBelowLeft.object_index) == false )){
    		hspeed = -hspeed;
    	}
    }
    if (y < other.y and jumpSpeed <= 0){
    	instance_destroy(other)
    } 
    else {
    	instance_destroy(self)	
    }
    Logo

    git push origin master

  • Then SSH to your server, navigate to your folder and git pull origin master

  • your dbarrow-up-right
    Flask-Migrate documentationarrow-up-right
    http://flask.pocoo.org/docs/1.0/errorhandling/arrow-up-right
    Sentry.ioarrow-up-right

    I can identify the three types of errors when programming.

  • I can describe the attributes of Java’s main function, including scope, instantiation, and return value.

  • hashtag
    Java is Portable

    Java's strength is also its greatest weakness. The JVM allows the same Java code to run on almost any machine. It does this by hosting a virtual machine, a simulated computer system that facilitates the interpretation of your code.

    We use the JDK so the JVM and its JIT will show us our code in the final result we call the JRE.

    hashtag
    Respect to Dennis Ritchie

    With his partner Ken Thompson, Dennis Ritchie solved a very big program for programmers. It's hard enough for programmers to design an app. It's just crazy if you have to program an app in assembly, telling the CPU and RAM how to handle each and every little operation. Programming languages like Ritchie's C allow coders to focus more on the app and less on how it has to interact with the machine. It's like the first, really powerful book of spells made for magicians.

    If you'd like to learn more about the history of Computer Science, I found this videoarrow-up-right to be very charming.

    hashtag
    Just in Time

    When you install an app on your computer, the JIT will interpret the developer's code and set it up to run on the given machine. The install process takes longer and it might not be compatible with every machine, but then the app is ready to run very quickly. Java doesn't play like that. Instead, it interprets the code in real-time while running through a virtual machine. So while it can run pretty much everywhere, there's a bottleneck in how fast it can perform.

    hashtag
    Extra Information

    Who made the Java programming language? When and why? Check it outarrow-up-right.

    hashtag
    Editing Code

    The JDK is a type of SDKarrow-up-right. We'll use tools to build apps like an IDEarrow-up-right and an interpreterarrow-up-right. We're going to have lots of bugs or errors in our code. They will take three different forms...

    hashtag
    Three types of errors

    1. Syntax or Compile-time: You can't compile this code. Something is way off and Java won't touch your mess.

    2. Runtime or crash: Something breaks while it's running as if you asked the computer to divide a number by zero.

    3. Logic: Everything runs okay. Nothing crashes. However, the answer you get is just wrong. If your app says 4+4 is 10, you've got a logic error.

    hashtag
    Java's Code Structure

    In Java, all code must be written inside methods, and all methods belong to a class. This means that every Java program is essentially a collection of classes, each containing methods that define the behavior of your program.

    • Classes must be defined inside a file that shares the exact same name as the class. For example, if your class is called MyProgram, then the file must be named MyProgram.java.

    • The entry point of every Java program is the main method, which tells Java where to begin executing your code.

    circle-info

    Exceptions

    While every class usually matches its file name, there are a few exceptions:

    • You can define inner classes within another class.

    • Files may contain more than one class, but only one can be public and match the file name.

    hashtag
    Java's Main Method

    Every Java app starts the same way, from a static method that returns nothing. Let's introduce these concepts now. Many of these ideas will seem strange, but they'll make more sense as you build up your background knowledge. You'll come back to this section later on and smile. But for right now, let's take a plunge into the deep end of the pool. We'll hurry right back to the basics but let's take a peek at how all Java apps start. public static void main(String[] args){} <=[ all Java apps start from that method! ]

    hashtag
    Scope

    Who can access this method or this variable? The main method must always be public because it's being triggered from outside the class.

    hashtag
    Instantiation

    Does this method belong to an instance of the class? What's the difference between an instance and a static class? Imagine we're building a game. We've got one file or class that describes a player and another that has helpful functions like drawing a random number. Every person that plays the game gets their own instance of the player class. It tracks each player's health and abilities in the computer's memory. But the helper class can be static, just one master copy--no instance needed.

    hashtag
    Return Type

    As the method closes, does it return anything? If so, what type of data is returned? The main method must always return void because it's the point of origin--there's nothing to return data to.

    hashtag
    Install

    Version control is essential for tracking changes in your code and collaborating on projects. We'll install Git command line tools first, then GitHub Desktop for a user-friendly interface.

    hashtag
    1. Git and GitHub Desktop

    hashtag
    For Windows Users

    Installing Git for Windows

    1. Visit git-scm.comarrow-up-right

    2. Download the latest version for Windows

    3. Run the installer with these recommended settings:

      • Use Visual Studio Code as Git's default editor

      • Use Git from the command line and also from 3rd-party software

      • Use the OpenSSL library

      • Checkout Windows-style, commit Unix-style line endings

      • Use Windows' default console window

    4. Complete the installation

    Verify Git Installation:

    1. Open Command Prompt

    2. Type: git --version

    3. You should see the Git version number

    hashtag
    For Mac Users

    Installing Git via Xcode Command Line Tools

    1. Open Terminal (Applications > Utilities > Terminal)

    2. Type: git --version

    3. If Git isn't installed, macOS will prompt you to install developer tools

    4. Click "Install" and follow the prompts

    5. Wait for the installation to complete (this may take several minutes)

    Verify Git Installation:

    1. In Terminal, type: git --version

    2. You should see the Git version number

    hashtag
    GitHub Desktop Installation (Both Platforms)

    Now that Git is installed, we'll add GitHub Desktop for an easier graphical interface:

    1. Visit desktop.github.comarrow-up-right

    2. Download GitHub Desktop for your operating system (Windows or Mac)

    3. Install the application

    4. Launch GitHub Desktop

    5. Sign in with your GitHub account (create one at if needed)

    6. Complete the initial setup wizard

    hashtag
    Configure Git Settings

    1. Open Command Prompt (Windows) or Terminal (Mac)

    2. Configure Git with your information:bash

    hashtag
    2. Java Development Kit (JDK) Installation

    The AP Computer Science A course requires Java 17 or later (Java 22 recommended). We'll provide multiple options for JDK installation.

    hashtag
    Option A: Eclipse Temurin (Recommended)

    Eclipse Temurin is a free, open-source JDK that's widely used in educational settings.

    For Windows:

    1. Visit adoptium.netarrow-up-right

    2. Select your operating system (Windows)

    3. Choose the latest LTS version (Java 17 or 21)

    4. Download the .msi installer

    5. Run the installer with default settings

    6. Important: Check "Set JAVA_HOME variable" during installation

    For Mac:

    1. Visit adoptium.netarrow-up-right

    2. Select macOS

    3. Choose the latest LTS version

    4. Download the .pkg installer

    5. Run the installer with default settings

    hashtag
    Option B: Oracle Java SE

    Oracle provides the official Java implementation, though it requires registration for recent versions.

    For Windows/Mac:

    1. Visit oracle.com/java/technologies/downloads/arrow-up-right

    2. Create a free Oracle account if prompted

    3. Download the appropriate installer for your operating system

    4. Run the installer with default settings

    hashtag
    3. Visual Studio Code Setup

    hashtag
    Required Extensions

    Install these extensions for optimal Java development:

    Essential Java Extensions:

    1. Extension Pack for Java (Microsoft)

      • Includes: Language Support, Debugger, Test Runner, Maven, Project Manager

      • Install this first - it includes most of what you need

    2. Code Runner (Jun Han)

      • Allows quick running of Java files with Ctrl+F5

    Helpful Additional Extensions: 3. Bracket Pair Colorizer 2 (CoenraadS)

    • Colors matching brackets for easier code reading

    1. GitLens (GitKraken)

      • Enhanced Git capabilities within VS Code

    2. Java Code Generators (Sohibe)

      • Helps generate common Java code patterns

    3. vscode-icons (VSCode Icons Team)

      • Better file icons for easier navigation

    hashtag
    Configuring Java in VS Code

    1. Open VS Code

    2. Press Ctrl+Shift+P (Cmd+Shift+P on Mac) to open the command palette

    3. Type "Java: Cofigure Java Runtime" and select it

    4. Verify that your installed JDK appears in the list

    5. If not detected automatically, manually add the path to your JDK installation

    I can parse a CSV file by splitting strings and converting data types.
  • I can write constructors that initialize multiple instance variables from parsed data.

  • I can implement utility methods that perform calculations using instance data.

  • hashtag
    Why Data Science in AP CSA?

    You've learned how to create custom classes, work with ArrayLists, and traverse collections. Now it's time to put all these skills together with real-world data. Data science is about taking raw information and extracting meaningful insights from it. In Java, we do this by:

    1. Modeling data as custom classes

    2. Reading files to populate collections of objects

    3. Analyzing data through methods that compute results

    This combination of object-oriented programming and data analysis is exactly what you'll encounter on the AP exam and in professional software development.

    hashtag
    Data Classes: Objects as Rows

    Think about a spreadsheet. Each row represents one thing (a person, a product, a measurement) and each column represents an attribute of that thing. In Java, we can model each row as an object.

    For example, imagine you're working with cereal nutrition data:

    Each line is one cereal. The columns are: name, calories, fiber, carbohydrates, and serving size in cups.

    hashtag
    Creating the Data Class

    We'll create a Cereal class where each instance represents one row:

    Let's say you read this line from a file: "100% Bran,70,10,5,0.33"

    Here's how to break it apart:

    Important: The split() method returns an array of Strings. You need to convert numeric strings to their proper types using parseInt() and parseDouble().

    hashtag
    Reading the Whole File

    To process an entire CSV file, you'll combine file reading with this parsing logic:

    Pattern to remember: Read line → Split line → Parse each part → Create object → Add to ArrayList

    hashtag
    Utility Methods: Objects Computing Their Own Results

    One of the most powerful aspects of OOP is that objects can answer questions about themselves. Instead of writing static methods that take an object as a parameter, we write instance methods that operate on the object's data directly.

    Let's switch to a different example to illustrate this concept. Imagine you're working with book sales data:

    Now let's add utility methods that let each book compute its own results:

    hashtag
    Why Write Methods Inside the Class?

    Compare these two approaches:

    Static approach (what you've done before):

    Instance method (what we're doing now):

    The instance method is:

    • Cleaner: No need to pass the object as a parameter

    • Encapsulated: Direct access to private instance variables

    • Object-oriented: The book knows how to calculate its own data

    • Reusable: Can be called on any Book object

    hashtag
    Using Utility Methods in Analysis

    Once you've added utility methods to your data class, you can write clean analysis code:

    Notice how readable this is. The logic is clear because each object knows how to compute its own values. You're not cluttering your analysis code with calculations—the Book class handles that internally.

    hashtag
    The Power of Encapsulation

    By putting these calculations inside the Book class, you get several benefits:

    1. Less repetition: Write book.totalRevenue() instead of book.getPrice() * book.getUnitsSold() everywhere

    2. Easier maintenance: If the revenue calculation changes (maybe add sales tax?), you only update it in one place

    3. Better organization: All book-related logic lives in the Book class

    4. Cleaner analysis: Your filtering and searching methods focus on logic, not arithmetic

    This is exactly what encapsulation is about—keeping related data and behaviors bundled together.

    hashtag
    Putting It All Together

    The workflow for data science in Java:

    1. Design your data class - What fields do you need? What calculations make sense?

    2. Write the constructor - Takes all the data needed to create one instance

    3. Add accessor methods - Getters for each field

    4. Add utility methods - Calculations and comparisons

    5. Parse the CSV file - Read, split, convert types, create objects

    6. Store in a collection - Usually an ArrayList

    7. Analyze the data - Filtering, finding max/min, calculating statistics

    This is the same pattern professional developers use when working with databases, APIs, and data files.

    hashtag
    Data Lab Assignment

    You're now ready to work with real-world nutritional data! In the next assignment, you'll:

    • Download authentic cereal data from Kaggle

    • Create a complete data class with multiple fields

    • Write a CSV parser that loads dozens of records into an ArrayList

    • Implement filtering and max-finding algorithms

    • Discover a data quality issue in the dataset

    The lab includes warm-up activities with live weather data using the Sinbad library, showing you how professional data scientists verify their data sources and fetch real-time information.

    You'll get a GitHub Classroom link to set up the project. Follow the detailed instructions in the README to complete each activity. This lab brings together everything you've learned in Unit 3: class creation, ArrayLists, and traversal algorithms.

    I can create a constructor to initialize an object.

  • I can override a parent method.

  • I can build unit tests for all methods in an aggregate object.

  • hashtag
    Inheritance

    circle-info

    Keep it DRY and OOP-y

    DRY stands for Don't Repeat Yourself. So far, that's meant that if you need to repeat a bit of code, you make a loop instead of sloppily copying and pasting the same commands a few times. Now we're seeing that OOP, or Object-Oriented Programming, has was to build classes off of one another. That means we can avoid repeating (aka DRY code) by using inheritance.

    hashtag
    Abstract Classes

    hashtag
    Polymorphism Practice

    Polymorphism is my favorite CS term because it sounds so much fancier than it really is (sort of a theme here). In class we'll build an abstract class called Shape with some encaspulated instance variables like length and width, abstract methods like .area(). Then we'll inherit from those methods when we create types of shapes like Circle, Rectangle, Triangle and so on. Let's look closer at why this is an example of inheritance and polymorphism.

    hashtag
    Why this is smart, object-oriented programming

    Creating a parent class called Shape that all your shapes will inherit means that the common properties and functions can live in one place. If new features or changes needed to happen across all the elements in your app, you would have a logical place to check.

    hashtag
    But why do we declare abstract methods?

    Let's take a look at a shortened Shape class:

    All the encapsulation shown between lines 3 - 14 should be familiar by now. Seek additional practice including your teacher's office hours if not. The cool new thing here is line 17. Because the parent is declaring this method, all its children (i.e class Circle extends Shape { )will have to build their own area method. The Circle class will return 3.14 * (length * length); for its area() implementation.

    hashtag
    So how exactly is this business "polymorphic?"

    Because all of my app's shapes will have a common parent, I can create a collection of Shape like: ArrayList<Shape> myShapes = new ArrayList<>();

    That allows me to to loop through the whole collection and report out their areas:

    hashtag
    Multiple Inheritance?

    What if I wanted to build a huge space game with thousands of types of ships. I'd make rules for cargo ships and warships. There may be times when I want multiple inheritances to be applied. Well there are some limits here in Java. You can have multiple vertical levels, like Ship --> Warship --> Battleship but a single ship can't inherit from two places simultaneously. Instead, there are Interfaces.

    hashtag
    Concepts to Review

    • Loops

      • Searching / counting while traversing an array and an ArrayList

        • Traverse to find max and mins: public static int findLargest(int[] nums){

        • Interact with an ArrayList

          public static void makeLowerCase(ArrayList<String> commands){

        • Keep count

          public static int countNames(ArrayList<String> names, String target){

        • Shuffle methods:

          public static void selectShuffle(int[] nums){ public static void perfectShuffle(Card[] cards){

      • Nested loops

        • Find common elements between two collections:

          public static ArrayList<String> findCommonNames(String[] roster1, String[] roster2){

    • Classes

      • Encapsulation with accessor and mutator methods

      • Implementing an abstract class (with encapsulation)

    hashtag
    Challenge

    Submit a completed NumSet class:

    hashtag
    Studying for the Test

    Your Unit 3 test will be a semi-randomized selection of multiple choice questions all taken from the same sources used for our Do Nows. There will be one free response question similar to the homework. Both of these parts of the test reflect the two portions of the AP test. Therefore, the best way to study would be to review AP practice problems from our relevant topics:

    • Redo homework assignments and previous drills

    • This site's Chapters 3-9: https://runestone.academy/runestone/books/published/apcsareview/index.htmlarrow-up-right

    • Take a practice test: http://ice.cc.gatech.edu/apexam_final/index.jsparrow-up-right

    • Do some Codingbat:

    hashtag
    Learning Target
    • I can describe a full-stack application and the tools required to build one using relevant vocabulary.

    hashtag
    What is a Stack?

    A stack is all the systems used to run an app. Usually, several computers are involved but that's not a must. Let's look at the various layers in a stack...

    Stackarrow-up-right: Web stack contains an operating system (OS), a programming language, database software and a Web server. A full-stack developer is someone capable of building an app or solution that addresses each of these components.

    Let's understand the layers by discussing the programming languages used in each.

    hashtag
    Client

    HTML and CSS:arrow-up-right This is what you see on your page. HyperText Markup Language, gives content structure and meaning by defining that content as, for example, headings, paragraphs, or images. CSS, or Cascading Style Sheets, is a presentation language created to style the appearance of content—using, for example, fonts or colors.

    JavaScript:arrow-up-right is a programming language commonly used in web development. It was originally developed by Netscape as a means to add dynamic and interactive elements to websites. It used to be used solely for client-side purposes, but now servers are running apps build using NodeJS. JavaScript has nothing to do with Java.

    ... but how do we get this HTML / CSS / JS on our client computer?

    HTTP Requestarrow-up-right: the message system that runs the World Wide Web. This is how website information is sent over the Internet. There are many different types of HTTP requests, including GET and POST, one asks for information from the server and the other submits information to the server.

    hashtag
    Web Server

    Shell/CLIarrow-up-right: In computing, a shell is a user interface for access to an operating system's services. In general, operating system shells use either a command-line interface (CLI) or graphical user interface (GUI). CLI is used to communicate to the shell in the form of text input.

    SSL Encryption:arrow-up-right (Secure Sockets Layer) is the standard security technology for establishing an encrypted link between a web server and a browser. This link ensures that all data passed between the web server and browsers remain private and integral.

    Operating System Servicearrow-up-right: An Operating System provides services to both the users and to the programs. It provides programs an environment to execute. It provides users the services to execute the programs in a convenient manner.

    hashtag
    Web Application

    Okay, we've got a web server receiving signals from our client's computer. Now comes the part where our server runs the app we've built and gives us cool information.

    Pythonarrow-up-right: Python is a high-level programming language designed to be easy to read and simple to implement. It is open source, which means it is free to use, even for commercial applications. Python can run on Mac, Windows, and Unix systems and has also been ported to Java and .NET virtual machines. Most Python distributions rely on CPython, which means your code will boil down and run using the C language. Flask is a Python library.

    Framework:arrow-up-right Framework is described as “an abstraction, in which software providing generic functionality can be selectively changed by additional user-written code, thus providing application-specific software, is a software framework that is designed to support the development of web applications including web services, web resources, and web APIs. Web frameworks provide a standard way to build and deploy web applications. Web frameworks aim to automate the overhead associated with common activities performed in web development. For example, many web frameworks provide libraries for database access, templating frameworks, and session management, and they often promote code reuse. (additional linkarrow-up-right)

    hashtag
    Database

    SQL:arrow-up-right Structured Query Language, used to request information from a database. SQL has been the favorite query language for database management systems running on minicomputersarrow-up-right and mainframesarrow-up-right. Increasingly, however, SQL is being supportedarrow-up-right by PC database systems because it supports distributed databasesarrow-up-right (databases that are spread out over several computer systemsarrow-up-right). This enables several usersarrow-up-right on a local-area networkarrow-up-right to accessarrow-up-right the same database simultaneously.

    PostgreSQLarrow-up-right: is an object-relational database management systemarrow-up-right (ORDBMS). As a database server, its primary functions are to store data securely and return that data in response to requests from other software applications.

    hashtag
    More Python Vocab

    Interpreterarrow-up-right: a computer program that directly executes, i.e. performs, instructions written in a programming or scripting language, without requiring them previously to have been compiled into a machine language program.

    Flask Application Contextarrow-up-right: One of the design ideas behind Flask is that there are two different “states” in which code is executed. The application setup state in which the application implicitly is on the module level and request handling.

    Imagine two people watching a movie at the same time. Because those two people have different life experiences, they will interpret the movie in a different way. When your app is running, it loads variables and libraries that gives it a particular “experience.” Our application context refers to the references at play.

    Modulearrow-up-right: encapsulates code and data to implement a particular functionality, has an interface that lets clients to access its functionality in an uniform manner, is easily pluggable with another module that expects its interface, is usually packaged in a single unit so that it can be easily deployed.

    A module is a loose term. Python uses the term to describe a single file, sometimes just one part of a larger library of tools that you can import and use within your app. If you put a single line of code in a file, you’ve built a module.

    Virtual Environmentarrow-up-right: A folder where a copy of all dependencies is kept separate from the system installation. This allows you to work on several apps without having to manually toggle which version of the language interpreter your system is using. It's a safe and responsible way to develop your apps.

    Virtual environment does not include “your app” this is separate. And you may have meant modules, not models. The model refers to the objects and database tables we’ll use in our app. Meanwhile, the libraries or modules that our app depends on in order to run will be installed in our virtual environment.

    Librariesarrow-up-right: “a collection of implementations of behavior, written in terms of a language, that has a well-defined interface by which the behavior is invoked.”

    Dependenciesarrow-up-right: A dependency is a file that something you are trying to install requires. These are the required libraries and modules for your app to function.

    An efficient programmer keeps their dependencies in a virtualenv, but it’s not required to do so. You can install them globally if you’d like, but other apps running on that machine might complicate things. There are other ways to manage dependencies too.

    Git Version Controlarrow-up-right: is a system for tracking changes in computer files and coordinating work on those files among multiple people. Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later.

    Throughout the course of the semester how often will we be referring back to older versions of our app?

    Objectarrow-up-right: An item in memory with a variable name, location reference, and the instantiated code provided by some class definition. Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object. This is known as aliasing in other languages. This is usually not appreciated on a first glance at Python, and can be safely ignored when dealing with immutable basic types (numbers, strings, tuples).

    Method (Python):arrow-up-right A method is a function that “belongs to” an object. (In Python, the term method is not unique to class instances: other object types can have methods as well. For example, list objects have methods called append, insert, remove, sort, and so on. However, in the following discussion, we’ll use the term method exclusively to mean methods of class instance objects, unless explicitly stated otherwise.)

    This method is not named according to PEP which recommends the use of snake_case

    Parameter:arrow-up-right In almost all programming languages, functions accept variables that are used in their code, (i.e. f(x) = x + 1). The parameter is simply the variables that are referenced within a method or behavior. This can also be referred to as an argument. A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with an __path__ attribute. parameter. A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments) that the function can accept.

    Constructor (init method)arrow-up-right: In class-based object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

    Inheritancearrow-up-right: Inheritance is a feature that represents the "is a" relationship between different classes. Inheritance allows a class to have the same behavior as another class and extend or tailor that behavior to provide special action for specific needs.

    DocString Commentarrow-up-right: A string literal specified in source code that is used, like a comment, to document a specific segment of code.

    In-line comments are written with a # and add extra notes around our app. ‘’’DocString’’’ comments provide more detailed explanations right underneath class and function headers.

    hashtag

    hashtag
    Learning Targets
    • I can implement a new HTML theme into a web app's base template.

    • I can create my own blueprint and prepare to expand my database schema.

    hashtag
    Implementing a new HTML theme

    We’ve got to build our base.html. That one file is the frame to our whole app. It’s a key HTML file in the T of our MVT. We’ll need to carefully setup the <head>’s attached files, the <body> and any wrapper/container structure your theme might be using, the <nav> bar, the {% block container %} where all other pages will be inserted, and your footer.

    circle-info

    Pro Tip: Sometimes it's nice to have more than one base.html, if say, you have areas of your site that look dramatically different than others. I sometimes have marketing_base.html for my front page and a base.html with all the controls a user has when logged in.

    hashtag
    Skinning your login page

    Our next task is to apply your theme’s design to the built-in login page. Applying a cosmetic, HTML layer to your application is sometimes referred to as “skinning.” The login’s template is provided by our Flask-Security pluginarrow-up-right installed in Flaskinni. If you were to delete one of the template files, the app would default to the built-in Flask-Security template. By having the files in our templates folder, we override the built-in look of the pages.

    HTML templating is fun

    Your theme, whether you got it for free or paid for it, will have a pattern to how it organizes the HTML each page (some themes use a series of containers, others <section>s, for example). Implementing a theme is about transferring static assets (like images and files) and separating the parts of your HTML code that are common on every page (and putting that in the base.html) and what is unique to the individual page (and putting that in individual template files).

    hashtag
    Configuring your notifications

    If you haven't learned about flash notices yet for homework, you can read about themarrow-up-right, or talk about them in class. Assuming you get the idea and see how Flaskinni uses them, let's now rewire the system so it looks good in your HTML template. Maybe we'll use a dismissible Bootstrap alert but maybe want to tie into some fancier features that come with some themes.

    Many HTML themes have notification div boxes like this

    Figure out where all of these messages are listed in their container. Replace the stock objects, (probably will be li elements) and that will be generated instead by this line: {% include "security/_messages.html" %}

    Note: When an HTML file is unable to stand up on its own because it's just a partial element, we put an underscore and the start of its filename.

    hashtag
    An old demo

    Here's a demonstration showing the implementation of Flaskinni's old theme.

    hashtag
    Create your blueprint

    The different parts of your app should be kept in separate sections or blueprints. It'll make it easier to take one cool blog feature from one site and add it to another project later on. It also keeps your code more organized and easier to work on.

    hashtag
    Files and Folders

    The stuff we have to add to create a new blueprint can be divided up into the MVT (which I'll address in reverse). But first, do you know the name of your blueprint? It should be an easy shorthand because you'll be typing it a lot like so: {{ url_for('why_is_my_blueprint_name_so_long.dashboard') }}

    This example uses a blueprint named "project" which is a pretty lame name. Hopefully you can do better.

    hashtag
    Template

    Inside the templates/ folder, create a new folder with your blueprint's name. I almost always use a _cards.html full of macros ready to build cards for all sorts of objects in my app. Might as well add that now, too. For all the new pages you add to your app, you should use use a blank_page.html that you can copy and paste then rename.

    hashtag
    Views

    Create a new folder within the app/ folder. Like always, spaces and capitals are a bad idea in folder names. Inside that folder create an __init__.py file. In the file, you'll need to customize this code for a folder name unoriginally titled project/:

    hashtag
    Model

    We keep a separate folder for our models. I typically have quite a few files. We'll talk more about building your schema next chapter. For now, know that any new classes you make need to be imported in the __init__.py file. That keeps our imports more organized.

    hashtag
    Connecting to Flaskinni

    When our app factory in app/__init__.py puts together an instance of our software, it registers our blueprints and imports our models. The app factory is the knot that holds everything together. So the final step is to register our blueprint there. You're now ready to start taking Flaskinni's application logic in a whole new direction.

    hashtag
    Making changes to the database

    In the next section, we’re about to build database schemaarrow-up-right. You must understand that anytime you tinker with a models.py file, (from the /inni folder or elsewhere) then you’ve altered your schema and now your database is likely now out of sync. For example, let’s say you wanted to combine User.first_name with User.last_name so there was just one field, User.name. The SQL tables that stored that information can’t adjust to your modified Python code so easily. All of the existing records (i.e. the rows in your tables) will need to now be migrated to a the new set of columns you’ve constructed. That can be really tricky!

    hashtag
    Destroy and rebuild (the wrong way)

    The right way to handle this situation is discussed in the next section. Let’s look at the lazy, dangerous way of keeping your database up-to-date through gross destruction. DANGER: This will destroy all saved user data. You have a sacred mission to keep this safe and private. This practice is only tolerable at this very early stage of development when we’re learning how to form effective and efficient database schemas. So if you can say to yourself, “who cares? There’s no data here and never has been,” then this might be the right way to update your database.

    Check private.py for the name of the database being used in our app: BLOG_DATABASE_NAME. In this example, it’s called, “db”.

    psql

    \l

    drop database db;

    \l

    create database db;

    \q

    hashtag
    Migrate and upgrade (the right way)

    Once your database has been configured and your tables all have columns, making changes is tough. Sure, rows (aka “records”) can be added and deleted without any major problem. But changing the schema so that an object, or table, has new properties (columns in your tables) is much more difficult. Changing the columns in your database tables is a delicate process. Fortunately there are tools like Flask-Migrate to help migrate the data from one version of the table to the next.

    hashtag
    Why does this work differently?

    These commands are different and likely to change in the future. Think about it: we're not using our Flask app. Instead, we're using some tool that detects changes in our database and automates the migration of our data in our old table to our new table. Delicate stuff! Before we'd use Flask-Script as an intermediate. Now we use Clickarrow-up-right to access terminal commands that will migrate our database.

    If you do it to one, you've got to do it to them all

    Typically, we don’t work on just one database at a time. Most projects have a staging version and a production version and both have their own databases. If you make a change to one, you'll have to migrate the other. That’s why we have Flask-Migrate! Don’t start this process until your teacher has told you your database schema is largely stabilized, (this should happen at the end of the next section of this guide).

    Must read: https://flask-migrate.readthedocs.io/en/latest/arrow-up-right

    Getting started:

    flask db init -- this command you'll only do the first time

    flask db migrate-- this command detects any changes and builds a migration strategy to change your database

    flask db upgrade-- this command executes the migration

    http://designmodo.github.io/Flat-UI/arrow-up-right
    Logo
    CSS Dinerflukeout.github.iochevron-right

    4: Code Setup

    hashtag
    Learning Targets

    • I can install and configure VS Code for web development

    • I can use Live Server to preview my websites locally

    • I can collaborate with others using Live Share

    • I can manage my code with GitHub Desktop and GitHub Classroom

    • I can follow a proper Git workflow (commit, push, pull)

    • I can use professional templates as starting points for projects

    hashtag
    Why Do We Need All These Tools?

    Think of web development like building a house. You wouldn't just show up with a hammer and start swinging – you'd need a complete toolkit, blueprints, and a way to work with others. Your development environment is your complete toolkit for building websites.

    Here's what each tool does:

    • VS Code: Your code editor – like Microsoft Word, but designed specifically for writing code

    • Live Server: Instantly preview your website as you work – no need to constantly refresh

    • Live Share: Collaborate in real-time, like Google Docs but for code

    Together, these tools create a professional workflow that real web developers use every day.

    hashtag
    Installing VS Code

    Visual Studio Code (VS Code) is a free, powerful code editor created by Microsoft. It's become the industry standard for web development.

    hashtag
    Download and Install VS Code

    1. Visit

    2. Click the big Download button (it will automatically detect your operating system)

    3. Once downloaded, run the installer

    First Launch Tips:

    • VS Code might ask if you want to install recommended extensions – say yes!

    • You can customize the theme (dark mode is popular) by going to File > Preferences > Color Theme

    • The interface might feel overwhelming at first – that's normal! You'll get comfortable with it quickly.

    hashtag
    Essential Extensions: Live Server and Live Share

    Extensions are like apps for VS Code – they add powerful features that make development easier.

    hashtag
    Installing Live Server

    Live Server automatically refreshes your webpage whenever you save changes. No more manually hitting refresh!

    Installation Steps:

    1. In VS Code, click the Extensions icon in the left sidebar (it looks like four squares)

    2. In the search box, type Live Server

    3. Look for "Live Server" by Ritwick Dey (it should be the top result)

    Using Live Server:

    • Open any HTML file in VS Code

    • Click the Go Live button in the bottom-right corner

    • Your default browser will open with your website

    hashtag
    Installing Live Share

    Live Share lets you collaborate with others in real-time. It's like Google Docs for code – multiple people can work on the same files simultaneously.

    Installation Steps:

    1. In the Extensions panel, search for Live Share

    2. Look for "Live Share" by Microsoft

    3. Click Install

    Why Live Share Matters: This is your primary way to get help! When you're stuck, you'll share a Live Share link with me via Google Chat, and I can join your workspace to help you debug or work through problems together. Later in the course, you'll use Live Share to collaborate on group projects.

    hashtag
    Installing GitHub Desktop

    GitHub Desktop makes version control visual and easy to understand. While professional developers often use command-line Git, GitHub Desktop provides a friendly interface that helps you learn the concepts.

    hashtag
    Download and Install

    1. Visit

    2. Download GitHub Desktop for your operating system

    3. Run the installer

    4. Launch GitHub Desktop

    Why GitHub? GitHub is where developers store and share code. Think of it as a combination of:

    • Save points: Like saving your game – you can always go back to previous versions

    • Cloud backup: Your code is safe even if your computer crashes

    • Collaboration: Work with others without emailing files back and forth

    hashtag
    Setting Up GitHub Classroom

    GitHub Classroom is how you'll receive and submit assignments in this class.

    hashtag
    Accepting Your First Assignment

    1. I'll share a GitHub Classroom link (it looks like: https://classroom.github.com/a/...)

    2. Click the link and authorize GitHub Classroom to access your GitHub account

    3. GitHub will create a repository (repo) for you – this is your personal copy of the assignment

    What Just Happened? You now have a copy of the assignment on your computer that's connected to GitHub. Any changes you make can be synced back to GitHub, where I can see your work.

    hashtag
    Opening Your Project in VS Code

    1. In GitHub Desktop, with your repository selected, click Repository > Open in Visual Studio Code

    2. Alternatively, in VS Code, go to File > Open Folder and select your cloned repository folder

    Now you're ready to start coding!

    hashtag
    Collaboration and Getting Help: Using Live Share

    When you need help, follow this process:

    hashtag
    Starting a Live Share Session

    1. In VS Code, click the Live Share button in the bottom status bar

    2. Click Start collaboration session

    3. VS Code will generate a unique link and copy it to your clipboard

    What I Can Do in Your Session:

    • See your code and files

    • Edit alongside you (like Google Docs)

    • Help debug problems

    • Answer questions about your code

    Important: Always start a Live Share session before asking for help. Don't just say "I'm stuck" – say "I'm stuck with [specific problem], here's my Live Share link: [link]"

    hashtag
    Using Live Share for Group Projects

    Later in the course, you'll work on group projects. Live Share makes this easy:

    • One person hosts the Live Share session

    • Team members join via the link

    • Everyone can edit simultaneously

    The host is responsible for committing and pushing changes (more on that next).

    hashtag
    The Git Workflow: Commit, Push, and Pull

    This is the most important section to understand. Proper Git workflow prevents lost work and merge conflicts.

    hashtag
    The Golden Rules

    At the END of every work session:

    1. Commit your changes (save a snapshot)

    2. Push to GitHub (sync to the cloud)

    At the START of every work session:

    1. Pull from GitHub (download any changes)

    hashtag
    Why This Matters

    Imagine you work on a project at school, then go home and work on it there. If you don't push at school, your home computer won't have your latest work. If you don't pull at home before starting, you might be working on an old version.

    hashtag
    Step-by-Step Git Workflow

    Committing Changes (Creating a Save Point)

    1. After working, save all your files in VS Code (Ctrl+S or Cmd+S)

    2. Switch to GitHub Desktop

    3. You'll see a list of changed files on the left

    Think of commits like save points in a video game – you can always go back to any commit if something breaks.

    Pushing to GitHub (Syncing to the Cloud)

    1. After committing, click Push origin in GitHub Desktop (top-right area)

    2. This uploads your changes to GitHub

    3. Now your work is backed up and I can see your progress

    Pulling from GitHub (Getting Latest Changes)

    1. At the start of each work session, open GitHub Desktop

    2. Click Fetch origin (top-right)

    3. If there are changes, click Pull origin

    hashtag
    When You'll Use Pull

    • Different computers: When you work at school then at home

    • Group projects: When a teammate makes changes

    • My feedback: When I make changes to your code during help sessions

    hashtag
    Common Mistakes to Avoid

    ❌ Don't forget to push at the end of class – your work won't be backed up ❌ Don't start working without pulling first – you might create conflicts ❌ Don't write vague commit messages like "update" or "fixed stuff" ❌ Don't work directly in the GitHub website – always work locally and push

    ✅ Do commit frequently (every major change) ✅ Do write descriptive commit messages ✅ Do push at the end of every session ✅ Do pull at the start of every session

    hashtag
    Using Templates to Build Faster

    Just like Bootstrap helps us build responsive websites faster, templates give us professional starting points for our projects.

    hashtag
    Why Use Templates?

    Professional web developers don't reinvent the wheel for every project. Templates provide:

    • Professional design: Beautiful layouts created by experienced designers

    • Tested code: Proven structures that work across browsers

    • Time savings: Focus on customization instead of starting from scratch

    hashtag
    StartBootstrap.com (Free Templates)

    For most projects this semester, we'll use templates from .

    How to Use a StartBootstrap Template:

    1. Browse

    2. Find a template that fits your project

    3. Click Download on the template's page

    What You'll Customize:

    • Text content (replace placeholder text with your own)

    • Images (swap demo images for your own)

    • Colors (modify the CSS to match your design)

    hashtag
    ThemeForest.net (Premium Templates)

    For final projects, we'll explore premium templates from . These offer more sophisticated designs and features.

    The Template Philosophy: Templates aren't "cheating" – they're professional practice. The skill is in:

    1. Choosing the right template for your needs

    2. Understanding how the template works

    3. Customizing it to make it your own

    4. Adding unique content and features

    Think of it like music: you learn to play by practicing songs others have written, then eventually you compose your own.

    hashtag
    Putting It All Together: Your Daily Workflow

    Here's what a typical work session looks like:

    hashtag
    Starting Your Session

    1. Open GitHub Desktop

    2. Click Fetch origin, then Pull origin if there are changes

    3. Click Repository > Open in Visual Studio Code

    hashtag
    During Your Session

    1. Make changes in VS Code

    2. Save frequently (Ctrl+S or Cmd+S)

    3. Preview automatically updates in browser

    4. If you get stuck, start a Live Share session and send me the link via Google Chat

    hashtag
    Ending Your Session

    1. Save all files in VS Code

    2. Switch to GitHub Desktop

    3. Review your changes

    4. Write a descriptive commit message

    Never leave class without pushing! This is the #1 cause of lost work.

    hashtag
    Key Takeaways

    Remember these essential practices:

    • VS Code + Live Server = Your coding environment with instant preview

    • Live Share = Your collaboration and help tool (always include the link when asking for help!)

    • GitHub Desktop = Your version control and backup system

    5: Tour Flaskinni

    hashtag
    Learning Targets

    • I can describe the MVT components of Flaskinni.

    • I can describe the thread's steps as my app starts up.

    hashtag
    Organization

    Remember, you can help add comments and docstrings to Flaskinni and submit pull requests. Even beginners can help contribute to open source projects in surprisingly substantial ways.

    hashtag
    App Factory

    We've got a handy little method that instantiates our app, loads the settings, and straps on all its expansion packs. Let's start our tour of the code where Flask is spawned. From "":

    The reason why the Application Factory is so important has to do with something called Flask's Application Context. Our app's "context" is what takes the assortment of Python files and modules which make up our app and brings them together so that they see and work with one another.

    When your app is serving hundreds or thousands of people at a time, your server will run many instances of your app. You may also run your app in different modes, like a text-only shell. An application factory addresses this need by spitting out instances of app

    hashtag
    Blueprints and MVT

    Flaskinni comes with a main and an api blueprint. That'll affect your use of url_for. So if you wanted to make a link to the homepage, it'd be <a href="{{ url_for('main.index') }}">home</a>

    hashtag
    Template

    Now that Flaskinni is running in your environment, local or cloud-based, let's take a tour.

    hashtag
    File structure

    The T part of our MVT all starts with base.html.

    The purpose of the base template is to give all the pages in your app common assets. This such as fonts, CSS files, nav bar. Every page must link to the base file. It is kept in the /templates folder, as base.html. The base template is like a picture frame, loading common elements like the nav bar, footer, and your little .

    This is the whole parent-child thing. The parent is the skeleton of your page. We named it base.html and it has <link>s to our Google Fonts, CSS files, and sets up nav bars and any other element that’s site-wide. It’s great! Pretty much sets up the whole theme of our site.

    To put our pages inside this metaphorical picture frame, we use the command, {% extends "base.html" %} at the top of every other HTML we put in our templates folder.

    The base template extends across all pages, so the website can share HTML code.

    hashtag
    Base's blocks

    We’re going to make a new template that inherits from our base.html so you can experiment with this handy tool. Create a new file in your templates folder called about.html. This page will need hardly any information at all because all the setup is done in the parent. All we need to do is pass some HTML into any block.

    hashtag
    Sass and JS

    Sass makes CSS easier, even if you have to spend a few minutes here and there refreshing yourself on how to use the Sass tricks and how to compile your Sass down to CSS. I personally use a to manage this automatically.

    Don't want to learn? There is a lazy way out and that's to edit your CSS directly. No judgments.

    1. Pick out a header and a body font at

    2. Add them to your collection and get the <link> we’ll use to embed a connection to Google Fonts.

    3. Replace the other <link> to fonts.google.com that was in your base.html file

    1. Launch your server

      1. (make sure you’ve got venv activated) source venv/bin/activate or on Windows: source venv/Scripts/Activate

    hashtag
    Views

    If you want to see the new template file in action, we’ve got to build a route to that page. As of this writing, there are only two locations for routes in Flaskinni, the master __init__.py file and the views.py file inside the blog module folder. Since our homepage route is in the first file, we’ll put our about route there, too.

    We later passed a variable to the template. We dropped <h1> {{ some_variable }} </h1> in our about.html file. Nothing shows up until we change the render_template call to something like this:

    Congratulations! You just passed your first variable to a template.

    hashtag
    url_for

    hashtag
    Flash Notifications

    We have cool, color-changing notifications in Flaskinni that rely on Bootstrap classes. So if you want to send a good alert message that something worked, you'd say: flash("Your message has been sent!", "success")

    But if something failed, you'd write:

    flash("Your message was destroyed by mistake. Whoops!", "danger")

    What other Flash notifications are there? How are the flash notifications being built? Let's look at where they come up in the base.html file, trace back the macro that builds the flash messages and then see what other options come with Flaskinni.

    hashtag
    Sessions

    Cookies!

    hashtag
    Models

    hashtag
    Users are special

    hashtag
    Example Queries

    Let's talk about how this blog post is queried from our database:

    hashtag
    Example Relationships

    Check out line #20.

    hashtag
    Extensions

    hashtag
    Flask-Security

    hashtag
    Flask-Mail

    hashtag
    Flask-Migrations

    hashtag
    Flask-Assets

    hashtag
    Flask-RESTful

    hashtag

    9: Advanced Topics

    hashtag
    Expectations

    From here on out, your project is going to vary from everyone else’s. Once your models are done, you’ve now got to build out each view and template that will serve the workflow of your MVParrow-up-right. Work with your teacher to identify what your MVP needs to do, (we’ll call this your requirements based off of the SRS stage of the IEEE software lifecyclearrow-up-right). Once we work out what exactly you’re building in your module, we’ll populate your Trello backlog with loads of tasks. And as we solve those weird tasks, we’ll start to build the collection of topics below.

    hashtag
    Learning Targets

    • I can research and hack together an MVP.

    hashtag
    Session

    hashtag
    Decorators

    The term decorators in programming refers to a sort of flag or notice put at the start of a method to signal some sort of special treatment. We use @login_required to trigger Flask-Security’s verification that the user is carrying the encrypted token from our system given to a confirmed user. I would imagine verification of authority and privileges is the most common reason to use a decorator in Flask. We use them .

    hashtag
    Forms

    The form is our primary method of collecting information from the user. Depending on your application's need, you may need to looking closely into . Meanwhile, here are a few recipes that have been requested.

    hashtag
    Drop-down

    When filling out a form, you may want to have a drop-down of a user's friends or some other set of data unique to that user. How can you provide those dynamic options within a form template?

    The most typically recommended answer is the .

    And what if you want one drop-down to populate the options of another dropdown?

    hashtag
    Build Options From a View

    Just use a SelectField with no real options and populate them after you build the form.

    hashtag
    Placeholders

    Examples:

    • (placeholders)

    hashtag
    Captcha

    hashtag
    SQLAlchemy and Databases

    hashtag
    backref VS back_populates

    Two back_populates equals one backref. Using backref declares a two-way relationship. It’s more efficient than dropping a back_populates on both ends of the relationship but I prefer it because I’ve been confused too many times staring at a class wondering about its relationships unaware that another class has declared a relationship backref in a different file.

    hashtag
    Relationship Loading: Lazy?

    Let’s say you want to query the database for a user’s contacts with a built-in relationship such as current_user.contacts. You can get a list back from the database with just that one command. However, what if you know you’ll always need additional filters on that query. You don’t want the results quite so fast, instead you’d like the SQLAlchemy query not to complete its task but rather to keep the search open and ready for additional filtering or sorting.

    hashtag
    Command Line Interface

    hashtag
    flask shell

    This is a really useful skill we should go over as it helps us test and figure out where things go wrong.

    flask shell

    if python just said it doesn't know what that is, then you need this line: from extensions import db

    from user.models import User

    my_users = User.query.all()

    look at your user(s): my_users my_users[0].email

    my_users[0].first_name

    hashtag
    Talking to Postgres

    Let's make sure we can login directly to our database. You can skip this step if you're, say, in the midst of a hackathon, the app is working, and you've got to keep moving. In the long-run, it's critical you know how to flex control over your database directly.

    If you're using Terminal, bash or PowerShell, you should be able to type psql to open a command-line version of PostgreSQL. You can also use a friendlier interface like pgAdmin, though I recommend making the effort to explore both. You'll need to specify your user when accessing psql. Specifying your user can vary a lot depending on how you approach it. Good thing you know how to Google.

    Linux:

    sudo service postgresql start psql (try listing the current databases) \l (if you need to quit) \q

    If you’re the superuser using sudo -i then you’ll be on the root account (don’t do that). Postgres has a built-in admin you can log into with su - postgres and then psql (you shouldn’t need that but it’s useful).

    You can edit accounts' psql access and credentials with stuff like:

    ALTER ROLE ubuntu WITH PASSWORD 'ubuntu';

    You probably won’t need this very often, but it’s important to know if you want to understand how your app works. Launch psql and be very careful as you tiptoe through our database:

    (connect to our database, which in this example is named “db”) \c db

    (check out the tables in our database) \dt

    (see what we’ve got in our post table) SELECT * FROM post;

    If there are no posts, we’re going to create the first one, which will have the ID of zero. If there are posts already, we’re going to create one with the next highest number.

    ( of a post)

    INSERT INTO post (id, user_id, title, subtitle, body, slug, live) VALUES (0, 0, “Some title”, “Some subtitle”, “Some body”, “someslug”, True);

    (let’s quit psql) \q

    Launch your app and check it out. ?

    (go back into psql and connect to our db then what we made)

    DELETE FROM post WHERE id=0;

    (make sure it’s gone) SELECT * FROM post;

    hashtag
    Configuring Flask-Mail

    This line needs to be in your settings.py:

    SECURITY_EMAIL_SENDER = private.ADMIN_EMAIL

    hashtag
    JavaScript

    hashtag
    Setting Nav Links Active

    hashtag
    Confirmation Buttons

    Just as we keep a custom.css file, your project should have a custom.js function. Something like this could be very handy. Now you can just add class=”confirmation” attribute to any <a></a> and it’ll have a JS-powered confirmation window.

    hashtag
    AJAX: Server Without Reloads

    Actions of our app are triggered by routes in our view. If you type in the url of your site, /index, your browser sends a GET request to that route to the homepage route in your app. Your browser loads the page. But what if you want to avoid refreshing the page? What if you want to send a message from a modal window and press submit without losing your spot on the current page?

    hashtag
    Passing Variables from Flask to JavaScript

    hashtag
    Calling a JavaScript Method on a Button

    <a onclick="hidePaidBills()" href="javascript:void(0);" data-toggle="tooltip" data-placement="top" title="hide paid"><i class="fa fa-eye"></i></a>

    hashtag
    Sending SMS Messages with Twillio

    hashtag
    Updating Dependencies

    We use as a sort of bubble that contains our version of Python, Flask, and all the many other libraries used. Each library is likely to see improvements and security fixes. It’s important to keep this codebase updated but it’s an awfully risky process. Updates might change how some of the libraries work and may force you to change or cause new bugs. Best practice is to keep a previous version of your handy and to build thorough .

    Before asking to do a lot of work, you may want it upgrade it first: pip install --upgrade pip

    Update all libraries (copied from StackOverflow)

    sudo -H python3 -m pip freeze --local | grep -v '^-e' | cut -d = -f 1 | xargs -n1 sudo python3 -m pip install -U

    If you don't want to overdo it with the sudo nonsense: pip freeze --local | grep -v '^-e' | cut -d = -f 1 | xargs -n1 pip install -U

    Create a requirements document:

    pip freeze > requirements.txt

    Test to make sure the app works. If it doesn't, undo changes tracked by git to get you your previous version of the requirements.txt. Reinstall your dependencies based on all the previously recorded versions.

    hashtag
    Documentation

    Inside docs/ folder are files produced by .

    Enable the support of the Google-style docstrings which are much easier to read:

    hashtag
    Unit Tests

    The most responsible way to build software is to start with unit tests. A script will mimic various types of users as they test every function on your site. The unit test will report when something acts differently than expected. I struggle with keeping to this discipline. A more sophisticated implementation of Flask’s unit test system will be the best sign of my own professional growth in this area.

    Introductiongetbootstrapchevron-right
    Check that you're looking at the latest version
    trinket: run code anywheretrinket.iochevron-right
    trinket: run code anywheretrinket.iochevron-right
    trinket: run code anywheretrinket.iochevron-right
    trinket: run code anywheretrinket.iochevron-right
    24.5. turtle — Turtle graphics for Tk — Python 2.7.18 documentationdocs.python.orgchevron-right
    trinket: run code anywheretrinket.iochevron-right

    4: Install Flaskinni

    hashtag
    Learning Target

    • I can run Flaskinni after having cloned its code, configured its dependencies in a virtual environment, set up a database, and added an environmental variables file.

    Gilmour AcademyGitHubchevron-right
    Coolors - The super fast color palettes generator!Coolors.cochevron-right
    How to Create a Cool Cut-Out Text Effect in IllustratorDesign & Illustration Envato Tuts+chevron-right
    https://99designs.com/blog/tips/types-of-logos/99designs.comchevron-right
    git config --global user.name "Your Name"
    git config --global user.email "[email protected]"
    100% Bran,70,10,5,0.33
    All-Bran,70,9,5,0.33
    Apple Jacks,110,1,11,1.0
    public class Cereal {
        // Instance variables - one for each column
        private String name;
        private int calories;
        private int fiber;
        private int carbohydrates;
        private double cups;
        
        // Constructor takes all the data for one row
        public Cereal(String name, int calories, int fiber, int carbs, double cups) {
            this.name = name;
            this.calories = calories;
            this.fiber = fiber;
            this.carbohydrates = carbs;
            this.cups = cups;
        }
        
        // Accessor methods
        public String getName() { return name; }
        public int getCalories() { return calories; }
        // ... more getters
    }
    String line = "100% Bran,70,10,5,0.33";
    
    // Step 1: Split by comma
    String[] parts = line.split(",");
    // Result: ["100% Bran", "70", "10", "5", "0.33"]
    
    // Step 2: Extract each piece
    String name = parts[0];           // Already a String
    int calories = Integer.parseInt(parts[1]);     // Convert to int
    int fiber = Integer.parseInt(parts[2]);        // Convert to int
    int carbs = Integer.parseInt(parts[3]);        // Convert to int
    double cups = Double.parseDouble(parts[4]);    // Convert to double
    
    // Step 3: Create the object
    Cereal cereal = new Cereal(name, calories, fiber, carbs, cups);
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class DataLoader {
        private ArrayList<Cereal> cereals;
        
        public DataLoader() {
            cereals = new ArrayList<>();
            
            try {
                File file = new File("cerealSubset.csv");
                Scanner scanner = new Scanner(file);
                
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    
                    // Parse the line
                    String[] parts = line.split(",");
                    String name = parts[0];
                    int calories = Integer.parseInt(parts[1]);
                    int fiber = Integer.parseInt(parts[2]);
                    int carbs = Integer.parseInt(parts[3]);
                    double cups = Double.parseDouble(parts[4]);
                    
                    // Create object and add to collection
                    Cereal c = new Cereal(name, calories, fiber, carbs, cups);
                    cereals.add(c);
                }
                
                scanner.close();
                
            } catch (FileNotFoundException e) {
                System.out.println("File not found!");
            }
        }
        
        public ArrayList<Cereal> getCereals() {
            return cereals;
        }
    }
    public class Book {
        private String title;
        private String author;
        private double price;
        private int pageCount;
        private int unitsSold;
        
        public Book(String title, String author, double price, int pages, int sold) {
            this.title = title;
            this.author = author;
            this.price = price;
            this.pageCount = pages;
            this.unitsSold = sold;
        }
        
        // Accessor methods
        public String getTitle() { return title; }
        public String getAuthor() { return author; }
        public double getPrice() { return price; }
        public int getPageCount() { return pageCount; }
        public int getUnitsSold() { return unitsSold; }
    }
    /**
     * Calculate total revenue generated by this book
     */
    public double totalRevenue() {
        return price * unitsSold;
    }
    
    /**
     * Calculate price per page (value metric)
     */
    public double pricePerPage() {
        return price / pageCount;
    }
    
    /**
     * Determine if this is a bestseller (over 10,000 copies sold)
     */
    public boolean isBestseller() {
        return unitsSold > 10000;
    }
    
    /**
     * Compare value: is this cheaper per page than another book?
     */
    public boolean isBetterValueThan(Book other) {
        return this.pricePerPage() < other.pricePerPage();
    }
    public static double calculateRevenue(Book b) {
        return b.getPrice() * b.getUnitsSold();
    }
    
    // Usage:
    double revenue = calculateRevenue(myBook);
    public double totalRevenue() {
        return price * unitsSold;
    }
    
    // Usage:
    double revenue = myBook.totalRevenue();
    // Find books that generated over $50,000 in revenue
    public ArrayList<Book> findHighRevenue() {
        ArrayList<Book> results = new ArrayList<>();
        
        for (Book b : books) {
            if (b.totalRevenue() > 50000) {
                results.add(b);
            }
        }
        
        return results;
    }
    
    // Find the book with the best value (lowest price per page)
    public Book bestValue() {
        if (books.isEmpty()) return null;
        
        Book best = books.get(0);
        
        for (int i = 1; i < books.size(); i++) {
            Book current = books.get(i);
            if (current.pricePerPage() < best.pricePerPage()) {
                best = current;
            }
        }
        
        return best;
    }
    import java.util.ArrayList;
    
    
    public class NumSet {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            /*
            ROUND 1 tests
            */
            
            // Create a random int array of a given length, low and high end of range
            int[] randArray = randArray(15, 0, 100);
            
            // Create a random Integer ArrayList of given length, low and high range
            ArrayList<Integer> randArrL = randArrL(8, 5, 50);
            
            // How many similar elements are in a given array and ArrayList
            System.out.print("There are this many similar elements: ");
            System.out.println(compareNums(randArray, randArrL));
            
            // printPretty takes an int array and prints it out nicely
            printPretty(randArray);
            // printPretty takes an Integer ArrayList and prints it out nicely
            printPretty(randArrL);
            
            /*
            ROUND 2 tests
            */
            
            // shuffle randomizes an int array (then calls printPretty)
            shuffle(randArray);
            
            // shuffle randomizes an Integer ArrayList (then calls printPretty)
            shuffle(randArrL);
            
            // divide all numbers by two
            divByTwo(randArray);
            divByTwo(randArrL);
            
            //sumArray
            sumArray(randArray);
            sumArray(randArrL);
            
        }
        /*
        ROUND 1 code
        */
        
        // TODO: randArray
        
        
        // TODO: randArrL
        
        
        // TODO: compareNums
        
        
        // TODO: prettyPretty (overloaded)
        
        /*
        ROUND 2 code
        */
        
        // TODO: shuffle array
        
        
        // TODO: shuffle ArrayList
        
        
        // TODO: divByTwo (overloaded)
        
        
        // TODO: sumArray (overloaded)
    }
    class Shape {
        
        // a single example encaspulated instance variable
        private float length;
        
        // accessor method
        public float length(){
            // using this. is not required but helpful when writing
            return this.length; 
        
        // mutator method
        public void length(float length){
            // now using this. is required to tell the local and instance var apart
            this.length = length;
    
        // example abstract method. Each shape will need to make or "implement" 
        pubilc abstract float area();
            
    }
    for (Shape x : myShapes) {
        System.out.println("This shape's area is: " + x.area() + " cm2");
    }
    {% with messages = get_flashed_messages(with_categories=true) %}
      {% for category, message in messages %}
        {% if category == "success" %}
        <li class="media">
    			<div class="mr-3">
    				<a href="#" class="btn bg-success-400 rounded-round btn-icon"><i class="icon-mention"></i></a>
    			</div>
    			<div class="media-body">
    				{{ message }}
    				<div class="font-size-sm text-muted mt-1">4 minutes ago</div>
    			</div>
    		</li>
        {% elif category == "danger" %}
        <li class="media">
    			<div class="mr-3">
    				<a href="#" class="btn bg-success-400 rounded-round btn-icon"><i class="icon-mention"></i></a>
    			</div>
    			<div class="media-body">
    				{{ message }}
    				<div class="font-size-sm text-muted mt-1">4 minutes ago</div>
    			</div>
    		</li>
        {% elif category == "info" %}
        <li class="media">
    			<div class="mr-3">
    				<a href="#" class="btn bg-success-400 rounded-round btn-icon"><i class="icon-mention"></i></a>
    			</div>
    			<div class="media-body">
    				{{ message }}
    				<div class="font-size-sm text-muted mt-1">4 minutes ago</div>
    			</div>
    		</li>
        {% elif category == "warning" %}
        <li class="media">
    			<div class="mr-3">
    				<a href="#" class="btn bg-success-400 rounded-round btn-icon"><i class="icon-mention"></i></a>
    			</div>
    			<div class="media-body">
    				{{ message }}
    				<div class="font-size-sm text-muted mt-1">4 minutes ago</div>
    			</div>
    		</li>
        {% else %}
        <li class="media">
    			<div class="mr-3">
    				<a href="#" class="btn bg-success-400 rounded-round btn-icon"><i class="icon-mention"></i></a>
    			</div>
    			<div class="media-body">
    				{{ message }}
    				<div class="font-size-sm text-muted mt-1">4 minutes ago</div>
    			</div>
    		</li>
        {% endif %}
      {% endfor %}
    {% endwith %}
    
    """
    project blueprint constructor - flaskinni/app/project/__init__.py
    """
    from flask import Blueprint
    
    project = Blueprint('project', __name__)
    
    from . import views, forms # you can split these into multiple files if they get big
    GitHub Desktop: Manage versions of your code and sync your work across computers
  • GitHub Classroom: Submit assignments and receive starter code

  • Follow the installation prompts (the default settings work great)
  • Launch VS Code when installation completes

  • Click the Install button
  • Once installed, you'll see a "Go Live" button in the bottom-right corner of VS Code

  • Make changes to your code, save (Ctrl+S or Cmd+S), and watch the page automatically update!
    You'll need to sign in with your Microsoft or GitHub account
  • Follow the prompts to complete the authentication

  • Sign in with your GitHub account (create one if you don't have it yet)

  • Click the green Code button, then Open with GitHub Desktop
  • Choose a location on your computer to save the project

  • Click Clone

  • Send this link to me via Google Chat
  • I'll click the link and join your workspace

  • Changes are saved on the host's computer
    In the bottom-left corner, write a
    commit message
    describing what you did:
    • Good: "Added hero section with background image"

    • Bad: "stuff" or "changes"

  • Click Commit to main

  • Now you have the latest version of your code
    Learning opportunities: Study how professionals organize and style their code
    Unzip the downloaded file
  • In GitHub Desktop, copy the template files into your assignment repository

  • Commit and push the files

  • Open in VS Code and start customizing!

  • Layout adjustments (add or remove sections as needed)
    Start the Live Server (click "Go Live")
  • Begin coding!

  • Click Commit to main

  • Click Push origin

  • Verify the push completed (the button changes to "Fetch origin")

  • Commit + Push = Your end-of-session ritual
  • Pull = Your start-of-session ritual

  • Templates = Your professional starting points, not shortcuts

  • https://code.visualstudio.com/arrow-up-right
    https://desktop.github.com/arrow-up-right
    StartBootstrap.comarrow-up-right
    https://startbootstrap.com/arrow-up-right
    ThemeForest.netarrow-up-right
    Space Invader Style Enemy Movement
    Logo
    Logo

    OOP: When should you move properties and methods to an abstract layer?

    • Name three properties or methods that would be suitable for a Human class and three that would go on an abstract Mammal class.

  • How do you declare an abstract class and an abstract method?

    • Declare an abstract class called Athlete, give it private properties of name, number, position, and is_active.

    • Make a constructor.

    • Make accessor methods for each property.

  • How do you declare a class to inherit the properties from an abstract class?

    • Create classes called SoccerAthlete and BasketballAthlete that both inherit from Athlete.

    • Give each class a toString method that returns the String, "My name is {name} and I'm a {position} in soccer. I'm #{number}." Only if they're active. If they're inactive, the returning String should read, "I used to be play basketball as a {position}."

  • How can you take advantage of polymorphism?

    • Create a runner class with a main method that creates an array of Athletes. Loop through them and have each one introduce themselves.

  • https://codingbat.com/java/AP-1arrow-up-right

    Add your CSS code to custom.css, something like:

    (use our flask-script to run the server)
    flask run
  • Check out your font changes!

  • Demystifying Flask’s Application Factoryarrow-up-right
    See how much of the documentation you can read before your brain wimps outarrow-up-right
    faviconarrow-up-right
    VSCode extensionarrow-up-right
    fonts.google.comarrow-up-right
    All the pieces of our app get bolted on in a structure called an "application factory"
    I can't remember where this picture in my notes came from but it's not my creation.
    Flash notification system is a great illustration of the power of templating
    There we include the _message.html partial
    Those are the options you've got. You can totally add your own.
    hashtag
    Install Party

    A day before some hackathons or events like RailsBridgearrow-up-right, experts will host a session to help everyone install the tools they'll need. If you serve pizza, you can call pretty much anything a party.

    hashtag
    Your OS

    Whether you're using Windows, macOS, or Linux, you have a responsibility to your teammates that you keep your machine updated and organized. Run system updates, keep files off your desktop, have a system of organizing your project files. Knock this out early so it doesn't jam you up while installing complex programming tools.

    hashtag
    Dev Tools

    Go slowly. Go patiently. Things may not work. You will have to Google stuff, study, maybe ask for help, and solve your problems. Keep hacking at the problem. That's how we all learn best.

    hashtag

    hashtag
    Python

    Your computer only understands Python code through a compiler arrow-up-rightor interpreterarrow-up-right. Your computer uses bytecode to run the software. Our interpreter changes our beautiful Python code into a jumble of machine instructions. Ensure you use the same version in development as you do in production. That means if your server will run, say, Python 3.10, that's what you use to build the thing.

    hashtag
    Postgres

    This is the open-source database tool we're going to use. You'll set up Postgres to host your own private database. It won't be available outside of your computer. It's just so while you work on an app, it can access a practice source of information.

    circle-exclamation

    Remember postgres password. Since my computer's database is only used for building and testing apps, I set the password also to postgres

    hashtag

    hashtag
    Git / GitHub

    Mac users should have Xcode arrow-up-rightand run xcode-select --install in their terminals. Windows users need to install Git for Windowsarrow-up-right. This gives you the commands to clone a repository, manage your changes to code, and sync

    hashtag

    hashtag
    NPM

    Once upon a time, Javascript was just used to make pictures slowly spin on a webpage. Now we've got NodeJS letting this language that used to be purely stuck inside a web browser to now run independently on your computer. It's so popular, the npmarrow-up-right tool to quickly install awesome new Node packages is a must-have.

    circle-info

    hashtag
    Choco & Brew

    Node Package Manager often encourages the installation of amazing CLI installers like choco or brew (Mac and Windows respectively). So if you like quickly installing awesome things and can accept the responsibility to do so safely, get one!

    (Windows) (Mac)

    hashtag

    hashtag
    Scss

    Old-school CSS is a pain to program at a large scale. Sass is much more powerful. Your computer has to have it to run the WebAssembly arrow-up-rightservice built into Flaskinni. If you've got Choco or Brew installed, adding Sass is a breeze.

    hashtag
    Editor

    hashtag
    VS Code

    I recommend these extensions

    • Cyberpunk themearrow-up-right

    • Custom iconsarrow-up-right (they make it much easier to see your files)

    • Better Jinjaarrow-up-right

    hashtag
    Setup Code

    You can edit your code on the cloud with cool sites like SourceLairarrow-up-right. A cloud-based IDE is likely going to be based on Linux. That means you'll need to know a bit about Linux CLIarrow-up-right. Linux plays well with coders and a cloud-based IDE makes it easy to share your development progress with people and get feedback faster. That's big.

    You can also set up right on your computer. You should know how to do this just so you can practice putting all the pieces together. I prefer to program in the cloud and locally and use GitHubarrow-up-right to keep the two environments in sync.

    hashtag
    Clone the repo

    Use VS Code's git tool to pull down the repo from GitHub.com: https://github.com/dadiletta/flaskinni

    hashtag
    Stand up the db

    "Stand up" a database just sounds so much cooler than "set up," but it's the same idea. You can see in settings.py that Flaskinni by default is going to reach out to a PSQL database named db-flaskinni on the server 0.0.0.0. The username and password used to access the database are also loaded there. Changes to this information shouldn't be done in settings.py but rather a .env fille. But before we do any of that, fire up pgAdmin and create a database.

    hashtag
    Env variables

    Our .env file doesn't and shouldn't ever get synced to GitHub. It's our secure place to keep the unique variables for each environment where our app will run.

    hashtag
    Virtual env

    First you use the correct version of Python to launch its venv module to create a folder for our dependencies (also named venv):

    • Windows: python -m venv venv

    • Mac: python3 -m venv venv (as of this writing, Mac still comes with now-defunct Python2, so you need to distinguish between them)

    circle-info

    Let's say you're using Windows and you need to specify a non-default version of Python. You may need a line like:/c/Users/smithj/AppData/Local/Programs/Python/Python3XX/python -m venv venv

    Then we activate the virtual environment so all our required "expansion packs" or dependencies will be installed in our little bubble:

    • Mac: source venv/bin/activate

    • Windows: (might need) Set-ExecutionPolicy Unrestricted -Scope Process .\venv\Scripts\activate

    • Windows (using bash instead of default Powershell): source venv/Scripts/activate

    If you've got a happy little (venv) before your terminal prompt, you're ready to run: pip install -r requirements.txt

    circle-exclamation

    Did one of the dependencies listed in requirements.txt fail to install correctly? It's a common problem that must be solved. uWSGI doesn't need to be installed in the development environment so you can #comment that line out. If psycopg2 is failing to install, you can comment that out and manually install the binary alternative, pip install psycopg2-binary. Running pip install wheel may also resolve many of the installation issues.

    circle-exclamation

    You're likely going to end up with the wrong version of Flask-Security. So next run: pip uninstall flask-security

    pip uninstall flask-security-too

    pip install flask-security-too

    hashtag
    Flask run

    After running flask run in VS Code, you should be able to visit http://127.0.0.1:5000arrow-up-right to see your website.

    hashtag
    Migrations

    This is important! Pity the poor programmers that forget to set up their migration tools. Once Flaskinni is up and running the first time, run flask db init to allow Flask-Migrate to help with any future changes to your models. We'll talk about why that's super important laterarrow-up-right.

    hashtag
    Alternate setups

    hashtag
    Replit

    Help! I don't know how to configure Replit's database service with SQLAlchemy. Their technical support doesn't know how to do it. They point me to the forumsarrow-up-right... and those folks can't crack it, either.

    hashtag
    Docker

    I need to study up on Docker. These are notes that I'll use to redo this section later. Trying new stuff is important, even if you're not moving it into your stack. Docker represents a booming growth in containers, and that's something serious web dev folks need to deploy at scale.

    1. Make sure Docker arrow-up-rightis installed, running, and logged in.

    2. Clone Flaskinniarrow-up-right git clone http://github.com/dadiletta/flaskinni

    3. Edit the Dockerfile with environmental variables

    4. docker-compose up --build

    triangle-exclamation

    hashtag
    What if it's not working?

    You're going to get stuck... a lot. This is where you can distinguish yourself as a programmer. Every problem big and small you hack your way through makes you more legit. So enjoy the grind. It's important to read around the problem and not just through it. Sloppy copying from StackOverflow once you copy and paste the error into Google can get you in trouble. Get background research done to understand some of the bigger concepts. Be willing to reach out for help, but respect that other people are grinding away too. Always show evidence of your research when asking for help as it will build trust with your support network.

    http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/arrow-up-right
    in Java to notify the system we’re overriding a parent’s methodarrow-up-right
    wtformsarrow-up-right
    QuerySelectFieldarrow-up-right
    https://stackoverflow.com/questions/46921823/dynamic-choices-wtforms-flask-selectfieldarrow-up-right
    https://stackoverflow.com/questions/9749742/python-wtforms-can-i-add-a-placeholder-attribute-when-i-init-a-fieldarrow-up-right
    http://screencast-o-matic.com/watch/cFfb2obVJJarrow-up-right
    http://docs.sqlalchemy.org/en/latest/orm/backref.html#relationships-backrefarrow-up-right
    http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.htmlarrow-up-right
    let’s add a new recordarrow-up-right
    Not pretty, rightarrow-up-right
    let’s deletearrow-up-right
    https://pythonhosted.org/Flask-Mail/arrow-up-right
    https://www.twilio.com/docs/sms/quickstart/pythonarrow-up-right
    VirtualEnvarrow-up-right
    requirements.txtarrow-up-right
    unit testsarrow-up-right
    pip arrow-up-right
    Flaskinni'sarrow-up-right
    Sphinxarrow-up-right
    http://flask.pocoo.org/docs/0.12/testing/arrow-up-right
    In case you forgot what a drop-down looks like?
    github.comarrow-up-right

    4-C: Sorting

    We will write our most complex algorithms as we study efficient ways to sort collections of data. Some of these algorithms will require recursion, our most abstract and challenging topic to date.

    hashtag
    Learning Targets

    • I can implement selection, insertion and merge sort algorithms.

    • I can compare sorting algorithms' efficiency.

    hashtag
    Algorithms

    We've talked about algorithms before, most especially around the shuffling patterns we've used in the Elevens lab.

    hashtag
    Efficiency

    The bigger the group of data, the more important it is to be efficient. Searching on the web or in a database needs to be awfully fast. We measure the efficiency of a complex search or sort algorithm in Big O notation.

    hashtag
    Searching

    Let's knock out a quick algorithm first, searching. The O(n) way is just a straight traversal. But we could chop that down to a O(log n) with a binary search:

    The visualization of these patterns / algorithms / methods / whatever, is surprisingly helpful. You can get a feel for how we chunk the computer's task to organize a long list of numbers.

    hashtag
    Selection Sort

    Let's start with a nested loop, a boring old O(n^2) traversal and sort.

    Now between the inner and otter loops, we do a 3-part-swap

    hashtag
    Insertion Sort

    Insertion sort has the same worst-case scenario efficiency as selection sort, but it has a much better best-case scenario efficiency.

    hashtag
    Step 1: Nested loop with an inner loop traversing in reverse.

    hashtag
    Still Step 1: The inner loop doesn't need to start at index[0]

    hashtag
    Step 2: The inner loop goes backwards so long as the number that the outer loop has is bigger

    hashtag
    Step 3: You'll have to move numbers over as you go to make room

    hashtag
    Assignment

    Create a class that uses Sortable and IntegerMonster. Hopefully, that and the code below is enough for you to figure out what to do next. If not, let's make some extra time to practice/read about inheritance in Java.

    circle-info

    You'll have to use extends before implements. Potentially helpful analogy: I imagine "extends" as the class's last name and "implements" as job titles.

    Surprise: Your client suddenly changes the SoW and insists that the sort methods' outer loops print the current state of the array neatly on one line. Each array during the sort should be labeled.

    hashtag
    Recursion

    What happens if I call a function that calls itself? You can use this as a trick to chunk information in a loop-like flow.

    A base case is the critical piece of a recursive function that will terminate the recursive calls, and start the domino effect in the opposite direction.

    If we have a base case in place (rhymes!) we can use recursion to solve some tricky problems in an elegant fashion.

    hashtag
    Merge Sort

    This is a great follow-up to the video below.

    Let's start with some numbers to sort:

    Check if nums has hit its base case. Is it already split up? If not, split it up.

    Then we send each side to mergeSort. Notice we send the left side first. And the next copy of mergeSort will break that side up first too--all the way down to the base case.

    But down at that last level, when they can't be broken down any further, we'll be left with a few useful ingredients, the (yellow) nums, the left side, l, and the right side, r. Now we'll shove l and r back together, in order, and overwrite the contents of nums. We'll do this in a separate function: merge(nums, l, r, mid, n - mid);

    There are all sorts of variations on mergeSort and the merge function. The one from is pretty clever and fun to talk over. Check it out:

    First notice how they include the post-operation increment, k++ (instead of ++k). This way, every time k is used, it increases the index tracker on the parent array. It's a clever touch. Meanwhile, i is serving similarly as the index tracker for the left side and j is serving the right side.

    The first while loop proceeds until one of the counters hits their max. Then only one of the two remaining while loops will execute, collecting the last number.

    hashtag
    Assignment

    Create a class that extends NameManager and implements all required methods.

    A Visual Introduction to Pythontrinket.iochevron-right
    Adobe Learnhelpx.adobe.comchevron-right
    Logo
    How to see full log from systemctl status service?Unix & Linux Stack Exchangechevron-right
    Application Performance Monitoring & Error Tracking SoftwareSentrychevron-right
    Sketch · Design, prototype, collaborate and handoffSketchchevron-right
    While I prefer Adobe XD, I've seen tons of great work on Sketch
    https://letsxd.com/prototypingletsxd.comchevron-right
    They really do a great job of teaching this stuff. I don't have to do anything
    https://www.youtube.com/watch?v=zOPA0NaeTBkwww.youtube.comchevron-right
    This example doesn't use Sass. Not great.
    Theming Bootstrapgetbootstrapchevron-right
    At least glance through the documentation
    Adobe XD Learn & Supportwww.adobe.comchevron-right
    Free, popular and loaded with tutorials
    Logo
    {% extends "base.html" %}   
    
    
    {% block content %}
        {# this is a comment #}
        <div class="row justify-content-md-center">
            <div class="col-md-6">
                <h1>Hi</h1>
            </div>
        </div>
    
    {% endblock %}
    body {
        font-family: 'Roboto Mono', monospace;
    }
    
    h1, h2, h3, h4, h5, h6 {
        font-family: 'Rammetto One', cursive;
    }
    # Created a new route used for rendering the about page template 
    # Custom app routes for the end of the website url
    @app.route('/about')
    @app.route('/about/')
    @app.route('/about.html')
    # Define app route
    def about():
            """Render the template"""
            return render_template('about.html')
    def about():
            """Render the template"""
            return render_template('about.html', some_variable="Hello!")
    @app.route('/article/<slug>')
    def read(slug):
        post = Post.query.filter_by(slug=slug).first_or_404()
        return render_template('main/article.html', post=post)
    class User(db.Model, UserMixin):
    
        # Our User has six fields: ID, email, password, active, confirmed_at and roles. The roles field represents a
        # many-to-many relationship using the roles_users table. Each user may have no role, one role, or multiple roles.
        id = db.Column(db.Integer, primary_key=True)
        first_name = db.Column(db.String(155))
        last_name = db.Column(db.String(155))
        phone = db.Column(db.String(20)) # let's guess it should be no more than 20
        address = db.Column(db.Text)
        about = db.Column(db.Text)
        image = db.Column(db.String(125))
        email = db.Column(db.String(255), unique=True)
        password = db.Column(db.String(255))
        # TOGGLES
        active = db.Column(db.Boolean(), default=True)
        public_profile = db.Column(db.Boolean(), default=True)
        # DATES
        confirmed_at = db.Column(db.DateTime())
        last_seen = db.Column(db.DateTime(), default=None)
        posts = db.relationship('Post', backref='user', lazy='dynamic')
    ###################
    ##  FLASK 
    ###################
    FLASK_ENV=development
    FLASK_APP=main
    DEBUG=True 
    SECRET_KEY='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    
    ###################
    ##  FLASKINNI  
    ###################
    # DO NOT STORE A PASSWORD IN AN .ENV WITHIN PRODUCTION. SERIOUSLY UNSAFE
    STARTING_ADMIN_PASS = 'flaskinni' 
    ADMIN_EMAIL='[email protected]'
    MAX_CONTENT_LENGTH = 2048 * 2048
    UPLOAD_EXTENSIONS = ['.jpg', '.png', '.gif']
    
    ###################
    ##  SQLAlchemy 
    ###################
    # Windows users change this to 127.0.0.1
    DB_HOST=0.0.0.0 
    DB_USERNAME='postgres' 
    DB_PASSWORD='postgres' 
    DB_PORT='5432'
    DATABASE_NAME='db-flaskinni'
    SQLALCHEMY_TRACK_MODIFICATIONS=False
    
    ###################
    ##  FLASK-SECURITY 
    ###################
    SECURITY_REGISTERABLE=True
    SECURITY_CONFIRMABLE=True
    SECURITY_RECOVERABLE=True  
    SECURITY_POST_LOGIN_VIEW='/'
    SECURITY_EMAIL_SENDER='[email protected]'
    SECURITY_PASSWORD_HASH ='pbkdf2_sha512'
    SECURITY_PASSWORD_SALT = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    
    ###################
    ##  FLASK-MAIL
    ###################
    MAIL_SERVER='sandbox.smtp.mailtrap.io'
    MAIL_PORT=2525
    MAIL_USE_SSL=False
    MAIL_USE_TLS=True
    MAIL_USERNAME='xxxxxxxxx'
    MAIL_PASSWORD='xxxxxxxxxxx'
    MAIL_DEFAULT_SENDER='[email protected]'
    
    ###################
    ##  JWT 
    ###################
    PROPAGATE_EXCEPTIONS = True
    JWT_BLOCKLIST_TOKEN_CHECKS = ['access', 'refresh']
    $('.confirmation').on('click', function () { 
    return confirm('Are you sure?'); 
    });
    // HIDE PAID BILLS
    function hidePaidBills(){
        $('.bill-paid').each(function() {
            $(this).hide();
        })
    https://code.visualstudio.com/Downloadcode.visualstudio.comchevron-right
    articlearrow-up-right
    Baeldungarrow-up-right
    The red shows the current lowest number
    The outer loop wants the smallest number. The inner loop will find it
    The first number is smaller! Oh joy!
    Outer is only supposed to have one "T". You know what does have two Ts?
    We found one even smaller–what a world we live in!
    Inner loop has finished and now we know the INDEX value of the smallest
    Let's reset the smallest index to the otter loop and start over
    This animation depends on an insert option to move over the other numbers
    Practice, practice, practice
    To avoid an infinite repeat, we've got to include a base case
    https://chocolatey.org/arrow-up-right
    https://brew.sh/arrow-up-right
    DotENVarrow-up-right
    Python Auto Envarrow-up-right
    Figma: The Collaborative Interface Design ToolFigmachevron-right
    Free for students!
    A full example of theme implementation
    Note to self: replace this old video. Many items here are outdated
    https://www.youtube.com/watch?v=K5LBC3hLl8wwww.youtube.comchevron-right
    PrettyPrinted is an awesome channel and I recommend buying his courses
    public static void selectionSort ( int[] num ){   
        // outer loop stops one early!   
        for ( int i = 0; i < num.length - 1; i++ ){      	
            //initialize the smallest_index    
    	int smallest_index = i;        		
    	//inner loop locates the smallest after starting one past the outer loop
    	for(int j = i + 1; j < num.length; j++) {
    	    // if I find a smaller number...
    	    if( num[ j ] < num[ smallest_index ] )
    	        smallest_index = j;    
    	}     	
    	// 3 part swap between loops   
    	int temp = num[ smallest_index ];         	
    	num[ smallest_index ] = num[ i ];     		
    	num[ i ] = temp;    
        } // close the otter loop          
    } // close the method
    
    public static void insertionSort(int[] nums){
        // outer loop starts one in b/c my inner loop goes bkwrds
        for(int j = 1; j < nums.length; j++){
            // start a weird 3-part-swap by backing up j
            int temp = nums[j];
            // inner loop goes backwards and it's a while loop
            // let's start the counter
            int i = j - 1; 
            // our counter can't go out of bounds AND 
            // the inner loop is looking at a number bigger than temp  
            while( i > -1 &&  nums[i] > temp ) {
               // skoootch numbers over  
               nums[i + 1] = nums[i];
               // move the inner loop counter down
               i--;
            }
            // complete the 3-way-swap, undoing the last i--
            nums[i+1] = temp;
        }
    }
    interface Sortable {
        void selectionSort(boolean lowToHigh);    
        void insertionSort(boolean lowToHigh);    
    }
    abstract class IntegerMonster {
    
      public int[] nums;
      
      public IntegerMonster(int length){
        nums = new int[length];
      }
      
      public void buildRandomArray(){
        for(int i = 0; i < nums.length; i++){
          nums[i] = (int)(Math.random() * 5000);
        }
      }
      
      public abstract void printArray();
      
    }
    public void recursive(){
        System.out.println("It was a dark and stormy night.");
        recursive();
    }
    public static void merge(
      int[] a, int[] l, int[] r, int left, int right) {
      
        int i = 0, j = 0, k = 0;
        while (i < left && j < right) {
            if (l[i] <= r[j]) {
                a[k++] = l[i++];
            }
            else {
                a[k++] = r[j++];
            }
        }
        while (i < left) {
            a[k++] = l[i++];
        }
        while (j < right) {
            a[k++] = r[j++];
        }
    }
    abstract class NameManager {
        /** Core data structure to hold your name list */
        protected ArrayList<String> names;
    
        /** Adds names to the list until a blank is submitted */
        abstract void buildList();
        
        /** Uses selection shuffle algorithm */
        abstract void shuffle();
        
        /** Sorts the list of names using insertion sort */
        abstract void insertionSort();
        
        /** Sorts the list of names using selection sort */
        abstract void selectionSort();
        
        /** Sorts the list of names using merge sort */
        abstract void mergeSort();
        
        /** Returns a random name from the names list */
        abstract String pickRandom();
    }
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    Logo
    https://pythonhosted.org/Flask-Security/index.htmlpythonhosted.orgchevron-right
    The Flask Mega-Tutorial, Part II: Templatesmiguelgrinbergchevron-right
    If you give this guide up and follow Mr. Grinberg's exclusively I won't judge.
    Sass: Sass Basicssass-lang.comchevron-right
    Building a secure admin interface with Flask-Admin and Flask-SecurityMediumchevron-right
    Modular Applications with Blueprints — Flask Documentation (3.1.x)flask.pocoo.orgchevron-right
    Flaskinni comes with one blueprint. You'll probably want to add more soon
    How Secure Is The Flask User Session?miguelgrinbergchevron-right
    sphinx.ext.napoleon – Support for NumPy and Google style docstrings — Sphinx documentationwww.sphinx-doc.orgchevron-right
    https://marketplace.visualstudio.com/items?itemName=njpwerner.autodocstringmarketplace.visualstudio.comchevron-right
    Use this VS Code extension to generage autodoc-compatable docstring comments
    Passing variables from Flask to JavaScriptStack Overflowchevron-right
    SMS and MMS Marketing Notifications with Python and FlaskTwiliochevron-right

    2-B: Strings

    We start to delve into algorithms and basic AI with our first CollegeBoard-issued lab. We will learn about String manipulation so we can have a conversation with our computer.

    hashtag
    Learning Targets

    • I can use common String methods to modify a string.

    Logo

    I can evaluate the contents of a String.

  • I can use a Scanner to take inputs.

  • I can isolate an object in the user's input and use it in Magpie's response.

  • hashtag
    Magpie Lab

    CollegeBoard used to have three official projects, Magpie, Elevens, and PicLab. A few years ago, they dropped those four and started four new ones: Celebrity, Consumer Review, DataLab, and Steganography. But I still think Magpie is the best lab for starters.

    hashtag
    What's a magpie?

    A bid that can mimic speech.

    Taken from giantfreakinrobot.com

    Check out the chatbot in Activity 1:

    hashtag
    Strings

    Check out the official documentationarrow-up-right.

    Strings are a special data type in Java. They're not primitives but they behave a little differently than most instantiated objects. In many ways, they're an array of primitive char objects. The biggest difference is that Strings also have many helpful methods to change their formatting, to search and examine the Strings, and lots of other helpful tools.

    hashtag

    hashtag
    StringExplorer

    Create a new class in our project called StringExplorer and drop this code in:

    Why you can't use == to compare the contents of two instantiated objects

    hashtag
    Activity 2 Starter Code

    Now we're going to add a few new classes to the project.

    hashtag
    Magpie.java

    Now write a commit message to bookmark these changes and push the new version to GitHub. Then following along with the exercises in Activity 2.

    hashtag
    Activity 3: Better method

    Magpie's current structure and use of .indexOf("something") >= 0 is full of logic errors. It's caps sensitive, it can't tell if you've entered no response at all, and it sees the word "no" inside of "know". Let's do better.

    Let's drop these two methods into your Magpie class (they're overloadedarrow-up-right):

    Now we've got to update our getResponse method to use this instead of indexOf.

    Let's use this chart to walk through what's happening:

    hashtag
    Activity 4: Slice and dice

    Okay, now you're ready to follow along the student guide with the class and ask some questions along the way.

    hashtag
    Review

    Let's review some basics before we move onto our next, advanced concept. Now's the time to hit codingbat, SoloLearn, Codecademy, or other training websites to practice. You want the basics down pat so you can focus on new concepts as we move forward.

    file-pdf
    169KB
    Magpie Lab Student Guide_updated_Sept_2014.pdf
    PDF
    arrow-up-right-from-squareOpen
    Student Guide from College Board
    Logo
    Logo
    Logo
    Logo
    Download PythonPython.orgchevron-right
    What version should you install? Whichever is the most stable on an Ubuntu server.
    https://code.visualstudio.comcode.visualstudio.comchevron-right
    https://www.npmjs.com/get-npmwww.npmjs.comchevron-right
    GitHub Desktop | Simple collaboration from your desktopGitHubchevron-right
    Sass: Install Sasssass-lang.comchevron-right
    PostgreSQL: Downloadswww.postgresql.orgchevron-right

    3-A: Class References

    We will look more closely at the object-oriented programming and the implications of instantiated objects.

    hashtag
    Learning Targets

    • I can describe what it means to be an object-oriented programmer.

    import java.util.Scanner;
    
    public class StringExplorer
    {
    	public static void main(String[] args)
    	{
          // Count down with a "T minus 5"
          
          // Declare and instantiate a Scanner
        
          // infinite loop 
          
              // take an input
        
              // repeat input + message
        
              // implement "equals" to stop with the word "stop"
              
          
          /*
          ---------------------------
              SAMPLE STUFF
          ---------------------------
          */
      		String sample = "The quick brown fox jumped over the lazy dog.";
      
          // Print the sample and add a blank line after
          System.out.println("OUR SAMPLE:");
      		
          //  Demonstrate the length method.
      		int l = 9999;
      		System.out.println ("sample.length() = " + l);
      
      		//  Demonstrate the indexOf method.
      		int position = 9999;
      		System.out.println ("sample.indexOf(\"quick\") = " + position);
    		
          //  Demonstrate the toLowerCase method.
    		  String lowerCase = sample.toLowerCase();
    		  System.out.println ("sample.toLowerCase() = " + lowerCase);
    		  System.out.println ("After toLowerCase(), sample = " + sample);
    				
    		  //  toUpperCase
    
    
          // lastIndexOf
    
    
          // substring
          
          
          // equals
    
    	}
    }
    
    import java.util.Scanner;
    
    
    /**
     * A simple class to run the Magpie class.
     * @author Laurie White
     * @version April 2012
     */
    public class MagpieRunner
    {
    	/**
    	 * Create a Magpie, give it user input, and print its replies.
    	 */
    	public static void main(String[] args)
    	{
    		Magpie maggie = new Magpie();
    		
    		System.out.println (maggie.getGreeting());
    		Scanner in = new Scanner (System.in);
    		String statement = in.nextLine();
    		
    		while (!statement.equals("Bye"))
    		{
    			System.out.println (maggie.getResponse(statement));
    			statement = in.nextLine();
    		}
    	}
    	
    }
    
    /**
     * A program to carry on conversations with a human user.
     * This is the initial version that:  
     * <ul><li>
    
     *       Uses indexOf to find strings
     * </li><li>
     * 		    Handles responding to simple words and phrases 
     * </li></ul>
     * This version uses a nested if to handle default responses.
     * @author Laurie White
     * @version April 2012
     */
    public class Magpie
    {
    	/**
    	 * Get a default greeting 	
    	 * @return a greeting
    	 */
    	public String getGreeting()
    	{
    		return "Hello, let's talk.";
    	}
    	
    	/**
    	 * Gives a response to a user statement
    	 * 
    	 * @param statement
    	 *            the user statement
    	 * @return a response based on the rules given
    	 */
    	public String getResponse(String statement)
    	{
    		String response = "";
    		if (statement.indexOf("no") >= 0)
    		{
    			response = "Why so negative?";
    		}
    		else if (statement.indexOf("mother") >= 0
    				|| statement.indexOf("father") >= 0
    				|| statement.indexOf("sister") >= 0
    				|| statement.indexOf("brother") >= 0)
    		{
    			response = "Tell me more about your family.";
    		}
    		else
    		{
    			response = getRandomResponse();
    		}
    		return response;
    	}
    	
    	/**
    	 * Pick a default response to use if nothing else fits.
    	 * @return a non-committal string
    	 */
    	private String getRandomResponse()
    	{
    		final int NUMBER_OF_RESPONSES = 4;
    		double r = Math.random();
    		int whichResponse = (int)(r * NUMBER_OF_RESPONSES);
    		String response = "";
    		
    		if (whichResponse == 0)
    		{
    			response = "Interesting, tell me more.";
    		}
    		else if (whichResponse == 1)
    		{
    			response = "Hmmm.";
    		}
    		else if (whichResponse == 2)
    		{
    			response = "Do you really think so?";
    		}
    		else if (whichResponse == 3)
    		{
    			response = "You don't say.";
    		}
    		
    		return response;
    	}
    }
    
    public class Drills {
        
        public static void main(String[] args) {
        
            // Declare 5 different data types with initial values (include at least one array)
            
            // A standard for loop printing numbers 1-5 with their squares (i.e. num * num)
            
            // Create an int array with test scores: 85, 92, 78, 95, 88, 73, 91
            // Use a for-each loop to traverse and print each score
            
            // Calculate and print the average of the test scores array
            
            // Count how many scores are above 85 using a loop
            
            // An infinite loop that collects user input
            
                // A short-circuit conditional with four tests
                // (check if input is: positive && less than 100 && even && divisible by 5)
            
                    // Break the loop if all conditions pass
            
            // Loop through each char in the String "DataScience"
            // Print each character on a separate line with its index
                    
            // Given String word = "Algorithm", print only the first three letters
            
            // Print all the odd numbers from 1-100 in rows of 10 numbers each
            
            // Create a Scanner and take a String input (ask for user's name)
            
            // Create a Scanner, take a number, print a countdown from that number to 0
            // Format: "T-minus [number]..."
            
            // Create a double array for temperatures: {72.5, 68.3, 75.1, 69.8, 71.2}
            // Find and print the highest and lowest temperatures
            
        }
        
        // Create a method that compares two arrays and returns the larger average
        // Include a proper JavaDoc comment
        
        // Create a method that formats a number as a percentage (returns String)
        // Include a proper JavaDoc comment
        
    }
    /**
     * Search for one word in phrase. The search is not case
     * sensitive. This method will check that the given goal
     * is not a substring of a longer string (so, for
     * example, "I know" does not contain "no").
     *
     * @param statement the string to search
     * @param goal the string to search for
     * @param startPos the character of the string to begin the search at
     * @return the index of the first occurrence of goal in
     *         statement or -1 if it's not found
     */
    private int findKeyword(String statement, String goal,
    		int startPos)
    {
    	String phrase = statement.trim().toLowerCase();
    	goal = goal.toLowerCase();
    
    	// The only change to incorporate the startPos is in
    	// the line below
    	int psn = phrase.indexOf(goal, startPos);
    
    	// Refinement--make sure the goal isn't part of a
    	// word
    	while (psn >= 0)
    	{
    		// Find the string of length 1 before and after
    		// the word
    		String before = " ", after = " ";
    		if (psn > 0)
    		{
    			before = phrase.substring(psn - 1, psn);
    		}
    		if (psn + goal.length() < phrase.length())
    		{
    			after = phrase.substring(
    					psn + goal.length(),
    					psn + goal.length() + 1);
    		}
    
    		// If before and after aren't letters, we've
    		// found the word
    		if (((before.compareTo("a") < 0) || (before
    				.compareTo("z") > 0)) // before is not a
    										// letter
    				&& ((after.compareTo("a") < 0) || (after
    						.compareTo("z") > 0)))
    		{
    			return psn;
    		}
    
    		// The last position didn't work, so let's find
    		// the next, if there is one.
    		psn = phrase.indexOf(goal, psn + 1);
    
    	}
    
    	return -1;
    }
    
    /**
     * Search for one word in phrase. The search is not case
     * sensitive. This method will check that the given goal
     * is not a substring of a longer string (so, for
     * example, "I know" does not contain "no"). The search
     * begins at the beginning of the string.
     * 
     * @param statement
     *            the string to search
     * @param goal
     *            the string to search for
     * @return the index of the first occurrence of goal in
     *         statement or -1 if it's not found
     */
    private int findKeyword(String statement, String goal)
    {
    	return findKeyword(statement, goal, 0);
    }
    Logo
    I can describe the difference between values and references.
  • I can build unit tests to check every method in my class definition.

  • hashtag
    Class Vocab

    hashtag
    Object-Oriented Programming

    Why don't we list all of our code in one long file? How do we start to organize big projects? We start with objects. Already we've been using a class with a main method as its starting point. All of our methods have been static. What if we wanted to make a game with a lot of monsters? We can define our own Monster class and create as many instances of that object as we need in the game. We can't use static methods anymore as a result.

    hashtag
    Let's try out a simple game in class using while-true loop and a Monster.

    hashtag
    Encapsulation

    Keep your data private, accessible only to methods that allow for more careful controls.

    hashtag
    Primitives and Refs

    References are links to the original. Passing by value makes a copy

    hashtag
    Intro to ArrayLists

    ArrayLists are introduced in this section because they're objects themselves. They illustrate some of the differences we see when working with objects. Instead of arrays when we can access an element just by printing someCollection[x], we now need to use someOtherCollection.get(x). Let's get into these differences.

    hashtag
    Different Kind of Loop

    Because ArrayLists are only accessible through methods, you can use the same type of access[index] you can with an array. Here's what a simple traversal looks like with a good ol' array:

    Notice how I used length as a property not as an accessor method() and I accessed an element from the collection using [brackets]. Now let's take a look at an ArrayList:

    There's a couple important things happening above you should look closely at:

    • Notice how I declared a List and then turned it into an ArrayList? It wouldn't have worked if I tried to do new List because a List is abstract. It's like mammal. You can tell the computer that you'd like to make a new mammal named x and it should run the new Dog() constructor. That's a polymorphic declaration. Use a general ancestor as a type and then be more specific during the constructor.

    • If you look inside the ArrayList class programmed inside our Java library, you'll notice it has an array at its core. It's a wrapper for an array. So there is a .length property that's relevant to its internal, private programming. Every time you .add(something) to an ArrayList it destroys its old array and copies all the content to a new, longer array. So .length is serious business. Since that's occupied, we use the .size() accessor method to retrieve the length of an ArrayList.

    hashtag
    SecureList: An Example

    What's the point of creating our own objects? How does an ArrayList differ from an array in practical implementation? Let's go through an example project to help iIllustrate these concepts.

    hashtag
    What is a SecureList?

    SecureLists are made up. They're a silly object that provides an extra layer of "security" by storing your list of 12 names in two different objects, an array and an ArrayList. Does that actually provide additional security? No, not really. But let's pretend it does so you have an opportunity to work with an array and an ArrayList simultaneously.

    Let's set up your project with the following files:

    circle-info

    Want some extra practice?arrow-up-right

    Logo
    Insertion Sort vs. Selection SortStack Overflowchevron-right
    Respect the YouTube level grind.
    Big O notationWikipediachevron-right
    Logo
    Logo
    import java.util.ArrayList;
    
    public class Practice {
    
    	public static void main(String[] args) {
    		
    		// create a primitive
    		int myPrimitive = 5;
    		// pass it by value to a method that adds one to the item.
    
    		addOne(myPrimitive);
    		// print the unchanged value of the primitive
    		System.out.println("Primitive: " + myPrimitive);
    		
    		// instantiate a list and store the reference to it in myRef
    		ArrayList<Integer> myRef = new ArrayList<>();
    		// add the value 5 to a new Integer 
    		myRef.add(5);
    		// pass it by reference to a method that adds one to the first element in the list
    		addOne(myRef);
    		// print what's now in the first spot of the object that was passed by reference
    		System.out.println("Reference: " + myRef.get(0));
    		
    	} // closes main
    	
    	public static void addOne(ArrayList x) {
    		// get the current value of the first item in the list, convert to int
    		int current = (int)x.get(0);
    		// set the first item's value to one more than its current
    		x.set(0, ++current);
    	}
    	
    	public static void addOne(int x) {
    		++x;
    	}
    
    } // closes the class
    	
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    
    import java.util.Scanner;
    
    public class App {
        
        // from a static method, we'll create instances of our made-up object
        public static void main(String[] args) throws Exception {
          
            System.out.println("Let's build a list of names to test.");
            Scanner s = new Scanner(System.in);
            
            // our example container
            String[] testList = new String[12];
            
            // build an example list to work with
            System.out.print("Would you like to enter names? (y/n): ");
            if(s.nextLine().equals("y")){
                // populate the array with names from user
                for(int x = 0; x < 12; x++){
                    System.out.print("\nInsert name at index " + x + ": ");
                    testList[x] = s.nextLine();
                    System.out.println();
                }  
            } else {
                // populate the array with just numbers
                for(int x = 0; x < 12; x++){
                    testList[x] = "Student #" + x;
                }  
            }        
           
            System.out.println("\n----- SecureList Unit Tests ------\n");
            
            // test the constructor
            SecureList test1 = new SecureList(testList);
            
            // test title mutator and accessor
            System.out.println("\nTITLE TEST: \n");
            test1.title("Demo"); // mutator 
            System.out.println(test1.title());  // accessor
    
            // implicitly call the .toString() method
            System.out.println("\nPRINT TEST: \n");
            System.out.println(test1);
            
            // draw a random name from the list
            System.out.println("\nGET RANDOM: \n");
            System.out.println(test1.getRandom());
            
            // check that each element in both collections match
            System.out.println("\nIS SECURE: \n");
            System.out.println(test1.isSecure()); // should print "true"
            
            // get the first name in the list
            System.out.println("\nGET STUDENT 0: \n");
            System.out.println(test1.getName(0));
            
            // get the first name in the list using the seat number not the index
            System.out.println("\nGET SEAT 1: \n");
            System.out.println(test1.getStudentBySeat(1));
            
            // randomize the order of the names
            System.out.println("\nSHUFFLE: \n");
            test1.shuffle();
            System.out.println(test1);
            
        }
    }
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    
    import java.util.ArrayList;
    
    /**
     * Doubles the protection of your data by storing your 12 names in both an array
     * and an ArrayList
     */
    public class SecureList {
        
        // ENCAPSULATED INSTANCE VARIABLES
        // a var for the title String
        
        // uninitialized String Array
         
        // uninstantiated ArrayList typecast to String
        
        
        // -----------
        // CONSTRUCTORS
        // -----------
            
        /**
         * This is the basic constructor that initializes all the instance variables
         */
        public SecureList(){
            // create a blank title
            title = "";
            // create a blank array of Strings
            nameArray = new String[12];
            // instantiate an ArrayList and then loop and add 12 blank Strings
            nameList = new ArrayList<String>();        
            for(int i = 0; i < 12; i++) nameList.add("");
        }
        
        /**
         * Extracts names from an ArrayList to store in both class containers
         * @param nameList : starting names
         */
        public SecureList(ArrayList<String> nameList){
            // call the first constructor to setup the blank stuff
            this();
            
            // copy the data from the given list
            
        }
        
        /**
         * Extracts names from an array to store in both class containers
         * @param nameArray : starting names
         */
        public SecureList(String[] nameArray){
            // call the first constructor to setup the blank stuff
            this();
            
            // copy the data from the given array
        }
        
        // -----------
        // ACCESSORS
        // -----------
        
        /**
         * Accessor method for the title instance variable
         * @return this.title
         */
        public String title(){
        
        }
        
        /**
         * After checking that the names between the two strings
         * @param n : the zero-indexed location of the name
         * @return
         */
        public String getName(int n){
            // use the isSecure method to check n
            if(!isSecure(n)){
                System.out.println("NOT SECURE");
                return null;
            }
            
            // return the name in the index location of n
            
        }
        
        /**
         * Wrapper for the getName method that is NOT zero-indexed
         * @param s: Seat location
         * @return
         */
        public String getStudentBySeat(int s){
            
        }
        
        // -----------
        // MUTATORS
        // -----------
        
        /**
         * Modify this instance's title property
         * @param title : new label for this secure list object
         */
        public void title(String title){
        
        }
        
        /**
         * Change the name of both collections at a given index location
         * @param n : index location to target
         * @param name : new name value to set
         */
        public void changeName(int n, String name){
            
        }
        
        // -----------
        // UTILITIES
        // -----------
        
        /**
         * Checks if the given index location is a blank "" string
         * @param n : index location to check
         * @return : true if the index location had a length of zero
         */
        public boolean isEmpty(int n){
            
        }
        
        /**
         * Returns the comparision between the two Strings in the container at position n
         * @param n : the zero-indexed location in the collection to check
         * @return true if the two Strings .equal
         */
        public boolean isSecure(int n){
            
        }
        
        /**
         * Traverses the length of the collection and checks in location is secure.
         * If any is found insecure, it returns false
         * @return list integrity 
         */
        public boolean isSecure(){
            // loop
                // if insecure at that postion, return false
    ​
            // if you make it through the loop safely, return true
        }
        
        /**
         * Draws a random index location and returns the name at that location
         * @return : the String value at a random index location
         */
        public String getRandom(){
            // generate a random number from 0 up until but not including the length
            
            // return the call to the getName method
        }
        
        /**
         * Randomizes the location of all the Strings using the Selection Shuffle
         * algorithm 
         */
        public void shuffle(){
            
        }
        
        /**
         * Traverses name collection, printing the seat location followed
         * by the name
         */
        @Override
        public String toString(){
            
        }
        
    }
    int[] myArray = {5, 10, 15, 20};
    for(int x = 0; x < myArray.length; x++){
        System.out.println(myArray[x]);
    }
    List myList = new ArrayList<Integer>(); 
    myList.add(5);  // I could loop and add all these
    myList.add(10); 
    myList.add(15);  
    myList.add(20);  
    for(int x = 0; x < myList.size(); x++){
        System.out.println(myList.get(x));
    }
    Logo
    Logo

    8: Standup Your DB

    hashtag
    Expectations

    By now you should have created your module or blueprint’s folder in your project’s directory and another in your templates. Now, we'll talk about what we should add into the models/ folder

    hashtag
    Learning Targets

    • I can create an ERD/UML to describe the data that will be stored in my app.

    • I can write new relational database objects and successfully stand up my database.

    hashtag
    Make Your Copy

    Here's a semi-accurate diagram of Flaskinni's starting objects. Make a copy of this document and share it with your team. Compare your UML's and your wireframes, to make sure all the data you need in your app is stored in a logical hierarchy.

    hashtag
    Example 1: Starsite

    hashtag
    Example 2: Fipplr

    Fipplr allows businesses to log work, manage invoices, and accept payment. This set of tools can be used by freelancers and employers. Fipplr works similarly to many other accounting tools but its simplicity and guided structure protects young entrepreneurs.

    hashtag
    Example Class

    hashtag
    Query Practice

    Invoice Count:

    • Invoice.query.count()

    • len(Invoice.query.all())

      • Count how many invoices have been submitted system-wide

    Paid/Unpaid:

    • Invoice.query.filter(Invoice.date_paid != None).all()

      • Check to see if an invoice has been officially paid. This will be a simple boolean check to see if it has been paid or not. Eventually, you will be able to filter paid and unpaid but to begin, it will just be paid.

    Project List:

    • Project.query.join(Project_User).filter(Project_User.user_id==current_user.id).all()

      • Print the list of all your current working (live) projects. For employers, this list would include the project name and who is assigned to it. For freelancers, it will list all the projects you are assigned to.

    Client/Employer List:

    • [Function name]

      • Find the full list of your clients. For employers, each client would be your subcontractors. For freelancers it will list all the clients that have hired you.

    Company List:

    • Company.query.join(Company_User).filter(Company_User.user_id==current_user.id).all()

      • All companies a user is connected to.

    Invoiced Work Check:

    • Query: [Function name]

      • Find the full list of work officially invoiced (submitted). If work is not invoiced pull up a separate list. In total there will be two lists, one for the officially invoiced (submitted) work and another for the unofficially invoiced (submitted) work.

    hashtag

    Star Sight is a collaborative story editor with a growing array of tools to help writers. You can control access to your work, track your characters, and roll dice to help make decisions. Stories also support rich media so your work can stand out.

    hashtag
    Relationships

    Database architecture, the way we build and connect elements in an app, often goes unappreciated by the average user. It’s a complex software engineering challenge that’s unique to every problem being solved. In this example we have some of the following relationships:

    • Story_Chapter

    • User_Story: A user has its own attributes (First and last name, email, and ID). A story also has its own attributes (A series it belongs to, and its own ID). In order to connect these two things, a helper table is created and used by pairing the ID of the user and the story it’s associated with.Its an additional object that connects to the two. It told to, it also gives the user permission to give other users access to a particular story.

    hashtag
    Example Class

    hashtag
    Query Practice

    • Story.query.join(Story_User).filter(User.id==current_user.id).all()

      • All stories the current user has

    • Chapter.query.join(Character_Story).filter(Character.id==x.id).all()

    hashtag
    Example 3: Overhaul Repair

    Overhaul Repair is an app that allows users to sign up to request a mail-in phone repair service. This web app will allow users to create accounts to monitor their device status and also add their devices into the account, allowing users to easily create repair orders from previously added devices. The app will also include an admin only finance management system.

    hashtag
    Example Class

    hashtag
    Query Practice

    • Query: Task.query.filter(Task.date_completed==None)

      • Explanation: Query searching through all phones that have unsolved open issues

    • Query: Task.query.order_by(Task.price)

    hashtag
    Example 4: TGene

    Tgene is a website that connects the Gilmour Academy molecular genetics lab to others around the world. My app allows the students and lab instructor, Doctor Edward Turk, to write and upload blog posts, pictures, and research about the current work being done in the lab. Through this shared information, collaboration can occur between labs through a contact feature to get teachers and researchers in touch. Collaboration also includes the sale of plasmids from the Gilmour Academy lab to other schools. Tgene is a project that allows Gilmour Academy high school molecular genetics class to share their research, work, and plasmids to other students and researchers across the country.

    hashtag
    Example Class

    Class for my register form that allows me to register as an admin

    hashtag
    Query Practice

    • Query: Moneyplasmid = DBSession.query(Plasmid).filter(plasmid.price)

      • Explanation: Returns all plasmids that cost money

    • Query: Freeplasmid= DBSession.query(Plasmid).filter(plasmid.price<1)

    hashtag
    Example 5: Ennounce

    An app to organize announcements for school clubs and teams and to efficiently communicate them to students. Our platform is a way for groups to connect with users. Members can subscribe to groups to stay up to date on what is going on with a group. Groups can post announcements and members can comments and react to them.

    hashtag
    Example Class

    hashtag
    Query Practice

    • Lists all the groups a certain user is in

      • Group.query.join(Membership).filter(Membership.user_id == 2).all()

    • Lists all of the announcement for a particular school base on school id

    hashtag
    Get Started

    Assuming you’re responsible enough to use some sort of project management tool like Trello, use the UML or ERD you’ve sketched as a reference to build out your todo list. For almost every table you’ve created in your database, you’ll probably need:

    • A form built in your forms.py that defines each field a user will fill out

    • A .html template where that form can be displayed. This form will be used to create a new object as well as editing an existing object

    • A route and function in your views.py for both the new and edit mode of your object form

    The point here is to think through the absolute minimal displays required to add and manage your data. Then layer in some basic commands next to that table of data.

    hashtag
    Comment Your Code

    hashtag
    Superadmin

    Once your models.py file is complete and your app is running, the first route I recommend building is /superadmin.

    We'll build control tables, here's how we load the data for the first one, users.

    hashtag
    How to query?

    There's a few ways to trigger a database query. I like to call the object statically so I can explain to students about those terms. You'll more often see db.session.query(Post). .

    Logo
    • All chapters that have a certain character

  • Series.query.join(Story).join(Story_User).filter(User.id==1).all()

    • All series that the current user has

  • User.query.join(Story_User)).all()

    • All users that have stories linked in the Story_User join table

  • User.query.except_(User.query.join(Story_User)).all()

    • All users that don’t have stories

    • Explanation: Order all tasks by price

  • Query:

    • Explanation: All phones that have completed repairs

  • Query: Device.query.filter(device. odel_number.contains(‘A1’))

    • Explanation:

  • Query: Message.query.filter(Message.user_id.contains('Robert Hayek'))

    • Explanation: All messages sent by employees

    • Explanation: Returns all plasmids that are free/ link to assistance

  • Query: PlasmidOrder=DBSession.query(Plasmid).order_by(Plasmid.price)

    • Explanation: Query all plasmids ordered by price

  • Query: Plasmidall= DBSession.query(plasmid)

    • For plasmid in Plasmid:

    • print plasmid.name

    • Explanation: Query all available plasmids for sale (free and $$)

  • plasmidgene = DBSession.query(Book).filter_by(gene_id=str)

    • Query that shows all the plasmids bought that include a specific gene (sort by genes)

  • Announcement.query.filter(Announcement.school_id == 2).all()

  • Lists all of the groups at a particular school

    • Group.query.filter(Group.school_id == 2).all()

  • # Gives all the announcements that a certain user has made

    • Announcement.query.filter_by(user_id=2).all()

  • # Gives all of the announcements of a particular group

    • Announcement.query.filter(Announcement.group_id == 2).all()

  • Membership.query.filter(Membership.user_id==current_user.id, Membership.role=='Leader').all()

  • # NOT WORKING---- Gives all of the announcements for a particular user based on their groups

    • Announcement.query.join(Group.query.join(Membership)).filter(Membership.user_id == 2).all()

    • .filter(Membership.user_id == 2).all()

    • Group.query.join(Membership).filter(Announcement.query.filter_by(user_id=2).all()

  • A link that will trigger the creation of a new object or editing an existing object

    https://www.codementor.io/sheena/understanding-sqlalchemy-cheat-sheet-du107lawlarrow-up-right
    https://www.codementor.io/sheena/understanding-sqlalchemy-cheat-sheet-du107lawlarrow-up-right
    https://www.codepowered.com/manuals/SQLAlchemy-0.6.9-doc/html/orm/query.htmlarrow-up-right
    https://www.codementor.io/sheena/understanding-sqlalchemy-cheat-sheet-du107lawlarrow-up-right
    https://stackoverflow.com/questions/4926757/sqlalchemy-query-where-a-column-contains-a-substringarrow-up-right
    https://www.codementor.io/sheena/understanding-sqlalchemy-cheat-sheet-du107lawlarrow-up-right
    https://www.python.org/dev/peps/pep-0257/#what-is-a-docstringarrow-up-right
    More info for the try-hardsarrow-up-right
    Logo
    Logo
    models.py
    
    class Company(db.Model):
        """
        An organization that will serve as the primary contact point between projects
        """
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(80))    
        description = db.Column(db.Text)
        address = db.Column(db.Text)  # where to send the bill?
        website = db.Column(db.String(120)) 
        active = db.Column(db.Boolean())
        
        # ONE-TO-MANY relationships
        invoices_issued = db.relationship('Invoice', back_populates='issuer', foreign_keys="Invoice.issuer_id", lazy='dynamic')
        invoices_received = db.relationship('Invoice', back_populates='recipient', foreign_keys="Invoice.recipient_id", lazy='dynamic')
        
        # MANY-TO-MANY relationships
        users = db.relationship("Company_User", back_populates="company") # association table: connects a user to a company
    
        def __repr__(self):
            if self.name:
                return self.name
            else:
                return "Company ID#%d" % self.id
    models.py
    class Story(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.String(80))
        subtitle = db.Column(db.String(80))
        description = db.Column(db.Text)
        order_in_series = db.Column(db.Integer)
        image = db.Column(db.String(125))
        slug = db.Column(db.String(125), unique=True)
        publish_date = db.Column(db.DateTime)
        live = db.Column(db.Boolean)
        series_id = db.Column(db.Integer, db.ForeignKey('series.id'))
        
        # relationships
        series = db.relationship("Series", back_populates="stories")
        chapters = db.relationship('Chapter', back_populates='story', lazy='dynamic')
        characters = db.relationship('Character_Story', back_populates='story')
        users = db.relationship("Story_User", back_populates="story")
    
    models.py
    class Device(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
        name = db.Column(db.String(80))
        model_number = db.Column(db.String(80))
        serial_number = db.Column(db.String(80))
        created_date = db.Column(db.DateTime)
        live = db.Column(db.Boolean)
        
        # relationships
        user = db.relationship("User", back_populates="devices")
        tasks = db.relationship("Task", back_populates="device")
    
        # return the date in readable English    
        @property
        def created_on(self):
            return humanize.naturaltime(self.created_date)
    
        def __init__(self, user=None, name=None, model_number=None, serial_number=None, live=True):
                if user:
                    self.user_id = user.id
    
                self.name = name
                self.model_number = model_number
                self.serial_number = serial_number
                self.live = live
                self.created_date = datetime.now()
    
        def __repr__(self):
            return '<Device %r>' % self.name
    models.py
    class Group(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(80))
        school_id = db.Column(db.Integer, db.ForeignKey('school.id'))
        image = db.Column(db.String(125)) # could be the logo, team photo, whatever..
        live = db.Column(db.Boolean)
        body = db.Column(db.Text)
        meeting_place = db.Column(db.Text)
        meeting_time = db.Column(db.Text)
        
        school = db.relationship('School', back_populates='group')
        users = db.relationship('Membership', back_populates="group")
        announcements = db.relationship('Announcement', back_populates='group')
        # get the whole image path
        @property
        def imgsrc(self):
            if self.image:
                return uploaded_images.url(self.image)
            else:
                return None
    
        def __init__(self, user=None, name=None, body=None, meeting_place=None, live=True, meeting_time=None):
            self.school_id = user.school_id
            self.name = name 
            self.body = body
            self.meeting_place = meeting_place
            self.meeting_time = meeting_time
            self.live = live
    
        def __repr__(self):
            if self.name:
                return "Group %s" % self.name
            else:
                return 'Group #%d' % self.id
    
        def has_member(self, user):
            membership = db.query(Membership).filter_by(user_id=user.id, group_id=self.id).first()
            return bool(membership and "applicant" not in membership.role)
    
    def some_function():
        """
        This function doesn't do anything. It's just an example of building-in 
        the explanations that may one day enable your app to grow. 
        """
        some_object.different_function(example_param)
    @app.route('/superadmin')
    @roles_required('admin')
    def superadmin():
        data = {}
        data['users'] = User.query.all()
        return render_template('my_module/superadmin.html', data=data)
    	<tbody>
    	    {% for user in data['users'] %}
    		<tr>
    			<td>{{ user.first_name }}</td>
    			<td>{{ user.last_name }}</td>
    			<td>{{ user.email }}</td>
    			<td>22 Jun 1972</td>
    			<td><span class="badge badge-success">Active</span></td>
    			<td class="text-center">
    				<div class="list-icons">
    					<div class="dropdown">
    						<a href="#" class="list-icons-item" data-toggle="dropdown">
    							<i class="icon-menu9"></i>
    						</a>
    
    						<div class="dropdown-menu dropdown-menu-right">
    							<a href="{{ url_for('user.edit_view', id=user.id, url=url_for('superadmin')) }}" class="dropdown-item"><i class="icon-pencil"></i> Edit object</a>
    						</div>
    					</div>
    				</div>
    			</td>
    		</tr>
    		{% endfor %}
    	</tbody>
    Logo
    https://youtu.be/T8dNBmK40d0youtu.bechevron-right
    Logo
    Logo
    FlaskinniUML.drawioGoogle Docschevron-right
    I admit I'm lax with my UML discipline
    http://somup.com/cqh20NnBZDsomup.comchevron-right
    https://www.codementor.io/sheena/understanding-sqlalchemy-cheat-sheet-du107lawlwww.codementor.iochevron-right
    Logo
    Logo
    Logo