google meet link: https://meet.google.com/umh-pgbg-mny
Note:
Continue working on Final Projects
JSON example here
Platformer state machine example here
Design and start implementing final projects
A separate repository for final project notes is here: https://github.com/cmorace/PeanutsPythonFinalProject
Eric: CandyCats Repository
Feng-Jun: MailModel Repository
Example 0. Check OpenCV version
import cv2 as cv
print("OpenCV version:", cv.__version__)
Example 1. Load, Save, and View an Image
import cv2 as cv
import sys
img = cv.imread("images/baboon.bmp")
if img is None:
sys.exit("Could not read the image.")
cv.imshow("Display window", img)
k = cv.waitKey(0)
if k == ord("s"):
cv.imwrite("saved_cv_image.png", img)
Example 2. Detect a cat’s face in an image
import cv2 as cv
print("OpenCV version:", cv.__version__)
cascade = cv.CascadeClassifier('cat_face_extended.xml')
img = cv.imread("01_cat.webp")
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cats = cascade.detectMultiScale(img_gray, scaleFactor=1.05, minNeighbors=4)
print(len(cats), "cat faces detected")
for (x, y, w, h) in cats:
cv.rectangle(img, pt1=(x, y), pt2=(x+w, y+h),
color=(255, 255, 0), thickness=2)
Download the cascade classifier XML file from here
View and save the image showing the detected cat’s face. If faces are not detected, tune the parameters for scaleFactor and minNeighbors.
Download other cascade classifiers from here and detect other objects in an image.
try/except
, Exceptions
conn, addr = socket.accept()
conn.sendto(sent_message.encode(), addr)
received_message = str(conn.recv(1024), encoding='utf-8')
conn.close()
thread = Thread(target=foo, args=(a,b,))
thread.start()
Main Thread
------------
set is_waiting_for_connection = False
while True
if not is_waiting_for_connection:
start thread to receive a connection
for each connection
if connection is not waiting for message
start a new receiving thread
Receive Connection Thread
---------------------------
set is_waiting_for_connection = True
when receive new connection:
add connection to list of connections
send back acknowledgment to cliet
set is_waiting_for_connection = False
Receive Message Thread (every connection has a seperate thread)
-------------------------
set connection_is_waiting = True
try to get a new message
receive message
set connection_is_waiting = False
send acknowledgement back to client
except error close connection
close connection
remove connection from list of connections
Set up two client windows and one server window and test.
Review Reference socket
a. socket.sendall()
vs. socket.sendto()
vs. socket.send()
b. socket.accept()
Review try/except
details. Reference: errors
Implement try/except
in server.py
Design and implement a state machine for the server.
a. Clean up the code. Make Server a class.
Introduce multi-threading. Reference threading
Implement multi-threading in server.py
types, arrays, pointers, sizeof
example of pass-by-value, pass-by-reference, and pass-by-pointer
using the apt package manager
introduce Bash scripting
introduce GNU make
Is docker-desktop still not working? It would be nice to work in the same environment if possible.
Last week our environments for practicing Linux and C
Aliases
alias update-pycat="pip install git+https://bitbucket.org/dwhite0/pycat.git -U"
alias python-class="code <your absolute workspace path>"
alias bashrc="code ~/.bashrc"
alias gcc="<path to gcc.exe>" # for windows
Export Path variable
export PATH="<bin directory>:$PATH"
Check your C compiler
gcc --version
Write two functions in C
Compile with gcc
Server
import socket
HOST = '127.0.0.1'
PORT = 8000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(10)
conn, addr = server.accept() # wait until get a message
serverMessage = 'connected to client'
conn.sendall(serverMessage.encode())
while True:
clientMessage = str(conn.recv(1024), encoding='utf-8')
print('Client message is:', clientMessage)
serverMessage = 'I\'m here!'
conn.sendall(serverMessage.encode())
Client
import socket
from pycat.core import Window, Sprite
HOST = '127.0.0.1'
PORT = 8000
clientMessage = 'Hello!'
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
w = Window(200, 200)
class Button(Sprite):
def on_create(self):
self.scale = 100
self.position = w.center
def on_left_click(self):
print("sending to server")
client.sendall(clientMessage.encode())
serverMessage = str(client.recv(1024), encoding='utf-8')
print('Server:', serverMessage)
w.create_sprite(Button)
w.run()
try
/except
Can we design a reusable module for a two-player server-client model?
My solutions are in the repository. I recommend trying your best to solve them on your own before looking. Note: the solution to question 4 exceeds the time limit for most test cases on ZeroJudge.
Linux is an open-source operating system with many distributions to choose from, e.g., Ubuntu, Debian, Red Hat, ArchLinux, CentOS, etc.
There are a few different options for running Linux distributions.
Installing a new operating system on your pc is risky and time-consuming. If anything goes wrong, you might have to reinstall. Don’t do this unless you have a lot of experience debugging installation and hardware problems with Linux.
Dual-boot: Partition your hard drive and install Linux on one of the partitions. One partition runs your current O.S., and the other runs a Linux distribution. Also time-consuming. Less risky than option 1. but requires some experience with Linux and partitioning your disk.
Use a virtual machine. We have done this in the past with the APCS environment. A virtual machine is a very safe option but requires some knowledge of the virtualization software, e.g., VirtualBox. Performance is limited.
Use a development container with Docker, the safest and easiest method, but you only have access to a shell environment. There is no GUI. Performance is usually better than running a virtual machine. Containers make it easy to set up, test quickly, and deploy different development environments but require some knowledge of Docker.
create a file with the touch <filename>
command
delete a file with rm <filename>
create a directory with mkdir <dirname>
navigate the filesystem with cd
print the working directory with the command pwd
show the contents of a file with the commands cat
, head
, and tail
show the contents of a directory with ls
how to use help
import socket
HOST = '127.0.0.1'
PORT = 8000
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(10)
while True:
conn, addr = server.accept()
clientMessage = str(conn.recv(1024), encoding='utf-8')
print('Client message is:', clientMessage)
serverMessage = 'I\'m here!'
conn.sendall(serverMessage.encode())
conn.close()
import socket
HOST = '127.0.0.1'
PORT = 8000
clientMessage = 'Hello!'
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))
client.sendall(clientMessage.encode())
serverMessage = str(client.recv(1024), encoding='utf-8')
print('Server:', serverMessage)
client.close()
Discuss the future of our class
a. Independent Project-Based (self-directed) vs. Planned Lesson (teacher-led)
b. More APCS practice/homework?
c. New directions? C/C++, Unity, Web Programming, 3D Graphics, Computer Vision, Machine Learning, Visualization, Operating Systems/Multi-threading/interprocess-communication, etc.
Today’s lesson
a. Look at new pycat projects
Asteroids
GeoGuesser
Animal Crossings
b. Choose a project and start working on it
Start with planned lessons
Add some C programming
Add some multiprocess lessons (server/client). Maybe turn Asteroids into a remote two-player game?
Add some Linux (Feng-Jun)
Do an independent project
Continue some APCS (more APCS content closer to the next test date, 2023-01-08)
Look at the most recent APCS problems https://yuihuang.com/apcs/. Then, work on the solutions and submit them to ZeroJudge. Review questions next class.
Continue working on your current Asteroids game.
Research/Design a two-player asteroid game.
a. Two computers with different IP addresses (two clients). One server synchronizes data between the two clients. Therefore, we need two programs, one for the client and another for the server.
b. Draw a diagram with the clients and server. What messages need to be sent and received for the game to work?
c. Draw one state-transition diagram for the server application and another for the client applications.
d. Explain your diagrams in the next class.
e. Research what python functions can send/receive data between multiple processes?
pip install git+https://bitbucket.org/dwhite0/pycat.git -U
clone pycat repo (optional)
git clone git@bitbucket.org:dwhite0/pycat.git