diff --git a/_data/content.yml b/_data/content.yml index 2c10423a..8cb2c6e3 100644 --- a/_data/content.yml +++ b/_data/content.yml @@ -3,146 +3,191 @@ assignments: title: Linked Lists and Recursion assigned: true regrade_form: - submit_link: + submit_link: https://bytes.usc.edu/cs104/submit/course/usc-csci104-summer2023 dates: - assigned: - checkpoint: - due: Friday, January 27th 11:59PM PST + assigned: Thursday, May 18 +# checkpoint: Friday, January 21 at 11:59PM PST + due: Tuesday, May 30 at 11:59PM Pacific - id: hw2 title: Inheritance, Polymorphism, and STL - assigned: false + assigned: true regrade_form: - submit_link: + submit_link: https://bytes.usc.edu/cs104/submit/course/usc-csci104-summer2023 dates: - assigned: - checkpoint: - due: Friday, February 10th 11:59PM PST + assigned: Sunday, May 28 +# checkpoint: Friday, Februrary 4 at 11:59PM PST + due: Thursday, June 8 at 11:59PM PST - id: hw3 title: Heaps - assigned: false + assigned: true regrade_form: - submit_link: + submit_link: https://bytes.usc.edu/cs104/submit/course/usc-csci104-summer2023 dates: - assigned: - checkpoint: - due: Friday, February 24th at 11:59PM PST + assigned: Thursday, June 8 +# checkpoint: Friday, Februrary 18 at 11:59PM PST + due: Saturday, June 17 at 11:59PM PST - id: hw4 title: AVL Trees - assigned: false + assigned: true regrade_form: - submit_link: + submit_link: https://bytes.usc.edu/cs104/submit/course/usc-csci104-summer2023 dates: - assigned: - checkpoint: - due: Friday, March 24th at 11:59PM PDT + assigned: Friday, June 16 +# checkpoint: Friday, March 25 at 11:59PM PST +# due: Sunday, July 2 at 11:59PM Pacific + due: Wednesday, July 5 at 11:59PM Pacific - id: hw5 title: Counting, Probability, Recursion - assigned: false + assigned: true regrade_form: - submit_link: + submit_link: https://bytes.usc.edu/cs104/submit/course/usc-csci104-summer2023 dates: - assigned: - checkpoint: - due: Friday, April 7th at 11:59PM PST + assigned: Thursday, June 29 +# checkpoint: Friday, April 8 at 11:59PM PST + due: Tuesday, July 11 at 11:59PM Pacific - id: hw6 title: Hash tables - assigned: false + assigned: true regrade_form: - submit_link: + submit_link: https://bytes.usc.edu/cs104/submit/course/usc-csci104-summer2023 dates: - assigned: - checkpoint: - due: Friday, April 28th at 11:59PM PST + assigned: Friday, July 7 +# checkpoint: Friday, April 22 at 11:59PM PST + due: Sunday, July 16 at 11:59PM Pacific labs: - - id: lab0 + - id: 0 + folder: su-lab0-curricula week: Before title: Getting Started assigned: true topics: Github, curricula, registration, setup - - id: lab1 + - id: 1 + folder: su-lab1 week: Week 1 title: Git Tutorial assigned: true topics: Git, github - slides: git_lab.pdf - - id: lab2 - week: Week 2 + slides: + - git_lab.pdf + - AppendixA_Git.pdf + - id: 2 + folder: su-lab2 + week: Week 1 title: GDB assigned: true topics: Debugging, GDB, tooling slides: Lab2_slides.pdf - - id: lab3 - week: Week 3 + - id: 3 + folder: lab3 + week: Week 2 title: Makefiles assigned: true topics: Make, makefiles, build systems slides: makefile_lab.pdf - - id: lab4 - week: Week 4 + - id: 4 + folder: su-gtest_lab + title: GTest + week: Week 2 + assigned: true + topics: Unit Testing, GTest + slides: gtest_slides.pdf + - id: 5 + folder: lab4 + week: Week 3 title: Inheritance and STL assigned: true topics: Object Oriented Programming slides: stl_inh_lab.pdf - - id: lab5 - week: Week 5 + - id: 6 + folder: lab5 + week: Week 4 title: Templates assigned: true topics: Object Oriented Programming slides: templates_lab.pdf - - id: lab6 - week: Week 6 + - id: 7 + folder: lab6 + week: Week 4 title: Heaps assigned: true topics: Heaps slides: heap_lab.pdf - - id: lab7 - week: Week 7 + - id: 8 + folder: su-llrec + week: Week 5 + title: LList Recursion + Makeup Lecture + assigned: false + topics: LinkedList Recursion + slides: + - ll_rec_practice.pdf + - ll_rec_practice_soln.cpp + - id: 9 + folder: lab7 + week: Week 6 title: Backtracking assigned: true topics: Recursive Backtracking - slides: Backtracking_Lab.pdf - - id: NO LAB - week: Week 8 - title: Optional Midterm Review - assigned: false - topics: - - id: lab9 - week: Week 9 - title: BST and AVL + slides: + - Backtracking_BST_AVL.pdf + - Backtracking_Lab_su22.pdf + - id: 10 + folder: bst-lab8 + week: Week 6 + title: BST and Traversal assigned: true topics: BST and AVL Trees - slides: Lab9_BST_AVL.pdf - - id: lab10 - week: Week 10 - title: Hashtables - assigned: true - topics: Hashtables - - id: lab11 - week: Week 11 - title: Counting + slides: + - Backtracking_BST_AVL.pdf +# - id: 10 +# folder: su-lab8-avl +# week: Week 6 +# title: BST and AVL +# assigned: true +# topics: BST and AVL Trees +# slides: Lab9_BST_AVL.pdf + - id: 11 + folder: mt + week: Week 7 + title: Midterm + assigned: false + topics: + - id: 12 + folder: lab11 + week: Week 8 + title: Counting! assigned: true topics: Counting slides: counting_lab.pdf - - id: lab12 - week: Week 12 - title: Probability + - id: 13 + folder: lab12 + week: Week 8 + title: Probability? assigned: true topics: Probability slides: probability_lab.pdf - - id: lab13 - title: Number Theory - week: Week 13 +# - id: NO LAB +# week: Week 8 +# title: Optional Midterm Review +# assigned: false +# topics: + - id: 14 + folder: lab10 + week: Week 9 + title: Hashtables assigned: true - topics: - - id: lab14 - title: GTest - week: Week 14 + topics: Hashtables + slides: hashtable_lab.pdf + - id: 15 + folder: lab13 + title: Number Theory + week: Week 9 assigned: true - topics: Unit Testing, GTest - - id: - title: Final Review - week: Week 15 - assigned: false - topics: + topics: Number Theory + slides: number_theory_lab.pdf +# - id: +# title: Final Review +# week: Week 15 +# assigned: false +# topics: diff --git a/_data/course.yml b/_data/course.yml index f210a006..a9ce729e 100644 --- a/_data/course.yml +++ b/_data/course.yml @@ -1,71 +1,21 @@ -semester: Spring 2023 -short: usc-csci104-spring2023 +semester: Summer 2023 +short: usc-csci104-summer2023 sections: lectures: - - id: 29989 + - id: 29903 days: Tuesday, Thursday - time: 8:00 AM to 9:20 AM Pacific - location: SGM 101 - instructors: Andrew Goodney - - id: 29905 - days: Tuesday, Thursday - time: 11:00 AM to 12:20 PM Pacific - location: THH 201 - instructors: Andrew Goodney + time: 9:30 AM to 11:45 AM Pacific + location: SLH 100 + instructors: Mark Redekopp labs: - - id: 29912 - days: Wednesday - time: 5:00-6:50pm - location: SAL109 - instructors: Charles Bickham - - id: 29914 - days: Wednesday - time: 3:00-4:50pm - location: SAL126 - instructors: Elan Markowitz - - id: 29915 - days: Wednesday - time: 12:00-1:50pm - location: SAL126 - instructors: Satyaki Das - - id: 30167 - days: Friday - time: 12:00-1:50pm - location: SAL109 - instructors: Leo Zhuang - - id: 30200 - days: Tuesday - time: 3:30-5:20pm - location: SAL126 - instructors: Matt Leslie - - id: 30238 - days: Tuesday - time: 5:30-7:20pm - location: SAL126 - instructors: Bridget Bell - - id: 30286 + - id: 29904 days: Wednesday - time: 12:00-1:50pm - location: SAL109 - instructors: Nicole Russack - - id: 30293 - days: Friday - time: 2:00-3:50pm - location: SAL126 - instructors: Nicholas Schumacher - - id: 30294 - days: Tuesday - time: 1:00-2:50pm - location: SAL126 - instructors: Mila Mathias - - id: 30379 - days: Thursday - time: 2:00-3:50pm - location: SAL127 - instructors: Charles Bickham - - id: 30394 + time: 10:00 AM to 11:50 AM Pacific + location: SAL 126 + instructors: Staff + - id: 29959 days: Wednesday - time: 2:00-3:50pm - location: SAL109 - instructors: Skylar Kim \ No newline at end of file + time: 10:00 AM to 11:50 AM Pacific + location: SAL 126 + instructors: Staff diff --git a/_data/navigation.yml b/_data/navigation.yml index 862d3c79..2b8e099a 100644 --- a/_data/navigation.yml +++ b/_data/navigation.yml @@ -1,6 +1,6 @@ items: - title: Office hours queue - url: /q/ + url: /queue/ menubar: false icon: /assets/img/icon/duration.svg - title: Staff and hours diff --git a/_data/people.yml b/_data/people.yml index 7e81040a..52ee7089 100644 --- a/_data/people.yml +++ b/_data/people.yml @@ -1,235 +1,56 @@ instructors: - - name: Andrew Goodney - email: goodney@usc.edu - image: /assets/img/staff/goodney.jpg - hours: '
10am - 12pm M/W
1pm - 3pm M
' - location: PHE 406 - -administrators: - - name: Tallulah Winston-Schrader - email: winstons@usc.edu - image: /assets/img/staff/tallulah.jpg + - name: Mark Redekopp + email: redekopp@usc.edu + image: /assets/img/staff/redekopp-crop.jpg + hours: "T,Th: 8-9 am and 12:30-1:30 pm, W: 1:30-2:30 pm" + location: EEB-222 assistants: - - name: Sumeet Batra - email: ssbatra@usc.edu - image: /assets/img/staff/sumeet.jpg + - name: Nathan Bartley + email: nbartley@usc.edu + image: /assets/img/staff/nbartley.jpg hours: >- See Google Calendar - - name: Charles Bickham - email: cbickham@usc.edu - image: /assets/img/staff/charles.jpg + location: Zoom + - name: Yuliang Cai + email: caiyulia@usc.edu + image: /assets/img/staff/caiyulia.jpg hours: >- See Google Calendar - - name: Satyaki Das - email: satyakid@usc.edu - image: /assets/img/staff/satyaki.jpg + location: Zoom + - name: Tingting Tang + email: tangting@usc.edu + image: /assets/img/staff/tangting.jpg hours: >- See Google Calendar - - name: Elan Markowitz - email: esmarkow@usc.edu - image: /assets/img/staff/elan.jpeg + location: Zoom + - name: Gozde Sahin + email: gsahin@usc.edu + image: /assets/img/staff/gozde_sahin.jpg hours: >- See Google Calendar + location: Zoom staff: - - name: Louis Addison - email: laddison@usc.edu - image: /assets/img/staff/louis.jpg - hours: >- - See Google Calendar - - name: Ishu Agrawal - email: ishuagra@usc.edu - image: /assets/img/staff/ishu.jpeg - hours: >- - See Google Calendar - - name: Anahita Ahmadi - email: anahitaa@usc.edu - image: /assets/img/staff/anahita.jpg - hours: >- - See Google Calendar - - name: Joshua Argote - email: argoteme@usc.edu - image: /assets/img/staff/joshua.jpg - hours: >- - See Google Calendar - - name: Siddhant Bajaj - email: bajajs@usc.edu - image: /assets/img/staff/siddhantbajaj.jpg - hours: >- - See Google Calendar - - name: Bridget Bell - email: bgbell@usc.edu - image: /assets/img/staff/bridget.jpg - hours: >- - See Google Calendar - - name: Nic Buxbaum - email: nbuxbaum@usc.edu - image: /assets/img/staff/nic.jpg - hours: >- - See Google Calendar - - name: Jessica Cheung - email: cheungje@usc.edu - image: /assets/img/staff/jessica.jpg - hours: >- - See Google Calendar - - name: James Fan - email: jlfan@usc.edu - image: /assets/img/staff/james.jpg - hours: >- - See Google Calendar - - name: Jason Gao - email: jasongao@usc.edu - image: /assets/img/staff/jasongao.jpg - hours: >- - See Google Calendar - - name: Isaac Gerstmann - email: ig_707@usc.edu - image: /assets/img/staff/isaac.jpg - hours: >- - See Google Calendar - - name: Paul Kim - email: pbkim@usc.edu - image: /assets/img/staff/paul.jpg - hours: >- - See Google Calendar - - name: Skylar Kim - email: kimsooye@usc.edu - image: /assets/img/staff/skylar.png - hours: >- - See Google Calendar - - name: Matt Leslie - email: mtleslie@usc.edu - image: /assets/img/staff/matt.jpg - hours: >- - See Google Calendar - - name: Kathleen Luo - email: krluo@usc.edu - image: /assets/img/staff/kathleen.jpg - hours: >- - See Google Calendar - - name: Jacob Ma - email: jingzema@usc.edu - image: /assets/img/staff/jacobma.jpg - hours: >- - See Google Calendar - - name: Mila Mathias - email: memathia@usc.edu - image: /assets/img/staff/mila2.jpg - hours: >- - See Google Calendar - - name: David Morales - email: davidm62@usc.edu - image: /assets/img/staff/davidmorales.jpg - hours: >- - See Google Calendar - - name: Nick Prestine - email: prestine@usc.edu - image: /assets/img/staff/nick.jpeg - hours: >- - See Google Calendar - - name: Sid Qian - email: sidqian@usc.edu - image: /assets/img/staff/sid.jpg - hours: >- - Ed Discussion Only - - name: Amy Rong - email: shiqingr@usc.edu - image: /assets/img/staff/amy.jpg - hours: >- - Ed Discussion Only - - name: Nicole Russack - email: russack@usc.edu - image: /assets/img/staff/nicole.jpg - hours: >- - See Google Calendar - - name: Nicholas Schumacher - email: naschuma@usc.edu - image: /assets/img/staff/nicolas.jpg - hours: >- - See Google Calendar - - name: Sam Sommerer - email: sommerer@usc.edu - image: /assets/img/staff/sam.jpg - hours: >- - See Google Calendar - - name: Monil Sorathia - email: msorathi@usc.edu - image: /assets/img/staff/monil2.jpg - hours: >- - See Google Calendar - - name: Madhu Suraj - email: msuraj@usc.edu - image: /assets/img/staff/madhu.jpg - hours: >- - See Google Calendar - - name: Winfred Wang - email: wzwang@usc.edu - image: /assets/img/staff/winfred.jpg - hours: >- - See Google Calendar - - name: Crystal Wu - email: wucrysta@usc.edu - image: /assets/img/staff/crystal.jpg - hours: >- - See Google Calendar - - name: David Xu - email: davidx@usc.edu - image: /assets/img/staff/david.jpg - hours: >- - See Google Calendar - - name: Xiaoqian Xu - email: xuxiaoqi@usc.edu - image: /assets/img/staff/xiaoqian.jpg + - name: Raymond Liu + email: liuraymo@usc.edu + image: /assets/img/staff/raymond.jpg hours: >- See Google Calendar - - name: Daniel Zeng - email: zengd@usc.edu - image: /assets/img/staff/danielzeng.jpeg + - name: Jonathan Ong + email: ongjd@usc.edu + image: /assets/img/staff/ongjd.jpg hours: >- See Google Calendar - - name: Zuoning Zhang - email: zuoningz@usc.edu - image: /assets/img/staff/zuoning.jpeg + - name: Linda Tam + email: lindatam@usc.edu + image: /assets/img/staff/lindatam.jpg hours: >- See Google Calendar - - name: Leo Zhuang - email: llzhuang@usc.edu - image: /assets/img/staff/leo.JPG + - name: Iman Arfa-Zanganeh + email: arfazang@usc.edu + image: /assets/img/staff/iman.jpeg hours: >- See Google Calendar graders: - - name: Deepa Avhad - email: davhad@usc.edu - image: /assets/img/staff/deepa.jpg - - name: Harshali Bedmutha - email: hbedmuth@usc.edu - image: /assets/img/staff/harshali.jpg - - name: Smit Kadvani - email: kadvani@usc.edu - image: /assets/img/staff/smit.jpg - - name: Suryakant Kashyap - email: suryakan@usc.edu - image: /assets/img/staff/suryakant.jpg - - name: Sarthak Mishra - email: sarthakm@usc.edu - image: /assets/img/staff/sarthak.jpg - - name: Kishan Murthy - email: knarasim@usc.edu - image: /assets/img/staff/kishan.jpeg - - name: Avanti Panchani - email: apanchan@usc.edu - image: /assets/img/staff/avanti.jpg - - name: Prakash Parajuli - email: parajuli@usc.edu - image: /assets/img/staff/temp.png - - name: Raj Patel - email: rajashif@usc.edu - image: /assets/img/staff/raj.jpg - - name: Sudhanshu Rai - email: sudhansh@usc.edu - image: /assets/img/staff/temp.png - - name: Ashutosh Sharma - email: asharma7@usc.edu - image: /assets/img/staff/ashutosh.jpeg diff --git a/_data/schedule.yml b/_data/schedule.yml index 7f715b30..f541d259 100644 --- a/_data/schedule.yml +++ b/_data/schedule.yml @@ -6,235 +6,180 @@ show: exams: - - name: MT - time: Thursday March 2nd at 7 PM Pacific - location: TBA + - name: MT1 + time: Wed, June 28 at 10 AM Pacific + location: In-Person link: mt1-info/ - name: Final - time: Wednesday, May 3rd, 8 AM - location: See Blackboard for specific assignment OHE 122, SOS B2, WPH B27, ZHS 159, ZHS 252, ZHS 352, ZHS 360 (OSAS) + time: Tues, July 18 at 9:30 AM Pacific + location: In-Person (GFS 116) link: final-info/ lectures: - # 1 Tue 8/23 + # 1 Thurs May 20 - topics: - Course overview - Motivation for Data Structures - - Review (Memory Allocation) + - Review (Memory Allocation, Classes) + - Runtime chapters: - Chapter 1.1-1.5 - Chapter 2 notes: - L01_Overview.pdf - L02a_MemAlloc.pdf + - L02b_Classes.pdf + - L02d_Runtime.pdf recording: - # 2 Thur 8/25 + # 2 Tues May 25 - topics: - - Classes (Initialization Lists) - - Linked Lists + - Review (Operator Overload, Linked Lists) + - Recursion chapters: - Chapter 1.4 - Chapter 3.3-3.5 - Chapter 1.3 notes: - - L02b_Classes.pdf + - L02c_OperatorOverloading.pdf - L02e_LinkedLists.pdf + - L03_Recursion.pdf recording: - # 3 Tue 8/30 - - topics: - - Linked Lists (cont.) - - Operator Overloading Review (if time) - - Runtime - chapters: - - Chapter 1.4 - - Chapter 3.3-3.5 - - Chapter 1.3 - notes: - - L02e_LinkedLists.pdf - - L02c_OperatorOverloading.pdf - - L02d_Runtime.pdf - recording: - - # 4 Thur 9/1 + # 3 Thurs May 27 - topics: - Recursion - - Copy Semantics + - ADTs + - STL chapters: - Chapter 1.3, 1.5 - Chapter 3.1-3.3, 4.8 notes: - L03_Recursion.pdf - - L02f_CopyConstructors.pdf - recording: - - # 5 Tue 9/6 - - topics: - - Recursion - - ADTs - - STL - chapters: - - Chapter 3.3,4.8 - - Course Notes - notes: - L04_ADTs.pdf - L05_STL.pdf recording: - # 6 Thur 9/8 + # 4 Tues Jun 1 - topics: - STL - Inheritance - Polymorphism chapters: - - Chapter 3.6-3.7 + - Chapter 3.3,4.8 + - Course Notes notes: - L05_STL.pdf - L06a_Inheritance.pdf - recording: - - # 7 Tue 9/13 - - topics: - - Polymorphism - - ArrayLists - chapters: - - Chapter 3.6-3.7 - notes: - L06b_Polymorphism.pdf - - L07_QueueStackDeque.pdf - - # 8 Thur 9/15 + recording: + + # 5 Thurs Jun 3 - topics: + - Review (Polymorphism, STL) - Stacks and Queues - - Templates chapters: - Chapter 3.6-3.7 - - Chapter 1.6 notes: - L07_QueueStackDeque.pdf - - L08_Templates.pdf + recording: - # 9 Tue 9/20 + # 6 Tues Jun 8 - topics: - Templates - - Trees + - Trees and Heaps chapters: + - Chapter 1.6 - Chapter 4.1-4.2 - notes: - - L09_PQHeaps.pdf - - # 10 Thur 9/22 - - topics: - - Heaps - chapters: - Chapter 6.1-6.5 - - Chapter 9.1 notes: + - L08_Templates.pdf - L09_PQHeaps.pdf - - # 11 Tue 9/27 + + # 7 Thurs Jun 10 - topics: - - Heapsort and build-heap - - Graph Algorithms + - More Heaps + - Graphs chapters: - - Chapter 9.3 + - Chapter 9.1 notes: - L10_GraphsAlgorithms.pdf - - # 12 Thur 9/29 + + # 8 Tues Jun 15 - topics: - - Graph Traversals + - Graph Algorithms - Tree Traversals chapters: - - Chapter 9.2-9.3,9.6 - - Chapter 4.1-4.2,4.6 + - Chapter 9.3 + - Chapter 4.1-4.2 notes: - L11_GraphTraversals.pdf - - # 13 Tue 10/4 + + # 9 Thurs Jun 17 - topics: - Recursion - All combinations - chapters: - - Chapter 2 - - Class Notes - notes: - - L12_BacktrackingSearch.pdf - - # 15 Tue 10/11 - - topics: - Recursion - Backtracking - Iterators chapters: - - Chapter 4.3-4.4 + - Class Notes notes: + - L12_BacktrackingSearch.pdf - L13_Iterators.pdf - - # 17 Tue 10/18 - - topics: - - Binary Search Trees - chapters: - - Chapter 4.3-4.4 - notes: - L14_BalancedBST_AVL.pdf - # 18 Thur 10/20 + # 10 Tues Jun 22 - topics: + - Binary Search Trees - AVL Trees chapters: - - Chapter 4.4-4.5,4.7 + - Chapter 4.3-4.4 notes: - L14_BalancedBST_AVL.pdf - - L14_BalancedBST_AVL_Handout.pdf - # 20 Tue 10/25 + # 11 Thurs Jun 24 - topics: + - AVL Trees - Splay Trees - - Hash Table introduction chapters: - - Chapter 4.7,5.1,5.3 + - Chapter 4.5 + - Chapter 5.1-5.3 notes: - L15_SplayTrees.pdf + - L16_HashingIntro.pdf - # 21 Thur 10/27 + # 12 Tues Jun 29 - topics: - Hash Table introduction - - Counting + - Midterm Review chapters: - Chapter 5.1-5.3 - - Lewis & Zax Chapter 22 notes: - L16_HashingIntro.pdf - # 22 Tue 11/1 + # 13 Thurs July 1 - topics: - Counting chapters: + - Lewis & Zax Chapter 22 - Lewis & Zax Chapter 23 notes: - L17_Counting.pdf - # 23 Thur 11/3 + # 14 Tues July 6 - topics: - Probability chapters: - Lewis & Zax Chapter 26 - notes: - - L18_Probability.pdf - - # 24 Tue 11/8 - - topics: - - Probability - chapters: - Lewis & Zax Chapter 27 - Lewis & Zax Chapter 28 notes: - L18_Probability.pdf - # 25 Thur 11/10 + # 15 Thurs July 8 - topics: + - Probability (cont.) - Number Theory chapters: - Lewis & Zax Chapter 29 @@ -242,49 +187,32 @@ lectures: notes: - L19_NumberTheory.pdf - # 26 Tue 11/15 + # 16 Tues July 13 - topics: - - Number Theory - - Hash Functions - chapters: - - Lewis & Zax Chapter 31 - notes: - - L19_NumberTheory.pdf - - L20_HashFunctions.pdf - - # 27 Thur 11/17 - - topics: - - Hash Functions and Bloom Filters + - Hash Functions & Bloom Filters + - Tries (During lab?) + - (Skip Lists, if time) chapters: - - Chapter 5 + - Chapter 12.4.2 notes: - L20_HashFunctions.pdf - - # 28 Tue 11/22 - - topics: - - Tries - - Skip Lists - chapters: - - Chapter 5 - - Chapter 12.4, 11.1, 11.5 - notes: + - L21_ProbabilisticStructures.pdf - L22_Tries.pdf - - L21_SkipLists.pdf - - # 30 Tue 11/29 + + # 17 Thurs July 15 - topics: - Amortized Analysis - Merge Trees + - Review and Wrapup chapters: - - Chapter 11.1,11.5 + - Chapter 12.4.2 notes: - L23_AmortizedAnalysis.pdf - L24_MergeTrees.pdf - # 31 Thur 12/1 + # 18 Tues July 20 - topics: - - Final Review + - Final chapters: - - Class notes notes: - - L25_Review.pdf \ No newline at end of file + diff --git a/_data/urls.yml b/_data/urls.yml index e36aae51..1827d69c 100644 --- a/_data/urls.yml +++ b/_data/urls.yml @@ -1,32 +1,25 @@ qa_tool: EdStem -piazza: https://edstem.org/us/courses/32694/discussion/ -admin_piazza: https://piazza.com/usc/spring2023/csci104/home -discussion: https://edstem.org/us/courses/32694/discussion/ -discussion-join: https://edstem.org/us/join/8gVhAf -admin_discussion-join: https://piazza.com/usc/spring2023/csci104 -calendar: https://calendar.google.com/calendar/embed?src=c_719cef00borqimhoifnopko60k%40group.calendar.google.com&ctz=America%2FLos_Angeles -github: https://github.com/usc-csci104-summer2022 -github_ssh: git@github.com:usc-csci104-summer2022 -github_org: 'usc-csci104-summer2022' +#piazza: https://edstem.org/us/courses/39168/discussion/ +discussion: https://edstem.org/us/courses/39168/discussion/ +calendar: https://calendar.google.com/calendar/embed?src=c_u2lqs93tskk0tkkm1b2a0e6ae4%40group.calendar.google.com&ctz=America%2FLos_Angeles +github: https://github.com/usc-csci104-summer2023 +github_ssh: git@github.com:usc-csci104-summer2023 +github_org: 'usc-csci104-summer2023' # discord: https://discord.gg/YNAzZkF vm: https://bytes.usc.edu/files/cs103/VM/StudentVM_Spring2018.ova blackboard: https://blackboard.usc.edu/ notes: http://david-kempe.com/teaching/DataStructures.pdf -# these are the same, the html and md files should be searched and fixed -regrades: https://forms.gle/Jj742f1EbM3vEdVcA -regrade_form: https://forms.gle/Jj742f1EbM3vEdVcA -slug: cs104-sp23 -slide_location: http://bytes.usc.edu/files/cs104/slides -extension_form: https://forms.gle/GBi6FR7wp31hYFtq7 +regrades: https://docs.google.com/forms/d/e/1FAIpQLSdlNBkRADp72r79-mN2HbjCpYV18fmxnfDIoyRAuDMNry912Q/viewform?usp=sf_link +slug: cs104-su23 +slide_location: http://ee.usc.edu/~redekopp/cs104/slides +extension_form: https://docs.google.com/forms/d/e/1FAIpQLSfK3DCfSHyumVF8X0hNN3cYVj5NAk1ZEu30QbMuETbhJMdIjg/viewform?usp=sf_link visual_code: https://code.visualstudio.com/download docker_repo: https://github.com/csci104/docker lab_form: git_tut_slides: http://ee.usc.edu/~redekopp/cs104/slides/L99_AppendixA_Git.pdf -osas_dsp_form: https://forms.gle/q4sUNnMMpaUEmXyT8 +osas_dsp_form: https://docs.google.com/forms/d/e/1FAIpQLSe7qclvtY3MvTYodIPDGjapkwKSlnaHJ4r0JeQxv4Z5kyQ0mw/viewform?usp=sf_link account_ta_name: Nathan Bartley account_ta_email: nbartley@usc.edu -ooqueue: https://immasignup.com/q/puuh/ -codio_course: https://codio.com/home/student?course_id=840256c1505b0176dc1e1af66a1e992b -codio_join: https://codio.com/p/signup?courseToken=pacific-lily -covid_lab: https://forms.gle/GuyuVfw33ehAx68S9 +osas: https://osas.usc.edu/ +uscsupport: https://campussupport.usc.edu/ \ No newline at end of file diff --git a/_includes/writeups/git-1.md b/_includes/writeups/git-1.md index 3da666f8..7634dfa6 100644 --- a/_includes/writeups/git-1.md +++ b/_includes/writeups/git-1.md @@ -13,7 +13,7 @@ When cloning a Git repo, which of the following should you avoid: Provide the appropriate git command to perform the following operations: 1. Stage an untracked file to be committed. The file is called 'hw1q2b.cpp'. -1. Display the details of the last three commits in the repository. +1. Display the details of the last three commits in the repository (hint: checkout this [webpage](https://git-scm.com/book/en/v2/Git-Basics-Viewing-the-Commit-History) ) #### Part (c) What is the full command to re-clone your private CSCI104 repo to your VM? Assume you are in an appropriate folder. diff --git a/_includes/writeups/git-2.md b/_includes/writeups/git-2.md index 69622d7d..db6969e4 100644 --- a/_includes/writeups/git-2.md +++ b/_includes/writeups/git-2.md @@ -7,7 +7,6 @@ Notes: - Parts (a) through (f) should be done in sequence. In other words, when you get to part (f), you should assume that you already executed the earlier commands (a), (b), ..., (e). You **must** use the terminology specified in the lifecycle shown above, for example the output of `git status` is not accepted as a valid answer. - For the purposes of this question, you can assume you have full access (i.e. read/write) to the repository. - - For this problem you may use online sources to look up information about `make` and Makefiles, but please cite your sources). - **Place your answers in a file named `hw2.txt`**. #### Part (a): diff --git a/_includes/writeups/hash-func-str.md b/_includes/writeups/hash-func-str.md index af7d3f59..fd080546 100644 --- a/_includes/writeups/hash-func-str.md +++ b/_includes/writeups/hash-func-str.md @@ -22,7 +22,7 @@ $$h(k) = (r[0]*w[0] + r[1]*w[1] + r[2]*w[2] + r[3]*w[3] + r[4]*w[4])$$ where the $$r[i]$$ values are either: - 5 random numbers created when you instantiate the hash function using the current time as your seed (i.e. `srand(time(0))`). Be sure to `#include ` and `#include `. - - 5 preset values for debugging (so we all get the same hash results): `r[0]=983132572, r[1]=62337998, r[2]=552714139, r[3]=984953261, r[4]=261934300` (these numbers were generated by random.org) + - 5 preset values for debugging (so we all get the same hash results): `r[0]=983132572, r[1]=1468777056, r[2]=552714139, r[3]=984953261, r[4]=261934300` (these numbers were generated by random.org) Note: We will allow h(k) to produce a large integer (beyond the range of `m`, the table size) and only mod it by the table size in the hash table (see other programming problem). diff --git a/_includes/writeups/make.md b/_includes/writeups/make.md index 41a5a32c..35e878e6 100644 --- a/_includes/writeups/make.md +++ b/_includes/writeups/make.md @@ -1,5 +1,7 @@ Continue your answers in `hw2.txt`. + - For this problem you may use online sources to look up information about `make` and Makefiles, but please cite your sources. + #### Part (a): Every *action* line in a makefile must start with a: diff --git a/_includes/writeups/policies.md b/_includes/writeups/policies.md index aa8b9294..99864c3f 100644 --- a/_includes/writeups/policies.md +++ b/_includes/writeups/policies.md @@ -5,21 +5,22 @@ Carefully study the information on the [course web site]({{site.url}}), then ans #### Part (a): Which of the following are acceptable behaviors in solving homeworks/projects (list all that apply)? -1. Looking up relevant C++ reference information online. +1. Looking up relevant C++ **reference** information online. 1. Looking up or asking for sample solutions online from sites like Chegg, Github, etc. 1. Talking to my classmates about general approaches about the problems (but no specific coding statements or description of your own code or someone else's code). 1. Copying code from my classmates or an online source, and then editing it significantly. 1. Asking the course staff for help. 1. Sitting next to my classmate and coding together as a team or with significant conversation about approach. 1. Sharing my code with a classmate, even if he/she just wants to read over it and learn from it +1. **Using chatGPT** to help write ANY part of my code. #### Part (b): -To dispute a grade on a HW assignment you should (list all that apply): - -1. Email the professor immediately. -1. Complete the regrade request form within 1 week of receiving the grade and wait for an issue to be posted to your Github repo. -1. Visit the designated regrade TA within 1 week of your score posting. +Which of the following are true regarding regrades and wrong submissions (indicate True/False): +1. *True/False*: If you forget to submit a file via GITHUB you can still apply for a regrade after the deadline and submit the missing file. +1. *True/False*: Email the professor when you want a regrade. +1. *True/False*: Complete the regrade request form within **7 days** of receiving the grade and wait for an email. Or if you don't hear back attend the designated regrade TA. +1. *True/False*: Regrades submitted after 7 days of the HW score posting will NOT BE ACCEPTED for any reason. #### Part(c): What is the late submission policy (list all that apply)? @@ -30,11 +31,11 @@ What is the late submission policy (list all that apply)? 1. Students need to get an approval before submitting an assignment late. #### Part(d): -After pushing your code to Gihub you should... (list all that apply) +After pushing your code to Gihub you should... (indicate True/False) -1. Do nothing. Once you push your code you are done. -1. Clone your repo to a temporary folder to ensure all the files you desire are pushed and that your code compiles. -1. Complete the online submission page using your FULL **(30 or more digit)** SHA. +1. *True/False*: Do nothing. Once you push your code you are done. +1. *True/False*: Clone your repo to a temporary folder to ensure all the files you desire are pushed and that your code compiles. +1. *True/False*: Complete the online submission page using your FULL **(30 or more digit)** SHA. #### Part (e): @@ -46,9 +47,6 @@ If you have NO grace days left and it is after the submission deadline, we will 1. If you email us your code as attachments. #### Part (f): -General submission policies (indicate True/False). +Write 2-3 sentences that describe why you will NOT use chatGPT or violate academic integrity in other ways. Also, indicate what the penalties are if we find your code is TOO similar to another students (past or currrent) or an online source. -1. *True/False*: Before submitting your HW you should reclone your repo to a separate folder and ensure all files are present and your code compiles. -1. *True/False*: If you forget to submit a file via GITHUB you can still apply for a regrade after the deadline and submit the missing file. -1. *True/False*: You only have 7 days to submit a regrade for homeworks, unless otherwise stated, and after that you are not eligible for a regrade for ANY reason. diff --git a/_posts/2023-05-15-1027.md b/_posts/2023-05-15-1027.md new file mode 100644 index 00000000..325d3860 --- /dev/null +++ b/_posts/2023-05-15-1027.md @@ -0,0 +1,6 @@ +--- +title: Welcome to Summer 2023 +--- + +We're excited to start this semester with you. Please feel free to take a look at the course schedule and syllabus. +It would be very helpful if you can start by taking a look at the labs, especially Lab 0 in which you set up your environment for course work development. \ No newline at end of file diff --git a/assets/img/staff/caiyulia.jpg b/assets/img/staff/caiyulia.jpg new file mode 100644 index 00000000..9953f7cc Binary files /dev/null and b/assets/img/staff/caiyulia.jpg differ diff --git a/assets/img/staff/lindatam.jpg b/assets/img/staff/lindatam.jpg new file mode 100644 index 00000000..90758a12 Binary files /dev/null and b/assets/img/staff/lindatam.jpg differ diff --git a/assets/img/staff/ongjd.jpg b/assets/img/staff/ongjd.jpg new file mode 100644 index 00000000..0979cd4c Binary files /dev/null and b/assets/img/staff/ongjd.jpg differ diff --git a/assets/img/staff/tangting.jpg b/assets/img/staff/tangting.jpg new file mode 100644 index 00000000..058f9ef6 Binary files /dev/null and b/assets/img/staff/tangting.jpg differ diff --git a/homework/hw1-sp22/index.md b/homework/hw1-sp22/index.md index 0aca3999..2cd3895b 100644 --- a/homework/hw1-sp22/index.md +++ b/homework/hw1-sp22/index.md @@ -20,7 +20,7 @@ hwpath: hw1 ### A Few Notes on Repositories 1. Never clone one repo into another. If you have a folder `cs104` on your VM, Docker, or laptop (wherever you created your Github keys from Lab 1) and you clone your personal repo `hw-username` under it (i.e. `cs104/hw-username`) then whenever you want to clone some other repo, you need to do it back up in the `cs104` folder or other location, NOT in the `hw-username` folder. -1. Your repos may not be ready immediately but be sure to create your GitHub account described in Lab 0 on the [Labs Page]({{site.url}}/labs/index.html). If you've followed those steps and still cannot access your repository, you can then make a private post on the [class Q&A]({{site.data.urls.piazza}}) to let your instructors know that your repository needs to be created. Be sure to include your USC username and github username for reference. +1. Your repos may not be ready immediately but be sure to create your GitHub account described in Lab 0 on the [Labs Page]({{site.url}}/labs/index.html). If you've followed those steps and still cannot access your repository, you can then make a private post on the [class Q&A]({{site.data.urls.discussion}}) to let your instructors know that your repository needs to be created. Be sure to include your USC username and github username for reference. ### Skeleton Code diff --git a/homework/hw1/index.md b/homework/hw1/index.md index 341303fb..a9df68f6 100644 --- a/homework/hw1/index.md +++ b/homework/hw1/index.md @@ -20,7 +20,7 @@ hwpath: hw1 ### A Few Notes on Repositories 1. Never clone one repo into another. If you have a folder `cs104` on your laptop (wherever you created your Github keys from Lab 0) and you clone your personal repo `hw-username` under it (i.e. `cs104/hw-username`) then whenever you want to clone some other repo, you need to do it back up in the `cs104` folder or other location, NOT in the `hw-username` folder. -1. Your repo is created when you register with our website (aka `curricula` system) as outlined in the Lab 0 writeup on the [Labs Page]({{site.url}}/labs/index.html). If you've followed those steps, accepted the invite to the Github organization that should be generated and emailed to you after you register with our website, and still cannot access your repository, you can then make a private post on the [class Q&A]({{site.data.urls.piazza}}) to let your instructors know that your repository needs to be created. Be sure to include your USC username and github username for reference. +1. Your repo is created when you register with our website (aka `curricula` system) as outlined in the Lab 0 writeup on the [Labs Page]({{site.url}}/labs/index.html). If you've followed those steps, accepted the invite to the Github organization that should be generated and emailed to you after you register with our website, and still cannot access your repository, you can then make a private post on the [class Q&A]({{site.data.urls.discussion}}) to let your instructors know that your repository needs to be created. Be sure to include your USC username and github username for reference. ### Skeleton Code diff --git a/homework/hw3/index.md b/homework/hw3/index.md index fe570010..b02f0a51 100644 --- a/homework/hw3/index.md +++ b/homework/hw3/index.md @@ -39,13 +39,6 @@ Some skeleton code has been provided for you in the `{{page.hwpath}}` folder and {% endfor %} -## Checkpoint - -For checkpoint credit, submit your working code for the linked list recursion problem. Ensure you add/commit/push your `hw-username` repo with a `{{page.hwpath}}` subfolder that contains: - - - Your `Makefile` and **all necessary source code files** so that running `make llrec-test` will compile and create a working executable: `llrec-test` that we can test. Failure to compile will result in 0 credit for your checkpoint. There should also be no memory/Valgrind errors of any kind when we run your test on any valid input file. It is fine to push input test files if you like, though we will not grade them. - - - **THEN** you must submit your SHA on our Submit page linked from the [Homework Page]({{site.baseurl}}/homeworks/). ## Submission Files diff --git a/homework/hw4/index.md b/homework/hw4/index.md index 844374bb..fe73cd8f 100644 --- a/homework/hw4/index.md +++ b/homework/hw4/index.md @@ -39,16 +39,6 @@ Some skeleton code has been provided for you in the `{{page.hwpath}}` folder and {% endfor %} -## Checkpoint - -For checkpoint credit, submit your working code for the BST/iterator implementation (though not necessarily the AVL tree). Ensure you add/commit/push your `hw-username` repo with a `{{page.hwpath}}` subfolder that contains: - - - `bst.h`, `print_bst.h` (it's fine to include your other **source** files like `avlbst.h`, `Makefile`, `bst-test.cpp`) - - **THEN** you must submit your SHA on our Submit page linked from the [Homework Page]({{site.baseurl}}/homeworks/). - - -We will use `hw4_tests/bst_tests/bst_tests` for the checkpoint. They must compile, run, and pass all tests with no `valgrind` or other memory errors. Failure to pass even one test or having 1 valgrind error will result in 0 credit for the checkpoint. It is fine to push input test files if you like, though we will not grade them. - ## Submission Files diff --git a/homework/index-su22.md b/homework/index-su22.md new file mode 100644 index 00000000..dbc6b943 --- /dev/null +++ b/homework/index-su22.md @@ -0,0 +1,134 @@ +--- +layout: asides +toc: true +title: Homework +--- + +# Homework + +Homework will be assigned once every **7-10 days**. It will be graded, and require substantial work. The average student should **expect to spend about 15-20 hours per homework**. Homeworks will typically contain a mix of programming exercises and "theory" questions about data structures and their implementation. + + +Each student will receive a private code repository on the course's [GitHub Organization]( {{ site.data.urls.github }}) to use it for the development and submission of all assignments. You will be using the **git** source code management tool to maintain your homework code. + +Please read the submission instructions and policies below **carefully**! Failure to follow the process (of pushing the appropriate files to Github and submitting your git commit SHA on our website) will result in a 0 on the assignment. + +

Schedule

+ + + + + + + + + + + + + + {% for assignment in site.data.content.assignments %} + + + + + + + + + + {% endfor %} + +
#LinkTitleCheckpointDueSubmitRegrade
{{ forloop.index }} + {% if assignment.assigned %} + Writeup + {% else %} + Write + {% endif %} + {{ assignment.title }}{{ assignment.dates.checkpoint }}{{ assignment.dates.due }}SubmitRegrade
+ +## Editors, Debuggers, and Git Help + +Checkout our [**Tools and Links page**]({{site.baseurl}}/resources) + +## Submission + +In order to properly submit your assignment, **please follow the course [submission instructions]({{ site.baseurl }}/homework/submission-instructions/)** which will show you the steps to submit a particular `git` commit of your code. + +For each assignment, a precise time will be specified on the due date (usually at 11:59 PM PST). The programming submission must be made correctly via your github account and your **`git` commit SHA** must be submitted on the appropriate submission page using the process described on the [submission instructions]({{ site.baseurl }}/homework/submission-instructions/) page. Read and follow those instructions carefully for each homework. **Failure to do so may lead to a 0 on the assignment** even though you may have had all the code working on your machine. Much of software development requires following strict processes, so it is important you start to understand and follow those processes. + + +**Important Note:** You will NOT receive an exception for failing to follow these instructions! + +For example, often times students forget to commit/push a file that is part of their solution to Github. If they had followed the submission instructions and re-cloned their repo to a temporary folder and attempted to build their assignment code, they would have easily found the issue. We cannot accept files that were not submitted or files where you submitted "the wrong version". We can only grade what you submitted. + +In addition to making sure your submission is on time, **please make sure that the code you submit is formatted and works as expected with `g++`**. We will grade your assignments using g++ at the command line in the virtual machine we provide for the course. You are free to use other compilers or IDEs to develop your code, but in the end, it has to work with `g++` on the course Docker container or virtual machine. + +You WILL lose points for submitting unreadable code, or for failing to follow submission instructions. **Be sure to refer to our Visual Inspection Rubric** before submitting. + +## Policies + +There will be **6 assignments**. In CS 104 we do not accept late submissions (except in the cases outlined below). We do realize that as a student, things will come up and other classes may need more focus on certain weeks. While 7-10 days per assignment should allow you to finish on time if you **start early** and **work consistently**, we will provide **5 grace days** to be used over the semester with a **maximum of 2 grace days allowed per assignment**. 48 hours after the due date, no submissions will be allowed. Once you have used your grace days, any late submission will not be accepted for any reason; thus, it will be graded as a 0. Our online submission system will automatically deduct and track late days, so you do NOT need to alert anyone. + +In this age of COVID, we realize that being sick or having sick family may preclude you from working on your assignments as you would be able to otherwise. If a confirmed COVID-related illness or other emergency occurs, please fill out [this form]({{site.data.urls.extension_form}}) and make a private note on {{site.data.urls.qa_tool}} to inform the course staff and we will try our very best to work out a flexible plan for completing the assignment. **Note:** A minor illness a few days before the deadline or a trip home to see family does not qualify for an extension. Start early anticipating that things may come up closer to the deadline. If you have not started early and ask for an extension, your request may be rejected. Commit and push your intermediate work often as a record of your effort on an assignment. + +For non-emergency issues (especially those close to the deadline), extensions are generally not applicable. Instead, **your grace days** are available and should be conserved for such circumstances. + +The most consistent advice from students who have done well in CS 104 is (you guessed it): **start early!** + +### HW Grades and Regrades +We will work hard to post HW scores and feedback within 1-2 weeks of the homework's due date. Exams will typically be graded within at most a few days of the exam date. Homework grades will normally be posted back as **ISSUES** on your `hw-username` Github repository and their release will be announced on {{site.data.urls.qa_tool}}. If you have not received your score (no issue was posted to your repo webpage) on a particular HW even though most other students in the class have (say, 24 hours after the score release date), post a private note on {{site.data.urls.qa_tool}} and someone will then follow up with your grader. + +Any disputes with posted grades **must** be raised within **7 days** (unless specifically noted) of the score posting. Then follow the process below for the type of regrade you are requesting. + +Fill out this [**HW regrade form**]({{site.data.urls.hw_regrade_form}}) **within 7 days** of grades being released. The TAs will review the request. If they can deal with it themselves, then they will do so and email you the result. If they cannot address it or you don't hear from them, please attend the special HW regrade office hours that the TAs will announce on {{site.data.urls.qa_tool}} for each homework. Again you must submit your regrade request within 7 days and **after 7 days no regrade requests will be considered** for any reason, even if it is our grading mistake. Be prompt and do not delay reviewing your HW grades. [Note: The regrades don't have to be resolved within 7 days, though hopefully they will; we just need you to raise the issue on the regrade form within 7 days]. + +Any regrade request will result in us trying to give the fairest possible grade to you, which could be higher or lower than the one you received originally. Finally, please note that regrades are not for "fixing" your code. For example: If there was just one line off that caused all the tests to fail, that might be a viable reason for a regrade but we have a standard policy over the years that each expression change on a regrade is a -10 deduction, because it was really your responsibility (especially if the test suite was released before submission) to ensure your code compiled, tested, and all files were submitted on Github which can be verified by the "Verification" process outlined at the end of each homework. + +### Exam Regrades +See your registered instructor. Only instructors can determine exam regrades. + + +## Academic Integrity +We take academic integrity very seriously in our CS courses to ensure that your grades reflect your mastery of the material presented in this class as well as to provide fairness to fellow students, to ensure the reputation of USC, and the expectations of our constituencies are met. + +Your homework assignments and exams should be individual efforts unless explictly stated otherwise. While collaboration and online searches are common in the workplace, taking code from those sources is usually not allowed due to licensing and can have legal ramifications. Similarly, while collaboration in a company is common, we are training you to be capable computer scientists and, thus, you need to develop the skills for yourself. You will have higher levels of collaboration for team-based projects in future courses and in the workplace. For homework assignments, you may only have high level discussions with classmates. Any discussion that includes specific code (describing variables, loops, functions, etc.) and implementation details is an **inappropriate level** of collaboration. **Looking for similar examples of code online is also a likely violation if you model your code after those online examples.**. We run all submissions through code similarity tools that compares every student to every other student from this semester and past semesters. If you are suspected of violating the academic integrity code of conduct you will: + +1. Be reported to SJACS which will acts as an impartial 3rd party to determine if a violation has occurred. +1. If a violation is deemed to have occurred, the recommended sanction is a 0 on the assignment and 1 letter grade deduction (i.e. if you would have gotten a B+ you would receive a B). +1. If SJACS determines this is not your first violation, they may initiate a review that could lead to suspension from the school. + +The official language on academic integrity is on the [**syllabus**]({{ site.url }}/syllabus.html), but what is written below acts as an additional, binding policy for this course: + +Collaboration is important in an academic environment. We want to be sure that you are aware of what is appropriate collaboration and conduct and what may be considered a violation of academic conduct rules. Here are examples to consider: + +### Acceptable Actions +- Discussing **high-level** ideas (no coding terms at all) with other students is fine. It is even helpful if you annotate your work with the names of your collaborators. +- Asking course staff (instructor, TAs, CPs) for help or to look at your code. +- Copying test cases from other students or {{site.data.urls.qa_tool}} when test cases are not graded is fine since it serves to teach you something, and there is no risk that you will get points for the work of other students. +- Looking up references on C++ library containers, functions, and syntax. However, looking up "similar" examples to a homework assignment is NOT okay. + +### Unacceptable Actions (Violations of Academic Integriy) +- Copying **EVEN A FEW LINES** of code from other students (current or former) or online sources, **even if you edit it significantly** is NOT okay. You must start from scratch or from the provided skeleton and come up with the design ideas and code yourself. Taking code from some other source and then saying you *understand* it doesn't make it your own code. +- Take care even coding together in the same room and talking through approaches. It often leads to describing your approach in specific coding terms that will lead to near-exact code structures. +- Having other students in the class look at your code or access a copy of your code is not acceptable. If test cases are graded, it is also not acceptable to let other students have copies of those test cases. +- Obtaining copies of code or test cases from students who were enrolled in a previous term of CSCI 104. (That would even be a violation for the student not enrolled in CSCI 104 this term.) +- **Even searching for similar code and solutions** on Github, StackOverflow, online sources (Chegg, etc.), or other textbooks is NOT allowed, even just for "reference". If you happen to find related work in a source that is not the course materials, it is best that you notify your instructor first to ask if it can be used and, if it can be, then cite the materials. +- Posting in online forums asking people to solve homework questions or paying for solutions. + +**In summary, any time that you are trying to get higher grades for work that you did not earn is not acceptable. Any behavior by which you are attempting to receive or grant an unfair advantage that your classmates who are following the rules do not have is not acceptable.** Please act with the integrity that is expected of USC Trojans. + +We run MOSS on all homework submissions to catch inappropriate collaboration and plagiarism. If there is suspected cheating, you will be reported to [SJACS](http://sjacs.usc.edu/), no exceptions. Follow the above guidelines to make sure this doesn't happen to you. + +In order to make sure that an appropriate level of collaboration is used between you and your classmates, please do not keep notes, pictures, or any records from your discussions. This will ensure that your work reflects only your understanding when you create it. Please do not sit coding next to each other while discussing the work. If you are concerned that an inappropriate level of collaboration has occured, please do the following: + +- **Keep no notes, pictures, or records from your discussions.** +- Cite your **high-level** collaborators in your comments in your work. +- Take at least a 30 minute break before you continue working and make sure that your work only reflects your own understanding of the solution. If you truly do not understand part of the solution, please do not include it as your own work. + diff --git a/homework/index.md b/homework/index.md index 16591971..89309039 100644 --- a/homework/index.md +++ b/homework/index.md @@ -9,18 +9,19 @@ title: Homework Homework will be assigned once every **7-10 days**. It will be graded, and require substantial work. The average student should **expect to spend about 15-20 hours per homework**. Homeworks will typically contain a mix of programming exercises and "theory" questions about data structures and their implementation. -Each student will be responsible for creating and using a GitHub repo for the development and submission of all assignments. You will be using the **git** source code management tool to maintain your homework code. +Each student will receive a private code repository on the course's [GitHub Organization]( {{ site.data.urls.github }}) to use it for the development and submission of all assignments. You will be using the **git** source code management tool to maintain your homework code. Please read the submission instructions and policies below **carefully**! Failure to follow the process (of pushing the appropriate files to Github and submitting your git commit SHA on our website) will result in a 0 on the assignment.

Schedule

- +
+ @@ -35,13 +36,14 @@ Please read the submission instructions and policies below **carefully**! Failu + {% endfor %} @@ -63,47 +65,52 @@ For each assignment, a precise time will be specified on the due date (usually a For example, often times students forget to commit/push a file that is part of their solution to Github. If they had followed the submission instructions and re-cloned their repo to a temporary folder and attempted to build their assignment code, they would have easily found the issue. We cannot accept files that were not submitted or files where you submitted "the wrong version". We can only grade what you submitted. -In addition to making sure your submission is on time, **please make sure that the code you submit is formatted and works as expected with `g++`**. We will grade your assignments using g++ at the command line. You are free to use other compilers or IDEs to develop your code, but in the end, it has to work with `g++` on the course Docker container or virtual machine. +In addition to making sure your submission is on time, **please make sure that the code you submit is formatted and works as expected with `g++`**. We will grade your assignments using g++ at the command line in the virtual machine we provide for the course. You are free to use other compilers or IDEs to develop your code, but in the end, it has to work with `g++` on the course Docker container or virtual machine. -## Policies - -There will be **6 assignments**. In CSCI 104L we do not accept late submissions (except as outlined below). We do realize that as a student, things will come up and other classes may need more focus on certain weeks. While 7-10 days per assignment should allow you to finish on time if you **start early** and **work consistently**, we have a flexible due-date policy that allows for submitting assignments within 5 days of the due date with minimal penalty. For each of the first five days **after** the due date you may submit an assignment with a penalty of 1% per day (for a total of 5% on the last day). After five days, there are no late submissions. +You WILL lose points for submitting unreadable code, or for failing to follow submission instructions. **Be sure to refer to our Visual Inspection Rubric** before submitting. -In this age of COVID, we realize that being sick or having sick family may preclude you from working on your assignments as you would be able to otherwise. If a confirmed COVID-related illness or other emergency occurs, please fill out [this form]({{site.data.urls.extension_form}}) and make a private note on [edStem]({{site.data.urls.discussion}}) to inform the course staff and we will try our very best to work out a flexible plan for completing the assignment. **Note:** A minor illness, injury or other incident a few days before the deadline or a trip home to see family does not qualify for an extension. Start early anticipating that things may come up closer to the deadline. If you have not started early and ask for an extension, your request may be rejected. Commit and push your intermediate work often as a record of your effort on an assignment. +## Policies -For non-emergency issues (especially those close to the deadline), extensions are generally not applicable. Instead, **your late days** are available and should be used for such circumstances. +There will be **6 assignments**. In CS 104 we do not accept late submissions (except in the cases outlined below). We do realize that as a student, things will come up and other classes may need more focus on certain weeks. While 7-10 days per assignment should allow you to finish on time if you **start early** and **work consistently**, we will provide **5 grace days** to be used over the semester with a **maximum of 2 grace days allowed per assignment**. 48 hours after the due date, no submissions will be allowed. Once you have used your grace days, any late submission will not be accepted for any reason; thus, it will be graded as a 0. Our online submission system will automatically deduct and track late days, so you do NOT need to alert anyone. -As a reward for starting early coding assignments turned in early will receive a 5% bonus. "Turned in early" means the assignment was marked-as-complete on Codio and the autograding script awarded full marks **before** the day of the deadline. Said another way, if you finish your assignment with full marks before the due date (not time) you will receive the bonus. This means you can earn up to 105% of the points on the homework portion of the course. +**Extensions:** With the lifting of pandemic restrictions and health orders, we will return to normal expectations for assignment submission, which is that you **save your grace days** for occasions of illness. Only emergencies cleared through [campus support services]({{site.data.urls.uscsupport}}) or [student accessibility services]({{site.data.urls.osas}}) will be granted extensions. Similarly, while we appreciate the mental health needs of our students, extensions will generally not be granted without campus support direction. The best strategy to reduce stress and give yourself the best chance of success, you should **start your assignments on the DAY THEY ARE RELEASED** and working at an even pace throughout the duration. By leaving the work for just a few days before the due date, you will increase your stress levels! With that said, if a true emergency does occur, you may fill out [this form]({{site.data.urls.extension_form}}) and make a private note on [edStem]({{site.data.urls.discussion}}) to inform the course staff. **Again**, start early anticipating that things may come up closer to the deadline. If you have not started early and something comes up, you may be denied since you chose to leave your work until the deadline. Commit and push your intermediate work often as a record of your effort on an assignment. -Late days and the 1% per day penalty apply **only** to the coding portion of the assignments. The written portions must be completed on-time by uploading your written answers to Codio before the deadline. The most consistent advice from students who have done well in CS 104 is (you guessed it): **start early!** ### HW Grades and Regrades -We will work hard to post HW scores and feedback within 1 week of the homework's due date. Exams will typically be graded within at most a few days of the exam date. Only the written portion of the homework is graded by a human. The score for the programming portion is determined by a grading script and is not avilable for regrading. +We will work hard to post HW scores and feedback within 1 week of the homework's due date. Exams will typically be graded within at most a few days of the exam date. + +Homework grades will normally be posted back as **ISSUES** on your `hw-username` Github repository and their release will be announced on {{site.data.urls.qa_tool}}. If you have not received your score (no issue was posted to your repo webpage) on a particular HW even though most other students in the class have (say, 24 hours after the score release date), post a private note on {{site.data.urls.qa_tool}} and someone will then follow up with your grader. + +Only the written portion of the homework is graded by a human. The score for the programming portion is determined by a grading script and is not available for regrading. Any disputes with posted grades **must** be raised within **7 days** (unless specifically noted) of the score posting. Then follow the process below for the type of regrade you are requesting. -Fill out this [**HW regrade form**]({{site.data.urls.regrade_form}}) **within 7 days** of grades being released. The graders will review your regrade request and if appropriate make any updates to your score on Codio. They will also respond via the Admin and Grading discussion board with a reply whether or not your score changed. +Fill out this [**HW regrade form**]({{site.data.urls.regrades}}) **within 7 days** of grades being released. The TAs will review the request. If they can deal with it themselves, then they will do so and email you the result. If they cannot address it or you don't hear from them, please attend the special HW regrade office hours that the TAs will announce on {{site.data.urls.qa_tool}} for each homework. Again you must submit your regrade request within 7 days and **after 7 days no regrade requests will be considered** for any reason, even if it is our grading mistake. Be prompt and do not delay reviewing your HW grades. [Note: The regrades don't have to be resolved within 7 days, though hopefully they will; we just need you to raise the issue on the regrade form within 7 days]. -Any regrade request will result in us trying to give the fairest possible grade to you, which could be higher or lower than the one you received originally. Finally, please note that regrades are not for "fixing" your code. For example: If there was just one line off that caused all the tests to fail, that might be a viable reason for a regrade but with the Codio submission process you will know that your code fails when you submit. It is your responsibility (especially if the test suite was released before submission) to ensure your code compiled, tested, and all files were submitted on Github which can be verified by the "Verification" process outlined at the end of each homework. +Any regrade request will result in us trying to give the fairest possible grade to you, which could be higher or lower than the one you received originally. Finally, please note that regrades are not for "fixing" your code. For example: If there was just one line off that caused all the tests to fail, that might be a viable reason for a regrade but we have a standard policy over the years that each expression change on a regrade is a -10 deduction, because it was really your responsibility (especially if the test suite was released before submission) to ensure your code compiled, tested, and all files were submitted on Github which can be verified by the "Verification" process outlined at the end of each homework. ### Exam Regrades -Exams may or may not have regrades enabled. If they do, then regrades will be handled through Gradescope. +Exams will likely be conducted via Gradescope and its regrade feature is the only method you may use for requesting an exam regrade. ## Academic Integrity We take academic integrity very seriously in our CS courses to ensure that your grades reflect your mastery of the material presented in this class as well as to provide fairness to fellow students, to ensure the reputation of USC, and the expectations of our constituencies are met. -Your homework assignments and exams should be individual efforts unless explictly stated otherwise. While collaboration and online searches are common in the workplace, taking code from those sources is usually not allowed due to licensing and can have legal ramifications. Similarly, while collaboration in a company is common, we are training you to be capable computer scientists and, thus, you need to develop the skills for yourself. You will have higher levels of collaboration for team-based projects in future courses and in the workplace. For homework assignments, you may only have high level discussions with classmates. Any discussion that includes specific code (describing variables, loops, functions, etc.) and implementation details is an **inappropriate level** of collaboration. **Looking for similar examples of code online is also a likely violation if you model your code after those online examples.**. We run all submissions through code similarity tools that compares every student to every other student from this semester and past semesters. If you are suspected of violating the academic integrity code of conduct the process will be as outlined at the [Office of Academic Integrity](https://academicintegrity.usc.edu/what-should-i-expect/process/): +**Collaboration**: Your homework assignments and exams should be individual efforts unless explictly stated otherwise. While collaboration and online searches are common in the workplace, taking code from those sources is usually not allowed due to licensing and can have legal ramifications. Similarly, while collaboration in a company is common, we are training you to be capable computer scientists and, thus, you need to develop the skills for yourself. You will have higher levels of collaboration for team-based projects in future courses and in the workplace. For homework assignments, you may only have **CONCEPTUAL** discussions with classmates. Any discussion that includes specific code (describing variables, loops, functions, etc.) and implementation details is an **inappropriate level** of collaboration and a **violation of academic integrity**. **Copying (and then modification) or just "viewing for reference"** any (**even small**) portion(s) of code from Internet sources or fellow students is prohibited unless explicitly cleared with the instructor. Simiarly, **ANY use of chatGPT or similar AI-generators** to generate ANY amount of code is a violation. Similarly you should NOT verbally describe your code at any level of detail. Instead, draw (non-code) pictures, ask questions that consider possible inputs or other scenarios, or provide advice on how to debug. Violations of this policy **will likely** result in an **F in the course**. + + If you are suspected of violating the academic integrity code of conduct the process will be as outlined at the [Office of Academic Integrity](https://academicintegrity.usc.edu/what-should-i-expect/process/): + The official language on academic integrity is on the [**syllabus**]({{ site.url }}/syllabus.html), but what is written below acts as an additional, binding policy for this course: @@ -125,7 +132,7 @@ Collaboration is important in an academic environment. We want to be sure that y **In summary, any time that you are trying to get higher grades for work that you did not earn is not acceptable. Any behavior by which you are attempting to receive or grant an unfair advantage that your classmates who are following the rules do not have is not acceptable.** Please act with the integrity that is expected of USC Trojans. -We run MOSS on all homework submissions to catch inappropriate collaboration and plagiarism. If there is suspected cheating, you will be reported to [SJACS](http://sjacs.usc.edu/), no exceptions. Follow the above guidelines to make sure this doesn't happen to you. +We run code similarity tools on all homework submissions to catch inappropriate collaboration and plagiarism. If there is suspected cheating, you will be reported to [OSAS](http://osas.usc.edu/), no exceptions. Follow the above guidelines to make sure this doesn't happen to you. In order to make sure that an appropriate level of collaboration is used between you and your classmates, please do not keep notes, pictures, or any records from your discussions. This will ensure that your work reflects only your understanding when you create it. Please do not sit coding next to each other while discussing the work. If you are concerned that an inappropriate level of collaboration has occured, please do the following: diff --git a/homework/submission-instructions/index-su22.md b/homework/submission-instructions/index-su22.md new file mode 100644 index 00000000..33cf6f6d --- /dev/null +++ b/homework/submission-instructions/index-su22.md @@ -0,0 +1,89 @@ +--- +layout: asides +toc: true +title: Submission Instructions +nav: homework +--- + +## Submission Instructions + +### Step 1. Prepare Your Code for Submission + + + Create a `README.md` in the directory for each assignment. + + Suppress all debug messages (remove any `cout`/`cerr` statements or other debug output). + + Ensure that all assignment files are in the correct directory with the proper names, as specified on the assignment page and are pushed to Github. Failure to submit a necessary file will lead to a 0 on that problem or at the least a **-10 point** deduction per missing file. + + Make sure your code compiles with no warnings and no errors, and throws no exceptions. Unless specified otherwise, we will compile your code with the parameters `g++ -g -Wall -std=c++11`, so your code should compile with those setting. If your code has warnings, a **deduction of up to 4 points** may be applied to the problem! + + If there are any specific actions and/or commands necessary to compile or run your code, or to access any required documentation for your assignment, include instructions in your `README.md` file. + + Your grader will grade the assignment in the course VM/Docker. Hence, your grader will use the same compiler as you will in the course VM/Docker. + + Ensure no `valgrind` errors exist. `valgrind` errors will result in a **deduction of up to 4 points** per programming problem. + + + + +#### Acceptable Document Formats +In many assignments, you will be required to submit documentation and/or textual answers. Your documentation should be in the base directory of the assignment. + +The following document formats are accepted: + + + Plain text + + Markdown + + PDF + +No other formats are accepted unless explicitly stated. These include, but are not limited to, Microsoft Word documents (e.g. `.doc`, `.docx`) and Rich Text Format (RTF) files. + +### Step 2. Push your commits to GitHub +After you have verified that your assignment is ready to be submitted, push your source code and all relevant files. Do not push binary files or "garbage" files. (Use the `.gitignore` file to make this as easy as possible on yourself as well as `make clean` to delete any object files or executables). You should NOT add/commit/push any of the test suite folders (and files) that may be released before the submission deadline (e.g. `hw1_tests`). This can easily happen if you use `git add .`. Instead, we recommend adding specific files (e.g. `git add file1.h file1.cpp file2.h file2.cpp Makefile`) or using specific wildcards: `git add *.h *.cpp Makefile` (which will leave out anything in a subfolder). If you do happen to add/commit/push a test suite, you can remove it by running `git rm -rf hw1_tests` followed by `git commit -m "Removed tests"` followed by `git push`. + +Run `git status` on your repository and make sure that there are no files listed as: + + + Changes to be committed, + + Changes not staged for commit, or + + Untracked files + +A `git status` on your master branch must return: + +``` +# On branch master +nothing to commit, working directory clean +``` + +If files that you do not want to push (i.e. `hw1_tests` or other object files ) appear in the untracked list, add that folder/filename(s) to your `.gitignore`. (Note: you must add/commit/push you `.gitignore` like any other file). + +### Step 3. Verify your commit **before** the Deadline + +Before the deadline and after pushing your submission to GitHub, you **must** ( **MUST** ) follow the verification steps listed at the end of each assignment page to clone your repo to a separate folder and follow the process you list in your own `README.md` to ensure your code compiles and works as you expect. We cannot emphasize enough how many bugs you will discover (and how many points you can avoid losing) by doing this simple 5-minute step. + +Our reference grading environment is the Virtual Machine we provide for the course. You should test your code on the VM to ensure that it works properly in the environment we will test it in. + +### Step 4. Fill out the Homework Submission Form +The submission form is available for each respective assignment on the [assignments page]({{ site.url }}/assignments/index.html). Make sure you are using the proper link. To complete the form, you will need to get the (long) SHA from your commit. + +It is easiest to obtain that SHA by executing the `git log` command on your terminal and select/copy the SHA that is listed for the (likely latest) commit that you just pushed. You can then paste that SHA into our form. + +You can also obtain the SHA from your repository's commit page on github.com as shown in the following screenshot: + +![SHA of latest commit]({{site.baseurl}}/homework/img/github_commit-sha.png) + +Make sure to use the **long** SHA (about 20+ digits/letters), not the short one (less than 10 digits)! If you use the short SHA, the submission script may work, but the actual scraping script in the background likely will not. This will make it appear as though you hadn't submitted the assignment, which would be pretty bad. + +When you submit your assignments, make sure to click on the "Check My Submission" button. Our script will perform a few quick checks to make sure your submission is valid. For instance, it will alert you to (some) missing files, and might also catch some compilation errors. (Of course, it cannot read your `README.txt`, so if compilation requires special instructions, it will not follow those.) You can resubmit as often as you want -- we will grade the submission with the most recently submitted SHA. + +### Late Submissions +Provided you have grace days, you can make a late submission even if you previously submitted on time. The late submission will then replace the on-time submission. After completing your (late) assignment, follow steps 1-4 from above. When you get to step 4, before you can successfully submit your homework, you will be prompted to confirm your late submission. Doing so will use a late day (unless you have already made other arrangements with your professor). If you have no late days remaining, then you will get a 0 for the assignment. No exceptions will be made to this policy except for University approved medical reasons. Interviews, conferences, or other trips are not valid reasons to obtain an extension. + + +### Submission FAQs +#### Q1. How do I check out a specific commit? +If you want to check out a specific version of your code, such as the commit used in grading your assignment, you first need to locate the SHA of that commit. As an example, to check out commit `d8da410b19cf0a9f5a3003120204a114b8496942` from ttrojan's repository, you would use: + +1. Go to your top level `cs104` folder of home folder (such as `cd ~`) +1. Delete your old `verify` folder if it exists: `$ rm -rf verify` +1. Create a `verify` directory: `$ mkdir verify` +1. Go into that directory: `$ cd verify` +1. Clone your `hw-ttrojan` repo: `$ git clone git@github.com:{{site.data.urls.github_org}}/hw-ttrojan.git` +1. Go into the appropriate `hw` folder `$ cd hw-ttrojan/hw1` +1. Checkout your paritcular commit: `$ git checkout d8da410b19cf0a9f5a3003120204a114b8496942` +1. Recompile and rerun your programs and tests to ensure that what you submitted works. + + +This creates a new directory with the specific version of your code. While there are ways to make edits to this version and then merge those edits suitably, we recommend a more pedestrian version (unless you are a git expert, in which case feel free to do what you want - just don't expect us to be able to fix things if you really screw them up). We recommend that you carefully go through your edits and your old version, and copy whatever you wanted to recover from the old version **into** the version that is in the most recent state. Once you've produced the new version you want, commit it, and simply delete the `verify` directory you created. diff --git a/homework/submission-instructions/index.md b/homework/submission-instructions/index.md index 3eb25f39..b81dc393 100644 --- a/homework/submission-instructions/index.md +++ b/homework/submission-instructions/index.md @@ -64,21 +64,23 @@ The long string of hexadecimal digits is your hash. Copy it to your clipboard. Before the deadline and after pushing your submission to GitHub, you **must** ( **MUST** ) follow the verification steps listed at the end of each assignment page to clone your repo to a separate folder and follow the process you list in your own `README.md` to ensure your code compiles and works as you expect. We cannot emphasize enough how many bugs you will discover (and how many points you can avoid losing) by doing this simple 5-minute step. -Our reference grading environment is Codio. You should test your code on Codio to ensure that it works properly in the environment we will test it in. +Our reference grading environment is the Virtual Machine we provide for the course. You should test your code on the VM to ensure that it works properly in the environment we will test it in. -### Step 4. Submit the hash to Codio and mark your assignment as complete +### Step 4. Fill out the Homework Submission Form +The submission form is available for each respective assignment on the [assignments page]({{ site.url }}/assignments/index.html). Make sure you are using the proper link. To complete the form, you will need to get the (long) SHA from your commit. -When you're ready to submit (and you're 100% the commit at the desired hash is ready-to-go) you paste the hash into the box on the Codio guide. This will run structural checks on your GitHub repo (can the hash be checked out, do the required files exist, etc.). If the script passes, then your assignment has been submitted! If the script detects any problems it will give you some feedback on how to fix the problem. Once you are able to submit a clean hash, mark the assignment as complete. +It is easiest to obtain that SHA by executing the `git log` command on your terminal and select/copy the SHA that is listed for the (likely latest) commit that you just pushed. You can then paste that SHA into our form. -When you mark the assignment as complete a background grading script will grade the assignment using the provided test suite against the code at your submitted SHA. +You can also obtain the SHA from your repository's commit page on github.com as shown in the following screenshot: -You can resubmit as often as you want -- the backgrund script will grade the most recently submitted SHA. +![SHA of latest commit]({{site.baseurl}}/homework/img/github_commit-sha.png) -### Late Submissions +Make sure to use the **long** SHA (about 20+ digits/letters), not the short one (less than 10 digits)! If you use the short SHA, the submission script may work, but the actual scraping script in the background likely will not. This will make it appear as though you hadn't submitted the assignment, which would be pretty bad. -As outlined on the top-level [homework](../) page, late submissions are accepted for the first five days after the due date. After that, the assignment will close and no further submissions are allowed. +When you submit your assignments, make sure to click on the "Check My Submission" button. Our script will perform a few quick checks to make sure your submission is valid. For instance, it will alert you to (some) missing files, and might also catch some compilation errors. (Of course, it cannot read your `README.txt`, so if compilation requires special instructions, it will not follow those.) You can resubmit as often as you want -- we will grade the submission with the most recently submitted SHA. -No exceptions will be made to this policy except for University approved medical reasons. Interviews, conferences, or other trips are not valid reasons to obtain an extension. +### Late Submissions +Provided you have grace days, you can make a late submission even if you previously submitted on time. The late submission will then replace the on-time submission. After completing your (late) assignment, follow steps 1-4 from above. When you get to step 4, before you can successfully submit your homework, you will be prompted to confirm your late submission. Doing so will use a late day (unless you have already made other arrangements with your professor). If you have no late days remaining, then you will get a 0 for the assignment. No exceptions will be made to this policy except for University approved medical reasons. Interviews, conferences, or other trips are not valid reasons to obtain an extension. ### Submission FAQs @@ -89,10 +91,10 @@ If you want to check out a specific version of your code, such as the commit use 1. Delete your old `verify` folder if it exists: `$ rm -rf verify` 1. Create a `verify` directory: `$ mkdir verify` 1. Go into that directory: `$ cd verify` -1. Clone your `hw1` repo: `$ git clone git@github.com:GHUSERNAME/hw1.git` -1. Go into the appropriate `hw1` folder `$ cd hw1` +1. Clone your `hw-ttrojan` repo: `$ git clone git@github.com:{{site.data.urls.github_org}}/hw-ttrojan.git` +1. Go into the appropriate `hw` folder `$ cd hw-ttrojan/hw1` 1. Checkout your paritcular commit: `$ git checkout d8da410b19cf0a9f5a3003120204a114b8496942` -1. Recompile and rerun your programs and tests to ensure that what you submitted works. If tests were provided you'll need to copy or extract the tests into this folder. +1. Recompile and rerun your programs and tests to ensure that what you submitted works. -This creates a new directory with the specific version of your code. While there are ways to make edits to this version and then merge those edits suitably, we recommend a more pedestrian version (unless you are a git expert, in which case feel free to do what you want - just don't expect us to be able to fix things if you really screw them up). We recommend that you delete the `verify` folder and go back to your main development repo to make any changes. Once that is working, repeat the above process with a the new ha -You should do this in either the root-level of the Codio assignment for the homework, or inside a private Codio project to verify that your assignment works on Codio. + +This creates a new directory with the specific version of your code. While there are ways to make edits to this version and then merge those edits suitably, we recommend a more pedestrian version (unless you are a git expert, in which case feel free to do what you want - just don't expect us to be able to fix things if you really screw them up). We recommend that you carefully go through your edits and your old version, and copy whatever you wanted to recover from the old version **into** the version that is in the most recent state. Once you've produced the new version you want, commit it, and simply delete the `verify` directory you created. \ No newline at end of file diff --git a/index.html b/index.html index 79abc466..305a0777 100644 --- a/index.html +++ b/index.html @@ -21,9 +21,9 @@

General

External

@@ -31,17 +31,13 @@

External

Useful Links

Announcements

- {% for post in site.posts limit:2 %} + {% for post in site.posts limit:1 %}

{{ post.title }}

{{ post }} diff --git a/labs/bst-lab8/assets/Backtracking_BST_AVL.pdf b/labs/bst-lab8/assets/Backtracking_BST_AVL.pdf new file mode 100644 index 00000000..d61f8dff Binary files /dev/null and b/labs/bst-lab8/assets/Backtracking_BST_AVL.pdf differ diff --git a/labs/index.md b/labs/index.md index ce111e6f..7e3013a2 100644 --- a/labs/index.md +++ b/labs/index.md @@ -30,24 +30,28 @@ Lab sessions are held every week and will be conducted by a team of TAs and Cour {% for lab in site.data.content.labs %}
+ + - - diff --git a/labs/lab10/assets/hashtable_lab.pdf b/labs/lab10/assets/hashtable_lab.pdf new file mode 100644 index 00000000..0a7111cb Binary files /dev/null and b/labs/lab10/assets/hashtable_lab.pdf differ diff --git a/labs/lab10/index.md b/labs/lab10/index.md index de07175a..9c6d79d3 100644 --- a/labs/lab10/index.md +++ b/labs/lab10/index.md @@ -9,7 +9,6 @@ title: Hashtables **Due at the end of your registered lab section** -As per usual, instructions/materials can be found on Codio. Code is also available [here](assets/resources.zip). --- diff --git a/labs/lab13/assets/number_theory_lab.pdf b/labs/lab13/assets/number_theory_lab.pdf new file mode 100644 index 00000000..821aeb11 Binary files /dev/null and b/labs/lab13/assets/number_theory_lab.pdf differ diff --git a/labs/lab13/index.md b/labs/lab13/index.md index 26be80d0..2bc2973c 100644 --- a/labs/lab13/index.md +++ b/labs/lab13/index.md @@ -7,7 +7,7 @@ title: Number Theory --- -**Due at the end of your registered lab section.** Material and questions are also available on Codio. The coding materials for exercise 3 can be downloaded [here](./resources/resources.zip). +**Due at the end of your registered lab section.** --- @@ -56,6 +56,7 @@ Here is a helpful theorem to remember: Using the theorem above, prove the following: * If $p$ is a prime and $p \mid ab$, then $p \mid a$ or $p \mid b$. + --- ### Quadratic Probing @@ -160,4 +161,4 @@ After you finish your implementation, type `make` in your terminal to run the te --- ## Checking Off -To get checked off, complete all three exercises in this lab and show your results to a CP/TA. \ No newline at end of file +To get checked off, complete all three exercises in this lab and show your results to a CP/TA. diff --git a/labs/lab14/hashtable_lab.pdf b/labs/lab14/hashtable_lab.pdf new file mode 100644 index 00000000..0a7111cb Binary files /dev/null and b/labs/lab14/hashtable_lab.pdf differ diff --git a/labs/lab3/makefile_lab.pdf b/labs/lab3/makefile_lab.pdf new file mode 100644 index 00000000..8b654baa Binary files /dev/null and b/labs/lab3/makefile_lab.pdf differ diff --git a/labs/lab4/assets/stl_inh_lab.pdf b/labs/lab4/assets/stl_inh_lab.pdf new file mode 100644 index 00000000..8bf24383 Binary files /dev/null and b/labs/lab4/assets/stl_inh_lab.pdf differ diff --git a/labs/lab4/index.md b/labs/lab4/index.md index 7f0fe67a..53801bdc 100644 --- a/labs/lab4/index.md +++ b/labs/lab4/index.md @@ -5,13 +5,8 @@ tasks: true title: Inheritance and STL --- ---- - -**Due at the end of your registered lab section** -[Here](assets/resources.zip) is the zip file with all required files. You can also find the lab on Codio. ---- ## Inheritance and STL diff --git a/labs/lab5/index.md b/labs/lab5/index.md index 38a14971..fcf7adc9 100644 --- a/labs/lab5/index.md +++ b/labs/lab5/index.md @@ -5,10 +5,6 @@ tasks: true title: Templates --- ---- -### Due at the end of your registered lab section - -[Here](assets/resources/resources.zip) is the zip file with all required files. You can also find the lab on Codio. --- diff --git a/labs/lab6/assets/heap_lab.pdf b/labs/lab6/assets/heap_lab.pdf index 4b0a6073..3c96f99b 100644 Binary files a/labs/lab6/assets/heap_lab.pdf and b/labs/lab6/assets/heap_lab.pdf differ diff --git a/labs/lab6/index.md b/labs/lab6/index.md index 506af1a2..7b4aa22d 100644 --- a/labs/lab6/index.md +++ b/labs/lab6/index.md @@ -10,8 +10,6 @@ title: Heaps In today's lab, we're going to focus on priority queues, an important data structure that you'll need to understand for the next assignment and beyond. -Code can be downloaded [here](assets/resources.zip), as well as viewed/edited on Codio. - ### Heaps Introduction In office hours, we use a standard FIFO queue system, where the student waiting the longest is called next. But what if we wanted to apply a more complicated calculation to found who was next? Maybe the person with the shortest question? The person who started the assignment the earliest? The person who's asked the fewest questions? We still want the popping functionality of a queue, where we just care about who's on top, and don't need to access anyone in the middle. However, we no longer want to process items in order of the arrival. diff --git a/labs/lab7/assets/Backtracking_BST_AVL.pdf b/labs/lab7/assets/Backtracking_BST_AVL.pdf new file mode 100644 index 00000000..d61f8dff Binary files /dev/null and b/labs/lab7/assets/Backtracking_BST_AVL.pdf differ diff --git a/labs/lab7/assets/Backtracking_Lab.pdf b/labs/lab7/assets/Backtracking_Lab_su22.pdf similarity index 100% rename from labs/lab7/assets/Backtracking_Lab.pdf rename to labs/lab7/assets/Backtracking_Lab_su22.pdf diff --git a/labs/lab9/assets/Backtracking_BST_AVL.pdf b/labs/lab9/assets/Backtracking_BST_AVL.pdf new file mode 100644 index 00000000..d61f8dff Binary files /dev/null and b/labs/lab9/assets/Backtracking_BST_AVL.pdf differ diff --git a/labs/lab9/assets/Lab9_BST_AVL.pdf b/labs/lab9/assets/Lab9_BST_AVL_su22.pdf similarity index 100% rename from labs/lab9/assets/Lab9_BST_AVL.pdf rename to labs/lab9/assets/Lab9_BST_AVL_su22.pdf diff --git a/labs/number_theory/assets/number_theory_lab.pdf b/labs/number_theory/assets/number_theory_lab.pdf new file mode 100644 index 00000000..e04339ee Binary files /dev/null and b/labs/number_theory/assets/number_theory_lab.pdf differ diff --git a/labs/number_theory/index.md b/labs/number_theory/index.md index 27ca04f3..d5b8f739 100644 --- a/labs/number_theory/index.md +++ b/labs/number_theory/index.md @@ -7,7 +7,6 @@ title: Number Theory --- -This lab would be covered by lab sections between Apr. 19, 2022 and Apr. 22, 2022. You need to get checked off by a TA/CP during your assigned lab section. @@ -161,4 +160,4 @@ After you finish your implementation, type `make` in your terminal to run the te ### Checking Off -To get checked off, complete all three exercises in this lab and show your results to a CP/TA. \ No newline at end of file +To get checked off, complete all three exercises in this lab and show your results to a CP/TA. diff --git a/labs/su-gtest_lab/assets/gtest_slides.pdf b/labs/su-gtest_lab/assets/gtest_slides.pdf new file mode 100644 index 00000000..c1ecf788 Binary files /dev/null and b/labs/su-gtest_lab/assets/gtest_slides.pdf differ diff --git a/labs/su-gtest_lab/index.md b/labs/su-gtest_lab/index.md new file mode 100644 index 00000000..8c616c7e --- /dev/null +++ b/labs/su-gtest_lab/index.md @@ -0,0 +1,236 @@ +--- +layout: default +toc: true +tasks: true +title: GTest +--- + +## Unit Testing and GTest +In this lab we want to dive into the topic of unit testing. The goal of this lab is to give you an overview of how to use the Google Test framework to build and run test cases for any C++ project. + +### 0 - Motivation + +Testing is absolutely essential to a typical development process. Having a complete test suite can ensure that the code that you spent hours building works, fits specification, and is bug-free. + +Suppose you have just finished homework and you think you have a pretty good implementation of a doubly linked list. How do you know, for sure, that this list behaves like how you intended it to be? You can manually read through the code a million times, but you might still miss something. + +A good test case program should: + + + Use your newly created data structure + + Perform simple operations with your data structure's methods + + Make sure that each method performs the way you intended it to be + +There are several advantages for having a well-crafted test program: + + + Help you think about edge cases - ones that you might not have thought of when implementing the data structure itself. + + Help you make sure each subpart of a problem works correctly. For example, when you implement a new data structure with your new LinkedList, and you encounter a problem, it's very hard to know whose fault it is - the new data structure or the underlying LinkedList. By thoroughly testing your LinkedList in its corresponding test, you will be able to nail down where to hunt for problems fast. + + When you make a change to your code, you can make sure that it did not break anything. + +The [Google Test documentation](https://code.google.com/p/googletest/wiki/Primer) has further guidelines for what constitute good test suites. + +### 1 - Testing a Fibonacci Program + +#### 1.1 - Introduction to Testing + +Let's first begin writing tests for a simple function that computes the nth Fibonacci number. But before you open the code for the Fibonacci program, ask yourself - what are some test cases that we'll need to test? + +**Nominal Cases** - You can always start with the most basic cases - that 5th fibonacci should be 5, 7th should be 13. It's a good idea to include a few basic cases so to be sure you weren't just lucky, but you shouldn't need anything more than that. + +**Boundary or Special Cases** - What are the boundaries for this function? For a Fibonacci calculation, it seems that there is only a "lower-bound", namely when n = 1. For some data structures that are slightly more complex, there might be multiple boundaries, like the resize limit ("`capacity`") for an array based implementation of a list. + +**Off-nominal Cases** - Your program should be completely fool-proof. That means your program should handle even input that does not make sense. For example, asking for the -2th Fibonacci number, or asking to insert at the 5th position for a 2 element array. Note that things that do not compile are not part of off-nominal cases. If your compiler cannot compile the code, you won't even have an executable to run. + +Notice that we came up with these cases **without the need of looking at code** - all we did was think about how a Fibonacci program should behave, and how a user would be using such a function. In fact, it's very common for industry software engineers to write the test cases first _before_ writing a single line of code; they call this [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development). + +A very simple test program might include a long list of test cases made of if statements that looks like this: + +``` +Fibonacci fib; +if (fib.get(5) == 5) { + std::cout << "OK" << std::endl; +} else { + std::cerr << "FAIL | 5th Fibonacci number should be 5." +} +``` + +However, a long list of these cases can get out of hand very quickly - it's annoying to read and even more so to write repetitive code. We can use a library called Google Test to help us out. + +#### What is enough, and how much is too much? + +Generally speaking, there should be at least one test case for each code execution path in a function. For example, if a function has 3 branch conditions, test at least each path once, to ensure all use cases are covered. There is no need to test a single path more than a few times - it doesn't hurt, but it's generally unnecessary as it increases testing time. This is only a rule of thumb, as some edge cases just cannot be predicted by looking at the code. + +When testing a class implementation, each public function should be tested. For example, an array implemntation of a list, `ArrayList`, should have test cases for functions `add()`, `set()`, `remove()`, `get()`, and so on. More on class testing in a little bit! + +#### 1.2 - Our First Google Test Case + +Navigate to the `part1` directory, and open the `test.cpp` file included for you. The meat of the test suite provided to you in this file is in these four lines: + +``` +TEST(FibTest, Nominal) { + Fibonacci f; + EXPECT_EQ(5, f.get(5)); + EXPECT_EQ(13, f.get(7)); +} +``` + +You should notice that this is not standard C++ syntax. We're using a **C++ Macro** here that is supplied by the framework. C++, when compiling, will automatically replace this code with some appropriate C++ code defined in the framework. It is likely a much longer chunk of code that Google Test wants to hide and save the user from an unnecessary amount of copy pasting. + +A test case is defined by calling this `TEST` macro. Two more things are important here: `FibTest` and `Nominal`, the two "parameters" that are "passed into" the Macro. The first parameter specifies the name of the test suite. As a rule of thumb, all tests in a file should belong to the same test suite, and in this case, FibTest. The second parameter is the name of this test. We're testing the trivial cases right now, so we're just going to call it the "Nominal" case. + +``` +EXPECT_EQ(5, f.get(5)); +``` + +Another macro here - `EXPECT_EQ`. The name of this macro is not too surprising - test cases are but a long list of expected results under different circumstances. In here, by calling `EXPECT_EQ`, you're saying: "When I call f.get(5), the value it returns should equal to 5." + +You can find the list of GTest Macros [here](https://github.com/google/googletest/blob/master/googletest/docs/Primer.md). + +#### 1.3 - Adding some more test cases + +As we've mentioned, there are more test cases worthy to be tested. Let's add them together to our `test.cpp` file. + +**Boundary or Special Case** + +In our Fibonacci calculation, we have a base case of "1" and "2" - they return special values unlike the nominal cases. We should add a test that makes sure this happens. + +We first start with a call to the macro, with the test suite name staying the same (`FibTest`), and the test case name something like ("Boundary"). + +``` +TEST(FibTest, Boundary) { + Fibonacci f; + ... +} +``` + +What goes inside? Expectation statements. What do you expect `f.get(1)` return? `f.get(2)`? + +``` + EXPECT_EQ(??, ??) + EXPECT_EQ(??, ??) +``` + +When you're done - _don't run the tests yet_! Finish the entire test suite first, before you try to see if anything's wrong. This is to prevent us tailoring our test cases to the code - you would be able to think about edge cases much more easily from a different perspective. + +- [ ] Write a test for the boundary case in `test.cpp`. + +**Off-Nominal Case** + +What else can go wrong? A rule of thumb is: never trust the user. If something can go wrong, it will; so it's essential that your program handles correctly. + +For the sake of this testing demonstration, let's assume that any invalid input should return a value of 0. Some invalid inputs in this case could be 0, -1. + +- [ ] Write a test case for this and include it in `test.cpp`. + +**Bonus**: There is one more edge case. Can you think what it is? (Hint: What's the type of the input?) + +#### 1.4 - Run the tests now + +Now that we have a complete test suite, we can see if our program works fully to our specs by running `make tests` on the terminal **in Docker**. Because our dependencies are set up properly, this will attempt to compile the `fib` object, and then the test executable. After all the compiling is done, it will then attempt to run the test executable. + +You should now see a fancy test runner output, that says the output is unexpected, followed by a segfault. It's okay, we'll fix them one by one. + +``` +// Line 5: Change from: +return 0; +// to: +return 1; +``` + +Run the tests again by calling `make tests` from your Docker shell. That nominal test case now passes successful, but the segfaults are still there in the Off-Nominal Case. Well, that's unexpected. As always, try to debug using gdb. + +``` +gdb fibTest +``` + +Run until the segfault happens, and then run `bt` to see how the error occurred. It seems that the program crashed because we ran out of stack space by calling too many recursions. Fix this by modifying our `fib.cpp`: + +``` +// Add after Line 3: +if (n <= 0) { + return 0; +} +``` + +Run the test again, and it should now pass with flying colors - green, that is. + +- [ ] Fix the segfault as instructed. + +### 2 - Testing a Class + +Now that we understand how to run tests, we're going to practice testing on a class implementation. We'll be writing tests for an `ArrayList` class. + +#### 2.1 - Understanding Fixtures + +When we test classes, we often need some initialization before we can test. For example, initializing classes with the correct constructor parameters, populating an array, etc. Because these setup are usually repeated across multiple test cases, we put them in "Fixtures" + +Open the `test.cpp` in the `part2` folder. You'll notice that this file is slightly longer than the one in the first part. The main difference being a definition of a class `ArrayListTest`. There are several characteristics to this class: + + + It inherits from a Google Test class `testing::Test`. We have not learned what inheritance works yet, but you will understand how it works in a little bit + + The class is largely empty, but it includes a declaration of a member variable of type `ArrayList`. This object is available for use in any of the test cases + + It has four methods you can insert code in: + - the class constructor and `SetUp()` is largely the same; both will be called before each test case + - similarly, the class destructor and `TearDown()` will be called after each test + +In order to have access to the fixture, tests need to be declared using the `TEST_F` fixture instead of `TEST`. The test suite name should also be the same as the class name. + +You can see all that comes to play in the sample `get()` test. Notice that we are able to read elements from the list right away without any other code inside the test. In fact, for every test in this test suite will inherit these setup instructions as well. This helps to keep the actual test code simple. + +### 3 - More about Testing + +A common mistake students make is that they write tests for their program to pass. This is wrong. Your job, when writing test cases, is to try as hard as you can to break your code. Try to think of all possible ways that your program can misbehave. When designing test cases, ask yourself these questions: + + + What promises does the program make in its documentation? + + If something is supposed to happen after a function call, does it happen? + + If nothing should happen, how can you make sure nothing happened? + + What edge cases might a programmer easily overlook? + + What input might cause the program to crash? + +Remember - the harsher you are when testing your own program, the less bugs will make it to the hands of your end users. + +### 4 - Assignment: Identify Two of the Bugs + +**TL;DR: Find 2 out of 3 bugs by writing tests, and describe them in a .txt file for credit..** + +In the `part2` folder, we have provided an implementation of ArrayList for you - there is a header file `arraylist.h`, with the specification of the expected function in the comments, and a pre-compiled `ArrayList` implementation. You do not have access to the source code. We do this because again, we do not want you to think about test cases in terms of the source, but in a wider perspective of "how things should work". + +There are **three** bugs in the source code, and it is your task to find the problems by writing a good suite of test. Write a good set of tests for each of `add()`, `set()`, and `remove()` according to the specification provided in the header file, and thinking about edge cases. Find two of these bugs and you're good to go. + +We have written a sample test case for you for the `get()` function, although it is by no means an exhaustive test case. There is also a simple Makefile included for you, simply compile and run the test with `make tests`. + +Some tips: + + + [Google Test documentation](https://code.google.com/p/googletest/wiki/V1_7_Primer) has a lot more macros you can use: `EXPECT_NE`, `EXPECT_LT`, `EXPECT_TRUE` etc. + + When you call a method, how should the state of the object change? + + What are the "boundaries" of this class? What happens there? + + What are the execution paths in each function? + + Big Hint: look at the test names we give you + + - [ ] Find two of the three bugs. Describe them in a .txt file for credit. + +### Appendix: A little bit more on the Makefile + +You might be a little more confused about the `GTEST_LL` variable and how we are able to use Google Test. There are several key parts to understand here: + + + The complete compile command is: `g++ -Wall -g test.cpp arraylist.o -I /usr/include/gtest/ -l gtest -l gtest_main -o arrayTest` The important files are `test.cpp` and `arraylist.o`, the rest are just flags. + + `GTEST_LL` - This is variable that contains the necessary flags to compile a Google Test program. There are several flags in here: + + `-I /usr/include/gtest/`: `-I` means "look up includes in this directory". This is how `#include "gtest/gtest.h"` worked in the test program - when C++ tries to look up a file, it looks not only in the current directory, but in whatever directories specified by `-I` as well. Including the gtest header ensures all necessary functions are imported. This is similar to how `-Ilib` works. + + `-l gtest`: Use the library called "gtest". This includes all extra dependencies not included in the header file + + `-l gtest_main`: Use the library called "gtest_main". Notice that there are no main functions at all in our test suite program. THat's because the `gtest_main` library comes with one. When we run the test, we're running a main function included in the Google Test framework that automatically detects all tests and execute them accordingly. + + `-pthread`: Because Google Test runs tests in parallelize, enable threading support. + +You can probably safely copy this variable everywhere. + +**fib.o** - This is the rule to compile the Fibonacci class by itself. Notice that the `-c` flag is used - when we compile the class by itself, we can include the compiled object everywhere - in an actual program, or in the test suite. + +**fibTest** - The main test rule. It has two dependencies: the compiled fib object, and the test suite itself. For the command, we simply take all the dependencies and compile them, with the `GTEST_LL` variable. It's important that the libraries are loaded after the source files, or else the linker will likely throw an error. + +**tests** - A rule that just runs the tests. Optional. Notice that this is a phony rule, because it doesn't actually create any file. + +### Checking off +To get credit please show a CP/TA the following: +- fib.cpp and test.cpp from part1 folder +- test.cpp from part2 folder +- a .txt file describing at least 2 bugs you found in part2 + + + diff --git a/labs/su-lab0-curricula/index.md b/labs/su-lab0-curricula/index.md new file mode 100644 index 00000000..539ea7b5 --- /dev/null +++ b/labs/su-lab0-curricula/index.md @@ -0,0 +1,293 @@ +--- +layout: asides +toc: true +tasks: true +title: Getting Started +--- + +# Getting Started + +Before you start out on your 104 journey you're going to have to complete a couple of setup steps. +Make sure you read each section carefully; if you don't, you may find yourself unable to submit assignments. + + +## Register with Github + +If you have not created a Github account yet, follow the instructions in this section. +If you already have a Github account and you wish to use it for this course, you can skip to the next section. + +We will be using git extensively this semester in labs and in programming assignments. +Github is a development ecosystem based around git. +In CSCI 104, we will be using Github to host our git repositories and we will take advantage of other GitHub features such as the issue tracker and wiki. + +We start by visiting Github's signup page. +You are free to choose your username; it does not necessarily need to match your USC username. +Likewise, you are welcome to any email, just **remember which email you use as you will need it later**. +You will be sent an email to verify your email address. +Do that before proceeding. + +If in doubt, use a GitHub account with your @usc.edu e-mail address. + +- [ ] Create or have a GitHub account + + +## Register with Curricula + +Curricula is our home-grown classroom software suite that we'll be using to handle things like submission, grading, and office hours. +Your next link your USC ID and GitHub account via the registration page. If you've take the class in the past and have an account with our "Curricula" system, just login with Github. Otherwise, if this is your first time, just click **Register** and go through the process of creating an account. Though you'll enter a username and password, you should use the "Login with Github" each subsequent time you need to login. It will authenticate you automatically when you click that button. + +This step is particularly important because it will also kickstart the processes that create your homework repository and add you to the necessary GitHub groups. + +- [ ] Register with Curricula Web + + +## Install Git + +You can skip this section if you have git installed or are using the VM, which has git installed. + +In order to actually install the git command line tools, go to the [git website](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git){:target="_blank"} and follow the instructions for your operating system. + +If you're installing on MacOS, installing the Homebrew package manager should also get you there: [brew.sh](https://brew.sh/){:target="_blank"} + +### Special Notes for Windows + +If you are using Windows, we recommend installing [git bash](https://git-scm.com/download/win), which will be provided as an option in the installer. +Git bash is a separate shell that provides access to git as well as other command line utilities. +If you have more experience with git or other command line tools, installing git and the other unix commands directly to your CMD is a pretty convenient option. + + +## Virtual Machine + +We have two options for running the compiler tools that we will use for grading. +While you are welcome to use any editor/IDE to develop your homework code, you must compile and run your code (and any of our tests) in a Linux virtual environment using a Linux VM, Docker, or some similar solution of your creation. + +We offer two solutions: a traditional VM and Docker. +**We recommend Docker, as it avoids emulating an entire desktop by giving you easy and low-latency command-line access to all the tools you need**. +Plus, you can use your own local editor to develop and write code. + +### Docker +Follow the directions in this Github **[repository](https://github.com/csci104/docker){:target="_blank"}.** + +You might want to [configure an SSH key for your github account](#configuring-an-ssh-key) first, but it is not necessary. + +If you want more information on how Docker works and how to use it, you can read the additional guide. + +- [ ] Read the additional guide or promise you know what you're doing. + + +### VM + +Alternatively, you can download and install the Course VM, the instructions for which are available [in the wiki]({{ site.baseurl }}/wiki/vm/). +This provides a full-featured virtual OS with graphical interface, etc. +It is larger, stores your files on a separate "virtual disk" that is not directly accessible from your computer's host OS, and can sometimes get corrupted, so please push your work to Github often. + +- [ ] Install Docker or a virtual machine. + + +## Configuring an SSH Key + +One of the main features of using a distributed version control system such as git is having a complete backup of your code and its history. +Git uses the [Secure Shell](http://en.wikipedia.org/wiki/Secure_Shell) protocol (SSH) when contacting remote servers. +To facilitate this communication, you need to generate a pair of encryption keys: one public and the other private. +In this step, we will generate the set of keys required to use SSH. +This will be done manually through the command line. + +**Important**: where you run the following instructions will depend on whether you're using Docker or the VM. +**If you are using Docker, you must open a terminal on your normal operating system. This is because Docker reboots itself from a pre-canned image everytime, which would erase all git configurations you had**. +If you're on Windows, installing Git should either give you Git Bash or access to unix commands in CMD. +**If you are using the VM, you have to open Terminal inside the virtual desktop**. +Going forward, whichever applies to you will be the terminal we refer to when we ask you to open or write commands in a terminal. + +- [ ] Open the correct terminal based on the instructions above. + +**Note**: you will be copying and pasting several commands in this lab. +If you are using the VM, you can use `ctrl + shift + c` to copy from Terminal and `ctrl + shift + v` to paste into Terminal. +You can also right-click in Terminal and choose Copy/Paste. +If you're using Docker, copy and paste should work how it normally does on your operating system. + +Use the following command to generate an SSH key, **replacing `ttrojan@usc.edu` with the email associated with your Github account**: + +```shell +ssh-keygen -t rsa -b 2048 -C "ttrojan@usc.edu" +``` + +- [ ] Generate an SSH key using the email associated with your GitHub account + +When prompted for a location to save the key, use whatever the default is. +The path may look slightly different than the one below, but that's fine. + +``` +Generating public/private rsa key pair. +Enter file in which to save the key (/home/cs104/.ssh/id_rsa): +``` + +After that, you will be prompted for a passphrase to secure your private key. +**We recommend you do NOT generate a passphrase (because you'll have to enter it each time you upload your code to Github) and simply hit Enter when prompted for a passphrase**. If you do decide to enter a passphrase, please note that your password will not show up in terminal as you type it. +When you are done typing your password (don't enter anything if you do not wish to set a passphrase), press `enter`. +You will be prompted to verify your passphrase. +Re-enter your passphrase (or nothing if you did not set one) and press `enter`. + +Upon success, you should receive confirmation that your key was generated. +It will most likely look something like this: + +``` +Your identification has been saved in /home/cs104/.ssh/id_rsa. +Your public key has been saved in /home/cs104/.ssh/id_rsa.pub. +The key fingerprint is: +SHA256:vC+4OG2u1PIeE0OKX9jiFFHuLnkYCBSsvIW8ybD873H ttrojan@usc.edu +The key's randomart image is: ++---[RSA 2048]----+ +| ++o. | +| S+.o *.* | +| +.X. o | +| 0. o + | +| ..o E . | +| .=S. . + .0 | +| .*=* ... | +|.+.=o*. .. *o* | +| .++*oo. .. | ++----[SHA256]-----+ +``` + +- [ ] Save the key to the default location + + +## Git Configuration + +The next step is to configure your git profile in your development environment. +This is important because your profile information is used to annotate your contributions to a repository/project. +It may not seem like a big deal when you are the only one committing to a repository. +However, it's a good habit to build since in a group setting, this information will help track what changes you made and how much you've contributed. + +You only need to do this configuration once for any machine or virtual machine you want to develop on. +We'll be setting the following fields: + +- Full name +- Email associated with GitHub +- Editor for commit messages, e.g. `nano`, `vi`, `emacs`, `notepad` +- Git message colors (make it prettier) +- Newline handling ([why is this a problem?](http://en.wikipedia.org/wiki/Newline#Common_problems)) + +To get started, have a terminal open. + +### Personal Information + +Please use your actual first and last name when configuring your git `user.name`. +For your email, you should **use the email address you've associated with your Github account**. +Configure your information as follows, replacing the example name and email with your own: + +```shell +git config --global user.name "Tommy Trojan" +git config --global user.email "ttrojan@usc.edu" +``` + +- [ ] Configure your `user.name` and `user.email` + +### Git CLI + +By default, git does not color its output. +Pretty printing git messages makes it easy read the output and take proper actions. +You can enable colors for interactive use with: + +```shell +git config --global color.ui auto +``` + +### Git Editor + +When committing code in git, the system requires a commit message. +If a message is not provided via the shell, git will launch the operating system's default text editor prompting you for a message. +You can customize this action by setting what command you want to invoke to open a text editor, for example: + +- `nano` is a simple and easy-to-use shell text editor +- `emacs`, `vi`, and `vim` have a steeper learning curve but offer more utility +- `subl -n -w` will open Sublime if you have that installed (won't work on Docker) +- `gedit` will open the default Ubuntu text editor (also doesn't work on Docker) + +Choose one of them (`nano` is likely the easiest) and run the following command: + +```shell +git config --global core.editor "nano" +``` + +- [ ] Set your git editor to the text editor command of your choice + +### Default branch name + +Recently GitHub has changed to `main` as the default branch. We need our local git command to respect that: + +```shell +git config --global init.defaultBranch main +``` + +### Miscellaneous Settings + +Operating systems implement new lines differently. +Here you will configure git to automatically normalize the line feed to properly match the platform: + +```shell +git config --global core.autocrlf input +``` + +- [ ] Set the line feed normalization to `input` + +Since Git 2.0, Git has updated its default push settings. +To avoid getting a warning when you push (we will explain what push means soon), apply the following setting: + +```shell +git config --global push.default simple +``` + +- [ ] Set the push strategy to `simple` + +You can double check your settings using the following command: + +```shell +git config --list +``` + +- [ ] Check that all settings have been set properly + + +## Github Profile + +You need to update your profile to include your name and SSH public key. +There are also some optional settings you can change such as your profile picture and email notifications. + +In your [profile settings](https://github.com/settings/profile): + +- Put your **real name** in the name field. + This is to ensure the TAs & CPs know who you are regardless of your username. +- Optionally, change your [profile image](http://gravatar.com/) + +In your [SSH key settings](https://github.com/settings/ssh): + +- Click `Add SSH Key`. +- Provide a name for the key, such as "CS104 VM Key" or "MacBook Key". +- Display the contents of your `id_rsa.pub` file by running `cat ~/.ssh/id_rsa.pub` in your terminal. +- Select all the contents of your `id_rsa.pub` file all the way through the end of the last line where your email is displayed and then copy/paste them into the key field. + Make sure you copy the entire contents of the `id_rsa.pub` file. + It should start with `ssh-rsa` and end with your email address. +- Click `Add Key`. + +In your [notification settings](https://github.com/settings/notifications), apply the following settings: + +- In your notification settings + - Automatically watch repositories: ON + - Participating: Email ON, Web ON + - Watching: Email OFF, Web ON +- In your email notification settings: + - Comments on Issues and Pull Requests: ON + - Pull Request reviews: ON + - Pull Request pushes: ON + - Include your own updates: OFF + +Homework grade reports are released through GitHub, and using the above settings will ensure that you receive email notifications when your grade report is available. + +- [ ] Set your profile name to your real name +- [ ] Upload your SSH key by adding the contents of your `id_rsa.pub` +- [ ] Enable Github and Github email notifications + + + + diff --git a/labs/su-lab1/assets/AppendixA_Git.pdf b/labs/su-lab1/assets/AppendixA_Git.pdf new file mode 100644 index 00000000..3e5853d2 Binary files /dev/null and b/labs/su-lab1/assets/AppendixA_Git.pdf differ diff --git a/labs/su-lab1/assets/git_lab.pdf b/labs/su-lab1/assets/git_lab.pdf new file mode 100644 index 00000000..d43f85e3 Binary files /dev/null and b/labs/su-lab1/assets/git_lab.pdf differ diff --git a/labs/su-lab1/assets/github-clone-button.png b/labs/su-lab1/assets/github-clone-button.png new file mode 100644 index 00000000..9a3c3cd8 Binary files /dev/null and b/labs/su-lab1/assets/github-clone-button.png differ diff --git a/labs/su-lab1/assets/github-clone-ssh.png b/labs/su-lab1/assets/github-clone-ssh.png new file mode 100644 index 00000000..2d52cde3 Binary files /dev/null and b/labs/su-lab1/assets/github-clone-ssh.png differ diff --git a/labs/su-lab1/assets/github-edit-pencil.png b/labs/su-lab1/assets/github-edit-pencil.png new file mode 100644 index 00000000..2e2a9556 Binary files /dev/null and b/labs/su-lab1/assets/github-edit-pencil.png differ diff --git a/labs/su-lab1/assets/github-edit-submit.png b/labs/su-lab1/assets/github-edit-submit.png new file mode 100644 index 00000000..4b2e7a4a Binary files /dev/null and b/labs/su-lab1/assets/github-edit-submit.png differ diff --git a/labs/su-lab1/assets/github-example-first-commit.png b/labs/su-lab1/assets/github-example-first-commit.png new file mode 100644 index 00000000..b497ab80 Binary files /dev/null and b/labs/su-lab1/assets/github-example-first-commit.png differ diff --git a/labs/su-lab1/assets/github-link-commits.png b/labs/su-lab1/assets/github-link-commits.png new file mode 100644 index 00000000..2e6747d1 Binary files /dev/null and b/labs/su-lab1/assets/github-link-commits.png differ diff --git a/labs/su-lab1/assets/vm-terminal.png b/labs/su-lab1/assets/vm-terminal.png new file mode 100644 index 00000000..d3536b07 Binary files /dev/null and b/labs/su-lab1/assets/vm-terminal.png differ diff --git a/labs/su-lab1/index.md b/labs/su-lab1/index.md new file mode 100644 index 00000000..01a212f7 --- /dev/null +++ b/labs/su-lab1/index.md @@ -0,0 +1,490 @@ +--- +layout: asides +toc: true +tasks: true +title: Introduction to Git +--- + +# Introduction to Git + +[Git](http://git-scm.com/) is a distributed source code version control system. +When you place your code under version control, you record the changes you make to your files over time and you can recall the history of each of your file changes at will. +We will be using git extensively this semester in homework assignments. + +[GitHub](https://github.com/) is a development ecosystem based around git. +In this course, we will be using GitHub to host our git repositories and we will take advantage of other GitHub features such as the issue tracker and wiki. + +**If you have not done [Lab 0]({{ site.baseurl }}/labs/lab0) to set up your GitHub account or install Docker or a VM, please do so now.** + +## Important: Using the correct terminal + +In order to complete this lab, make sure you are using the correct terminal to run commands: + +* If you are running Docker, then there are two types of terminals you are going to interact with: + - The **native terminal** refers to the terminal provided by your native OS, not docker. On Windows, type + `Win + R` and then `powershell` to start it. On Mac, open you app launcher and search for "terminal". + - The **docker terminal** refers to the terminal you obtain by typing the following in your **native terminal**: + +```shell +ch start csci104 +ch shell csci104 +``` + +From now on, every sequence of command we show you would be annotated with either *`[native]`* or *`[docker]`*. This denotes the +terminal you should be running the command from if you are using Docker. (If you are using the VM, then always use the VM terminal). + +Examples (You do **NOT** need to run these commands): + +*`[native]`* +```shell +notepad.exe cat.txt +``` + +The above command shall be ran from your **native terminal**. + +*`[docker]`* +```shell +vim cat.txt +``` + +The above command shall be ran from your **Docker terminal**. + +* If you are running the course VM (through Virtual Box), then **all commands** from this lab shall be ran from + the terminal within the VM. To open a terminal in the VM, press `Ctrl + Alt + T` (Windows) or `Cmd + Option + T` (Mac). + Alternatively, you could open it by searching for "terminal" in the quick launcher: + +
+ +## Cloning the `resource` and `hw-username` repositories + +### The Concept of the *working directory* + +Every open terminal has a *working directory*. When you run a command inside that terminal, +the command would interpret paths and filenames to be relative to that working directory, for example: + +``` +mkdir sub +``` + +creates the subdirectory named `sub` under the current *working directory*. If the *working directory* is `/usr/root/parent`, then this will +create the directory `/usr/root/parent/sub`. + +### Step 1. Changing working directory to Docker's assigned `/work` directory + +First open your **native (Mac/Windows) terminal**. Then, change the working directory to the directory you [assigned to Docker during setup](https://github.com/csci104/docker#step-5-set-your-working-directory). + +If you are working on the course VM, you may use any directory you like on the VM (e.g. `~/csci104`). + +The command for changing the working directory is `cd` (which stands for "**c**hange **d**irectory"). In my case, the path to change to is: +`C:\Users\rin\Documents\csci104\home` (yours might be different, depending on how you configured your docker), therefore I just type: + +*`[native]`* +```shell +cd C:\Users\rin\Documents\csci104\home +``` + +**Note: You will need double quotes around the path if your path contains space, e.g. `cd "C:\My Documents\Home"`** + +If you have forgotten which path you have assigned to Docker, you could check it by typing: + +*`[native]`* +```shell +ch list +``` + +And you will see an output that looks like: + +``` +Name: csci104 + Image: usccsci104/docker:20.04 + Volume: C:\Users\rin\Documents\csci104\home:/work + SecOpt: seccomp:unconfined + CapAdd: SYS_PTRACE + Port: :2222 +``` + +The path after `Volume: ` (excluding `:/work`) is what you are looking for. + +### Step 2. Obtaining clones of the `hw-username` and `resources` repositories + +This step assumes that you have already finished the git, GitHub, and SSH key setup from Lab 0. + +Once you are inside the correct working directory, type the following commands (**replace the `username` in `hw-username` with your actual USC Net Id, the same goes for everything that follows. Your USC NetId is your USC email address without the "@usc.edu" part, not the 10-digit Student ID**): + + +*`[native]`* +```shell +git clone git@github.com:{{site.data.urls.github_org}}/hw-username.git +git clone git@github.com:{{site.data.urls.github_org}}/resources.git +``` + +If you see the following dialog in your command line, type `yes` and press `enter`. +It's basically asking if you want to trust `github.com` as an SSH server. + +``` +The authenticity of host 'github.com (192.30.255.112)' can't be established. +RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8. +Are you sure you want to continue connecting (yes/no)? +``` + +After every clone command, you should see something like this (exact output might be different): + +``` +remote: Counting objects: 4, done. +remote: Compressing objects: 100% (3/3), done. +remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0 +Receiving objects: 100% (4/4), done. +Checking connectivity... done. +``` + +A few notes about cloning: + - **Never clone a Git repository** into a Dropbox or other sync'ed folder (Google Drive, etc.). + - **Never clone a Git repository** under another repository folder. They should be at the same level. + +## Running the Example Project + +We have provided an `example` project to test whether you have the correct environment setup to compile our homeworks. Make sure you follow the steps below and the output on your terminal matches the ones on this page. + +### Step 3. Copy the `example` dirctory to your `hw-username` directory + +For every assignment from this class, we would provide the it's skeleton code inside the `resources` repository, and you need to copy it into your +`hw-username` directory when you start the assignment. You should then do all of your work in your `hw-username` repo instead of the +`resources` repo. + +The `example` project is also provided in the `resources` repo. To copy it, first start the **docker terminal** if you are using Docker: + +*`[native]`* +``` +ch start csci104 +ch shell csci104 +``` + +Then, make sure your working directory is where you put the `hw-username` and `resources` clones. You could check this by typing: + +*`[docker]`* +``` +ls +``` + +and you should see `hw-username` and `resources` in the output. + +If not, you have to use `cd` to change to the correct working directory. + +To copy the directory, type: + +*`[docker]`* +``` +cp -r resources/example hw-username/example +``` + +where `cp` stands for "copy" and the `-r` standard for "recursive" which allows copying of directories. + +### Step 4. Building the example project + +Now, go into your `hw-username/example` directory by typing: + +*`[docker]`* +``` +cd hw-username/example +``` + +Then, run the following command: + +*`[docker]`* +``` +make run +``` + +If the build is successful, you should see something like this: + +``` +Running main() from /build/googletest-j5yxiC/googletest-1.10.0/googletest/src/gtest_main.cc +[==========] Running 3 tests from 2 test suites. +[----------] Global test environment set-up. +[----------] 2 tests from SimpleReturnTest +[ RUN ] SimpleReturnTest.Returns42 +[ OK ] SimpleReturnTest.Returns42 (0 ms) +[ RUN ] SimpleReturnTest.Returns37 +test.cpp:12: Failure +Expected equality of these values: + returns_37() + Which is: 36 + 37 +[ FAILED ] SimpleReturnTest.Returns37 (0 ms) +[----------] 2 tests from SimpleReturnTest (0 ms total) + +[----------] 1 test from SummationTest +[ RUN ] SummationTest.SumsAreEqual +[ OK ] SummationTest.SumsAreEqual (0 ms) +[----------] 1 test from SummationTest (0 ms total) + +[----------] Global test environment tear-down +[==========] 3 tests from 2 test suites ran. (0 ms total) +[ PASSED ] 2 tests. +[ FAILED ] 1 test, listed below: +[ FAILED ] SimpleReturnTest.Returns37 + + 1 FAILED TEST +make: *** [Makefile:8: run] Error 1 +``` + +You **don't** have to worry about the red `[FAILED]` message as long as it shows up (it is intentional), +but in case it does not show up, please ask for help from your lab instructor. + +### Step 5. Fixing the FAILED test case + +What you have just seen above is an example of an automated test. We run automated tests to grade your +assignments, and you will learn more about them in later labs. For now, you could just think of them +as programs that feeds some input into your assignment code and test whether they produce the correct +output. + +Obviously, it is not good to have a FAILED test case! (You would lose points in an actual assignment if your +program fail our test cases) So let's fix it! + +Open `library.cpp` and look at the function `int returns_37()`. As you can see it returns `36` instead of +the suggested `37`. If you look at the FAILED test case carefully you would see: + +``` +Expected equality of these values: + returns_37() + Which is: 36 + 37 +``` + +which points to exactly the same issue. + +Therefore, change the return value to `37` and run `make run` again. This time every test should pass. + +### Step 6. Committing and pushing to your homework repository + +Now that you have finished the work locally, you would also want to push the changes to GitHub. + +To do so, open your **native** terminal (or the VM terminal is you are using the course VM) and change +the working directory to `hw-username`. Then type + +*`[native]`* +``` +git status +``` + +The output should look like this: + +``` +Your branch is up to date with 'origin/main'. + +Untracked files: + (use "git add ..." to include in what will be committed) + example/ +``` + +which means that nothing from your `example` directory is tracked by git. + +To track those files run the following command: + +*`[native]`* +``` +git add . +``` + +This command tells git to track all modification you have done to the repo (adding a new file, modifying a file, deleting a file, renaming a file, etc.). You could also specify individual files to track by providing their name instead of `.` (e.g. `git add library.cpp`). + +Now, if you check `git status`, you would see: + +``` +On branch main +Your branch is up to date with 'origin/main'. + +Changes to be committed: + (use "git restore --staged ..." to unstage) + new file: example/.vscode/launch.json + new file: example/.vscode/settings.json + new file: example/.vscode/tasks.json + new file: example/Makefile + new file: example/README.md + new file: example/library.cpp + new file: example/library.hpp + new file: example/library.o + new file: example/test + new file: example/test.cpp +``` + +All the changes are now ready to be *committed*. You could now run the following command: + +*`[native]`* +``` +git commit -m "fixed the example" +``` + +This tells git to create a snapshot of the repository that reflects the changes you just asked it to track. +The snapshot is called a **commit**. Each commit must have a message, as specified by the `-m` option. It can be anything, +but it's a good practice to keep it informative of what changes you have made. + + +Now, if you type `git status`, you would see: + +``` +On branch main +Your branch is ahead of 'origin/main' by 1 commit. + (use "git push" to publish your local commits) + +nothing to commit, working directory clean +``` + +This tells that your local repo has one commit that the remote does not have. To +upload the commit, simply type: + +*`[native]`* +``` +git push +``` + +Now, if you everything runs successfully, the changes you have made would be synced to GitHub. Go to +the repo page on GitHub (it should be at https://github.com/usc-csci104-spring2022/hw-username, with `username` +replaced with your actual Net ID), and navigate to `example`, you should see the following files: + +
+ +If you read the `library.cpp` file, you should be able to see the code you have just modified. + +However, if you look at the `example` directory (in the image above), you would see the file `test`. Those are the binary files created by the `make run` command while building +the project. As a good practice you should never push anything generated by a build process. We would deduct +points if you submitted your assignment with those files (unless otherwise specified). + +**NOTE: You may not be able to see the `library.o` file on GitHub, that is to be expected +with the homework repository.** + +### Step 7. Removing the extra files from your repo + +To tell git to remove those files from the repo, first go back to your native terminal and change directory +to `hw-username/example`. Then type the following: + +``` +git rm test +``` + +This will remove the two files from the directory and ask git to track the removal. + +### Step 8. Prevent accidentally adding files with .gitignore + +The `git rm` command only solves the problem temporarily. What if in the future you run `make run` again and +generated the files again? It would be an annoyance to run `git rm` every time you push. + +Fortunately, git offers a way to prevent files from being tracked by the `git add` command. To achieve this, +create a file called `.gitignore` (with no extensions) in your `hw-username/example` directory, and open it in a text editor. + +**NOTE: a file or directory starting with `.` is hidden by default on most systems. To make your system show +those files, follow these instructions:** + +* [Windows](https://support.microsoft.com/en-us/windows/view-hidden-files-and-folders-in-windows-97fbc472-c603-9d90-91d0-1166d1d9f4b5#WindowsVersion=Windows_10), +* [Mac](https://www.pcmag.com/how-to/how-to-access-your-macs-hidden-files) + +Once you are inside the text editor, add the following lines: + +``` +test +``` + +This line tells git to ignore any file +named `test`. + +Note that since the `.gitignore` file is placed under +the `example` directory, the rules would only be enforced +there. In general you would want separate `.gitignore` files +for each of your assignment. + +The `library.o` file is being ignored because it is included in the `.gitignore` file at the root +of the homework repository. + +Now, if you type + +*`[native]`* +``` +git add . +git status +``` + +you would see something like: + +``` +Your branch is up to date with 'origin/main'. + +Changes to be committed: + (use "git restore --staged ..." to unstage) + new file: .gitignore + deleted: test +``` + +You could then commit and push the changes to GitHub: + +*`[native]`* +``` +git commit -m "removed extra file and added .gitignore" +git push +``` + +If you now go to the GitHub repo page, you would see that `test` +and `library.o` are no longer there. + + +## Pulling changes from GitHub + +Sometimes you would like to download changes from the remote repo because +someone else (or even you from another machine) modified the remote repo. +This is the case when we release the skeleton code in the `resources` repo +for a new assignment and you would like to download it. + +This won't happen until assignment 1 of course, so let's do this to your `hw-username` +repo instead. + +### Step 9. Modifying a file on GitHub + +First navigate to the `example/README.md` file in your `hw-username` GitHub repo page, and +click the pencil icon (see the image below): + +
+ +Then make an edit to the markdown file (any edit will do), and click `Commit Changes`: + +
+ +**Note in general we do not recommend modifying files directly on GitHub, it is used +here just for demonstration purposes** + +### Step 10. Pulling the change + +Now change your directory into `hw-username` in your local terminal, and then type: + +*`[native]`* +``` +git pull +``` + +The output should look like this: + +``` +remote: Enumerating objects: 7, done. +remote: Counting objects: 100% (7/7), done. +remote: Compressing objects: 100% (3/3), done. +remote: Total 4 (delta 1), reused 0 (delta 0), pack-reused 0 +Unpacking objects: 100% (4/4), 742 bytes | 32.00 KiB/s, done. +From github.com:ph3rin/hw-demo + dcdcc61..eb57bef main -> origin/main +Updating dcdcc61..eb57bef +Fast-forward + example/README.md | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) +``` + +Now if you read the `hw-username/example/README.md` file on your local machine, it should +match the one on GitHub. + +## Checkoff + +Show your TA both your local version of the changed `example` code and your updated repository on github.com. + +## In Closing + +There are tons of git cheatsheets all over the web. +Here's [one by Tower](https://www.git-tower.com/blog/git-cheat-sheet/) and [another by Atlassian](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet). +You can use one of these your make your own; git has a bit of a learning curve and at the end of the day comes down to memorizing the most useful commands and what they do. +Don't worry if it takes a little while. diff --git a/labs/su-lab1/lab1/assets/git_lab.pdf b/labs/su-lab1/lab1/assets/git_lab.pdf new file mode 100644 index 00000000..d43f85e3 Binary files /dev/null and b/labs/su-lab1/lab1/assets/git_lab.pdf differ diff --git a/labs/su-lab1/lab1/assets/github-clone-button.png b/labs/su-lab1/lab1/assets/github-clone-button.png new file mode 100644 index 00000000..9a3c3cd8 Binary files /dev/null and b/labs/su-lab1/lab1/assets/github-clone-button.png differ diff --git a/labs/su-lab1/lab1/assets/github-clone-ssh.png b/labs/su-lab1/lab1/assets/github-clone-ssh.png new file mode 100644 index 00000000..2d52cde3 Binary files /dev/null and b/labs/su-lab1/lab1/assets/github-clone-ssh.png differ diff --git a/labs/su-lab1/lab1/assets/github-edit-pencil.png b/labs/su-lab1/lab1/assets/github-edit-pencil.png new file mode 100644 index 00000000..2e2a9556 Binary files /dev/null and b/labs/su-lab1/lab1/assets/github-edit-pencil.png differ diff --git a/labs/su-lab1/lab1/assets/github-edit-submit.png b/labs/su-lab1/lab1/assets/github-edit-submit.png new file mode 100644 index 00000000..4b2e7a4a Binary files /dev/null and b/labs/su-lab1/lab1/assets/github-edit-submit.png differ diff --git a/labs/su-lab1/lab1/assets/github-example-first-commit.png b/labs/su-lab1/lab1/assets/github-example-first-commit.png new file mode 100644 index 00000000..b497ab80 Binary files /dev/null and b/labs/su-lab1/lab1/assets/github-example-first-commit.png differ diff --git a/labs/su-lab1/lab1/assets/github-link-commits.png b/labs/su-lab1/lab1/assets/github-link-commits.png new file mode 100644 index 00000000..2e6747d1 Binary files /dev/null and b/labs/su-lab1/lab1/assets/github-link-commits.png differ diff --git a/labs/su-lab1/lab1/assets/vm-terminal.png b/labs/su-lab1/lab1/assets/vm-terminal.png new file mode 100644 index 00000000..d3536b07 Binary files /dev/null and b/labs/su-lab1/lab1/assets/vm-terminal.png differ diff --git a/labs/su-lab1/lab1/index.md b/labs/su-lab1/lab1/index.md new file mode 100644 index 00000000..22699100 --- /dev/null +++ b/labs/su-lab1/lab1/index.md @@ -0,0 +1,487 @@ +--- +layout: asides +toc: true +tasks: true +title: Introduction to Git +--- + +# Introduction to Git + +[Git](http://git-scm.com/) is a distributed source code version control system. +When you place your code under version control, you record the changes you make to your files over time and you can recall the history of each of your file changes at will. +We will be using git extensively this semester in homework assignments. + +[GitHub](https://github.com/) is a development ecosystem based around git. +In this course, we will be using GitHub to host our git repositories and we will take advantage of other GitHub features such as the issue tracker and wiki. + +**If you have not done [Lab 0]({{ site.baseurl }}/labs/lab0) to set up your GitHub account or install Docker or a VM, please do so now.** + +## Important: Using the correct terminal + +In order to complete this lab, make sure you are using the correct terminal to run commands: + +* If you are running Docker, then there are two types of terminals you are going to interact with: + - The **native terminal** refers to the terminal provided by your native OS, not docker. On Windows, type + `Win + R` and then `powershell` to start it. On Mac, open you app launcher and search for "terminal". + - The **docker terminal** refers to the terminal you obtain by typing the following in your **native terminal**: + +```shell +ch start csci104 +ch shell csci104 +``` + +From now on, every sequence of command we show you would be annotated with either *`[native]`* or *`[docker]`*. This denotes the +terminal you should be running the command from if you are using Docker. (If you are using the VM, then always use the VM terminal). + +Examples (You do **NOT** need to run these commands): + +*`[native]`* +```shell +notepad.exe cat.txt +``` + +The above command shall be ran from your **native terminal**. + +*`[docker]`* +```shell +vim cat.txt +``` + +The above command shall be ran from your **Docker terminal**. + +* If you are running the course VM (through Virtual Box), then **all commands** from this lab shall be ran from + the terminal within the VM. To open a terminal in the VM, press `Ctrl + Alt + T` (Windows) or `Cmd + Option + T` (Mac). + Alternatively, you could open it by searching for "terminal" in the quick launcher: + +
+ +## Cloning the `resource` and `hw-username` repositories + +### The Concept of the *working directory* + +Every open terminal has a *working directory*. When you run a command inside that terminal, +the command would interpret paths and filenames to be relative to that working directory, for example: + +``` +mkdir sub +``` + +creates the subdirectory named `sub` under the current *working directory*. If the *working directory* is `/usr/root/parent`, then this will +create the directory `/usr/root/parent/sub`. + +### Step 1. Changing working directory to Docker's assigned `/work` directory + +First open your **native terminal**. Then, change the working directory to the +directory you [assigned to Docker during setup](https://github.com/csci104/docker#step-5-set-your-working-directory). + +If you are working on the course VM, you may use any directory you like on the VM (e.g. `~/csci104`). + +The command for changing the working directory is `cd` (which stands for "**c**hange **d**irectory"). In my case, the path to change to is: +`C:\Users\rin\Documents\csci104\home` (yours might be different, depending on how you configured your docker), therefore I just type: + +*`[native]`* +```shell +cd C:\Users\rin\Documents\csci104\home +``` + +**Note: You will need double quotes around the path if your path contains space, e.g. `cd "C:\My Documents\Home"`** + +If you have forgotten which path you have assigned to Docker, you could check it by typing: + +*`[native]`* +```shell +ch list +``` + +And you will see an output that looks like: + +``` +Name: csci104 + Image: usccsci104/docker:20.04 + Volume: C:\Users\rin\Documents\csci104\home:/work + SecOpt: seccomp:unconfined + CapAdd: SYS_PTRACE + Port: :2222 +``` + +The path after `Volume: ` (excluding `:/work`) is what you are looking for. + +### Step 2. Obtaining clones of the `hw-username` and `resources` repositories + +This step assumes that you have already finished the git, GitHub, and SSH key setup from Lab 0. + +Once you are inside the correct working directory, type the following commands (**replace the `username` in `hw-username` with your actual USC Net Id, the same goes for everything that follows. Your USC NetId is your USC email address without the "@usc.edu" part, not the 10-digit Student ID**): + + +*`[native]`* +```shell +git clone git@github.com:{{site.data.urls.github_org}}/hw-username.git +git clone git@github.com:{{site.data.urls.github_org}}/resources.git +``` + +If you see the following dialog in your command line, type `yes` and press `enter`. +It's basically asking if you want to trust `github.com` as an SSH server. + +``` +The authenticity of host 'github.com (192.30.255.112)' can't be established. +RSA key fingerprint is SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8. +Are you sure you want to continue connecting (yes/no)? +``` + +After every clone command, you should see something like this (exact output might be different): + +``` +remote: Counting objects: 4, done. +remote: Compressing objects: 100% (3/3), done. +remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0 +Receiving objects: 100% (4/4), done. +Checking connectivity... done. +``` + +A few notes about cloning: + - **Never clone a Git repository** into a Dropbox or other sync'ed folder (Google Drive, etc.). + - **Never clone a Git repository** under another repository folder. They should be at the same level. + +## Running the Example Project + +We have provided an `example` project to test whether you have the correct environment setup to compile our homeworks. Make sure you follow the steps below and the output on your terminal matches the ones on this page. + +### Step 3. Copy the `example` dirctory to your `hw-username` directory + +For every assignment from this class, we would provide the it's skeleton code inside the `resources` repository, and you need to copy it into your +`hw-username` directory when you start the assignment. You should then do all of your work in your `hw-username` repo instead of the +`resources` repo. + +The `example` project is also provided in the `resources` repo. To copy it, first start the **docker terminal** if you are using Docker: + +*`[native]`* +``` +ch start csci104 +ch shell csci104 +``` + +Then, make sure your working directory is where you put the `hw-username` and `resources` clones. You could check this by typing: + +*`[docker]`* +``` +ls +``` + +and you should see `hw-username` and `resources` in the output. + +If not, you have to use `cd` to change to the correct working directory. + +To copy the directory, type: + +*`[docker]`* +``` +cp -r resources/example hw-username/example +``` + +where `cp` stands for "copy" and the `-r` standard for "recursive" which allows copying of directories. + +### Step 4. Building the example project + +Now, go into your `hw-username/example` directory by typing: + +*`[docker]`* +``` +cd hw-username/example +``` + +Then, run the following command: + +*`[docker]`* +``` +make run +``` + +If the build is successful, you should see something like this: + +``` +Running main() from /build/googletest-j5yxiC/googletest-1.10.0/googletest/src/gtest_main.cc +[==========] Running 3 tests from 2 test suites. +[----------] Global test environment set-up. +[----------] 2 tests from SimpleReturnTest +[ RUN ] SimpleReturnTest.Returns42 +[ OK ] SimpleReturnTest.Returns42 (0 ms) +[ RUN ] SimpleReturnTest.Returns37 +test.cpp:12: Failure +Expected equality of these values: + returns_37() + Which is: 36 + 37 +[ FAILED ] SimpleReturnTest.Returns37 (0 ms) +[----------] 2 tests from SimpleReturnTest (0 ms total) + +[----------] 1 test from SummationTest +[ RUN ] SummationTest.SumsAreEqual +[ OK ] SummationTest.SumsAreEqual (0 ms) +[----------] 1 test from SummationTest (0 ms total) + +[----------] Global test environment tear-down +[==========] 3 tests from 2 test suites ran. (0 ms total) +[ PASSED ] 2 tests. +[ FAILED ] 1 test, listed below: +[ FAILED ] SimpleReturnTest.Returns37 + + 1 FAILED TEST +make: *** [Makefile:8: run] Error 1 +``` + +You **don't** have to worry about the red `[FAILED]` message as long as it shows up (it is intentional), +but in case it does not show up, please ask for help from your lab instructor. + +### Step 5. Fixing the FAILED test case + +What you have just seen above is an example of an automated test. We run automated tests to grade your +assignments, and you will learn more about them in later labs. For now, you could just think of them +as programs that feeds some input into your assignment code and test whether they produce the correct +output. + +Obviously, it is not good to have a FAILED test case! (You would lose points in an actual assignment if your +program fail our test cases) So let's fix it! + +Open `library.cpp` and look at the function `int returns_37()`. As you can see it returns `36` instead of +the suggested `37`. If you look at the FAILED test case carefully you would see: + +``` +Expected equality of these values: + returns_37() + Which is: 36 + 37 +``` + +which points to exactly the same issue. + +Therefore, change the return value to `37` and run `make run` again. This time every test should pass. + +### Step 6. Committing and pushing to your homework repository + +Now that you have finished the work locally, you would also want to push the changes to GitHub. + +To do so, open your **native** terminal (or the VM terminal is you are using the course VM) and change +the working directory to `hw-username`. Then type + +*`[native]`* +``` +git status +``` + +The output should look like this: + +``` +Your branch is up to date with 'origin/main'. + +Untracked files: + (use "git add ..." to include in what will be committed) + example/ +``` + +which means that nothing from your `example` directory is tracked by git. + +To track those files run the following command: + +*`[native]`* +``` +git add . +``` + +This command tells git to track all modification you have done to the repo (adding a new file, modifying a file, deleting a file, renaming a file, etc.). You could also specify individual files to track by providing their name instead of `.` (e.g. `git add library.cpp`). + +Now, if you check `git status`, you would see: + +``` +On branch main +Your branch is up to date with 'origin/main'. + +Changes to be committed: + (use "git restore --staged ..." to unstage) + new file: example/.vscode/launch.json + new file: example/.vscode/settings.json + new file: example/.vscode/tasks.json + new file: example/Makefile + new file: example/README.md + new file: example/library.cpp + new file: example/library.hpp + new file: example/library.o + new file: example/test + new file: example/test.cpp +``` + +All the changes are now ready to be *committed*. You could now run the following command: + +*`[native]`* +``` +git commit -m "fixed the example" +``` + +This tells git to create a snapshot of the repository that reflects the changes you just asked it to track. +The snapshot is called a **commit**. Each commit must have a message, as specified by the `-m` option. It can be anything, +but it's a good practice to keep it informative of what changes you have made. + + +Now, if you type `git status`, you would see: + +``` +On branch main +Your branch is ahead of 'origin/main' by 1 commit. + (use "git push" to publish your local commits) + +nothing to commit, working directory clean +``` + +This tells that your local repo has one commit that the remote does not have. To +upload the commit, simply type: + +*`[native]`* +``` +git push +``` + +Now, if you everything runs successfully, the changes you have made would be synced to GitHub. Go to +the repo page on GitHub (it should be at https://github.com/usc-csci104-spring2022/hw-username, with `username` +replaced with your actual Net ID), and navigate to `example`, you should see the following files: + +
+ +If you read the `library.cpp` file, you should be able to see the code you have just modified. + +However, if you look at the `example` directory (in the image above), you would see the file `test`. Those are the binary files created by the `make run` command while building +the project. As a good practice you should never push anything generated by a build process. We would deduct +points if you submitted your assignment with those files (unless otherwise specified). + +**NOTE: You may not be able to see the `library.o` file on GitHub, that is to be expected +with the homework repository.** + +### Step 7. Removing the extra files from your repo + +To tell git to remove those files from the repo, first go back to your native terminal and change directory +to `hw-username/example`. Then type the following: + +``` +git rm test +``` + +This will remove the two files from the directory and ask git to track the removal. + +### Step 8. Prevent accidentally adding files with .gitignore + +The `git rm` command only solves the problem temporarily. What if in the future you run `make run` again and +generated the files again? It would be an annoyance to run `git rm` every time you push. + +Fortunately, git offers a way to prevent files from being tracked by the `git add` command. To achieve this, +create a file called `.gitignore` (with no extensions) in your `hw-username/example` directory, and open it in a text editor. + +**NOTE: a file or directory starting with `.` is hidden by default on most systems. To make your system show +those files, follow these instructions:** + +* [Windows](https://support.microsoft.com/en-us/windows/view-hidden-files-and-folders-in-windows-97fbc472-c603-9d90-91d0-1166d1d9f4b5#WindowsVersion=Windows_10), +* [Mac](https://www.pcmag.com/how-to/how-to-access-your-macs-hidden-files) + +Once you are inside the text editor, add the following lines: + +``` +test +``` + +This line tells git to ignore any file +named `test`. + +Note that since the `.gitignore` file is placed under +the `example` directory, the rules would only be enforced +there. In general you would want separate `.gitignore` files +for each of your assignment. + +The `library.o` file is being ignored because it is included in the `.gitignore` file at the root +of the homework repository. + +Now, if you type + +*`[native]`* +``` +git add . +git status +``` + +you would see something like: + +``` +Your branch is up to date with 'origin/main'. + +Changes to be committed: + (use "git restore --staged ..." to unstage) + new file: .gitignore + deleted: test +``` + +You could then commit and push the changes to GitHub: + +*`[native]`* +``` +git commit -m "removed extra file and added .gitignore" +git push +``` + +If you now go to the GitHub repo page, you would see that `test` +and `library.o` are no longer there. + + +## Pulling changes from GitHub + +Sometimes you would like to download changes from the remote repo because +someone else (or even you from another machine) modified the remote repo. +This is the case when we release the skeleton code in the `resources` repo +for a new assignment and you would like to download it. + +This won't happen until assignment 1 of course, so let's do this to your `hw-username` +repo instead. + +### Step 9. Modifying a file on GitHub + +First navigate to the `example/README.md` file in your `hw-username` GitHub repo page, and +click the pencil icon (see the image below): + +
+ +Then make an edit to the markdown file (any edit will do), and click `Commit Changes`: + +
+ +**Note in general we do not recommend modifying files directly on GitHub, it is used +here just for demonstration purposes** + +### Step 10. Pulling the change + +Now change your directory into `hw-username` in your local terminal, and then type: + +*`[native]`* +``` +git pull +``` + +The output should look like this: + +``` +remote: Enumerating objects: 7, done. +remote: Counting objects: 100% (7/7), done. +remote: Compressing objects: 100% (3/3), done. +remote: Total 4 (delta 1), reused 0 (delta 0), pack-reused 0 +Unpacking objects: 100% (4/4), 742 bytes | 32.00 KiB/s, done. +From github.com:ph3rin/hw-demo + dcdcc61..eb57bef main -> origin/main +Updating dcdcc61..eb57bef +Fast-forward + example/README.md | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) +``` + +Now if you read the `hw-username/example/README.md` file on your local machine, it should +match the one on GitHub. + +## In Closing + +There are tons of git cheatsheets all over the web. +Here's [one by Tower](https://www.git-tower.com/blog/git-cheat-sheet/) and [another by Atlassian](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet). +You can use one of these your make your own; git has a bit of a learning curve and at the end of the day comes down to memorizing the most useful commands and what they do. +Don't worry if it takes a little while. diff --git a/labs/su-lab2/assets/Lab2_slides.pdf b/labs/su-lab2/assets/Lab2_slides.pdf new file mode 100644 index 00000000..a1815dbc Binary files /dev/null and b/labs/su-lab2/assets/Lab2_slides.pdf differ diff --git a/labs/su-lab2/assets/game_of_pointers.png b/labs/su-lab2/assets/game_of_pointers.png new file mode 100644 index 00000000..77807bd3 Binary files /dev/null and b/labs/su-lab2/assets/game_of_pointers.png differ diff --git a/labs/su-lab2/assets/gdb_house_of_horrors.png b/labs/su-lab2/assets/gdb_house_of_horrors.png new file mode 100644 index 00000000..b83a8613 Binary files /dev/null and b/labs/su-lab2/assets/gdb_house_of_horrors.png differ diff --git a/labs/su-lab2/index.md b/labs/su-lab2/index.md new file mode 100644 index 00000000..a4dfbcbb --- /dev/null +++ b/labs/su-lab2/index.md @@ -0,0 +1,483 @@ +--- +layout: asides +toc: true +tasks: true +title: Jamie's GDB House of Horrors +--- + +--- + +**Due: 21 Jan, 2022 @4:00 pm** + +You are expected to show your work to any CP/TA to get checked off during the lab section +you registered for. + +--- + +# Jamie's GDB House of Horrors + +Can you survive the maze of segfaults, and banish a battery of blatantly bad behavior, all in the name of improving your GDB skills? +This lab will guide you through hunting down the kind of bugs that keep programmers awake at night. +Do you dare take it on? + +
+ GDB House of Horrors +
+ +## Lab Materials + +The files we'll be using for this lab are posted in the `resources` repository, which you've probably already cloned for the homework skeleton code. +In the `lab2` directory you should see the following files: + +1. `answers.txt` +2. `game_of_pointers_student1.cpp` +3. `game_of_pointers_student2.cpp` +4. `input1.txt` +5. `input2.txt` +6. `input3.txt` +7. `Makefile` +8. `output1.check` +9. `output2.check` +10. `output3.check` + +## What is a debugger? + +At its core, a debugger is a tool used to inspect a program while it is running. +You run it on the command line, passing an executable as an argument, and it interposes itself between the program and the system and monitors everything that the program does. +It runs through a program until it hits a preset point, called a *breakpoint*, which tells it to pause the program. +When paused, you can ask it to evaluate variables, call functions, and examine the call stack. +You can then resume your program, or step through it line-by-line. + +Debuggers are critical tools in any programmer's debugging arsenal, and are best when you need to trace the flow of your code through a complex process or algorithm. +Today, we will be illustrating how to use one! +But first, let's go over some common tips and tricks for debugging. + +### Identify the Issue + +The most common two ways your code will terminate (besides a successful execution) is by a Segmentation Fault (`SIGSEGV`) or by an Abort (`SIGABRT`). +These will automatically trigger the debugger to break, so you don't have to. + +- **Segfault**: when a program tries to read or write outside the memory that is allocated for it, or to write memory that can only be read. +- **Abort**: indicates an error detected by the program itself. + +The other issues could be: + +- **Infinite loop or recursion**: caused by faulty logic or base case. +- **Logic**: `2 + 2 == 5`? code is correct but the logic is faulty. +- **Translation error**: the logic is correct but it was just coded incorrectly. + +### Isolate the Problem + +In order to successfully find the issue, you need to be able to answer a few questions: + +1. What line is the problem occurring on? + - Read through long standard library backtraces. + Often, a segfault or exception will happen deep inside C++ standard library code, and you will get a backtrace with several frames of obscurely named and templated functions at the top. + Just ignore those, and find the highest frame that mentions your code. + That is usually where the actual error is. + - Use Valgrind as well. + If all you need is the backtrace for a segfault, Valgrind can give that to you without any hassle. + Also, note that GDB will always stop on the first memory error. + Valgrind, on the other hand, will keep continuing the program until there's an unrecoverable error. + This can help you see the bigger picture for certain memory issues. + - You can also use break points and `cerr` statements to find what line the problem is occurring on. + +2. When does this bug occur? + - Are their certain situations where the issue presents itself? + - Is it only when I am using a certain function or trying to do a specific action. + +3. Can I reliably produce this bug over and over again? + - Create a separate test case to make the problem clear. + +### Why is the Issue Occurring? + +The main question to ask is, "is the problem conceptual, logical, or coding error?" +To answer, understand what your function/code is trying to and then use `cerr` statements or GDB in order to identify what the values of variables are to determine if they are correct or not. + +- Carefully place breakpoints. + You want to break at the start of the area where the problem might be occurring, not before and not after. + If you have to step a long distance through the code, you might accidentally step through something important. + If your error is happening on the 12,000th loop through a giant algorithm, you might want to refactor your code to give you someplace to put a breakpoint. +- Print important variables. + Use the `print` GDB command to check the values of any suspicious variables. + Don't forget that by calling print with a struct or class, it will print out all the member variables of that class. +- Use `cerr` statements. + For localizing a fault to a specific area of the code, or tracing the flow of an entire program, it's invaluable to just print out important values and messages throughout your program. + Remember to use `cerr` rather than `cout` so your output is guaranteed to be flushed to the terminal before the program terminates. + +### GDB Command Cheat Sheet + +This cheatsheet is also available on the [wiki]({{ site.baseurl }}/wiki/gdb/) for future reference. + +- `run/r [arguments]` runs the program with the given arguments. +- `break/b [file.cpp:line number]` puts a breakpoint at the given line number in the given file. + Note that if you only have one file, just break `[line number]` will suffice. +- `break/b [function name]` places a breakpoint at the start of the given function. +- `clear [file.cpp:line number]` clears a breakpoint at the given line number in the given file. + Note that if you only have one file, just clear `[line number]` will suffice. +- `clear [function name]` removes the breakpoint on the given function. + Note: function breakpoints will not work on functions that take strings as arguments (it's complicated) on your course VM due to an incompatibility between GCC and GDB. + However, this will work properly on newer systems. +- `layout next` From the begining of GDB, entering 'layout next' once the program is running will show you source code around your current location in the program. + This view can be helpful to those who are new to gdb, and especially helpful when working with source code you are not farmiliar with. + Repeating 'layout next' shows your program in assembly language. +- `layout prev` Takes you back to the previous layout mode. +- `bt` shows the function call stack, every function that you've run through since the line you've arrived at. +- `frame [number]` goes to the selected frame in the call stack. +- `continue/c` continues the program after being stopped by a breakpoint. +- `print/p [variable]` prints out the variable value. + If you pass it a class/struct instance, it will print all the data members in the class. +- `display/d [variable]` is like print, but reprints the information after every instruction. +- `next/n` executes the current source line and moves it to the next one. + Will skip over any function calls. + If you were to have the line `x = getValue(y)` and used `n`, you would go to the next line in the current function call, ignoring what happens in `getValue(y)`. + Useful for when you're testing out a function and you KNOW your helper functions work. +- `step/s` executes the current source line and moves it to the next one. + Will step INTO any function calls. + If you were to have the line `x = getValue(y)` and used `s`, you would go into the `getValue(y)` function. +- `finish/f` executes the rest of the current function. + Will step OUT of the current function. +- `l/list` prints the area around the current line in the current source file. +- `where` displays the current line and the function stack of calls that got you there. +- `quit` exits GDB. + +## Game of Pointers + +The code we will be debugging today is a student assignment from a past iteration of the class. +The details are not super important, but essentially it is a simulator for a battle between two armies, the protectors and the invaders. +The members of one row/column of each army duel in each skirmish, and the battle ends either when there is a gap in the ranks of the protectors, or when the protectors are able to last through every round of the fight. +The twist is that one of the armies is laid out sideways, so row `i` of the invaders duels column `i` of the protectors. +Think of it like matrix multiplication, but with more violence! + +
+ Game of Pointers +
+ +Two students (whose names have been omitted to protect the guilty) attempted this problem, but didn't get it quite right. +We're now going to find the bugs in their programs with GDB. + +### Directions + +For each problem below, answer in `answers.txt` with: + +- The line number where the error was. +- A **short** explanation of the nature of the error (one or two sentences). +- A **short** explanation of what you did to fix the error. + + +## Problem 1 (Guided) + +Okay, so let's check out the first student's program. +Open a terminal in the assignment directory, and run the simulation with `make test_game1`. + +If you are using Docker, please first move the `resources` directory into the directory you mounted to the Docker container in Lab 0, if it is not already in there. Remember to open a shell before proceeding (ie, by running `ch shell csci104`). If you don't have a container running yet, remember to run `ch start csci104` before opening a shell! + +- [ ] Double check that `resources` is in the directory you mounted to the Docker container in Lab 0. +- [ ] Start/open a shell. + +You should get something like: + +``` +****************************************************************** + Testing Student 1's Game +****************************************************************** +./game_student1 input1.txt output1-stu1.txt +Makefile:15: recipe for target 'test_game1' failed +make: *** [test_game1] Segmentation fault (core dumped) +``` + +- [ ] Run `make test_game1`. + +Uh-oh. +That's not good. +In the past, you might have ran screaming from an error like this, but now we have tools to attack it! +Run GDB on the program with the terminal command `gdb ./game_student1`. +You should now have a terminal prompt that looks like: + +``` +(gdb) +``` + +- [ ] Start `gdb` with the newly compiled `game_student1`. + +The program has not been started yet, and GDB is now awaiting your commands. +Just to practice, let's set a breakpoint at the start of the program so it will stop right away. +Run the command `break main`. +You should get: + +``` +(gdb) break main +Breakpoint 1 at 0x401d81: file game_of_pointers_student1.cpp, line 198. +``` + +- [ ] Set a breakpoint on `main`. + +Now, let's start the program, supplying the command line arguments for its input and output files: `run input1.txt output1-stu1.txt`. +You should get: + +``` +(gdb) run input1.txt output1-stu1.txt +Starting program: ./game_student1 input1.txt output1-stu1.txt + +Breakpoint 1, main (argc=3, argv=0x7fffffffdc58) + at game_of_pointers_student1.cpp:198 +198 { +``` + +- [ ] Run the program with input and output files. + +GDB has now started your program, and it stopped on the breakpoint we set earlier. +You can set these breakpoints on any function name or source line in your code, and GDB will stop there. + +If you enter the `n` command a few times, you can now step through the main function one line at a time. +Cool, right? +However, it would take forever to search through the entire program this way. +Instead, let's just head straight to the segfault. +Luckily, GDB automatically breaks on segfaults, so we don't have to worry about breakpoint positioning right now. +Enter `c` to continue straight to the issue. +You should get: + +``` +(gdb) c +Continuing. + +Program received signal SIGSEGV, Segmentation fault. +0x0000000000402050 in main (argc=, argv=) + at game_of_pointers_student1.cpp:252 +252 invaders[invaderRow][invaderCol]->power = invaderRow * 10 + (invaderCol + 1) * 10; +``` + +- [ ] Use `continue` to get to our error. + +GDB is now at the point of the segfault, ready for you to analyze what's wrong. +Since the segfault is occurring on this line, we already have a pretty big clue on what's wrong. +There's only one pointer being dereferenced here. +Let's check out its value: `print invaders[invaderRow][invaderCol]` + +``` +(gdb) print invaders[invaderRow][invaderCol] +$1 = (Warrior *) 0x0 +``` + +- [ ] Check the value of the dereferenced pointer. + +GDB is telling us it's a null pointer! +Fantastic! +We now know where the problem is, and that's usually more than half the battle in debugging. +But we still have to figure out *why* it's null. +Open `game_of_pointers_student1.cpp` and look at what allocates `invaders[invaderRow][invaderCol]`, on line 249: + +```cpp +invaders[invaderRow][invaderRow] = new Warrior(); +``` + +See anything suspicious on that line? +Perhaps, with the array indices of `invaders`? +Compare the indices on that line to the ones used on line 252. +The issue should be fairly clear. + +- [ ] Fix the mistake and describe your solution in `answers.txt` as outlined above. + +## Problem 2 (Semi-Guided) + +When you run `make test_game1` again, you should see that the segfault is fixed, but the program fails its first test case. +The output file should be + +``` +Invader killed +Duel ends in draw +Winner: protectors +``` +but instead it's + +``` +Invader killed +Invader killed +Winner: protectors +``` + +Clearly there is some sort of logic error affecting the result of the second duel. +To debug this, we will need to trace the issue back through the code. +It looks like `"Invader killed"` is being output inside skirmish() at line 135: + +```cpp +else if (result == result_protector) +{ + output << "Invader killed" << std::endl; + delete invader; + invader = nullptr; +} +``` + +`result`, meanwhile, comes from the call to `getDuelResult()` on line 99. + +That if statement looks like a good place to start our investigation. +We can check if the result really is set wrong, or if there is some sort of logic error causing `result` to be interpreted incorrectly. + +Again, run GDB on the `game_student1` executable. +Since we want to investigate the if statement in skirmish, let's set a breakpoint on line 101: `break game_of_pointers_student1.cpp:101` +Next, run the program from GDB like you did in Problem 1. + +``` +(gdb) run input1.txt output1-stu1.txt +Starting program: ./game_student1 input1.txt output1-stu1.txt + +Breakpoint 1, skirmish (protectors=protectors@entry=0x61a0a0, + invaders=invaders@entry=0x61a0c0, skirmish_col=0, rows=2, columns=3, + reserves=@0x7fffffffd724: 1, output=...) + at game_of_pointers_student1.cpp:101 +101 if (result == result_invader) +``` + +- [ ] Rerun `gdb` with `game_student1`. +- [ ] Set the breakpoint and run the program. + +Now, the program ran until it hit the breakpoint. +However, only the second duel is producing an incorrect result, so we want to wait until the second time this code runs. +Continue the program once with `c`. + +``` +(gdb) c +Continuing. + +Breakpoint 1, skirmish (protectors=protectors@entry=0x61a0a0, + invaders=invaders@entry=0x61a0c0, skirmish_col=0, rows=2, columns=3, + reserves=@0x7fffffffd724: 1, output=...) + at game_of_pointers_student1.cpp:101 +101 if (result == result_invader) +``` + +Now, we're at the second skirmish. +Check the value of `result` with `print result`. + +``` +(gdb) print result +$1 = "protector" +``` + +- [ ] Continue to the second skirmish. +- [ ] Print the value of `result`. + +Now we have some useful information. +Clearly result is being set wrong in `getDuelResult()`. +_Your_ job is to figure out why. +Set a breakpoint wherever you think is appropriate, restart the program using the same run command as you used before, and figure out what the issue is inside `getDuelResult()`. +Describe your solution and your fix in `answers.txt`. + +- [ ] Figure out what's going wrong in `getDuelResult()`. +- [ ] Write up the answer in `answers.txt`. + +## Problem 3 (Semi-Guided) + +Run `make test_game1` in terminal, and you should see the first test pass! +Unfortunately, the second test gets stuck in an infinite loop. +Luckily, GDB lets us debug infinite loops easily! +We may not be able to catch the issue with a breakpoint since we don't know where the loop is, but there is another strategy that works great here. + +First, load the program into GDB and run it without setting any breakpoints. +Don't forget to use the second input and output files in this run command! + +- [ ] Load the program into `gdb`. +- [ ] Run the program with the second input and output files. + +Like you can cancel a program on the command line, GDB lets you use `ctrl-c` to stop a program wherever it currently is. +Hit `ctrl-c` now to break the infinite loop. + +``` +(gdb) run input2.txt output2-stu1.txt +Starting program: ./game_student1 input2.txt output2-stu1.txt +^C +Program received signal SIGINT, Interrupt. +0x000000000040142f in findOpenInvaderPos (invaders=invaders@entry=0x61a0c0, + numRows=numRows@entry=5, numCols=numCols@entry=2) + at game_of_pointers_student1.cpp:64 +64 if (invaders[rowIdx][colIdx] == nullptr) +``` + +- [ ] Use `ctrl-c` to send a `SIGINT` interrupt. + +So, the code is stopped at some point within the infinite loop, but we don't really know where in the program we are. +To find out, use the backtrace command: `bt` + +``` +(gdb) bt +#0 0x000000000040142f in findOpenInvaderPos (invaders=invaders@entry=0x61a0c0, numRows=numRows@entry=5, numCols=numCols@entry=2) + at game_of_pointers_student1.cpp:64 +#1 0x0000000000401a55 in skirmish (protectors=protectors@entry=0x61a0a0, invaders=invaders@entry=0x61a0c0, skirmish_col=1, rows=2, columns=5, reserves=@0x7fffffffd724: 1, output=...) + at game_of_pointers_student1.cpp:103 +#2 0x0000000000402112 in main (argc=, argv=) + at game_of_pointers_student1.cpp:284 +``` + +- [ ] Backtrace to figure out where you are. + +This backtrace contains a wealth of useful information. +Each numbered paragraph represents one frame in the current call stack of the program. +Frame `#0` is always the current function, and we see frames going up to the `main()` function of the program. +The first hexadecimal number is the address of the function in memory (not really important right now). +Next, we have the name of the function and the arguments it was called with, and finally the file and line number. +The backtrace is an extremely useful tool since it lets you get a quick glance at which functions were called to bring the program to its current state. + +We are also able to move around through the backtrace and inspect the environment at each stack frame. +Let's switch to frame 1 with the command `frame 1`. + +``` +(gdb) frame 1 +#1 0x0000000000401a55 in skirmish (protectors=protectors@entry=0x61a0a0, invaders=invaders@entry=0x61a0c0, skirmish_col=1, rows=2, columns=5, reserves=@0x7fffffffd724: 1, output=...) + at game_of_pointers_student1.cpp:103 +103 Warrior **firstOpenInvaderPos = findOpenInvaderPos(invaders, columns, rows); +``` + +- [ ] Switch to frame 1. + +The program is in skirmish() at line 103. +Let's check out the values of `columns` and `rows`. + +``` +(gdb) print columns +$1 = 5 +(gdb) print rows +$2 = 2 +``` + +- [ ] Check `columns` and `rows`. + +Those numbers match the dimensions in input2.txt, so they seem legitimate. +Your job, now, is to figure out why the code is getting in a loop. +I highly suggest changing back to frame 0 and stepping the code forward with `n` to figure out where exactly it is looping. + +- [ ] Figure out the cause of the loop and describe your solution in `answers.txt`. + +## Problem 4 + +Now, run the second student's program by running `make test_game2` in the terminal. +You'll find that the code won't finish executing because of a segmentation fault. + +When debugging this error, keep in mind that the invader and protector arrays are different sizes. +Try to find out what those sizes are, and determine whether they're used consistently in the `AllocateWarriors` and `DeallocateWarriors` functions. + +- [ ] Fix the mistake, and describe your solution in `answers.txt`. + +After you've fixed it, you should be passing two of the three tests. + +## Problem 5 + +A common use case of GDB is to figure out which code path is executing. +In cases where there are many conditional statements, GDB can be a much quicker tool to use than print statements. +Student 2's code contains a logical error: some duels aren't turning out as they should. +Run `make test_game2` and use your test output along with GDB to figure out exactly what went wrong. + +You will probably want to break the code inside `Skirmish()` and observe how the logic in there is behaving. +The most straightforward way to do this is to set a breakpoint on the first `if` statement in that function. +Once GDB breaks there, you will be on the first call to `Skirmish()`. +If you want to go to the next call, just resume the program with the `c` command and wait for it to hit the breakpoint again. +Think, which call to `Skirmish()` does the program output the wrong thing on? Go to the correct iteration and step through the logic, and the issue should show itself. + +- [ ] Fix the mistake, and describe your solution in `answers.txt`. + +### That's it! + +You have stood fast in the face of overwhelming peril, and banished the bugs back to whence they came! +The world the town your computer is safe once again! + +- [ ] Show a CP or TA `answers.txt` to get checked off!! diff --git a/labs/su-lab3/index.md b/labs/su-lab3/index.md new file mode 100644 index 00000000..71155f02 --- /dev/null +++ b/labs/su-lab3/index.md @@ -0,0 +1,533 @@ +--- +layout: asides +toc: true +tasks: true +title: Makefiles +--- + +--- + +**Due at the end of your registered lab section** + +--- + +We are holding the hybrid labs sections this week - they will be recorded and streamed over Zoom, and you could get checked off over zoom. However you are strongly recommended to go to the physical location, unless you have COVID concerns (e.g. you tested positive or have symptoms). + +# Makefiles + +In this lab, we will review Makefiles, how they work, and how to write them. +In order to do this, we will also be reviewing how to use GCC to effectively compile your code with the right settings and configuration. +We will also explore some advanced techniques you can use to streamline your Makefile as your projects get larger. + +## Extra - Running Homework 1 Tests + +Before we get into Makefiles, here is something important for homework 1: running and debugging +the tests. We have posted the instructions [here](https://bytes.usc.edu/cs104/wiki/cmake-tests/). + +We will also do live demo in each lab section. If you would like to see it in action ASAP, you +could check the lab recordings for earlier sections. + +## GCC and Makefiles + +GCC (GNU Compiler Collection) is a program that we use to compile our program into executables. +You have already used it in previous homework. + +Make (GNU Make) is a program that makes other programs. +This is especially useful when your programs become large, and recompiling after an edit requires multiple steps. +Using a `makefile`, we can configure a program to compile simply by typing the `make` command into terminal. +This lab will teach you how to write a basic makefile to be used in assignments from here on out. + +### 1 - GCC + +You might have noticed that we have been using some magic commands when we compile files. +Namely, you should have seen `g++`, `-g`, `-Wall`, `-o`, and `-c`. +Here is a brief explanation of what exactly these commands do. + +First of all, `g++` is used to compile your programs using the GNU Compiler Collection (GCC). +The `g++` command tells GCC that you want to compile a C++ program. +There are other compilers out there, and when you want to use other compilers, you replace `g++` with the command that's used by the other compiler, such as `clang++`. +In this class, we ask that you always compile your program with GCC using the `g++` command, because that's what we use when we grade you. + +When you see a terminal command that has a `-` followed by some text, this is usually a flag (also called options). +A flag can be used to specify a setting or add additional information about the command. +An option may or may not take an argument. +If an option takes in an argument, the argument is followed immediately after the flag. +To use a flag, simply include it with your compile command. + +In the `g++` command, you will often see `-g`, `-Wall`, `-o`, `-c`, and `-std=` command. +Here's a descriptino of what they do and how to use them: + + + `-g`: Provide debugging feature for your program. + You will need this when you want to use gdb or valgrind. + To use this flag, simply append the command to the end of your compile command. + + `-Wall`: Turn on all warnings. + This is helpful because, as you might have seen, not all errors cause your program to not compile. + There are some problematic operations that can cause undefined or unexpected behaviors in edge cases. + By turning on all warnings, you make sure that you eliminate these potentially dangerous operations. + + `-o`: This flag controls the output name of your compilation. + By default, the binary file name is `a.out`. + When you append `-o filename` to the end of your compile command, the compiled binary output will be the filename you specificed. + Be carefule that the filename is not an existing file because you will overwrite the file. + + `-c`: Compile the files but do not link them. + This is usually used to compile intermediate object files. + We will explain this more in later parts of the lab. + + `-std=`: This flag is used to specify the c++ version that you would like to use. + As you expect, c++ is an evolving language, and it keeps adding new features to the language. + Therefore, if you use a feature that's introduced in a newer version but try to compile the code with an older version, the compiler wouldn't know what the features are and the compilation will fail. + You use this flag by appending this flag to the end of your compile comand and speficy the version number after the equal sign (i.e. `-std=c++17`). + In this class, most of the times you can get away with using the default version and don't need to include this command at all. + There are times when you need to use the c++ 17 and you do it with `-std=c++17`. + + `-fmax-errors=N`: This tells the compiler to stop after encountering N errors in your code. + Usually we don't use it, because we want to see all errors in a code, and fix them together. + However, at times you will find that some error messages are long and there are so many of them that you can't see the top one (and if you are not fixing your compile errors starting with the first one, you should start doing that). + This is when it becomes handy to stop compilation after some number of errors. + + `-Wfatal-errors`: This is similar to the previous one, except that the compiler will treat an error as fatal and stop on first error. + +Lastly, you might sometimes see people compile files with `g++ something.cpp main.cpp -o main -g -Wall`, and you might wonder why they list the source files before the options. +As it turns out, the order that you specify the options does not matter. +If you really want to, you can even use `g++ something.cpp -g -Wall main.cpp -o main` to compile your program. +However, by convention, we usually group the list of source files together and the list of options together. + +### 2 - Using Make + +GCC is nice to compile our programs, but it gets annoying if we have to type a 20 character command 10 times during development. +This is when a makefile comes in handy. + +When you type `make` into terminal, Make will look for a file named `makefile` or `Makefile` for instructions. +Let's start with a makefile for a single cpp file. + +In the part 1 folder, you will find a file called `charizard.cpp`. +You can compile this simply with the following instruction: + +``` +g++ -g -Wall charizard.cpp -o charizard +``` + +That's too much typing if we need to do it 20 times during developing, so let's use make. + +#### 2.1 - Syntax and Structure + +A basic makefile's structure is the following: + +``` +target: dependencies + command_1 + command_2 + ... + command_N +``` + +Each of these is called a rule. +A target is a file that Make tries to create, commands are used to create the target, and dependencies are the files that determine whether the commands need to be executed. +When you type `make `, the make tool searches for the appropriate target in the directory and checks whether any of its dependencies need to be rebuilt. +If the file is not found, or if any of its dependencies is newer than the target file, all commands in the rule will be executed. + +In this instance, we want to create a charizard executable using `g++ -g -Wall charizard.cpp -o charizard`, and we need to recompile the file if charizard.cpp changes. +Therefore, our rule should look like this: + +``` +charizard: charizard.cpp + g++ -g -Wall charizard.cpp -o charizard +``` + +Note that the system command is and must be precedeeded by a **tab**. + +If you ever get an error message like this: + +``` +makefile:2: *** missing separator. Stop. +``` + +It means on line 2, make is expecting a tab but didn't find it. + +Editors like VSCode will convert tabs to spaces automatically. Normally that's fine but it's not okay for Makefiles. +If you're using VSCode, you can use tabs as indentation this way: + +1. Open the command pallete with `Ctrl+Shift+P` (Windows) `Cmd+Shift+P` (MacOS) +2. Search/Run the command: "Convert indentation to tabs" +3. (Suggested for MacOS users) In the command pallete, run the command "Shell Command: Install 'code' command in PATH" + + +- [ ] Compile your code by running `make charizard` + +#### 2.2 - Default Target + +What happens when you just run `make`? +Good question! +By default, `make` will execute the first target in a makefile. +By convention, we add a target called `all` and list targets we wish to build on `make` command after `all`. + +Let's have 'all' make the charizard file, which will become the name of our target. +Our resulting `makefile` is as below: + +``` +all: charizard + +charizard: charizard.cpp + g++ -g -Wall charizard.cpp -o charizard +``` + +- [ ] Compile your code by running `make all` + +Save this file as `Makefile` in the part1 directory and type make. +Congratulations, you've just made your life 100x easier. + +### 3 - Compiling Multi-File Programs + +#### 3.1 - Object Files + +Compiling a multi-file program requires two main steps: compiling each `.cpp` file separately, and putting them all together to form the executable. +The first step is know as compilation, during which the compiler checks for syntax and semantic mistakes, such as missing semicolons, calling a function that's not declared, or returning the wrong type in a function. +The second step is known as linking, during which the linker "links" your function calls - it finds where the body of a function is so that it knows what line to execute when you call that function. + +When you compile a program with `g++ -g -Wall charizard.cpp -o charizard`, you are actually compiling and linking it. +It turns out that it's possible to do them separately. +This comes in handy when you have multiple files in your project. +When you change one of the files, you can re-compile only files that depend on the change, and run linker, without having to re-compile the entire project. + +In order to do that, we introduce a new binary file type: .o files, or object files. +These are the intermediate files we make in preparation to compile the executable. + +Let's look inside the part 2 folder. + +``` +$ cd ../part2 +$ ls * +``` + +You will find three classes: `AttackMove`, `Battle`, and `Pokemon`. +We want to compile each of these into their own .o file of the same name. + +Since we're going to have a lot of binary files beyond this point, let's make a `bin` directory to hold them all for easy cleanup. + +``` +$ mkdir bin +``` + +To make an object file, we simply need to add the `-c` flag in the compile command, which tells g++ to not run linker. +Let's compile `AttackMove` first. + +``` +g++ -g -Wall -c attackMove.cpp -o bin/attackMove.o +``` + +Simple as that. +Do the same for the other two classes, and we can then compile the main. + +- [ ] Run compile commands for battle.cpp and pokemon.cpp + +[^1]: Or a library + +#### 3.2 - Putting It All Together + +To compile the main, we just have to include all the `.o` files that we've already made in the g++ command. + +``` +g++ -g -Wall bin/attackMove.o bin/battle.o bin/pokemon.o main.cpp -o bin/pokemon +``` + +**Note:** A `.o` file is compiled code that doesn't get linked to other code even if it calls functions from other classes. +We tell the compiler this using the `-c` flag so that the compiler does not check whether the functions from other classes are implemented. +When we want to compile the full executable, we do not want to have the `-c` flag in that statement because we want the compiler to link all the code together in the final step. + +And you have your own pokemon battle simulator! Run it like normal using: + +``` +./bin/pokemon +``` + +- [ ] Run the command to compile main to and then run `./bin/pokemon` + +#### 3.3 - Makefile Dependencies + +Well that's great and all, but how do we do that in a makefile? + +Let's go back to the basic make rule structure: + +``` +target: dependencies + command_1 + command_2 + ... + command_N +``` + +We skipped dependencies before, but it's something we want to use now. +If a target has dependencies, make first checks if those dependencies exist before executing the system command associated with that rule. +If the dependencies don't exist, make will run the rule to make those dependencies if they exist. + +Make will also check to see if the dependencies have been updated since the last make and will only recompile the dependencies that have changed. +This can save you a lot of time if you make a change and don't want to recompile all the files in your project. + +Remember that dependencies are the files that can affect the compilation result of your target. +This includes all the non-standard-library files that you `#include`, a class's own header file and .cpp file, and, if you are compiling into an executable, all the .o files you need. + +(Note: techincally speaking, `#include` files should be considered as transitive dependencies, that is: if `A` includes `B`, and `B` includes `C`, then `C` would also be a dependency of `A`. However, handling transitive inclusion is more complicated and not covered here) + +A multi-file program might have a Makfile like this: + +``` +all: bin/pokemon + +bin/pokemon: main.cpp bin/attackMove.o bin/battle.o bin/pokemon.o + g++ -g -Wall main.cpp bin/attackMove.o bin/battle.o bin/pokemon.o -o bin/pokemon + +bin/attackMove.o: attackMove.h attackMove.cpp + g++ -g -Wall -c attackMove.cpp -o bin/attackMove.o + +bin/: + + +bin/: + +``` + +If you run `make`, this will fail. +You will be filling in all the `` at the end of the lab. + +- [ ] Fill in the blanks in the sample code to get your program to successfully compile + +### 4 - More Makefiles + +#### 4.1 - Variables + +Your professors decides they don't like the students compiling to the `bin` directory. +They instead want the directory to be named `exe`. +You could easily find and replace bin with exe, but that's messy and could generate errors. +Why not take advantage of variables instead? + +At the top of your makefile, let's define: + +``` +BIN_DIR = exe +``` + +Now let's replace every instance of `bin` with `$(BIN_DIR)`, like so: + +``` +$(BIN_DIR)/attackMove.o: attackMove.h attackMove.cpp + g++ -g -Wall -c attackMove.cpp -o $(BIN_DIR)/attackMove.o +``` + +Now when the profesors change their mind again and want a different name for the directory, we can just change the variable at the top. +By convention, we keep the binaries in a directory named `bin`. +(For homework, don't put your final executable in a bin directory unless we tell you to do so.) + +Another use for this is to have a CPPFLAGS (compiler flags) variable that holds all the flags you frequently use to compile. +We can have a CXX variable to specify which compiler to use. For example: + +``` +CXX = g++ +CPPFLAGS = -Wall -g +BIN_DIR = exe + +$(BIN_DIR)/attackMove.o: attackMove.h attackMove.cpp + $(CXX) $(CPPFLAGS) -c attackMove.cpp -o $(BIN_DIR)/attackMove.o +``` + +- [ ] Rewrite your compile commands to use your new `BIN_DIR` variable + +The most useful variables you will use are **Automatic Variables**. +Things that look like `$@`, `$<`, and `$^` are called automatic variables. +When Make parses through the Makefile, it'll automatically substitute them with the correct string. + + + `$@`: target name + + `$<`: first dependency + + `$^`: entire dependency list. + +Using these variables, we can rewrite our makefile rules as so: + +``` +CXX = g++ +CPPFLAGS = -Wall -g +BIN_DIR = exe + +$(BIN_DIR)/pokemon: main.cpp $(BIN_DIR)/attackMove.o $(BIN_DIR)/battle.o $(BIN_DIR)/pokemon.o + $(CXX) $(CPPFLAGS) $^ -o $@ + +$(BIN_DIR)/attackMove.o: attackMove.cpp attackMove.h + $(CXX) $(CPPFLAGS) -c $< -o $@ +``` + +- [ ] Rewrite your compile commands to use automatic variables + +#### 4.2 - DIRSTAMP + +There is one problem with the above approach. If you now run + +```shell +rm -r exe +g++ -Wall -g -c attackMove.cpp -o exe/attackMove.o +``` + +you'll probably get an error that the `exe` directory doesn't exist. +We could just use `mkdir exe` everytime we compile our program, but that's a pain. + +Let's define a rule to make sure the `exe` directory exists. + +``` +$(BIN_DIR)/.dirstamp: + mkdir -p $(BIN_DIR) + touch $(BIN_DIR)/.dirstamp +``` + +The `.dirstamp` file is a hidden file we make to make sure a directory exists. +Notice that this rule does not have any dependency. +When a rule has no dependency, it will be executed if the target does not exist. +You can add this rule to the dependency list of your compile commands. + +``` +all: $(BIN_DIR)/.dirstamp $(BIN_DIR)/pokemon +``` + +It's important that you list `.dirstamp` before `pokemon`, because Make will check the dependencies in order. Since building `pokemon` requires that `$(BIN_DIR)` exists, make needs to create `.dirstamp` before `pokemon`. + +- [ ] Add `.dirstamp` to your Makefile where needed + +#### 4.3 - PHONY and Clean + +Now large projects will eventually generate a lot of binary files. +We want to keep our workspace relatively clean by writing a rule to delete the generated files. +This is also helpful when you're having mysterious problems as they sometimes go away after you delete and recompile your binaries. + +Here's our `clean` rule: + +``` +clean: + rm -rf $(BIN_DIR) +``` + +You can add this to the end of your makefile. +Now clean your directory using the `make clean` rule. + +- [ ] Add `clean` as a target in your Makefile + +Very nice, but there's a small problem with the original rule. +If a file named 'clean' exists in our directory, make won't run the clean rule because it sees that the file already exists! + +To get around this, we declare the clean rule as PHONY to tell make that `clean` is not associated with a file. + +``` +.PHONY: clean +clean: + rm -rf $(BIN_DIR) +``` + +Now `clean` will always run when you use `make clean`. + +- [ ] Add a `.PHONY` target + +**Note:** there's a danger when using rm -rf as it will irreversably delete whatever `BIN_DIR` is without prompting additional confirmation. +Be good and don't delete your entire OS (or worse, delete your grader's VM). + +#### 4.4 - Search Path + +If you look at files under `src` or `main.cpp`, you will see that we are including header files by writing out the relative path to it. +It can be annoying if we wish to move our header files into a different directories, because we need to go to every single file that includes the header and change the path. +We can avoid this by adding additional **Search Paths** during compilation. + +You should create a separate `lib` and `src` directory and move your `*.h` files into `lib` and `*.cpp` files into `src`. Here's some commands to help do that: + +```shell +# run this in part2 folder +mkdir lib src +mv *.h lib/ +mv *.cpp src/ +``` + +Now that every `cpp` file has been moved to the `src/` directory, you need to change +your Makefile to reflect that. Change `main.cpp` to `src/main.cpp` and `attackMove.cpp` to +`src/attackMove.cpp`, and `attackMove.h` to `lib/attackMove.h`. + +``` +$(BIN_DIR)/pokemon: src/main.cpp $(BIN_DIR)/attackMove.o $(BIN_DIR)/battle.o $(BIN_DIR)/pokemon.o + $(CXX) $(CPPFLAGS) $^ -o $@ + +$(BIN_DIR)/attackMove.o: src/attackMove.cpp lib/attackMove.h + $(CXX) $(CPPFLAGS) -c $< -o $@ +``` + +There is another problem, however. By default, GCC will look in the current directory of the file (i.e. `src` when compiling a file in `src`), but it will not look under nested directories. +In addition, GCC also searches for standard libraries. + +In order to add a directory to its search paths, you use the -I*dir* option, where *dir* is the relative directory path from where you run the compile command. +If you are using a Makefile, the path will be relative to where your Makefile is. + +In our case, we want to ask GCC to look for files under the `lib` directory. +We can add append the option to the end of `CPPFLAGS`: + +``` +CPPFLAGS = -Wall -g -Ilib +``` + +Technically, this is not a makefile feature, but a compiler option. +However, you don't normally group files into different directories unless your have a bigger project, in which case you should be using a Makefile (or IDE) to manage compilation. + +- [ ] Add `-I` to your compile commands + +### 5 - Assignment: Complete the Makefile + +Your final makefile should look something like this. +Note: if you copy and paste the code from course website and paste it into your makefile, you will need to fix all the spaces and change them into tabs. + +``` +BIN_DIR = exe +CXX = g++ +CPPFLAGS = -g -Wall -Ilib + +all: $(BIN_DIR)/.dirstamp $(BIN_DIR)/pokemon + +$(BIN_DIR)/pokemon: + + +.o: + + +.o: + + +.o: + + +.PHONY: clean +clean: + rm -rf $(BIN_DIR) + +$(BIN_DIR)/.dirstamp: + mkdir -p $(BIN_DIR) + touch $(BIN_DIR)/.dirstamp +``` + +After finishing this part, you should be able to run + +```shell +make +exe/pokemon +``` + +to see a marvelous battle between pokemons! + +- [ ] Show your final Makefile to a CP or TA for checkoff. Be prepared to answer some of the review questions below! + +#### 5.1 - Review Questions + +1. What is the purpose of the `-c` flag? +1. What is the advantage of compiling to .o files via makefile compared to compiling the executable together in one step? +1. What files should be in a rule's dependency list? + +### 6 - More about Makefiles + +If you would like to know more about Makefile, you can visit [GNU Make Manual](https://www.gnu.org/software/make/manual/make.html). +It covers both the basic and more advanced topics of the Makefiles. + +**CAUTION** Do not use these advanced make commands until you are very comfortable with Makefiles. + +### 7 - More about GCC + +We have listed some commonly used flags and options that you will see in this class. +This is just a list of the common flags that you will use in this class. +This is in no way comprehensive. +If you see a flag that you do not understand, or if you are curious about other options, you can refer to this [official document from GCC](https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html). +Feel free to play around with the flags in your free time. + +**IMPORTANT** We will be compiling your code with `-g -Wall -std=c++11`, so you must use the same options to check that your code compiles and produces no warnings. diff --git a/labs/su-lab8-avl/assets/rotations.gif b/labs/su-lab8-avl/assets/rotations.gif new file mode 100644 index 00000000..da6a7c74 Binary files /dev/null and b/labs/su-lab8-avl/assets/rotations.gif differ diff --git a/labs/su-lab8-avl/index.md b/labs/su-lab8-avl/index.md new file mode 100644 index 00000000..3260390d --- /dev/null +++ b/labs/su-lab8-avl/index.md @@ -0,0 +1,127 @@ +--- +layout: default +toc: true +tasks: true +title: AVL Trees +--- + +--- + +**Due at the end of your registered lab section** + +--- + +## Maintaining the BST and Height-Balancing Properties + +We will study these details more carefully in a few weeks. However, this is a good preview to start familiarizing yourself with these ideas. The BST property is maintained by smart insertion and deletion. In an insert, you traverse the tree based on the key to be inserted. Once you encounter a situation where you can't traverse any further, you know that the key can be placed there. Because we are traversing based on the key value, we are inherently upholding the BST property. + +The same thing can be said about a deletion in a BST. This is done by choosing which node to promote. Either the predecessor, if the node has two children, or the child if the node has 1 child. By doing this, the BST property is being maintained. + +A BST that maintains its balance throughout all insertions and deletions is called a self-balancing BST. These types of trees that auto-balance or self balance inherently with the insertion are called Self-Balancing Binary Search Trees. Examples are: + +1. Splay Trees +2. AVL Trees +3. Red Black Trees +4. B-Trees +5. 2-3 Trees + +For all of these self-balancing binary search trees, the height-balancing property is upheld by the nature of an insert or remove. The best way to do so is with rotation, or series of rotations. We're going to briefly review how those rotations work below. + +#### 1 - Rotations + +A rotation changes the local structure of a binary tree without changing its ordering. This means that in between rotations, the BST property is still maintained. + +Rotations can be broken up into left and right rotations which are just inversions of each other. + +
rotations
+ +Rotaions make up the foundation of the AVL tree. In your homework, you will need to implement these rotations in a variety of scenarios. There are 4 combinations of rotations: left-left, left-right, right-left, right-right. Sometimes, these rotations are referred to as "zig zig" or "zig zag", or something similar. The point is, during these sequences of rotations, the tree becomes more balanced than it was before. + +__If longer subtrees are left and then left__ + +``` +T1, T2, T3 and T4 are subtrees. + z y + / \ / \ + y T4 Right Rotate (z) x z + / \ - - - - - - - - -> / \ / \ + x T3 T1 T2 T3 T4 + / \ + T1 T2 +``` + +__If longer subtrees are left and then right__ + +``` + z z x + / \ / \ / \ + y T4 Left Rotate (y) x T4 Right Rotate(z) y z + / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ +T1 x y T3 T1 T2 T3 T4 + / \ / \ + T2 T3 T1 T2 +``` + +__If longer subtrees are right and then right__ + +``` + z y + / \ / \ +T1 y Left Rotate(z) z x + / \ - - - - - - - -> / \ / \ + T2 x T1 T2 T3 T4 + / \ + T3 T4 +``` + +__If longer subtrees are right and then left__ + +``` + z z x + / \ / \ / \ +T1 y Right Rotate (y) T1 x Left Rotate(z) z y + / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ + x T4 T2 y T1 T2 T3 T4 + / \ / \ +T2 T3 T3 T4 +``` + +By using combinations of rotations during insertion and removal, we are able to maintain consistent balance throughout the lifetime of the tree. + +### 2 - Inserting + +During insertion, we start by inserting the value at its correct location as a normal BST would. Then, we traverse up the tree, evaluating the local height of each node and fixing that portion if the height of the left and right subtrees differ by 2 or more. We only need to traverse up the tree from the inserted node because the subtree containing the new node is the only subtree where height can change and we need to rotate. + +We fix the tree beginning with the newly inserted node. + +### 3 - Removing + +During removal, we remove as normal and then proceed to fix the tree by traversing up, starting with the parent of the deleted node. The process of checking balanace and fixing height is the same as outlined in the insertion part. + +### 4 - Exercise + +Take some time to confirm your understanding by showing the tree after each of the following operations in a new file named `lab8-avl.txt`. + +__Initial Tree__ + +``` + 13 + +--------+---+ + 10 15 + +---+---+ +--+ + 5 11 16 ++---+---+ +4 8 +``` ++ Insert 14 ++ Insert 3 ++ Remove 3 ++ Remove 4 + +- [ ] In `lab8-avl.txt` (or draw it out on paper), show what the tree looks like after each of the above operations. Operations should happen sequentially (ie, Insert 3 happens after Insert 14). + +### Checking off + +To get checked off, show your results for the exercise to a CP or TA. This should include: + +- The AVL tree after every step of insertion/removal \ No newline at end of file diff --git a/labs/su-llrec/assets/ll_rec_practice.pdf b/labs/su-llrec/assets/ll_rec_practice.pdf new file mode 100644 index 00000000..fbd25b19 Binary files /dev/null and b/labs/su-llrec/assets/ll_rec_practice.pdf differ diff --git a/labs/su-llrec/assets/ll_rec_practice_soln.cpp b/labs/su-llrec/assets/ll_rec_practice_soln.cpp new file mode 100644 index 00000000..c72e7c18 --- /dev/null +++ b/labs/su-llrec/assets/ll_rec_practice_soln.cpp @@ -0,0 +1,254 @@ +#include +#include +using namespace std; + +struct Node { + int data; + Node* next; +}; + +class LList { + public: + Node* head; +}; + +int ll_len(Node* head); +void ll_unique(Node* head); +void ll_partial_sum(Node* head); +Node* ll_rotate(Node* head, int n); +int ll_compare(Node* lhs, Node* rhs); + +LList* make_list(int input[], int size){ + LList* ret = new LList(); + Node* head = new Node(); + Node* temp; + ret->head = head; + for (int i = 0; i < size; i++){ + head->data = input[i]; + if (i < size -1) { + head->next = new Node(); + head = head->next; + } + } + + head->next = NULL; + head = NULL; + return ret; +} + +void print_list(Node* head){ + if (head == NULL){ + return; + } + if (head->next == NULL){ + cout << head->data << endl; + return; + } else { + cout << head->data << " -> "; + print_list(head->next); + } +} + + +int main() { + int l1[] = {1,2,3}; + int l2[] = {1,1,2,4,4,4,5,4}; + + LList* ll1 = make_list(l1, 3); + LList* ll2 = make_list(l2, 8); + + cout << "l1: "; + print_list(ll1->head); + cout << "l2: "; + print_list(ll2->head); + + cout << "length of l1: " << ll_len(ll1->head) << endl; + cout << "length of l2: " << ll_len(ll2->head) << endl; + + ll_unique(ll1->head); + ll_unique(ll2->head); + cout << "ll_unique on l1: "; + print_list(ll1->head); + cout << "ll_unique on l2: "; + print_list(ll2->head); + + ll1 = make_list(l1, 3); + ll2 = make_list(l2, 8); + + ll_partial_sum(ll1->head); + cout << "ll_partial_sum on l1: "; + print_list(ll1->head); + + cout << "rotated l2: "; + print_list(ll_rotate(ll2->head, 2)); + + int l2a[] = {1,2,3,4,5}; + LList* ll2a = make_list(l2a, 5); + cout << "l2a: "; + print_list(ll2a->head); + + cout << "rotate l2a by 2: "; + print_list(ll_rotate(ll2a->head,2)); + + ll2a = make_list(l2a, 5); + cout << "rotate l2a by 3: "; + print_list(ll_rotate(ll2a->head,3)); + + ll2a = make_list(l2a, 5); + cout << "rotate l2a by 0: "; + print_list(ll_rotate(ll2a->head,0)); + + ll2a = make_list(l2a, 5); + cout << "rotate l2a by 5: "; + print_list(ll_rotate(ll2a->head, 5)); + + + int l3[] = {1, 2, 3, 4}; + int l4[] = {}; + int l5[] = {0, 1, 2, 3, 4}; + int l6[] = {1, 2, 3, 5}; + LList* ll3 = make_list(l3, 4); + LList* ll4 = make_list(l4, 0); + LList* ll5 = make_list(l5, 5); + LList* ll6 = make_list(l6, 4); + + cout << "l3: "; + print_list(ll3->head); + cout << "l4: " << endl; + print_list(NULL); + cout << "l5: "; + print_list(ll5->head); + cout << "l6: "; + print_list(ll6->head); + + cout << "compare l3, l3: " << ll_compare(ll3->head, ll3->head) << endl; + cout << "compare l3, l4: " << ll_compare(ll3->head, ll4->head) << endl; + cout << "compare l3, l5: " << ll_compare(ll3->head, ll5->head) << endl; + cout << "compare l3, l6: " << ll_compare(ll3->head, ll6->head) << endl; + + return 0; +} + + +int ll_len(Node* head) { + if (head == NULL) { + return 0; + } + else { + return 1 + ll_len(head->next); + } +} + +void ll_unique(Node* head) { + if (head == NULL || head->next == NULL) { + return; + } else { + if (head->data == head->next->data) { + Node* temp = head->next; + head->next = head->next->next; + delete temp; + ll_unique(head); + } else { + ll_unique(head->next); + } + } + +} +void partial_sum_hlp(Node* head, int sum){ + if (head == NULL){ + return; + } else { + sum += head->data; + head->data = sum; + partial_sum_hlp(head->next, sum); + } +} +void ll_partial_sum(Node* head){ + if (head == NULL){ + return; + } else { + partial_sum_hlp(head, 0); + } + +} + +// example soln with while loop + +Node* ll_rotate_hlp(Node* cur, int n, Node* head){ + // traverse to get to the nth position + if (cur == NULL){ + return head; + } + if (n > 0){ + return ll_rotate_hlp(cur->next, n-1, head); + } + + Node* last = cur; + while (last->next != NULL){ + last = last->next; + } + last->next = head; + head = cur->next; + cur->next = NULL; + + return head; + +} +// example soln without while loop +/* +void ll_rotate_hlp2(Node* cur, Node* head) { + // Continue Traversing until end, and connect end of list to new head + if(cur->next == NULL) { + cur->next=head; + } + else { + ll_rotate_hlp2(cur->next, head); + } +} + +Node* ll_rotate_hlp(Node* cur, int n, Node* head){ + if (cur == NULL){ + return head; + } + if (n > 1){ + // If before nth position, continue traversing + return ll_rotate_hlp(cur->next, n-1, head); + } + else { + // If right before nth position disconnect the two parts of the list + if(cur->next == NULL) { + return head; + } + Node* tempNext = cur->next; + cur->next = NULL; + ll_rotate_hlp2(tempNext, head); + // Return the new head + return tempNext; + } +}*/ + +Node* ll_rotate(Node* head, int n) { + if (head == NULL || n == 0){ + return head; + } else { + return ll_rotate_hlp(head, n, head); + } + +} + +int ll_compare(Node* lhs, Node* rhs){ + if ((lhs == NULL) && (rhs != NULL)) return -1; + if ((lhs != NULL) && (rhs == NULL)) return 1; + if ((lhs == NULL) && (rhs == NULL)) return 0; + if (lhs->data < rhs->data) { + return -1; + } + if (lhs->data > rhs->data) { + return 1; + } + else { + return ll_compare(lhs->next, rhs->next); + } + +} + diff --git a/labs/su-llrec/ll_rec_practice_soln.cpp b/labs/su-llrec/ll_rec_practice_soln.cpp new file mode 100644 index 00000000..c72e7c18 --- /dev/null +++ b/labs/su-llrec/ll_rec_practice_soln.cpp @@ -0,0 +1,254 @@ +#include +#include +using namespace std; + +struct Node { + int data; + Node* next; +}; + +class LList { + public: + Node* head; +}; + +int ll_len(Node* head); +void ll_unique(Node* head); +void ll_partial_sum(Node* head); +Node* ll_rotate(Node* head, int n); +int ll_compare(Node* lhs, Node* rhs); + +LList* make_list(int input[], int size){ + LList* ret = new LList(); + Node* head = new Node(); + Node* temp; + ret->head = head; + for (int i = 0; i < size; i++){ + head->data = input[i]; + if (i < size -1) { + head->next = new Node(); + head = head->next; + } + } + + head->next = NULL; + head = NULL; + return ret; +} + +void print_list(Node* head){ + if (head == NULL){ + return; + } + if (head->next == NULL){ + cout << head->data << endl; + return; + } else { + cout << head->data << " -> "; + print_list(head->next); + } +} + + +int main() { + int l1[] = {1,2,3}; + int l2[] = {1,1,2,4,4,4,5,4}; + + LList* ll1 = make_list(l1, 3); + LList* ll2 = make_list(l2, 8); + + cout << "l1: "; + print_list(ll1->head); + cout << "l2: "; + print_list(ll2->head); + + cout << "length of l1: " << ll_len(ll1->head) << endl; + cout << "length of l2: " << ll_len(ll2->head) << endl; + + ll_unique(ll1->head); + ll_unique(ll2->head); + cout << "ll_unique on l1: "; + print_list(ll1->head); + cout << "ll_unique on l2: "; + print_list(ll2->head); + + ll1 = make_list(l1, 3); + ll2 = make_list(l2, 8); + + ll_partial_sum(ll1->head); + cout << "ll_partial_sum on l1: "; + print_list(ll1->head); + + cout << "rotated l2: "; + print_list(ll_rotate(ll2->head, 2)); + + int l2a[] = {1,2,3,4,5}; + LList* ll2a = make_list(l2a, 5); + cout << "l2a: "; + print_list(ll2a->head); + + cout << "rotate l2a by 2: "; + print_list(ll_rotate(ll2a->head,2)); + + ll2a = make_list(l2a, 5); + cout << "rotate l2a by 3: "; + print_list(ll_rotate(ll2a->head,3)); + + ll2a = make_list(l2a, 5); + cout << "rotate l2a by 0: "; + print_list(ll_rotate(ll2a->head,0)); + + ll2a = make_list(l2a, 5); + cout << "rotate l2a by 5: "; + print_list(ll_rotate(ll2a->head, 5)); + + + int l3[] = {1, 2, 3, 4}; + int l4[] = {}; + int l5[] = {0, 1, 2, 3, 4}; + int l6[] = {1, 2, 3, 5}; + LList* ll3 = make_list(l3, 4); + LList* ll4 = make_list(l4, 0); + LList* ll5 = make_list(l5, 5); + LList* ll6 = make_list(l6, 4); + + cout << "l3: "; + print_list(ll3->head); + cout << "l4: " << endl; + print_list(NULL); + cout << "l5: "; + print_list(ll5->head); + cout << "l6: "; + print_list(ll6->head); + + cout << "compare l3, l3: " << ll_compare(ll3->head, ll3->head) << endl; + cout << "compare l3, l4: " << ll_compare(ll3->head, ll4->head) << endl; + cout << "compare l3, l5: " << ll_compare(ll3->head, ll5->head) << endl; + cout << "compare l3, l6: " << ll_compare(ll3->head, ll6->head) << endl; + + return 0; +} + + +int ll_len(Node* head) { + if (head == NULL) { + return 0; + } + else { + return 1 + ll_len(head->next); + } +} + +void ll_unique(Node* head) { + if (head == NULL || head->next == NULL) { + return; + } else { + if (head->data == head->next->data) { + Node* temp = head->next; + head->next = head->next->next; + delete temp; + ll_unique(head); + } else { + ll_unique(head->next); + } + } + +} +void partial_sum_hlp(Node* head, int sum){ + if (head == NULL){ + return; + } else { + sum += head->data; + head->data = sum; + partial_sum_hlp(head->next, sum); + } +} +void ll_partial_sum(Node* head){ + if (head == NULL){ + return; + } else { + partial_sum_hlp(head, 0); + } + +} + +// example soln with while loop + +Node* ll_rotate_hlp(Node* cur, int n, Node* head){ + // traverse to get to the nth position + if (cur == NULL){ + return head; + } + if (n > 0){ + return ll_rotate_hlp(cur->next, n-1, head); + } + + Node* last = cur; + while (last->next != NULL){ + last = last->next; + } + last->next = head; + head = cur->next; + cur->next = NULL; + + return head; + +} +// example soln without while loop +/* +void ll_rotate_hlp2(Node* cur, Node* head) { + // Continue Traversing until end, and connect end of list to new head + if(cur->next == NULL) { + cur->next=head; + } + else { + ll_rotate_hlp2(cur->next, head); + } +} + +Node* ll_rotate_hlp(Node* cur, int n, Node* head){ + if (cur == NULL){ + return head; + } + if (n > 1){ + // If before nth position, continue traversing + return ll_rotate_hlp(cur->next, n-1, head); + } + else { + // If right before nth position disconnect the two parts of the list + if(cur->next == NULL) { + return head; + } + Node* tempNext = cur->next; + cur->next = NULL; + ll_rotate_hlp2(tempNext, head); + // Return the new head + return tempNext; + } +}*/ + +Node* ll_rotate(Node* head, int n) { + if (head == NULL || n == 0){ + return head; + } else { + return ll_rotate_hlp(head, n, head); + } + +} + +int ll_compare(Node* lhs, Node* rhs){ + if ((lhs == NULL) && (rhs != NULL)) return -1; + if ((lhs != NULL) && (rhs == NULL)) return 1; + if ((lhs == NULL) && (rhs == NULL)) return 0; + if (lhs->data < rhs->data) { + return -1; + } + if (lhs->data > rhs->data) { + return 1; + } + else { + return ll_compare(lhs->next, rhs->next); + } + +} + diff --git a/resources/final-info/index.md b/resources/final-info/index.md index 0e5b3179..5873de30 100644 --- a/resources/final-info/index.md +++ b/resources/final-info/index.md @@ -12,10 +12,10 @@ nav: Resources - The test will be set for **2 hours.** - If you have USC approved accommodations, please confirm with me via email and we will make preparations for your approved time. - Location: {{site.data.schedule.exams[1].location}} (leave a blank seat between you and your neighbor, if possible) - - If you have 1.5x time accommodations: ZHS 360 + - If you have 1.5x time accommodations: Check with Professor **5 days** before the final. - If you have **2x or 1.5x (with other) accommodations** you should schedule your exam at the OSAS offices **for the day of the exam** -- The final will be on Gradescope +- The final will be written (paper exam and paper coding...no laptop). - The exam is **Closed book, Closed notes, Closed Internet (search/reference)**. You may use your mind and blank scratch paper but nothing else. - You are allowed 1 **8.5x11 handwritten (front and back) cheatsheet**. No **typed** cheat sheets. No **single-sided, taped** pages to form a double-sided sheet. You will be asked to turn your cheatsheet in when you are done with the exam (so if you want it for posterity, make a copy beforehand). diff --git a/resources/mt1-info/index.md b/resources/mt1-info/index.md index 14ba4909..dd2b8ded 100644 --- a/resources/mt1-info/index.md +++ b/resources/mt1-info/index.md @@ -14,16 +14,11 @@ The test will be **IN PERSON** - Time/Date: **{{site.data.schedule.exams[0].time}}** - The test will be set for **1 hour, 50 minutes** - If you have USC approved accommodations, you must upload your accomodation information [HERE]({{site.data.urls.osas_dsp_form}}) by 11am on Thursday February 9th, otherwise you will not be able to use your accomodations. -- Location: THH - - 11AM section: - - THH 101 - - 8AM section: - - Last Name starts with A-K: THH 102 - - Last Name starts with L-Z: THH 301 - - If you have **1.5x time accommodations**: THH 213 (starting at 7pm running to 9:45pm) +- Location: Lab room + - If you have **1.5x time accommodations**: TBA - If you have **2x or 1.5x (with other) accommodations** you should schedule your exam at the OSAS offices **for the day of the exam** -- The test will be taken on Gradescope. You will be added to this course on Gradescope automatically, but you should test your Gradescope login sometime before the exam. +- The test will be taken on Paper and Gradescope. You will be added to this course on Gradescope automatically, but you should test your Gradescope login sometime before the exam. - The exam is **Closed book, Closed notes, Closed Internet (search/reference)**. You may use your mind, and blank scratch paper but nothing else. No referencing your labs, homeworks, etc. - You are allowed 1 **8.5x11 handwritten (front and back) cheatsheet**. No **printed** cheat sheets. No **single-sided, taped** pages to form a double-sided sheet. You will be asked to turn your cheatsheet in when you are done with the exam (so if you want it for posterity, make a copy beforehand). diff --git a/staff/index.html b/staff/index.html index ea6f7ec6..30f42d13 100644 --- a/staff/index.html +++ b/staff/index.html @@ -6,9 +6,9 @@

Staff and Hours

For special questions, you can contact your instructor. - However, we encourage you to use the course edStem page so that other students can also benefit from these questions or answer them. + However, we encourage you to use the course edStem page so that other students can also benefit from these questions or answer them. Note that we may change the listed office hours as needed, or add more before homework deadlines or examinations. - For an up to date listing please see the Google Calendar + For an up to date listing please see the Google Calendar below.

diff --git a/syllabus/index-su22.md b/syllabus/index-su22.md new file mode 100644 index 00000000..eafb6f62 --- /dev/null +++ b/syllabus/index-su22.md @@ -0,0 +1,212 @@ +--- +layout: asides +toc: true +tasks: false +title: Syllabus +--- + +# CSCI 104 Syllabus + +The course covers the fundamentals of data structures. +As a programmer becomes more proficient, they realize that how well and efficiently a problem can be solved often depends on how the data are stored. +Some of the ideas are quite sophisticated and clever, and we will explore a spectrum of them in this class, ranging from fairly basic to moderately advanced structures. + +The other side is that once one realizes the importance of data structures, it is natural to think of programs not as sequences of instructions that pass around some data, but as data packets that come with the code needed to process them. +This is at the heart of the object-oriented design paradigm, and often leads to more modular and extensible (and readable) programs. + +The class will put significant emphasis on a theoretical understanding of data structures, their implementation, and the object-oriented viewpoint. Assignments will contain significant programming projects along with programming-free questions to explore how data structures work. + +## Learning Objectives + +1. Ability to choose appropriate and efficient data structures and algorithms to solve a problem. +2. Ability to compare data structures and algorithms for efficiency using algorithm analysis and experiments. +3. Ability to apply algorithm analysis and knowledge of discrete mathematics to evaluate algorithms and data structures. +4. Ability to implement and use linear data structures, including stacks, queues, lists. +5. Ability to implement and use search structures and algorithms including binary search, search trees, and hash tables. +6. Ability to use and implement search data structures, including search trees and hash tables. +7. Ability to use and implement priority queues. +8. Knowledge of and ability to implement sorting algorithms and compare their performance analytically and empirically. +9. Understanding of graphs and their representations; ability to implement graph search using BFS, DFS, and Dijkstra's Algorithm. +10. Ability to write recursive functions and understand when recursion is appropriate to a problem. +11. Ability to write readable and maintainable code. +12. Ability to explain computational solutions in person and in writing. +13. Use probability as a tool in analyzing the efficiency of various data structures +14. Use basic number theory to analyze basic hash functions + +## Catalog Entry + +Introduces the student to standard data structures (linear structures such as linked lists, (balanced) trees, priority queues, and hashtables), using the C++ programming language. + +### Prerequisites + +- CSCI 103: Introduction to Programming +- CSCI 170: Discrete Methods in Computer Science + +## Course Websites + +- [All content & info]({{ site.baseurl }}/) +- [Blackboard]({{ site.data.urls.blackboard }}) +- [CSCI 104 GitHub Organization]({{ site.data.urls.github }}) +- [Piazza]({{ site.data.urls.discussion }}) + +## Grading Weights and Scale + +The following point structure will be used in determining the grade for the course. +Your final grade will depend solely on your own performance, graded according to the scale given below. + +
+
# Link Title DueSubmit Regrade
{{ forloop.index }} {% if assignment.assigned %} - Codio + Writeup {% else %} - + Writeup {% endif %} {{ assignment.title }} {{ assignment.dates.due }}Submit Regrade
+ {{ lab.id }} + {{lab.week}} {% if lab.assigned %} - {{ lab.id }} + {{ lab.title }} {% else %} - {{ lab.id }} + {{ lab.title }} {% endif %} {{ lab.week }}{{ lab.title }} {{ lab.topics }} {% if lab.slides %} - {{ lab.slides }} + {% for slide_link in lab.slides %} + {{ slide_link }}
+ {% endfor %} {% endif %}
+ + + + + + + + + + + + + + + + + + + + + + +
WeightItem
36%Homework
6%Lab Exercises
28%Midterm Exams
30%Final Exam
+ + +### Grading Scale + +We will guarantee that you will get at least the grade indicated by the following scale. +Because of the fairly generous scale we will not round up if you are close to the lower threshold of a letter grade. +At the end of the semester, we may decide to lower the scale if the exams were more difficult than intended. + +
+ + + + + + + + + + + +
GradeLetter
85%A
80%A-
75%B+
70%B
65%B-
+ + + + + + + + + + + +
GradeLetter
60%C+
55%C
50%C-
45%D+
40%D
+
+ +### Assignments and Labs + +Information regarding [homework]({{ site.baseurl }}/homework/) and [labs]({{ site.baseurl }}/labs/) are available on their respective pages. +They contain **policies** related to grading, assignments, and policies related to submission, contesting grades, academic integrity, etc. +You are **responsible** for reading those pages *carefully* and following all of its stated policies, which should be considered as part of this syllabus. + +## Attendance + +While regular attendance will not be taken, class participation and attendance is **expected**. + +## Textbook + +We will be using **"Data Structures and Algorithm Analysis in C++" by Mark Weiss**. In addition, you should have a Discrete Mathematics textbook (whichever book you used for CSCI 170 will suffice): I will specificially refer to reading from "Essential Discrete Mathematics for Computer Science" by Lewis & Zax. +You may also find the course lecture notes useful. You may download (and possibly print) the [lecture notes]({{ site.data.urls.notes }}). +These are based on teaching of CSCI 104 in past semesters, and cover the material quite accurately as presented in class. +However, the lecture notes may be out of order and cover different topics, as we have changed the schedule significantly. +We will also be providing detailed lecture slides and recorded videos that you may also use. + +We want to provide you with additional references that may enhance study and may be cited during video recordings. +In addition to the textbook used for CSCI 103, for the C++ Language the following references are available for free online from the USC Library: + +- [Lippman, Stanley, Barbara Moo, and Josee Lajoie. C++ Primer](https://uosc.primo.exlibrisgroup.com/permalink/01USC_INST/273cgt/cdi_askewsholts_vlebooks_9780133053036). Addison-Wesley Professional, 2012. +- [Stroustrup, Bjarne. A Tour of C++](https://uosc.primo.exlibrisgroup.com/permalink/01USC_INST/hs9vaa/alma991043008444003731). Upper Saddle River, NJ: Addison-Wesley, 2014. +- [Stroustrup, Bjarne. The C++ Programming Language](https://uosc.primo.exlibrisgroup.com/permalink/01USC_INST/273cgt/cdi_askewsholts_vlebooks_9780133522853). Pearson Addison Wesley, 2013. + +For data structures specifically: + +- Weiss. Data Structures and Algorithm Analysis in C++ 4th Ed. Pearson, 2014. +- Carrano, Frank and Thomas Henry. Data Abstraction & Problem Solving with C++ 6th Ed. Pearson, 2013. +- [Goodrich, Michael T, Roberto Tamassia, and David M Mount. Data Structures and Algorithms in C](https://uosc.primo.exlibrisgroup.com/permalink/01USC_INST/hs9vaa/alma991043327161803731). Wiley, 2011. + +## Reading Assignments + +Readings from lecture notes and other sources form the base of your learning pyramid. +These readings contain theoretical concepts, examples and usable code that will be very helpful for all the work in this course. We also recommend reviewing the lecture slides/notes after each lecture (or at the end of each week to see what you still remember, what doesn't make sense now that you have to do an exercise yourself, etc.) This will help you retain the content, increase mastery, and prime you to ask quesitons in future lectures. + +## Exams + +Exams will involve analysis and coding. Questions require students to demonstrate their mastery over the material. Exams are currently expected to be in person but will likely be given via Gradescope and require you to bring a laptop. More details will be posted at least 1 week before the exam. + +## Accommodations + +If you have USC approved (OSAS) accommodations, you **MUST** upload your OSAS generated PDF letter for this class to the **[linked form]({{site.data.urls.osas_dsp_form}})**. + +## Statement on Academic Conduct + +Below is USC's official language. + However, **we have specific rules in CS 104 which are outlined on the [assignments & grading page]({{ site.url }}/homework/)**. + +Plagiarism - presenting someone else's ideas as your own, either verbatim or recast in your own words - is a serious academic offense with serious consequences. +Please familiarize yourself with the discussion of plagiarism in *SCampus* in Part B, Section 11, *Behavior Violating University Standards* [https://policy.usc.edu/scampus-part-b/](https://policy.usc.edu/scampus-part-b/). +Other forms of academic dishonesty are equally unacceptable. +See additional information in SCampus and university policies on scientific misconduct, [http://policy.usc.edu/scientific-misconduct/](http://policy.usc.edu/scientific-misconduct/). + +## Support Systems + +- **Student Counseling Services (SCS)** - (213) 740-7711 - 24/7 on call + Free and confidential mental health treatment for students, including short-term psychotherapy, group counseling, stress fitness workshops, and crisis intervention. + [engemannshc.usc.edu/counseling](engemannshc.usc.edu/counseling) + +- **National Suicide Prevention Lifeline** - 1 (800) 273-8255 + Provides free and confidential emotional support to people in suicidal crisis or emotional distress 24 hours a day, 7 days a week. + [www.suicidepreventionlifeline.org](www.suicidepreventionlifeline.org) + +- **Relationship and Sexual Violence Prevention Services (RSVP)** - (213) 740-4900 - 24/7 on call + Free and confidential therapy services, workshops, and training for situations related to gender-based harm. + [engemannshc.usc.edu/rsvp](engemannshc.usc.edu/rsvp) + +- **Sexual Assault Resource Center** + For more information about how to get help or help a survivor, rights, reporting options, and additional resources, visit the website: [sarc.usc.edu](sarc.usc.edu) + +- **Office of Equity and Diversity (OED)/Title IX Compliance** - (213) 740-5086 + Works with faculty, staff, visitors, applicants, and students around issues of protected class. + [equity.usc.edu](equity.usc.edu) + +- **Bias Assessment Response and Support** - Incidents of bias, hate crimes and microaggressions need to be reported allowing for appropriate investigation and response. + [studentaffairs.usc.edu/bias-assessment-response-support](studentaffairs.usc.edu/bias-assessment-response-support) + +- **The Office of Disability Services and Programs** + Provides certification for students with disabilities and helps arrange relevant accommodations. + [dsp.usc.edu](dsp.usc.edu) + +- **Campus Support and Intervention** - (213) 821-4710 + Assists students and families in resolving complex issues adversely affecting their success as a student EX: personal, financial, and academic. + [studentaffairs.usc.edu/ssa](https://campussupport.usc.edu/) + +- **Diversity at USC** + Information on events, programs and training, the Diversity Task Force (including representatives for each school), chronology, participation, and various resources for students. + [diversity.usc.edu](diversity.usc.edu) + +- **USC Emergency Information** + Provides safety and other updates, including ways in which instruction will be continued if an officially declared emergency makes travel to campus infeasible. + [emergency.usc.edu](emergency.usc.edu) + +- **USC Department of Public Safety** - UPC: (213) 740-4321 - HSC: (323) 442-1000 - 24-hour emergency or to report a crime. + Provides overall safety to USC community. [dps.usc.edu](dps.usc.edu) diff --git a/syllabus/index.md b/syllabus/index.md index a308183a..d3e4da5e 100644 --- a/syllabus/index.md +++ b/syllabus/index.md @@ -46,7 +46,7 @@ Introduces the student to standard data structures (linear structures such as li - [All content & info]({{ site.baseurl }}/) - [Blackboard]({{ site.data.urls.blackboard }}){:target="_blank"} -- [EdStem]({{ site.data.urls.piazza }}){:target="_blank"} +- [EdStem]({{ site.data.urls.discussion }}){:target="_blank"} ## Grading Weights and Scale @@ -129,7 +129,7 @@ We will be using **"Data Structures and Algorithm Analysis in C++" by Mark Weiss You may also find the course lecture notes useful. You may download (and possibly print) the [lecture notes]({{ site.data.urls.notes }}). These are based on teaching of CSCI 104 in past semesters, and cover the material quite accurately as presented in class. However, the lecture notes may be out of order and cover different topics, as we have changed the schedule significantly. -We will also be providing detailed lecture slides and recorded videos that you may also use. +We will also be providing detailed lecture slides that you may also use. We want to provide you with additional references that may enhance study so in addition to the textbook used for CSCI 103, for the C++ Language the following references are available for free online from the USC Library: @@ -139,7 +139,6 @@ We want to provide you with additional references that may enhance study so in a For data structures specifically: -- Weiss. Data Structures and Algorithm Analysis in C++ 4th Ed. Pearson, 2014. - Carrano, Frank and Thomas Henry. Data Abstraction & Problem Solving with C++ 6th Ed. Pearson, 2013. - [Goodrich, Michael T, Roberto Tamassia, and David M Mount. Data Structures and Algorithms in C](https://uosc.primo.exlibrisgroup.com/permalink/01USC_INST/hs9vaa/alma991043327161803731). Wiley, 2011. @@ -150,7 +149,7 @@ These readings contain theoretical concepts, examples and usable code that will ## Exams -Exams will involve analysis and coding. Questions require students to demonstrate their mastery over the material. Exams are currently expected to be in person but will likely be given via Gradescope and require you to bring a laptop. More details will be posted at least 1 week before the exam. +Exams will involve analysis and coding. Questions require students to demonstrate their mastery over the material. Exams will likely be given via Gradescope and require you to bring a laptop. More details will be posted at least 1 week before the exam. ## Accommodations @@ -158,14 +157,32 @@ If you have USC approved (OSAS) accommodations, you **MUST** upload your OSAS ge ## Statement on Academic Conduct + + +## Statement on Academic Conduct and Support Systems + Below is USC's official language. - However, **we have specific rules in CS 104 which are outlined on the [assignments & grading page]({{ site.baseurl }}/homework/)**. + However, **we have specific rules in CS 104 which are outlined on the [assignments & grading page]({{ site.baseurl }}/homework/)** and below: + + **Collaboration**: Your homework assignments and exams should be individual efforts unless explictly stated otherwise. While collaboration and online searches are common in the workplace, taking code from those sources is usually not allowed due to licensing and can have legal ramifications. Similarly, while collaboration in a company is common, we are training you to be capable computer scientists and, thus, you need to develop the skills for yourself. You will have higher levels of collaboration for team-based projects in future courses and in the workplace. For homework assignments, you may only have **CONCEPTUAL** discussions with classmates. Any discussion that includes specific code (describing variables, loops, functions, etc.) and implementation details is an **inappropriate level** of collaboration and a **violation of academic integrity**. **Copying (and then modification) or just "viewing for reference"** any (**even small**) portion(s) of code from Internet sources or fellow students is prohibited unless explicitly cleared with the instructor. Simiarly, **ANY use of chatGPT or similar AI-generators** to generate ANY amount of code is a violation. Similarly you should NOT verbally describe your code at any level of detail. Instead, draw (non-code) pictures, ask questions that consider possible inputs or other scenarios, or provide advice on how to debug. Violations of this policy **will likely** result in an **F in the course**. + +### Academic Integrity: +The University of Southern California is a learning community committed to developing successful scholars and researchers dedicated to the pursuit of knowledge and the dissemination of ideas. Academic misconduct, which includes any act of dishonesty in the production or submission of academic work, comprises the integrity of the person who commits the act and can impugn the perceived integrity of the entire university community. It stands in opposition to the university’s mission to research, educate, and contribute productively to our community and the world. + +All students are expected to submit assignments that represent their own original work, and that have been prepared specifically for the course or section for which they have been submitted. You may not submit work written by others or “recycle” work prepared for other courses without obtaining written permission from the instructor(s). + +Other violations of academic integrity include, but are not limited to, cheating, plagiarism, fabrication (e.g., falsifying data), collusion, knowingly assisting others in acts of academic dishonesty, and any act that gains or is intended to gain an unfair academic advantage. + +The impact of academic dishonesty is far-reaching and is considered a serious offense against the university. All incidences of academic misconduct will be reported to the Office of Academic Integrity and could result in outcomes such as failure on the assignment, failure in the course, suspension, or even expulsion from the university. + +For more information about academic integrity see the [student handbook](https://policy.usc.edu/studenthandbook/) or the [Office of Academic Integrity’s website](http://academicintegrity.usc.edu/), and university policies on [Research and Scholarship Misconduct](https://policy.usc.edu/research-and-scholarship-misconduct/). + +Please ask your instructor if you are unsure what constitutes unauthorized assistance on an exam or assignment, or what information requires citation and/or attribution. + +Students and Disability Accommodations: + +USC welcomes students with disabilities into all of the University’s educational programs. The Office of Student Accessibility Services (OSAS) is responsible for the determination of appropriate accommodations for students who encounter disability-related barriers. Once a student has completed the OSAS process (registration, initial appointment, and submitted documentation) and accommodations are determined to be reasonable and appropriate, a Letter of Accommodation (LOA) will be available to generate for each course. The LOA must be given to each course instructor by the student and followed up with a discussion. This should be done as early in the semester as possible as accommodations are not retroactive. More information can be found at [osas.usc.edu](http://osas.usc.edu/). You may contact OSAS at (213) 740-0776 or via email at osasfrontdesk@usc.edu. -Plagiarism - presenting someone else's ideas as your own, either verbatim or recast in your own words - is a serious academic offense with serious consequences. -Please familiarize yourself with the discussion of plagiarism in the USC Student Handbook, Integrity and Accountability: Acadmic Integrity (page 11): - [https://policy.usc.edu/studenthandbook/](https://policy.usc.edu/studenthandbook/). -Other forms of academic dishonesty are equally unacceptable. -See additional information in the USC Student Handbook and university policies on scientific misconduct, [http://policy.usc.edu/scientific-misconduct/](http://policy.usc.edu/scientific-misconduct/). ## Support Systems