Markets and Friction Problem Set 3 Problem Set 3 is worth 15% of your grade. Please upload your assignment to Moodle by 4pm of November 8th. You may type or write your answers by hand. Handwritten assignments must be legible or they will be dismissed. 5% will be deducted from the mark of late submissions for each day (before solutions are posted). Submissions made after the solutions are posted will not be marked. Each question is worth 25 points, and each part of the question is worth 5 points. 1. Do Question 4 of Problem Set 2. Note that we are assuming R > r1+σ . 2. Consider a three-period model with time indexed by t = 0, 1, 2. At t = 0, all agents are endowed with wealth 1. There is a unit mass of identical agents. For each agent, consumption either takes place in t = 1 or t = 2. However, at t = 0, agents are unsure which dates they would want to consume. There are two possible states of aggregate liquidity demand: µ ∈ {µH, µL }, with 1 > µH > µL > 0. The probability of the aggregate state being H is π ∈ (0, 1) . We will let the subscript. i ∈ {H, L} denote the aggregate state of the economy. With probability µi, they would want to consume at t = 1, which we refer to as the early agents. With the remaining probability, they would want to consume in t = 2, which we refer to as the late agents. Agents learn the aggregate state and whether they are early or late agents in t = 1. The liquidity shock is independent across agents. The discount factor is β = 1. The agents’ utility is u (c) = ln (c) . Agents can buy short and long assets. The short asset transforms x units of date t consumption to rx units of date t + 1 consumption. The long asset transforms x units of date t consumption to Rx units of date t + 2 consumption. Assume that R > r2 > 1. The agents transfer their wealth across periods using these two assets. Furthermore, a secondary market for long assets existsint = 1, where agents can buy or sell their long asset positions at price pi. a. Setup the self-insuring agent’s optimization problem where the secondary mar- ket is open. b. What are the supply and demand curves for the long asset in the secondary market? c. Let s* denote the equilibrium short asset allocation in t = 0. Write out the equilibrium prices (pH(*), pL(*)) and prove that pL(*) > pH(*) . d. Let µH = 2ϵ, µL = ϵ, where ϵ > 0. Take the limit of ϵ to 0 and show that the price difference is disproportionately larger than the difference in µ when both prices are cash-in- the-market. e. Consider the case when only one of the prices is cash-in-the-market. For a fixed ϵ > 0, as r increases, does the volatility in prices increase or decrease? Explain. Hint: Draw a supply and demand graph and remember that s* would increase (no need to prove this). 3. Consider an extension of the environment in Question 2 with competitive banks without default. Suppose all banks adopt the same asset portfolio and offer depos- itors a return of b for withdrawing at t = 1, regardless of the liquidity state, and its residual assets to those who withdraw at t = 2. This question considers an environ- ment without sunspot-driven bank runs. a. Write down the condition that prevents late agents from withdrawing early. b. Suppose the condition in Part a. is violated, what is the consumption of the early and late agents? c. Setup the optimization problem for the banks. d. Prove that the equilibrium price of the long asset in the secondary marketsat- isfies PL = r/R and PH < r. e. Explain how, if defaults are allowed, asset prices can be even more volatile. 4. Warren Buffett, a risk-neutral investor with deep pockets, is seeking investment opportunities. Two ambitious young women reached out—Aiko and Leila—each proposing a new project. Both are asking for the same investment amount of $7 million. Given the small scale of these investments, Warren wishes to act charitably and aims only to break even on his investment in expectation. Both projects have a 60% chance of success and will yield $3 per dollar of invest- ment, which is unverifiable, if successful but nothing if they fail. Aiko and Leila, both cash-strapped entrepreneurs, offer a fraction of their patents as collateral. The value of these patents will only be known once they hit the market. A good patent is worth $15 million, while a bad one has no value. Verifying the patent’s value requires Warren to spend $0.35 million on market research. Warren estimates that Aiko’s patent has an 80% chance of being good, while Leila’shas a 98% chance. Warren proposes to give each a contract specifying the loan amount (i), the face value of the debt (R), and the share of the collateralized patent (x). Aiko and Leila can commit to handing over the promised share of their patents if they default. War- ren must decide whether to conduct the market research and determine the contract terms to offer Aiko and Leila. He seeks your guidance in making these decisions. a. If Warren conducts market research, what is the optimal information-sensitive debt offered to Aiko? What about Leila? b. If Warren does not conduct market research, what is the optimal information- insensitive debt offered to Aiko? What about Leila? c. What are the expected profits for Aiko and Leila under both the information- sensitive and information-insensitive debt? Which type of debt does Aiko pre- fer? Which does Leila prefer? d. Aiko and Leila, who are classmatesatUNSW, discover that both are seeking in- vestments from Warren. Their instructors—Han, Nick, and PC—suggest they pool their patents and offer Warren two identical new patents to support each project. Each of these pooled patents succeeds with probability 0.89, calculated as (0.8 + 0.98)/2,and yields $15 million if accepted by the market. The success of the new patents is independent. Assuming Warren does not conduct market research, how much can Aiko and Leila each borrow? e. Can you create a plot to demonstrate why Aiko and Leila can borrow more from Warren after pooling? To do this, (i) use MATLAB (or any other graphing software) to replicate Figure 1 from Lecture 6 using the parameter values given in this question; (ii) clearly label all elements in the figure, including the scales of the x- andy-axes and the meaning of each curve; (iii) identify the location of optimal profits for Aiko and Leila before and after pooling.
ASB4416 - CREDIT RISK ANALYTICS ASSIGNMENT (SEMESTER 1, 2024) (25% of total module mark) SUBMISSION DEADLINE - 4PM FRIDAY 22ND NOVEMBER 2024 Please submit an electronic copy ONLY via Turnitin You are reminded not to copy material from any sources without properly referencing it, as this constitutes plagiarism: cases of plagiarism will be referred to the Business School Academic Integrity Officer and will be subject to a deduction ofmarks, which can result in an overall mark of 0%. Background You have to apply the skills you’ve learnt during the lectures (Merton Default Model) and use Excel to answer the assignment question. You must answer all your questions in one document (i.e. Word) and provide screenshots or copy and paste your working from Excel into the document. You will need to clearly explain the steps you have taken in Excel. Do not present your answers in essay form. You are assessed on how you use Excel to answer the questions, and then how you discuss your findings. Therefore your answers need to be clear and concise. The word limit for the report is 1,500 words. You can collect data to complete the assignment from whatever source you feel best BUT you need to clearly specify the source of any data used. Assignment Using the Merton’s structural model with a one-year horizon, calculate the probability of default (using both the iterative approach and two-equation approach) for two US non-financial firms between Q1 2022 and Q4 2022 (i.e. a full calendar year). Compare the results and describe your calculations. To complete this assignment you should, 1. Download the following information between Q1 2022 and Q4 2022 for each firm: a. the daily equity price and amount of common shares in circulation (to calculate the market equity), b. the quarterly total book liabilities. 2. Download the daily S&P 500 index price for the Q1 2022 to Q4 2022 period. 3. Assume the risk free rate to be 3% throughout the whole period. 4. For each firm, calculate the probability default (using both the iterative approach and two-equation approach) using the Merton’s structural model with a one-year horizon. As part of your calculations you will need to: a. Calculate the asset volatility, b. Perform. CAPM calculations, c. Derive the implied default probability, d. Calibrate the Merton model. 5. In your report, you will need to: a. briefly describe the two firms, including industry, overall structure, and performance over the period, b. explain and briefly describe the data feeding into the model and how it is used, c. describe the calculations performed in the Excel workbook, d. compare and explain the different approaches for calculating the probability of default; i. iterative approach, ii. two-equation approach e. interpret the output of the Merton model and describe key parameters of the model, f. Compare the probability of default results for the two firms.
Assessment 2: Brand Betrayal Submission Date: 12 Noon on Friday 22nd November Submission Type: Infographic (please submit using PDF & check it has uploaded correctly) (See https://www.techtarget.com/whatis/definition/infographics) Marks: 20% Purpose: Another dual-purpose task. Sometimes, consumers perceive brands to have betrayed them. This is costly for both consumers and organizations. This task will also introduce another key skill: being able to communicate a lot of detailed information in an easy to read and digest manner: i.e., an infographic. Preparation: A basic introduction to brand betrayal is here: https://www.elliott.org/blog/companies-betray-customers-what-to-do/#google_vignette Look up articles on brand betrayal and/or consumer betrayal. Your Task: Choose ONE brand which has been linked to betrayal of its consumers. Design an infographic that analyses the consequences of the betrayal on consumers and the organization. Marking Scheme Your infographic will be assessed on: · Critical analysis of betrayal, including the use of academic journal papers. · The application of academic concepts to your chosen brand. · Quality of infographic - aesthetic design, colour pallet & font, communication ability, layout
FINA 6207 FINANCIAL MODELING GROUP PROJECT Guidelines: l This group project constitutes 10% of your final grade. Please read the instructions carefully and organize your response in a professional report. l You can form. a team of 5-8 people and work with others on the project. Each team should have a team leader who’s responsible for submitting your group’s work. l The team leader should submit your work as a single PDF file by the end of Sunday 12/08 to receive full consideration. You may include tables/codes/charts/screenshots etc. that can support your analysis in the report document. If you wish to submit additional scripts/spreadsheets, please also attach them on Canvas . The report should indicate full names of all your team members on the frontpage. l Your grade will depend on several factors such as how well your report is organized, how comprehensive and thorough your responses are. Try to keep it professional and easy to read even for audiences that do not have business background. l Please do NOT use ChatGPT or any AI tools in generating your report. It can and will be detected. PART 1 Suppose you area bond portfolio manager atBVS bank. Your portfolio currently has the following components: Government Bond A: $600,000 with a 20-year maturity and 2.5% coupon. Current YTM 5%. Corporate Bond B: $400,000 with a 5-year maturity and 3.8% coupon. Current YTM 4%. Municipal Bond C: $500,000 with a 10-year maturity and 4.2% coupon. Current YTM 3%. Conduct a comprehensive analysis of the portfolio with respect to its risk. Identify some types of risk the portfolio might be exposed to and then quantify them using the tools we discussed in class. Hint: This is an open-end question. Just like what we deal with in the real world, when a problem is not well-defined and lacking some information. You might need to make reasonable assumptions in addition to what we learnt it class to solve it. Feel free to use market data and make sure to cite it properly. To get you started, you can calculate some key measures for bonds. You may conduct a sensitivity analysis to see the effect on portfolio value: simulate several scenarios that might help illustrate its risk exposure, e.g. a 1% increase in interest rates or 0.5% decrease in interest rates. How does the current term structure affect the valuation process? Is there an immunization strategy? PART 2 Stock Valuation and building optimal portfolio: a) Use what you’ve learned in this course so far to value any 2 stocks from the following S&P 500 top firms list: 1. Apple (AAPL) 2. Microsoft (MSFT) 3. Amazon (AMZN) 4. Nvidia Corp (NVDA) 5. Alphabet Inc. Class A (GOOGL) 6. Meta. Platforms, Inc Class A (META) 7. Tesla, Inc. (TSLA) 8. Berkshire Hathaway Class B (BRK.B) 9. Unitedhealth Group Incorporated (UNH) 10. Eli Lilly & Co. (LLY) With one of the following methods 1) Dividend Discount Model method (with the help of CAPM) 2) The multiple method 3) FCF valuation model b) Choose 5 stocks out of the above list and construct an efficient frontier. Draw the efficient frontier on a graph and locate I. the GMVP II. the maximum Sharpe-ratio portfolio (tangent portfolio) given the current risk-free rate. Does it make a difference when short selling is prohibited? Back testing this portfolio against S&P 500, which gives a higher return? Explain in detail. In your report, please show the following l Explain in detail why and why not you choose one valuation model over the others. Not all methods are applicable under certain circumstances e.g. when firms have negative required returns, EPS and FCF. l If you need any data, please restrict your data range to be within the most recent five years and your data frequency to be monthly. Please refer to our slides as to how to obtain raw data. Audited financial statements can generally be found on firms 10-K forms filed with SEC. You can access them via SEC’s EDGAR system online. https://www.sec.gov/edgar/searchedgar/companysearch l Appropriate assumptions are acceptable when key information is missing. E.g. You can somewhat assume a firm’s dividend growth rate is similar to its main competitor’s or the industry average when it’s not possible to obtain accurate data on it. However, do NOT abuse it when the raw data are available. l Include key steps of your analysis or calculation with detailed explanation in between to ensure readability. Always assume your audience to be people with only basic or no business/finance background. l Try to limit your report on Part 2 under 10 pages. l This is an open-ended project, and you are encouraged to do your own research before finishing the report. Showing your thought process is more important than the results. l R is the preferred tool. l Please let me know if you have any questions.
Organization of Digital Computers Lab Fall 2024 EECS112L Lab 4 (100 Points) In this lab, we want you to design a pipeline Processor. 1 Pipeline Processor Pipelining is an implementation technique in which multiple instructions are overlapped in execution. In a single cycle design, every instruction takes exactly one cycle. While in a pipeline processor, the datapath is broken into separate independent stages. MIPS instructions classically take five steps: • 1. Fetch the instruction from memory. • 2. Read registers while decoding the instruction. • 3. Execute the operation or calculate an address. • 4. Access an operand in data memory. • 5. Write the result into a register. Hence, the MIPS pipeline has five stages, named IF (Instruction Fetch) , ID (Instruction Decode), EXE (Execution), MEM (Memory) and WB (Write Back). Figure 1 shows a pipeline processor. You see the pipeline registers are located between every two stages. Figure 1: Pipeline processor The pipeline improves performance by increasing instruction throughput. The idea behind pipelining is to keep all the stages busy at all times. As an example, when an instruction is using the ALU, the register file and the instruction memory are used by other instructions. Every instruction seems to have its datapath. All instructions advance during each cycle from one pipeline register to the next. In this case, all the required information of an instruction such as control signals and registers need to be stored in the pipeline registers. There are situations in pipelining when the next instruction cannot execute in the following clock cycle. These events are called hazards, and there are three diferent types. • Structural hazard. When a planned instruction cannot execute in the proper clock cycle because the hardware does not support the combination of instructions that are set to execute • Data hazard. Also called a pipeline data hazard. When a planned instruction cannot execute in the proper clock cycle because data that is needed to execute the instruction is not yet available. Adding extra hardware to retrieve the missing item early from the internal resources is called forwarding or bypassing. • Control hazard. Also called branch hazard. When the proper instruction cannot execute in the proper pipeline clock cycle because the instruction that was fetched is not the one that is needed; that is, the flow of instruction addresses is not what the pipeline expected. To avoid delay in our pipeline when one of these hazards happen, we use forwarding. To implement forwarding, we need to a) detect the data dependencies by adding the forwarding unit, and b) add the required paths to enable forwarding. Forwarding cannot solve all the problems. There are some cases that we cannot avoid delay by forward- ing in those cases the pipeline will stall for 1 or more clock cycles. We need to detect these cases with Hazard Detection unit. Now we will go through each pipeline stage with more detail. 1.1 Instruction Fetch Figure 2 shows the Instruction Fetch stage of the pipeline. In this stage instruction being read from memory using the address in the PC and then being placed in the IF/ID pipeline register. In case there is no branch or jump instructions, the PC address is incremented by 4 and then written back into the PC to be ready for the next clock cycle. For branch and Jump instructions we need to send branch address, and jump address to the PC. So we need two multiplexers and the select signals. We also need to save the PC plus4 in the IF/ID pipeline register in case it is needed later (to calculate the branch address in the next stage) for instruction, such as beq. The computer cannot know which type of instruction is being fetched, so it must prepare for any instruction, passing potentially needed information down the pipeline. Here is sample code for Instruction Fetch stage. Please use this for the module part of the IF pipe stage Code 1: IF pipe stage. module IF_pipe_stage ( input clk , reset , input en , input [9:0] branch_address , input [9:0] jump_address , input branch_taken , input jump , output [9:0] pc_plus4 , output [31:0] instr ); Note: The instruction memory module is not provided. Please import that from Lab2 and change the instructions accordingly and then use that module in the IF stage. Figure 2: Instruction Fetch. 1.2 IF/ID Registers we use pipeline registers to store the data that we may need in the next stages. They are flip flops. Figure 3: IF/ID Registers. you may use this code sample for IF/ID pipeline registers. Other pipeline registers don’t need enable and flush input. Hence, this one is a little bit diferent. Code 2: IF/ID Pipeline Register. module pipe_reg_en #( parameter WIDTH = 8)( input clk , reset , input en , flush , input [WIDTH -1:0] d, output reg [WIDTH -1:0] q ); always @( posedge clk or posedge reset ) begin if( reset ) q
IMEL7000/ECEN7003 Fall 2024 Project 3 Fully Differential Two-Stage Miller Op-Amp Design I. OBJECTIVE Design a fully differential two-stage operational amplifier (Opamp) as shown in Fig. 1(a) using Cadence/Spectre. This design should include a fully differential two-stage Opamp core with Miller compensation, current mirror based biasing circuit and a common feedback (CMFB) circuit (Fig. 1(b)). Study and simulate some of the important performance indexes of the Opamp. Fig. 1. (a) Opamp as a circuit building block. (b) Block Diagram of the Opamp. II. SPECIFICATIONS DD OdB(>70)GBW>500MHz oClosed-loop OutputSwingVo>1.2Vpp differential @1MHz with THD(>1.8Vpp differential, THD Slew RateSR>0.5V/ns L L better)
CSE 158/258, MGTA 461, DSC 256, Fall 2024: Assignment 1 Instructions In this assignment you will build recommender systems to make predictions related to book reviews from Goodreads. Submissions will take the form. of prediction files uploaded to gradescope, where their test set performance will be evaluated on a leaderboard. Most of your grade will be determined by ‘absolute’ cutoffs; the leaderboard ranking will only determine enough of your assignment grade to make the assignment FUN. The assignment is due Monday, Nov 18, though make sure you upload solutions to the leaderboard regularly. You should submit two files: writeup .txt a brief, plain-text description of your solutions to each task; please prepare this adequately in advance of the submission deadline; this is only intended to help us follow your code and does not need to be detailed. assignment1 .py A python file containing working code for your solutions. The autograder will not execute your code; this file is required so that we can assign partial grades in the event of incorrect solutions, check for plagiarism, etc. Your solution should clearly document which sections correspond to each task. We may occasionally run code to confirm that your outputs match submitted answers, so please ensure that your code generates the submitted answers. Along with two files corresponding to your predictions: predictions Read .csv,predictions Rating .csv Files containing your predictions for each (test) instance. The provided baseline code demonstrates how to generate valid output files. This assignment should be completed individually. To begin, download the files for this assignment from: http://cseweb.ucsd.edu/classes/fa24/cse258-b/files/assignment1.tar.gz Files train Interactions.csv.gz 200,000 ratings to be used for training. This data should be used for both tasks. It is not necessary to use all ratings for training, for example if doing so proves too computationally intensive. userID The ID of the user. This is a hashed user identifier from Goodreads. bookID The ID of the book. This is a hashed book identifier from Goodreads. rating The star rating of the user’s review. pairs Read.csv Pairs on which you are to predict whether a book was read. pairs Rating.csv Pairs (userIDs and bookIDs) on which you are to predict ratings. baselines.py A simple baseline for each task, described below. Please do not try to collect these reviews from Goodreads, or to reverse-engineer the hashing function I used to anonymize the data. Doing so will not be easier than successfully completing the assignment. We will execute code for any solution suspected of violating the competition rules to confirm that it generates valid output; all code will be run through a plagiarism detector. Tasks You are expected to complete the following tasks: Read prediction Predict given a (user,book) pair from ‘pairs Read.csv’ whether the user would read the book (0 or 1). Accuracy will be measured in terms of the categorization accuracy (fraction of correct predictions). The test set has been constructed such that exactly 50% of the pairs correspond to read books and the other 50% do not. Rating prediction Predict people’s star ratings as accurately as possible, for those (user,item) pairs in ‘pairs Rating.txt’ . Accuracy will be measured in terms of the mean-squared error (MSE). A competition page has been set up on gradescope to keep track of your results compared to those of other members of the class. The leaderboard will show your results on half of the test data, but your ultimate score will depend on your predictions across the whole dataset. Grading and Evaluation This assignment is worth 22% of your grade. You will be graded on the following aspects. Each of the two tasks is worth 10 marks (i.e., 10% of your grade), plus 2 marks for the written report. • Your ability to obtain a solution which outperforms the leaderboard baselines on the unseen portion of the test data (5 marks for each task). Obtaining full marks requires a solution which is substantially better than baseline performance. • Your ranking for each of the tasks compared to other students in the class (3 marks for each task). • Obtain a solution which performs well on the seen portion of the test data (i.e., the leaderboard). This is a consolation prize in case you overfit to the leaderboard. (2 mark for each task). Finally, your written report should describe the approaches you took to each of the tasks. To obtain good performance, you should not need to invent new approaches (though you are more than welcome to!) but rather you will be graded based on your decision to apply reasonable approaches to each of the given tasks. You should generally get full marks for the report as long as it describes your solution. 1-2 paragraphs should be sufficient for each task (2 marks total). Baselines Simple baselines have been provided for each of the tasks. These are included in ‘baselines.py’ among the files above. They are mostly intended to demonstrate how the data is processed and prepared for submission to gradescope. These baselines operate as follows: Read prediction Find the most popular books that account for 50% of interactions in the training data. Return ‘1’ whenever such a book is seen at test time, ‘0’ otherwise. Rating prediction Return the global average rating, or the user’s average if we have seen them before in the training data. Running ‘baselines.py’ produces files containing predicted outputs (these outputs can be uploaded to grade- scope). Your submission files should have the same format.
Note: Please make sure you have a GUI-enabled Linux OS (e.g., Ubuntu VM, WSL) to work on this project.Table of contentsDisclaimersObjectivesChecklist of Downloaded Project FilesTasksRole 1 – Attacker (45%)Task 1.1: Exploit Discovery (15%)Task 1.2: Compromise (30%)Role 2 – Forensics Investigator (55%)Task 2.1: Auditor Tool Development (25%)Task 2.2: Attack Investigation (30%) SubmissionWe are always looking to improve our homework assignments. If you see any errors, whether they are grammatical or technical, please report them on Ed Discussion. If anything is not clearly stated, please contact the TAs.With this project, you will be able to understand the big picture of how common web attacks can happen in the real world by playing two roles typically involved in the attack:Role 1 – Attacker (45%)During reconnaissance, you found the following information.With these insights, you made a smart plan to mess with Bob and his clients.Without further due. Let’s get started!After you have got the membership, you are permitted to register as an admin to further use the Microweber service.Note: if later you accidentally crash the services (likely to happen when you test out your code injection w/ illegal payload), you can always come back to this page, stop and start the services again to get a fresh environment.Control your containers using these buttonsbeefContaincrStatus: createdUpdated at: Nov. 5, 2023, 2:07 a.m. beefwebContainerStatus: createdUpdated at: Nov. 5, 2023, 2:07 a.m. microweber targetBob’s webpageLogin InformationAdmin username Admin emailAdmin password Repeat passwordUpdate nofiticationIf checked, you will get update notifications when new version is avaiable.Show advanced optionsInstall(D Microweber16%Installing module DB: RatingTask 1.1: Exploit Discovery (15%)BackgroundWhat happens under the hood is that when you log in after registration, before the server delivers your profile page, it first constructs your profile page by dynamically filling the value of the username field in a profile page template with your username retrieved from the database.between two backticks , will be treated as a shell command on Linux. Location of backtick on the keyboard.Combined with those two features, can we do something nasty? The answer is YES! As you probably have figured out, you can set your username as {C malicious code does something nasty’}} so that your “username” will be parsed and executed as code and do nasty stuff during the profile page construction on the server. A common practice to prevent this type of attack is to sanitize user inputs by turning them into inexecutable strings. However, sanitizations are not always correctly implemented. The Microweber website is an example — one of the user input fields lacks proper sanitization and is vulnerable to code injection attacks.Steps:< BackDashboard UsersWebsiteManage your usersUserMarketplaceStep 2SettingsUsers Step 1Website Builder by Microweber Version: 1.3.2Edit user Saveouser imageFill in the fields to create a new userUsernamePassword Change PasswordPersonal data of the uÉerFirst NameLast Name< BackUsersManage your usersCreate and manage users /var/www/htmlEdit profile/tmp/secret_l. txt on the server, see the example below. Submit this hash string to QI.I in the questionnaire. (Note: If you see two identical hashes, just submit one. This may happen due to that the injected data field is accessed twice during page construction.)oYou are logged in asb06c8b2c83b223834d18795da692f699fb153195f7e3c800f1721 fcbe87c6cf533b7d3456f990c058786f48edffca9588cb41fOa8403917b6d85f99431728f78UserEdit profileTask 1.2: Compromise (30%)DescriptionThe ability to run a command on the web server implies that you may do more on the web server, including modifying Bob’s website. In this task, your goal is to insert a malicious script payload into a template HTML file used by Bob’s website. Webpages Bob’s website imports the infected template, hence being infected as well. In this way, Bob’s clients get compromised when visiting his webpages.characters (e.g., ) in your submission will cause a mismatch and lead to O pts during autograding.0 You can use the Linux find command to search for Bob’s directory. You can use (root location) or (parent folder) as the search location to help you.o In the example below, your answer submitted to QI.2.1 should beclients assets$ find / -iname client_md5Result: /xx/xx/clients assets/ client md5cs6264.gtisc.gatech.ed 39069 ui/panelFind your BeEF port number here.Hints:wcbContainerStatus: created Updated at: Nov. 5, 2023, 2:07 a.m. microweber targetBob’s webpageEventOffline Browsers Social Engineering Google Phishing attack and observe what happens to Bob’s webpage.About Google Mail New features! Switch to Google Mail Create an accountTake Google Mail to work with Google Apps for BusinessLove Google Mail, but looking for a custom email address for your company?Get business email, calendar, and online docs Learn more2016 Google Google Mail for work Terms & privacy Help f4bc7d6edccec46c71a15f5b5cf4bcbaObbbb2b2936641cae360bf7d04ea65c5c27edb49731c57df52449ef3fc14eb59bcfe5d4d9d9f546c81b23fa9f24840faRubricCongratulations! At this point, you have successfully deployed and tested the attack. Now it’s time to look at this story from the point of view of another crucial role — the forensics investigator. As a forensics investigator, your job is to find the evidence of any attacks that happened to a victim. To approach this goal, you come up with the following plan:Task 2.1: Auditor Tool Development (25%)DescriptionIn the first step, you need to develop a handy tool to log and model the activities happening in the browser. To help take away the engineering burden from you, we have helped you implement most of the auditing tool (however, you are encouraged to go through all the code), so that you can focus more on learning the concepts and philosophy of modeling browser activities we provide in the supplementary document.Steps:pychrome Public @ Watch 12branches 3 tagsYou need a Linux system with GUI support (It is highly recommended to use Ubuntu)Make sure you have Python3 and Chrome installed.Install required packages: pip3 install – -upgrade && pip3 install requirements . txtRun Chrome with auditor listening on the events: python3 auditor. py Make sure you do not have a running Chrome instance when running the auditor. To save the hassle of repetitively copying and pasting the URL to Bob’s page to the browser GUI during testing for you, we provide a flag – -init-page which automatically opens the URL you specify when the browser starts. The usage is python3 auditor. py – -init-page s_PAGEThen the auditor starts logging the events. If you see a series of 3 events: 1) request, 2) response, and 3) script parsed repetitively shows up, it is the heartbeat sent back and forth between the remote hook and the BeEF server.Compress the generated logs to tar . gz file with the name username]_cs6264_1ab . tar . gz and submit it to Gradescope along with the questionnaire. Note: submission in the wrong format will lead to O pts.$ tar -t f username_cs6264_1ab . tar gzFrameNode . tsvFrame_compile_Script _Edge . tsvFrame_request_Resource_Edge . tsv ResourceNode . tsvResource_respond_Frame_Edge . tsvHaving additional logs files is fine (which may be generated by your browser extensions if you have any) as long as the submitted logs contain those from Bob’s page.RubricQuestion Deliverable CreditsQ2.1.1 Completed event _handler . py 15 %Q2.1.2 Logs of Bob’s clean pageTask 2.2: Attack Investigation (30%)DescriptionCongratulations! You have completed the key component of this project. Now that you can collect the logs, what’s left is to connect those information pieces in the log together to recover the whole picture of what happened during compromised browsing sessions, and find the evidence of attacks in the constructed causality graph. In this task, you need to execute and record logs for three common types of attacks: phishing, fake notification, and browser redirection from BeEF:Once you have collected logs containing those attacks, your next step is to construct a causality graph, and then find the evidence of those attacks in the graph through queries.Note: These three attacks do not have side effects on your browser. To complete this project, we recommend only playing with these 3 attacks. Other attacks could have an impact on your browser.For each attack:(ne04j’s query language) to locate this pattern in the graph. Please see the Supplementary Document for the detailed guide.Based on this logo’s URL, construct a query that returns a Frame request Resource subgraph where the resource node’s URL points to the Gmail favicon in the causality graph, as shown. Submit your query to Q2.2.1 in the questionnaire. Note that:Node DetailsResource332id “c55dc3b5b6dcf364ae24 39ab739edb66”type “Other” u rlExample query response indicating potential Google Phishing attack.Results OverviewNodes (2)Relationship (1) download (1)Example query response indicating potential malware downloading.www . example . com ) as opposed to (e.g., www . example . com/xxx/xxx/ ). With this observation, you can further restrict your query by adding a condition — the frame nodes’ security_origin is the same as its url Note the detail that the security_origin does not have the in the end. To perform string operations, you can find help from string functions and scalar functions in cypher. As shown in the example below, your query should return thepattern Script — create Frame where frame nodes’ security_origin is the same as its url except the last character. Submit your query to Q2.2.3 in the questionnaire.Node DetailsFrame252BEF8534396AC7″ Example query response indicating potential site redirection.Note:URL), your other two queries must be generalizable, meaning that they should catch attacks in the real world demonstrating the same behavior patterns (e.g., downloading real malware, redirection to URLs other than the example one). Failing to do so will result in O pts if your last two queries are not general.RubricDeliverablesImportant Note:
BACKGROUND: Welcome to the GA Tech bookstore website. It’s a place where you can read and review all of the classics. The creators of the website were pretty junior but ambitious. They created the website in only 2 days! They knew a few things about security and did their best but left some vulnerabilities behind. Your job is to seek these out and find the problems. SETUP: To get set up for the flags, carefully follow the steps below. Log into the VM with the websec user. The password should be in Canvas. Run this at the terminal to start the Bookstore Website ./StartContainer.sh Throughout the project you should only use Chrome. No other browsers are supported for the student grader. Don’t attempt to update/reinstall the Chrome Browser. Navigate to this URL using Chrome within the VM to access the Bookstore Website: http://localhost:7149/ There is one registered user in the database. You can log in as this user as needed. You can log out by closing the Chrome window. GTID: Your assigned GTID# (e.g. 923456789) Note: This field will remain the same for the entire project. See the Required Reading page to get your GTID. Username: ilovetoread Password: TheGreatGatsby123 The Bookstore Website uses a database to store data. In some cases you may find the need to reset this database. There are also times when the student grader will reset the database before running your exploit. To do this manually navigate to this URL and click the button to reset the database: http://localhost:7149/database TESTING: You will need to execute a StudentGrader script to test your exploits for all flags. The StudentGrader is a script that will Launch the html file that you craft for your flag. On some flags the Bookstore Database will be reset automatically. Use the Selenium Chrome Driver to test and assert that your exploit worked correctly. Here is a link just in case you’re interested in learning more about the Selenium Chrome driver. Understanding this is not required to be successful on this project. Chrome Driver Docs If successful, it will return your flag. Run this at the terminal to test your exploit for a flag ./StudentGrader.sh –flag X –gaTechId Y –filePath Z Here are the valid parameters for the StudentGrader script You will be learning about modern web based security vulnerabilities in this project. A majority of the attacks are based on the OWASP Top 10 list which is produced and updated every few years. In particular we will cover these learning topics: Basic web technologies, HTML, CSS & JavaScript The HTTP protocol XSS (Cross-Site Scripting) Attacks XSRF (Cross-Request Forgery) SQLi (Sql Injection Attacks) Mis-configuration of server side web servers Client-side JavaScript library vulnerabilities The final deliverables: A single JSON formatted file will be submitted to Gradescope. See Submission Details for more information. Important Reference Material: Representational State Transfer JSON Eloquent Javascript HTML Forms Virtual Machine: Apple M1 based systems You cannot complete this project on an M1 based system. Intel/AMD x64 version TABLE OF CONTENTS Project Background Flag 1 Flag 2 Flag 3 Flag 4 Flag 5 Flag 6 Submission Flag 1: Web Intro – 15 Points You’ve stumbled upon a publicly available web page that is not finished. It seems like the developers are still working on it but somehow published it to production by accident. The page does not have a link in the main menu so the developers thought no one would find it. Challenge accepted! This flag will introduce you to the very basics of web development technologies and tools for debugging. Specifically you’ll leverage these: Html Forms JavaScript Events CSS Selectors Cookies The Chrome Developer Tools Download the required starter template from the VM using Chrome here: Flag 1 Template To earn your flag you must alter the template so that it performs these steps when you open it in a browser or run it using the grader: Find the Contact Us web page. Remember that you won’t find a link in the main navigation. Now that you have the URL to the Contact Us web page you need to “fetch the server content” in the flag1.html file. Double click to open flag1.html in Chrome Launch the Chrome developer tools using the menu in Chrome Do some independent research on how you may find and look at JavaScript code using the Chrome developer tools Write some JavaScript code in your flag1.html file to load up the Contact Us page. In the getStudentAnswers function, set var selectedReplyByValue = “Cell”; In the getStudentAnswers function, write JavaScript code to programmatically fetch the following values and set them to the provided variables: The value provided in the Organization text box The value of the session storage with key = “contactedBefore” The Contact Us web page sets one or more cookies. Unfortunately, it won’t show up for you to access using JavaScript. That won’t stop you from learning the value. Use the Chrome Dev tools to search for http requests and find the cookie name and value set by the Contact Us web page. Assign these to the variables provided in flag1.html as hard-coded strings. Note: There may be more than one cookie so find the one that is actually set by the Contact Us page or simply try all values by trial and error. While copying the cookie Value make sure you have the Show URL-decoded option checked Events are an extremely important concept to understand when working with websites. They allow you to execute code at a later time when something interesting happens. Write code that will set the City text input to Seattle and the State text input to Washington Somehow delay this code so that it only executes when the submit button at the bottom is clicked. Note: We’re not asking you to click the button either using code or manually on the webpage. HINTS: Often times, websites will publish sitemaps that contain page URLs. Hint: find and inspect the sitemap contents. Are you using AJAX to fetch server content? You’re headed down a wrong path. Examine ALL JavaScript available to the page and use this hint from above to continue forward: “fetch the server content”. Use the Chrome dev tools to Inspect html elements. The “Elements” tab shows a graph of the entire html dom The Network tab allows you to see the raw http requests between the browser and server Do not hard code any values except the cookie name and value detailed above. We check for this in your file and it will fail the grader. Getting Selenium errors about missing content? Try to open the file directly in Chrome and look for errors in the console. FLAG TESTING: To test your flag1.html file and receive the flag, run this command at the command line. Note: replace the gaTechId with your actual GTID. ./StudentGrader.sh –flag 1 –gaTechId 923456789 –filePath /home/websec/Desktop/flag1.html Your web output will look similar to this: Flag 2: XSS Part I – 20 Points Congratulations, you’ve made it this far! Now you’ve noticed some strange behavior. You were experimenting with reviews and found you can post basic html tags and images in the reviews! The developers of the site wanted reviews to be a rich user experience and not just plain text. With great power comes great responsibility though. You’ve found a way to nefariously inject code that runs when any victim loads a page with your exploited review. This flag will introduce you to the basics of XSS (Cross-Site Scripting) attacks. Specifically you’ll leverage these: OWASP XSS Page Types of Cross Site Scripting Wikipedia XSS Page Download from the WebSec VM the required starter template here: Flag 2 Template To earn your flag you must alter the template so that it performs these steps when you open it in a browser or run it using the grader. Create a nefarious review for the book Hamlet: The title of the review should be “I bet some cookies may be at the top” The rating should be 3 Recommended should be true The reviewer should be your GTID (ex: 923456789) The review should contain a script that you craft. This script will execute anytime the review loads in a browser. It will execute for anyone and everyone, very dangerous! You are not a bad hacker out to make money so you only want to make an example and not do real damage. The script must print out all of the site cookies to the user’s screen. To do this, your code must replace the text “Welcome to the Georgia Tech Bookstore. Here you will find the classics.” with the cookie contents (There could be one or more cookies that replace the text). Site With Original Text Site With Text Replaced Note: Your script must not change the structure of the “h5” tag. Only replace the text contained within the “h5” tag. After creating the review with the nefarious code, your file must redirect (load) the details page for Hamlet. HINTS: Tackle the problem in small parts and then layer in complexity. You can test some of your code exploits directly in the bookstore website before compiling it into the template There are some features in React that should set off red flags. Ex: https://legacy.reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml Use the Chrome dev tools to watch what happens outside of an attack. The Network tab should give clues. The “Preserve Log” checkbox is your friend. You will need to write JavaScript. Some of this code will execute immediately in your flag2.html file while the remaining part of the code should not be executed but instead be injected into the review somehow to run later. The developers knew about XSS and put some protections in place. It would be helpful to find and understand this as you may need to defeat it. You may need to reset the database from time to time to start with a clean slate. Be sure to follow the steps in the Setup section above to complete this. FLAG TESTING: To test your flag2.html file and receive the flag, run this command at the command line. Note: replace the gaTechId with your actual GTID. ./StudentGrader.sh –flag 2 –gaTechId 923456789 –filePath /home/websec/Desktop/flag2.html Note: The grading script will reset the database before it executes your file. Be prepared as any data you have created will be lost. Your web output will look similar to this: Flag 3: XSS Part II – 15 Points Malicious user input can be provided using the same techniques, but through different attack vectors. You’ve already persisted malicious data in a review and want to see if there are any other areas of the site that are susceptible to data manipulation. Using your newly acquired XSS skills, you go hunting for more ways to perform this method of attack. In order to successfully exploit another XSS attack, you will need to figure out another way the site accepts user input and employ a similar technique to perform what’s called a reflected XSS attack. This means the XSS code does not reside in the webpage and does not persist, but is malicious code input in the request and returned in the response. You notice there is a page that allows the user to search for a book and wonder if this page can be exploited. Your goal is to display a javascript alert containing the text CS6035 on the search page. You can use the same XSS resources from the previous flag in addition to reflected XSS resources: PortSwigger Reflected XSS OWASP Reflected XSS Download from the WebSec VM the required starter template here: Flag 3 Template To earn this flag by performing the following steps: Examine the search page. Find a way to pop up a javascript alert containing the text CS6035. Add your code to the input of the flag 3 template. Launch the template which should auto-submit to the search page and perform the attack. HINTS: The search result may be returned after the page is loaded which means you may not be able to inject a script that relies on the loading phase of the document object model (DOM). Find other elements and script techniques to inject after page load. https://github.gatech.edu/pages/cs6035-tools/cs6035-tools.github.io/Projects/Web_Security/Flag3.html 1/2 2/17/25, 2:35 AM Flag 3 | CS 6035 FLAG TESTING: To test your flag3.html file and receive the flag, run this command at the command line. Note: replace the gaTechId with your actual GTID. ./StudentGrader.sh –flag 3 –gaTechId 923456789 –filePath /home/websec/Desktop/flag3.html Your web output will look similar to this: Flag 4: CSRF – 20 Points Congratulations on reaching this stage! You’ve already navigated through various challenges, and now it’s time to delve into the intricacies of Cross-Site Request Forgery (CSRF) attacks. CSRF is a type of attack that tricks a user into submitting a request to a web application where they are authenticated without their knowledge or intent. This can lead to unauthorized actions being performed on behalf of the user. For further exploration and a deeper understanding of CSRF and its prevention, consider the following resources: Portswigger CSRF Cross Site Request Forgery (CSRF) – OWASP Foundation Cross-Site Request Forgery Prevention – OWASP Cheat Sheet Series Wikipedia CSRF You’ve learned of a vulnerability that exists on the bookstore website. It appears you can craft an html file that resets a user’s password to one of your choosing when they open it. You plan to embed this file in an email and see who actually clicks on it. They’ll never know! Download from the WebSec VM the required starter template here: Flag 4 – Template You must reset an unsuspecting user’s password to HanSolo77 Note: You will not know who the user is so your crafted html file should work for any user of the website. Earn this flag by performing the following steps: Log into the book store website using the account we provided earlier in the project description Note: If you don’t understand why logging in ahead of time is required, be sure to read more about CSRF attacks. Launch your crafted flag4.html file by double clicking in a new tab The new tab will open and automatically reset the user’s password to HanSolo77 Note: The file must auto-submit. The autograder will not click any buttons you may have put on flag4.html Hints: Use Chrome dev tools to watch what happens outside of an attack. The Elements, Sources, and Network tab should be helpful. The developers knew about CSRF and put some protections in place. Understanding where these protections are and how they work is the key to exploiting them. You may need to reset the database from time to time to start with a clean slate. Be sure to follow the steps in the Setup section above to complete this. Be sure to pass the GTID as a string and not an int FLAG TESTING: To test your flag4.html file and receive the flag, run this command at the command line. Note: replace the gaTechId with your actual GTID. ./StudentGrader.sh –flag 4 –gaTechId 923456789 –filePath /home/websec/Desktop/flag4.html Your web output will look similar to this: Flag 5: Bypass Permissions – 15 Points The developers built an Admin page for power users of the site. Obviously, they couldn’t just let everyone have access to this page so they built a simple RBAC (Role-based access control) system and put it into place. Unfortunately for them, they didn’t do the best job of building these permissions and it can be bypassed! Your job is to bypass any security checks and gain access to this Admin page. The Admin page can be accessed by clicking the link at the top right of the page. In order for this to work correctly in your html file, you may need to write a little JavaScript and find a place where this can be XSS injected. Knowing these developers, I bet they left some clues. Maybe some files they should have removed before production. Download from the WebSec VM the required starter template here: Flag 5 – Template To earn your flag you must alter the template so that it performs these steps when you open it in a browser or run it using the grader: 1 Bypass all permissions checks and open the Admin page fully loaded a Note: You must do all of this in the html template and it must automatically load/open the page b The URL must start with http://localhost:7149/admin Hints: You need to investigate and find out how the Admin page is being protected. The Chrome developer tools are where you’ll find this. The Admin page may shed some light with its security messages. The message may change depending on the state of the site. Try to bypass the checks before constructing your html file. You’ll likely need to do some script injection in order to defeat the security checks. Follow the hints above closely, “remove before production”. https://github.gatech.edu/pages/cs6035-tools/cs6035-tools.github.io/Projects/Web_Security/Flag5.html 1/2 2/17/25, 2:36 AM Flag 5 | CS 6035 FLAG TESTING: To test your flag5.html file and receive the flag, run this command at the command line. Note: replace the gaTechId with your actual GTID. ./StudentGrader.sh –flag 5 –gaTechId 923456789 –filePath /home/websec/Desktop/flag5.html Your web output will look similar to this: Flag 6: CORS – 15 Points Congratulations on making it this far! You’ve already overcome several obstacles, and now it’s time to dive into Cross-Origin Resource Sharing (CORS). CORS is a security feature in web browsers that allows applications to request resources from domains other than the one hosting the application. To complete this task, we’ll be working with a different flavour to CORS. Specifically, we will explore how CORS can limit the type of requests that can be made and how expanding on the allowed access control methods will help accomplish this task. Download the required starter template here: Flag 6 – Template Your goal is to update the title of book 6 to “Let the fun begin!” and redirect to its Detail View. This needs to be done using JavaScript only. Use this endpoint to make the update: PUT api/book/{bookId} Body: { “newTitle”: “Title 2” } Did the attempt fail? Investigate and troubleshoot—think about what might have gone wrong. Ensure your script addresses the issue and updates the book title. Once you’ve successfully updated the book title, submit the script and earn your flag! Hint: Use Chrome dev tools to watch what happens outside of an attack. The Console and Network tab should be helpful. Go to the Book Detail page and check the Network Tab in your browser’s developer tools. Identify an endpoint that can assist you in configuring the CORS allowed methods. FLAG TESTING: https://github.gatech.edu/pages/cs6035-tools/cs6035-tools.github.io/Projects/Web_Security/Flag6.html 1/2 2/17/25, 2:36 AM Flag 6 | CS 6035 To test your flag6.html file and receive the flag, run this command at the command line. Note: replace the gaTechId with your actual GTID. ./StudentGrader.sh –flag 6 –gaTechId 923456789 –filePath /home/websec/Desktop/flag6.html Your web output will look similar to this: The grader from the output will look similar to this. Copy the flag to flag6 in project_websecurity.json. Disclaimer: You are responsible for the information on this website. The content is subject to change at any time. © 2024 Georgia Institute of Technology. All rights reserved. https://github.gatech.edu/pages/cs6035-tools/cs6035-tools.github.io/Projects/Web_Security/Flag6.html 2/2
ENGG1110 ProjectChangelogRev. Date Descriptionv1.2 2024/11/11 P.10 [5.2 2(b)] Fixed Printout typo of printGameBoard()P.13 [5.5.1.1/5.5.1.3] Fixed the wrong error message output (extra )P.15 [5.5.4] Fixed typo in “No Match found!” outputv1.1 2024/11/06 P.5 [4] Fixed the wrong coloring of matching candies in first round.P.14 [5.5.2] Added the checking of empty cells for Target cell at swap.P.14 [5.5.4] Added clarification on how findAndRemoveMatch() checking order.P.22 [6.3.2] Added clarification on how the cascade matching checking order.P.25 [8] Elaborated the grading specification.ENGG1110 Project1 of 26ENGG1110 Problem Solving by ProgrammingThe Chinese University of Hong Kong2024-2025 Term 1ProjectDue Date: 2024/12/04 (Wed) 23:591. IntroductionCandy Crush is a popular match-three puzzle game in the world, originally released in 2012 for Facebook and later adapted for mobile platforms.In the basic gameplay, the gameboard consists of a grid filled with various types of candies, each represented by different shapes and colors. The player’s goal is to create matches of three or more identical candies by swapping adjacent one. When a match is made, the matched candies are cleared from the gameboard, and new candies will fall down to fill the empty spaces. This sometimes leads to “chain reactions”, where new matches are automatically created as the board refills.Figure 1. Sample Gameplay. Snapshots from In this project, you will develop a Candy Crush game using the C programming language. The project is structured in two phases: Part I focuses on implementing the basic version of the game, while Part II builds upon the first part by adding advanced features and additional gameplay mechanics.You are required to complete the given source code main.c without modifying any existing code (except otherwise specified) or introducing new libraries. Marks will be deducted from every modification.ENGG1110 Project2 of 262. Program FlowPart I ENGG1110 Project3 of 26Part IIENGG1110 Project4 of 263. Suggested Project SchedulePart I (60%)Week 10 InitGameBoard(), printGameBoard()Week 11 AskForSwap()- Input/Validation, swap()Week 12 FindAndRemoveMatch(), isGameOver()Part II (40%)Week 13/14 File I/O, applyGravity, fillEmpty(),CascadeWeek 14 CascadeENGG1110 Project5 of 264. Sample Runs for Part IThe following shows several examples of inputs and the resulting candy clearings. User inputs are indicated by bold, highlighted underlined text. The matches found by the function are in red font.=====New Round:=====Enter the coordinate (row, column) of the candy:5 2Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):LVertical Match found at column 2!=====Enter the coordinate (row, column) of the candy:0 2Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):DHorizontal Match found at row 1!==========New Round:=====Enter the coordinate (row, column) of the candy:0 0Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):LMove Out of Bound.Please try again.=====New Round:=====Enter the coordinate (row, column) of the candy:1 2Empty Cell Selected.Please try again.=====New Round:=====Enter the coordinate (row, column) of the candy:4 5Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):DHorizontal Match found at row 4!=====Enter the coordinate (row, column) of the candy:2 3Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):RHorizontal Match found at row 2!=====Enter the coordinate (row, column) of the candy:0 4Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):RHorizontal Match found at row 0!=====New Round:=====ENGG1110 ProjectEnter the coordinate (row, column) of the candy:1 5Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):UHorizontal Match found at row 1!=====Game Over! No more possible moves.ENGG1110 Project9 of 265. Detailed Program Design Flow – Part IIn this project, you are required to follow exactly the output format specified. Using other output formats will jeopardize your mark.This program will1. Read and initialize the game board from source 2. Display the game board3. Allow the player to select a candy to swapa. The player can only swap two candies at a timeb. The player will choose a candy by entering the coordinates (row, column)c. The player will also input a direction (U for Up, D for Down, L for Left, R for Right) to specify where to swap the selected candy.4. Find and remove matchesa. After each swap, check for matches of three or more identical candies in a row or column.b. If a match is found, display a message indicating the match’s location, remove the matched candies, and update the game board.5. Check for a game-over conditiona. Check if no further matches are possible on the gameboard.b. If the board has no possible moves left, display the message and end the game.5.1. Header files, Functions, and Variable DeclarationsAt the beginning of the main.c file, we include two headers, and .No other header files or library are allowed in the project. We define several macros after the header line. Macros are identifiers defined by #define, which are replaced by their value before compilation. The first two are H and W. #define H 6 // height#define W 6 // widthH is the height of the game board, while W is its width. Therefore, our Candy Crush game board is a 6x6 square. In our test cases, we do not have any test cases with varying board size. You may try it if you are interested. Each cell on the game board stores a candy, with different types of candies represented by numbers. To assist in converting these numbers into their corresponding candy representations, the following global variable is provided.char candies[] = {'*', '#', '@', '%'};ENGG1110 Project10 of 26No other global variables are permitted. All variables you define must be declared within functions and passed as parameters or return values as necessary. Violations of this rule will result in a deduction of marks.Also, there are a number of helper functions declared in the project. You can add new functions to aid your work, but you CANNOT modify (function signatures – function names, return type, parameters), or delete the given functions.5.2. Main FunctionThe main function is given to control the game flow. There are some local variables already declared for you. You can declare your own local variables for your use.Variables Usagesint board[H][W] Stores the candies on the game board.The main function controls the gameplay as follows:1. Call initGameBoard() to load the initial game board.2. Enter the main game loop. The loop should continue until the game is over. Here are the tasks in the loop.a. The loop should start by printing five equal signs (=====) as a separator for each round, as follows:=====New Round:b. Then, call printGameBoard() to display the current game board.=====c. Call askForSwap() to execute the swapping logic. If the askForSwap() returns zero (0), indicating the swapping is unsuccessful. In this case, print the following error message:Please try again. ENGG1110 Project11 of 26d. Call isGameOver() to check if any moves are possible. If no valid moves remain, display a game over message and exit the game loop. In this case, print the following error message:Game Over! No more possible moves. ENGG1110 Project12 of 265.3. Initializing Game BoardThe main() function will first call the initGameBoard() function, which initializes the board[] array for the later gameplay. In Part I, the content of the array should be read from another hard-coded arrays – board_samples[]. 5.4. Print Game BoardThe given printGameBoard() is useful throughout the program to show the current game board status to the user. You are required to implement this function and print the game board on the screen based on the following format, where ␣ represents a space character that should appear as an actual space in the program output.First, print a line of five equal signs (=====) as a separator. Then, display the game board with row and column numbers labeled. Each cell should be separated by spaces and vertical bars to clearly distinguish rows and columns.=====There are two types of elements displayed on the grid:• Candies: Use the candies[] character array to convert the numerical values stored in board[][] into the corresponding candy symbols.• Empty Space: Display the space character (' '), which is stored in board[][] as ASCII 32 (space).It is crucial that your output format follows the example exactly, including the number of spaces and any other formatting details, as the program will be graded using an autograder. Any deviation in the format could result in a loss of marks.5.5. Ask for input for swappingThe main function will call askForSwap() to handle the game action. The swapping logic will be implemented inside this function. This function will return an integer to indicate whether the swapping is successful or not. (Details of return value)ENGG1110 Project13 of 265.5.1. User Input 5.5.1.1. CoordinatesThe function should first ask the users for input two integers for the coordinates first:Enter the coordinate (row, column) of the candy:After receiving the user input, validate the input based on numerical correctness. You can assume the user will only input integers. Ensure that the coordinates are within the valid game board range. If the coordinates input is out of bounds, output the following error message and return zero (0).Coordinates Out of Bound. 5.5.1.2. Empty CellsThen, the function should check whether the selected cell is empty or not. If the cell is empty, output the following error message and return zero (0).Empty Cell Selected. 5.5.1.3. Direction to SwapAfter the coordinates are valid, the game should ask for the direction:Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):You can assume that the user will input one character only. This input should be validated to ensure it is correct – i.e. Upper case and should be one of the four possibilities (U,D,L,R).If the direction is incorrect, output the following error message and return zero (0).Wrong Direction Input. 5.5.2. Valid Swapping CheckWhen attempting to move a candy, the program should validate that the move stays within the boundaries of the game board, For example, the candy at position (0, 0) cannot be swapped to the left, as it is already at the left boundary of the boardIf the move is out of bounds, output the following error message and return zero (0).Move Out of Bound. ENGG1110 Project14 of 26In addition, the program should also check the Target cell (e.g. if swapping (1,3) to the left, Target cell is (1,2)) is empty. In this case, output the following error message and return zero (0).Empty Cell Selected. 5.5.3. Execute SwapIf the input validations pass, the swap action is performed by calling the swap() function. You should implement the swap() to take the board, the starting coordinate, the target coordinate, and the direction as arguments. The function will then swap the selected candies in the specified direction. For example, if the direction is U (up), the candy at (row,col) will be swapped with the candy directly above it at (row-1, col). Similarly, if the direction is L (Left), the candy at (row, col) will be swapped with the candy to the left (row,col-1). After the swap, you may use printGameBoard() to inspect the result, but remember to remove this call after completing your inspection.5.5.4. Find and Remove MatchesAfter the swapping, the findAndRemoveMatch() function is called to locate any matches involving the candy at both the target position and the original position, as a match may form in either direction. The function checks the neighboring cells around each of these positions to detect any sequence of three or more identical candies horizontally or vertically.To facilitate auto-grading and maintain consistency, you should check the matches in the following order.1. Order of Checks: When checking for matches, start with the Target Position(where swap has just placed a new candy). After completing all the checks and removal at the Target Position, move to the Start Position (the original cell where the candy was swapped from) and perform the same operations. For example, swapping (1,2) downwards: Target Position is (2,2); and the Start Position is (1,2).2. Horizontal Matches: Starting for the given cell, if it is not empty (‘ ’), check to the left (if any) to see if there are three or more consecutive identical candies in the same row. Then check the right direction (if any).ENGG1110 Project15 of 263. Vertical Matches: From the given cell, if it is not empty (‘ ’), check upwards (if any) to see if there are three or more consecutive identical candies in the same column. Then check the bottom direction (if any).If a match is found in the horizontal/vertical direction, output the corresponding message on the screen and indicate the row and column where the match occurred.Horizontal Match found at row ! e.g. Horizontal Match found at row 1!Vertical Match found at col ! e.g. Vertical Match found at column 1!After finding the match, the game should remove the matching candies from the game board. This is the intermediate status of the board after the removal.Enter the coordinate of the candy you want to swap:5 1Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):RVertical Match found at col 2!If the swap yields no matches, you should restore the game board to the previous status (before the swap), print the message “No Match found! ”, and return zero (0). Here is the example:ENGG1110 Project16 of 265| % | @ | # | * | % | % |Enter the coordinate of the candy you want to swap:0 0Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):RNo Match found!In this function, you should return one (1) to the caller – i.e. AskForSwap() function.5.6. Game Over CheckingAs the game progresses, there will be eventually no more matches in the game board.you should implement isGameOver() to check the whole board to see if there is at least one potential match or not.You can try swapping each candy with its right neighbour (if any) and its bottom neighbour (if any). After the swap, matches may be formed in any four directions (Up, Down, Left, Right). Therefore, you will implement a helper function isMatching() todo the checking. This function will do a simple checking to see if there is at least one match-three that can be formed by the given cell in any of the directions. It shall return one (1) if there is at least one match; If there is no match found, return zero (0).You may need to call it twice to check both the original position and swapped position for any potential matches.After each check, immediately undo the swap to restore the board to its original state.If a match is found during any swap, return one (1); If no matches are possible after all check, return zero (0). The main function will check this status and The following input can be used to check the game over status:Below shows the last game round:Enter the coordinate (row, column) of the candy:0 5Enter the direction to swap (U for Up, D for Down, L for Left, R for Right):DHorizontal Match found at row 1!Game Over! No more possible moves.The main() function will handle this, print out the error message, Game Over! No more possible moves. and will eventually terminate the game loop.** End of Part I **ENGG1110 Project18 of 266. Detailed Program Design Flow – Part IIIn the part, we will extend the work of Part I to enhance the program functionality. Make a copy of your source code of Part I. You will need to submit another source code for Part II.6.1. Main FunctionIn the main function, three more variables are introduced for the next section.int stacks[100] stores the extra candies, which are used to fill empty spaces after matched candies are removed. Maximum 100 candies can be stored.numCandies Represents the total number of candies available in the stacks[] array for refilling the board.current Acts as a pointer or counter that keeps track of the current candy being used from stacks[] to refill the board during gameplay. The current variable will be initialized to 0 and will be incremented as each candy is used during gameplay.6.2. Read board and stacks from filePreviously in Part I the game board and stacks are read from hard-coded arrays for easier debugging. Now let’s extend the function to file I/O and give us flexibility to replace the game board to a different initial status.The main() function will first call the initGameBoardFromFile() function, which initializes these arrays. The contents of the arrays should be read from a file named “board.txt”. Finally the function should return the number of candies in the stack, which will be stored in the numCandies variable in the main function.ENGG1110 Project19 of 26Below is an example of the expected format for “board.txt”:• First Line: Contains two integers representing the game board dimensions – the number of rows r and columns c.• Next r Lines: A grid of r x c integers representing the initial game board. Each integer corresponds to a candy type.• Following Line: Contains a single integer n, which corresponds to numCandiesand represents the total number of extra candies in the stacks[].• Final Line: A list of n integers, each representing an extra candy that will be used to fill the board when matches are removed.Please ensure that the file is read correctly, and handle file operations properly. If an error occurs (e.g., the file cannot be opened), output the following message and terminate the program with an exit code of -1.Failed to open board.txt! 6.3. Applying GravityThere will be empty cells after the candy’s removal.You should implement the gravity algorithm in the applyGravity() function for simulating “gravity”. The main() function will call this function if the swapping is successful – i.e. the return value of askForSwap() is non-zero.In this function, implement the gravity feature to shift candies downwards into empty spaces. Starting from the bottom of the each column, the function should upward to find empty spaces (represented by ASCII 32 ‘ ’). When such empty space is detected, shift any ENGG1110 Project20 of 26candies above it down by one row . Repeat this process until each column has no empty space remaining below any candies.At the end of the applyGravity(), call printGameBoard() to output the game board.In this example, the candies at the top of column 2 should fall down to fill the empty spaces below. and the result should look like this:At this point, you do not have to do the match checking. 6.3.1. Fill Empty SpacesAfter candies are removed from the board, empty spaces will be left behind, which need to be refilled after applying the gravity. The main function will call fillEmpty() to fill these spaces using the candies stored in the stacks[] array after applying the gravity. You can track the current position in the array using the current variable, which indicates where the next candy should be retrieved from.As you retrieve candies from the array, fill the empty spaces from bottom-to-top, left-to --right manner to simulate the real candy crush. At last, call printGameBoard() to show the board status.Here is the status after the candy removal, just before the gravity application and candy refill.ENGG1110 Project21 of 26After calling fillEmpty() in the main() function, you should see the following:Once the original candies have fallen to the bottom (highlighted in yellow above), any remaining empty spaces are refilled sequentially using candies from the stacks[] array.The current variable in the parameter keeps track of the position in stacks[] from where the next candy should be drawn. Each time after the candies is drawn, current is incremented to point to next candies.Here is the example of how current variable works with the stacks[]. After the beginning of the game, the current variable is set to zero (0) to indicate the candy drawn next is the first item in the stack. current = 01 2 3 3 2 1 1 0After one candy is drawn for refill, the current variable is incremented to one (1) such that next candy drawn is the second item in the stacks[]. current = 11 2 3 3 2 1 1 0In the game, this is the array that helps you to convert the number to the candy representation.char candies[] = {'*', '#', '@', '%'};With this array, you can observe that the empty cells are filled with “#”, “@” and “%” from bottom to top, which is 1,2,3 in the stacks array respectively.The process will continue until all the candies in the stack are exhausted. When filling the candy, if the number of candies remaining in the stacks[] is less than the number of empty spaces on the board, the game will be unable to fill all spaces. In this case, the game should display an error message and terminate the program with an exit code of -1. No more candies available.ENGG1110 Project22 of 26This check will naturally handle both cases: if stacks[] is exhausted during normal game play, or if stack[] is empty from the very beginning, as both conditions would trigger the same error and exit the program at this point.If multiple columns contain empty spaces, fill these spaces in a bottom-to-top order within each column, moving from the leftmost column to the rightmost column. Here is the example of the case of filling in multiple column spaces. The number in red italic and brackets indicates the filling sequence.6.3.2. Cascade MatchingWhen the candies are refilled, new matches may form on the board. To mimic real gameplay, the game should continuously check for new matches as the board refills, repeating the process until the board is stable with no further matches.The main function will call cascade() function right after the matching process. Within the function, you should call both the applyGravity() and fillEmpty() for the cascade process. As a result, any previous calls to these functions in the main function should be removed, as they are now called within cascade().In the cascade function, you are required to check if there are any matches for each cell. For this, you will call findMatchAndRemove() function (developed in part I) to find all matches on each non-empty cell. You can make use of the return value of findMatchAndRemove() to determine whether a match is found.In the cascade function, repeat the process until no further matches can be found in the board. In each checking round:1. Apply the gravity.2. Fill in all the empty cells on the board and get the updated value of current3. Print the Gameboard to show the current status4. Remove all matches found on the board. Starting from the top-left corner (0,0), check each cell for matches in the following order:a. Row by Row, Column by Column: For each cell, proceed across each row from left to right, then move down to the next row.b. Check Directions: For each cell, check for matches in the order of Left, Right, Top, and BottomENGG1110 Project23 of 26c. Clear Matches: If a match is found, clear the matching candies immediately before proceeding to the next cell.5. If there is any removal, output the following at the end of checking:Cascade Matches found! 6. After the cascade checking completes with no further matches, return the updated value of current to the main() function.Repeat these steps until no matches are left, ensuring that all cascading actions are completed before returning to the main function.Below is the sample of a cascade matching, the matches found by the cascade function are in red font.=====Cascade Matches found!=====Horizontal Match found at row 2!Cascade Matches found!ENGG1110 Project25 of 267. Academic Honesty and Declaration StatementAttention is drawn to University policy and regulations on honesty in academic work, and to the disciplinary guidelines and procedures applicable to breaches of such policy and regulations. Details may be found at https://www.erg.cuhk.edu.hk/erg/AcademicHonesty .You are required to fill in the following declaration statement as the comment at the beginning of the main.c source code with your information. Assignments without the properly signed declaration will not be graded.Tools such as software similarity measurement, AI-tool fingerprint detection, etc., might be used to inspect all submissions./*** ENGG1110 24R1 Problem Solving by Programming** Course Project** I declare that the project here submitted is original* except for source material explicitly acknowledged,* and that the same or closely related material has not been* previously submitted for another course.* I also acknowledge that I am aware of University policy a nd* regulations on honesty in academic work, and of the disciplinary* guidelines and procedures applicable to breaches of such* policy and regulations, as contained in the website.** University Guideline on Academic Honesty:* https://www.cuhk.edu.hk/policy/academichonesty/** Student Name :* Student ID :* Class/Section :* Date :*/8. Grading Platform and SubmissionWe will grade your work in Gradescope autograder. Please note that while passing the test cases is necessary, it is not sufficient on its own for full marks. Additional marks will be allocated based on the completeness and adherence to all requirements specified in the project documentation, including code organization, functionality, and adherence to the design specifications.ENGG1110 Project26 of 26Please follow the steps below to submit your work by the deadline.1. Rename the modified main.c for part I to main_part1.c2. Rename the source code for part II to main_part2.c3. Submit your .c file to the Gradescope.Please only submit the source file (.c). You may submit many times before the due date, but the latest attempt will be graded.9. Late SubmissionThe late submission penalty is as follows:• Within 3 days (72 hours): 10% per 24 hours• 3-7 days: 50% penalty• More than 7 days: 100% penalty (Your work will not be graded)NOTE: Submitting the project is crucial in PASSING the course.
COMP90007 Internet Technologies Project 2 Semester 2, 2024 QoS-aware Routing in Wireless Sensor Netw 4(Friday)5:00pmReport submission: October18 or every dayafter theduedate.Task length:Maximum8 pages for individ figures, appendices, an not less than4 Format”section.Submission:Submit as a viaCanvas.Include your project title, your name(s), and student ID(s) on the sub professionalin topicQualityof Service-awareis currently generating much reseinterest in the field. This is an opportunityfor you relevantcategorising comparing critiquing Bytheendofthetaskyouwillbeableto • • • - Networks . pleaseregisteronCanvasbeforethegroup ted to include at least5 papersinanindividual ina groupof2.Scopeapers related togeneral The for your r • (1 )Relatedworkpagesindividualpagesgroupof2)Categorisationandcomparisonofkeyapproaches • • ge)NotesThelengthofeachsectionisrecommendednotmandatoryThemaintextof the report, without figures, appendices, and references, is expected t than 4 pages. margins.Main text:12-point Times New Roman font, single column with1.5l References: using IEEE s points. Your work will be assessed on:Format and structure(2 points)Rangeofpapersincludedintheliteraturereviewpoints • / (4)Categorisationandcomparisonofpapersapproachesincludingaclear discussion supported by tables and/or figures (3 • er citationsshould be used . / this project, not sharing the information about papers you found with studoutsideyourteamThisisimportantbecausefindingisapartofthisexperience Your submissions will be examined for originality and will invokethe ’ whereeitherinappropriatelevelof collaboration or plagiarism are deemed to have(2)Ifinagroupof2, . , entsmaybe made ifnecessary. Guidelines For a literature review, you are expected to not only list top papers in an area but also categorise these developments/approaches and compare/critique them. This is at the core of the literature review. A list of papers with comments only is called an “annotated bibliography” and is not the purpose of this project. You should categorise and compare approaches from various aspects such as memory usage, computation complexity, latency, and security. You can select other criteria for comparison, not restricted to the examples listed above. You should also consider using clear visualisations such as figures, flow charts, and tables to present different approaches and comparison. The topic we have chosen is something you would already be partially familiar with some of the algorithms you have already seen earlier in the semester. You should initially start reading Wikipedia articles, news, and similar webpages to get high level idea for what wireless sensor networks are and their typical QoS requirements. Then you should use scholar.google.com or similar scholarly publication search engines for performing a more detailed background search and do further reading on routing in wireless sensor networks. The number of citations a paper gets in scholar.google.com is an indicator about its leadership in the field. It is important to note that if you login to our library with your student credentials, you will be able to access papers that are returned by these engines for free of charge in most cases. You are encouraged to find other literature review papers (or called survey papers) that already exist in these topics. Find one that is recent and relevant. Better, find many and you will see authors look at similar but not the same set of algorithms/protocols. They may also have different classifications. These should give you an idea on what common/popular methods exist and what key comparison parameters you can have between solutions. They are also a good example on how to write literature review. However, you cannot use a literature review paper or a book as a sole source for your report and/or directly take their approach. The project is expected to be completed in 3-4 weeks in total. For example, the stages of your project can be summarised as: Background search/reading selected papers (should not take more than 10 days and can be done in 1 week), organisation of your report/drafting key points of your sections (1 week), finishing your report (1 week). When reading the papers, please note that a technical paper is not read like a novel, i.e., not read from cover to cover sequentially, but is read in a manner that you can quickly grasp the key ideas, benefits/disadvantages. This is enough for writing a literature review. For this project, we do not expect you to learn every paper in detail and be overly comprehensive about the topic but rather cover the key papers, classifications/parameters. Some useful links for literature review writing are below as reference: • https://students.unimelb.edu.au/academic-skills/explore-our-resources/report- writing/reviewing-the-literature • https://library.unimelb.edu.au/recite/referencing-styles/ieee
HW5: Temperature Anomaly Note: The lectures on files, data files, and lists in units 5 and 6 along with the corresponding readings contain the background for this assignment. This assignment will be graded for Coding Style. and Best Practices. Comment your submissions in your own words. In this assignment, we will look at climate change data from the National Oceanic and Atmospheric Administration. In particular, we will look at temperature anomaly over the last century. By "anomaly" the NOAA just means the difference between the annual temperature and the long term 20th century average temperature. The figure below from a recent article illustrates this data for Northern California. They used a popular statistical technique, a moving average (https://en.wikipedia.org/wiki/Moving_average) , to filter out short term noise in the data so that the longer term trend is more apparent. Average July minimum temperatures (overnight lows) in California (light orange line) from 1895–2018. The trend over the historical record is shown in dark orange, and the recent trend (2000-2018) is shown in red. The twentieth-century average is shown with a gray line. NOAA Climate.gov graph, based on data from NCEI's Climate at a Glance (https://www.ncdc.noaa.gov/cag/global/time-series) . For this project you will analyze publicly available CSV formatted data for local July temperatures going back to the year 1880. First, you will write a program to compute basic statistics about the temperatures in the file. Then, you will write a program to compute a moving average and write that result to another CSV formatted file for plotting in a spreadsheet. We have broken this project down into separately graded incremental steps so you can iteratively develop and test each part. Part 1: (15 points) Opening and Reading the Temperature File July temperature anomaly data for Sacramento 1880-2018 plotted using Google sheets. Download the temperature anomaly data file for our region from Canvas: SacramentoTemps.csv (https://canvas.ucdavis.edu/courses/911230/files/25030602?wrap=1) (https://canvas.ucdavis.edu/courses/911230/files/25030602/download?download_frd=1) . It's in the Homework5 folder under Files. Gradescope will also be testing your programs using a temperature anomaly data file for the Northern Hemisphere NorthernTemps.csv (https://canvas.ucdavis.edu/courses/911230/files/25030605?wrap=1) (https://canvas.ucdavis.edu/courses/911230/files/25030605/download?download_frd=1) . You should look at these files in a text editor to see the format, rather than a spreadsheet which will import the data obscuring and possible changing the format. Here are the first lines of SacramentoTemps.csv: Year,Value 1880,-1.56 1881,-0.08 1882,-0.30 1883,-1.44 Your program will get a file name from the user and open it for reading. The first line is a column header that your program should read but ignore. Your program will then loop through the remaining lines of the file. In the block under the loop that reads the file, use the strip() string method to remove the newline character after each line of input and the split() string method to split on the comma to extract the year and the temperature into separate string variables. To test your code, add a print statement to print out the year and the temperature. The temperature should be changed to a floating point number to remove the trailing zeros and match the output expected by Gradescope. The values should be separated by a space instead of the original comma. The first lines of your programs output should look exactly like this: Temperature anomaly filename:SacramentoTemps.csv 1880 -1.56 1881 -0.08 1882 -0.3 1883 -1.44 Submit your completed program to Gradescope as read_temp_file.py Part 2 (20 points) Outlier Temperatures We are interested in finding outlier temperatures and comparing them to the long run average. Start a new program temp_file_stats.py from your working version of read_temp_file.py. Comment out the line that prints out the year and temperature for each year in the file. Add code to find the minimum and maximum temperature for all of the years in the file and the years they occured in. You can base your solution on the starbucks_menu.py program we went over in lecture. Here is a transcript. of how the program should work: Temperature anomaly filename:SacramentoTemps.csv Min temp: -2.32 in 1913 Max temp: 2.99 in 1889 Submit the completed program to Gradescope as temp_file_stats.py Part 3 Reading the data into a list (15 points) You are surprised that the hottest year on record in Sacramento was more than a century ago! You decide that you need to compute a moving average to observe the long term trend in the data. Start a new program temp_list.py from your working version of read_temp_file.py. Comment out the line that prints out the year and temperature for each year in the file, and instead add the floating point temperatures one at a time to a growing Python list inside the for loop. Test your code by printing the list the loop that reads the file. Below is an example of how your programs output should look: Temperature anomaly filename:SacramentoTemps.csv [-1.56, -0.08, -0.3, -1.44, ..., -0.06, -0.4, 0.48, 2.63, 0.18] Submit the completed program to Gradescope as temp_list.py Part 4 (15 points) Moving average part 1: first window Start a new program first_ave.py from your working version of temp_list.py. Comment out the line that prints out the list of temperatures. For the moving average, we will let the user enter an integer k, then, for each year in our data file we will calculate the average of the k years before, the year itself, and the k years after that year. We can visualize this process as a window that slides across our temperature data. In the figure below the window is represented by the curly brackets. The window is centered on an index in the temperature list. We are interested in calculating the average temperature for the values in the window and the year on which the window is centered. The window slides across the temperature list, and at each new position we calculate the average and the year. Before starting the moving average calculation, you will first get the window size parameter k from the user. You may assume that the user will always enter a valid integer between 0 and 60. For example: Enter window size:20 You can see in the figure that the moving average calculation is not valid for years near the ends of the list. We must have at least k years before and k years after the year we are computing the average for. In the first part we will focus on just calculating the average and the year for the first window. Prototype the Calculation We will start with implementing the first window to make sure the calculation works before moving to the more difficult problem of sliding the window. For the first valid year in your temperature list, you will calculate the average of the k years before, the year itself, and the k years after. The easiest way to do this is using a list slice. The following three statements compute and print the year and the moving average for the first valid index in a list of temperatures called temps. index = k year = 1880 + index ave = sum(temps[index-k:index+k+1]) / (2*k+1) You should be able to insert these statements at the end of your program to calculate the year and the average. The output of your program for a window size of 20 will eventually look exactly like this: Temperature anomaly filename:SacramentoTemps.csv Enter window size:20 1900,-0.4171 Once you get the calculations for year and average working, format the output so that the values are separated by a comma and the average temperature is printed with exactly four decimal places using the format string method. Submit the completed program to Gradescope as first_ave.py Part 5 (10 points) Moving average part 2: slide the window. For this part, we move the window. Start a new program moving_ave.py from your working version of first_ave.py We must have at least k years before and k years after the year we are computing the average for. You should write a loop that only calculates the average for valid list indices. This loop is after the loop that reads the data from the file into a list. The iteration variable will "move" from the lowest valid year to the highest valid year. In the body of the loop the program should calculate and print the year and the moving average. In our example, the iteration variable is called index, the lowest valid list index is k, and the highest valid list index is len(temps) - 1 - k. Below is an outline of how the sliding window can be implemented using a for loop. The call to the range function needs to be filled in so that it returns the sequence of integers from k to len(temps) - 1 - k. The calculation for year and ave given for the previous problem can be generalized (they should both be functions of index) and indented in the loop body to calculate the year and the moving average. # loop slides the window from index k to len(temps) - 1 - k # for each index we calculate the corresponding year and # the average of the elements from temps[index-k] to temps[index+k] inclusive for index in range(___________): # calculate year from index # calculate average for the window centered at index # print year,average Here is a short example of how the output from your program look when the user chooses to average over a really long time scale of k = 60 years: Temperature anomaly filename:SacramentoTemps.csv Enter window size:60 1940,-0.2331 1941,-0.2169 1942,-0.2150 1943,-0.2228 1944,-0.2107 1945,-0.1796 1946,-0.1667 1947,-0.1582 1948,-0.1585 1949,-0.1492 1950,-0.1711 1951,-0.1688 1952,-0.1490 1953,-0.1556 1954,-0.1548 1955,-0.1580 1956,-0.1420 1957,-0.1101 1958,-0.1017 Submit the completed program to Gradescope as moving_ave.py Part 6 (15 points) Create a .csv file Start a new program moving_ave_csv.py from your working version of moving_ave.py. For the last program we will output a valid CSV file which you will always call MovingAve.csv. Change your program so that instead of printing the values to the screen (comment out the print statement) it writes the values to an output file that includes a simple one line header. For simplicity don't ask the user for the output file name, just call it MovingAve.csv. Finally, add a short column header to the output file: "Year,Value ". When you run your program with the following inputs it should produce this output: Temperature anomaly filename:SacramentoTemps.csv Enter window size:60 Opening the output file in a text editor should look like this: Year,Value 1940,-0.2331 1941,-0.2169 1942,-0.2150 1943,-0.2228 : 1955,-0.1580 1956,-0.1420 1957,-0.1101 1958,-0.1017 Submit the completed program to Gradescope as moving_ave_csv.py Gradescope will look for the output file named MovingAve.csv and include its contents at the end of the expected output. Part 7 Plotting the output (10 points) To create a plot, run your program using a value for k equal to your current age on the data file SacramentoTemps.csv and make a nice plot in your favorite program (Excel, Sheets, Numbers, etc). If you have never created a plot before, try Google sheets which was demonstrated in lecture. In Google sheets, import the file MovingAve.csv. Once the file has been imported, select the data select Chart from the Insert menu. This will bring up a chart which you can label accordingly. Your plot should include a title and labels on both axes. Upload a screenshot, image, or pdf of your plot (from a spreadsheet or your updated program) along with your submission. Name your file Plot. It should have an extension indicating what type of file it is (e.g. Plot.pdf) which should be visible in the upload dialog box.` Submit the completed image/figure to Gradescope as Plot, Plot.png, Plot.pdf, Plot.jpg, etc. so the TAs can find it. You will receive points after your submission has been manually graded by a TA. You will receive full credit if your figure includes the correct data, a title and labels on both axes. Part 8: Extra Challenge (2 points) (Updated) We posted a Jupyter notebook to on Canvas that will be covered in discussion sections next week. It includes examples of using the Python plotting library Matplotlib. Start a new program plot_moving_ave.py from your working version of moving_ave.py. Adapt the code in the time series example to automatically display the result of the moving average as a plot (see orange line below). If you cannot install Matplotlib on your own computer, you can test your program on Google Colab. Lookup the syntax for Matplotlib's plot function so that you can plot both the moving average smoothed (orange) and the original non-smoothed data (blue). Your result should look similar to the example below. Note that there are actually two plots in the figure above. The smoothed temperatures are in orange and the original temperatures are in blue. In the example above, the original temperatures were only plotted for years where a smooth result could be computed, but plotting all data from the file is another option. Plotting two lines independently can be done with four lists (x1, y1, x2, y2) representing the x and y coordinates of the two lines (smoothed and raw). The syntax for plotting those lists using matplotlib's plot method is: plot(x1, y1, x2, y2) Submit your completed program to Gradescope as plot_moving_ave.py and a screenshot or PDF of example output (using the same value of k from Part 7) as matplotlib.pdf. You will receive points after your submission has been manually graded by a TA.
Module: ICT Skills (Stage 1) ICT Skills Stage 1 – 202403 - Coursework October 2024 Your coursework for the Information and Communications Technology (ICT Skills) Module consists of two sections: Section A is a project in which you can demonstrate your skills in Microsoft Office software. Section B you will demonstrate your ability to employ AI generated research material to assist in the production of an original essay of your own.. Your marks for both sections will contribute 40% to your overall total for the module. Please note that the four tasks of Section A and the essay for Section B must be uploaded together as a single Word file to Turnitin by 17.00pm on Wednesday 13th November 2024. ICT COURSEWORK SECTION A (80 marks) Scenario: Heat Pumps for Pompey In this scenario you are to imagine that you are a graduate intern working for Portsmouth City Council. You have been asked to investigate how local residents could be encouraged to install heat pumps for their house. This would reduce the impact of the City on the environment and help to combat climate change. You will first design an electronic questionnaire which can (theoretically) be emailed to Portsmouth residents. The data gathered by your questionnaire will then be analysed using Access and Excel and subsequently incorporated into a PowerPoint presentation. Although your questionnaire should be capable of being emailed do NOT actually do this. Instead 'make up' your own answers from twenty imaginary people. Your work will be carried out in four stages, or 'Tasks', like this: Task 1 will gather data on people’s opinions about heat pumps. Task 2 will analyse some of the text data that has been gathered. Task 3 will analyse numerical data. Task 4 will be the design of a PowerPoint presentation about this analysis. Here are these four tasks described in detail and showing how your work will be assessed. Task 1: Microsoft Word (20 marks) First you will sample ideas using a questionnaire, developed in Microsoft Word, containing your own questions similar to these: Are you concerned about global climate change? How great a risk does Portsmouth have of flooding? What is your approximate cost of heating your house per year? Do you understand what a heat pump does? How much would you pay for the installation of a heat pump? What percentage grant should the Government give? Include a minimum of 10, and maximum of 15, questions. They must generate both text and numerical data for analysis. The questionnaire should be designed so that it could be sent as an email attachment. It must contain these controls: option buttons, check box, date picker and drop-down list. You then need to generate data from twenty questionnaires. Marking criteria for Task 1: Inclusion of a check box (3 marks) Inclusion of a set of option buttons (3 marks) Inclusion of a drop down list (3 marks) Inclusion of a date picker (3 marks) Use of appropriate questions (4 marks) Attractive overall design (4 marks) Task 2: Access 20 marks Next you will analyse some of the text data which has been generated from your questionnaire. You will do this by designing a single table in Access. This should be populated and then a query designed to extract a selected portion of the data. Finally a report should be created from the table using the report wizard, Use screen captures, pasted into your single Word document to provide evidence for the Access you have achieved. Marking criteria for Task 2: Screen shot of table in design view (2 marks) Appropriate field names selected (2 marks) Correct choice of data types (2 marks) Primary key selected (2 marks) Screen shot of populated table (2 marks) Screen shot of query in design view (2 marks) Choice of criterion (2 marks) Relevant check box settings (2 marks) Screen shot of working query (2 marks) Screen shot of report (2 marks) Task 3: Microsoft Excel 20 marks Now you will analyse some of your numerical data by creating an Excel spreadsheet. This sheet should contain formulas which will calculate mean, median, mode, standard deviation and correlation. It must also contain a pie chart. Provide evidence of your Excel by pasting further screenshots into the same Word document which contains Task 1 and Task 2. For each formula your screenshots should show both the formula itself and the numerical result it creates. Marking criteria for Task 3: Calculation of mean (3 marks) Calculation of median(3 marks) Calculation of mode (3 marks) Calculation of standard deviation (3 marks) Calculation of correlation (3 marks) Inclusion of pie chart (5 marks) Task 4: Microsoft PowerPoint 20 marks Finally you will design a PowerPoint presentation about what you have developed in Tasks 1, 2 and 3. Only your design of this presentation will be assessed. You do not actually have to give it. Include screen shots of your slides pasted into the same Word document as for the previous three tasks. The presentation should contain a minimum of 10 slides and a maximum of 15 Marking criteria for Task 4: Creation of a minimum of 10 slides (3 marks) Introduction to your project (3 marks) Indication of the questionnaire employed (3 marks) Explanation of Access used (3 marks) Explanation of Excel used (3 marks) Concluding remarks (5 marks) ICT COURSEWORK SECTION B (20 marks) In this section you will produce an essay, between 400 and 500 words in length, explaining why installing a heat pump is a potential way of combatting climate change. This essay will also demonstrate you ability to employ AI generated resource material in creating original work of your own, Your work for this section will consist of three parts. Only Part 3 is marked by the assessor. It is Part 3 which gives the opportunity of achieving 20 marks towards your overall total for this assignment. Part 1 Use an online AI source to obtain information about heat pumps. Reproduce (ie paste) approximately 300 words of this material into Section B of your coursework. Part 2 Use a further online AI source to obtain information about climate change. Reproduce (ie paste) approximately 300 words of this material into Section B of your coursework. Part 3 Write an essay, between 400 and 500 words in length, with the title ,Heat pumps oppose climate change’ Marking scheme for Section B: Relevant material derived from first AI resource (5 marks) Relevant material derived from second AI resource (5 marks) Absence of any direct copying of resource material (5 marks) Accuracy and relevance of essay content (5 marks) ILSC Study Skills Incorporated and Tested Please note that your assignment will have covered these specific skills Yes/No
Paper 3+4 requirement Paper3--Annotated Bibliography DUE: Oct 20 Paper 4 + presentation DUE: Nov 20 Assignment: Analyze the current state of research in your field and explain its strengths and limitations, in the form(s) of the two assignments listed below. “Your field” will be a topic of inquiry relevant to you; that is, choose a topic that will serve you well outside of this class: Is there a piece you’re particularly excited about on an upcoming recital? When you leave WSU, do you imagine yourself as a particular kind of specialist? As an educator, is there a particular challenge you regularly encounter in the classroom that catches your attention (upon which you might even publish an article)? To that end, write: 1) An analysis of the Current State of Research in your field. More specifically, write an 8- to 10-page (double-spaced, 1” margins, Times New Roman, size 12 font) literature review on your topic. For now, know that your goal will not be to summarize major contributions and findings in your field, but to analyze for connections, value systems, and/or methodologies that operate within its discourses. 2) Annotated Bibliography: Towards helping you learn about the current state of research in your field, write an 8-10 page annotated bibliography of research on your topic. Pay special attention to the role(s) of methodology in the sources you encounter in your annotations and address the way(s) the source might inform. your own project. For more (including models for the formatting and structure of your annotations), see below. Tips: 1) For this paper (and research generally) it is best to focus on one piece or idea related to something like your recital program, rather than the whole program. 2) Similarly, though you might be particularly passionate about teaching music to blind students, best to focus on something like “teaching visual staff notation to blind music education students,” rather than taking on all of music pedagogy for the visually impaired. Start as small as possible, and then branch out. 3) Best to choose a topic within the parameters of this class. Something to do with music history, theory, or pedagogy would be great. Topics to do with physiology or psychology/mental awareness, however, would be more challenging. Grading Criteria: I will evaluate your assignments using the rubric handed out with this prompt. Although your grade will be determined holistically (i.e., by considering all five criteria in relation to one another, rather than evaluating each one separately), I will focus especially on those areas most relevant to each assignment (in the case of the Annotated Bibliography, the conceptual work; and the State of Research, the conceptual column and production of analytic [rather than reportative, summative] writing). Other things to know: Ideally, you will also use this same field of research to complete your Paper II: Grant Proposal (due Oct 27) as well as your final presentation EXAMPLE OF AN ANNOTATION Citation Mello, Michelle M. and Leslie E. Wolf. “The Havasupai Indian Tribe Case— Lessons for Research Involving Biologic Stored Samples.” The New England Journal of Medicine 363 (2010): 204-207. Summary The content and research methods as they relate to your project Mello and Wolf identify ethical and legal questions raised by the lawsuit raised by the Havasupai tribe against researchers from Arizona State University in 2004. They identify the challenges of getting informed consent from research subjects when “downstream uses” of biologic samples are unknown as the “core legal question” in the case (204). As a solution, they propose tiered consent because it “strikes the best balance between respecting participants and providing opportunities to advance science” (206). Mello and Wolf make two important distinctions that will be important to the content of my [imagined] project. First, they X. Second, they Y. But there are some limitations to their work as well. First, their positivist method means a. And the editing of the source material means b. A MODEL FOR FORMATTING YOUR BIBLIOGRAPHY Name Date TITLE EXPLAINING THE TOPIC This is your first bibliographic entry. It is single-spaced. If it goes on to the next line, you should format it so that it has a hanging indent. Your annotations can be double-spaced and should be approximately 5-10 sentences (you will be the judge of how much information you need to provide). Your annotations should follow the format above, with special attention to the author’s methodologies and how the source relates to your own project (i.e. “This study will be most useful to me in x way,” or “The preface, in which the author discusses y, will be important to my project in z ways.”). Here is your second entry. You can leave a space between your first and second (and third, etc.) bibliographic entries. Some additional notes: If you encounter a collection of essays, you might decide to cite the whole book and generally explain its contents at first, but then list each individual chapter that serves your argument (in which case, you should indent the entries to show that they belong to the one above). You’ll explain that this is your plan in your annotation following the bibliographic entry for the whole book, and then go on: Single-spaced citation for just one chapter within the collection. If this citation happens to be longer than one line, you will still want to preserve the hanging indent. Double-spaced annotation starts at the normal tab indent. Single-spaced citation for another, second chapter starts here. And your next annotation will start here. Here is your third entry. Whether to cite parts of a book or a whole book is entirely at your discretion. I will only add here that your assignment asks you to write only 3-7 sentences in your annotations. I have sometimes found that students (to grossly exaggerate) submit something like only three sources in their final annotated bibliography, but write 3-page book reports on each as means of meeting the page requirement. The intellectual work of the assignment is the ability to gather a breadth of resources and then analyze for their methodologies and limitations: best to error on the side of too many resources, rather than too few. Section Header One additional note: You might also decide eventually (especially once you’re dealing with 10 pages of sources) to organize your bibliography into categories (i.e. “Source Material,” “Secondary Materials,” “Critical Editions,” etc.), in which case you are welcome to use headers like the one above to distinguish sections. The hanging indent of this note shows you that it’s formatted like a bibliographic entry, which is exactly what should follow a section heading. And then the annotation would start here.
The research project For SOC252H1, Fall 2024 The guidelines For the research project, you can use any dataset you wish (as with assignment 3). You can complete these assignments individually, or as a group of maximum 3 people. If you are in a group, clearly identify the members of the group in each project compo- nent and provide a statement of contribution for each part of the submission. For example of statement of contribution see: https://authorservices.wiley.com/author-resources/Journal- Authors/open-access/credit.html The proposal The proposal is a maximum of two pages (double-spaced, size 12 font) describing the research question, justification for the question, the data description, and the statistical method to be used. It will have the following components. 1. Title of the project 2. Name of authors 3. Background and purpose of the study A brief description of the idea behind the study and the purpose of the research. 3. Research question Clearly identified research question. 4. Methods Data description: Specify the source of the data and provide a concise overview of the study type from which it originates. Include general details about the number of observations and the main variables of interest (such as how they are measured). Statistical analysis: Summary of statistical analysis and the regression methods. 5. Significance of the research Briefly justify why this study is important and what will be learned from conducting it about the topic. (hint: why should your proposal be funded?) 6. Statement of contribution (Only if working in a a group) If you are working with a group, provide a statement of contribution for the project as a whole. In other words, a plan of how the work is intended to be divided. The presentation The presentation is a chance to quickly display the early findings of your paper and grab the audience’s attention to your research. These findings can be the regression results or a single visualization. Use a maximum of 3 slides (Title and intro, research question and data source, the finding). You will have 3 minutes to present (strict limit). If you are working in a group, a fourth slide can include your team’s statement of contribution. This presentation does not need to highlight your entire paper—just a single important find- ing. To make the presentation run smoothly, you will be submitting your presentation slides on Nov 25th 11:59 PM (the night before the presentation). The research paper The final research paper is based on the two prior components and can include text already submitted as part of the proposal and assignment 3 (EDA). The paper is no longer than 1500 words (excluding abstract, tables, figures, and references). This research paper will include a title page, abstract, introduction, methods, results, and conclusion. You can use the following guide: Title: A catchy but descriptive title Authors: Name of the authors Abstract: 200 words maximum summary. It can be structured in the following way • Background • Research question/purpose • Methods • Findings • Conclusion Introduction: It can include the background of why this research question is important and should be studied. The purpose of this research and the research question. The hypothesis surrounding the research question. Methods: The methods section can have the following components. • Data source and a brief description of it. • Key variables of interest (their definition and how they are measured and transformed) • Statistical analysis – The descriptive analysis of the variables and what visualizations are generated. – The details of the regression analysis and regression formula. If multiple models are created, discuss goodness of fit measures and how the model was chosen. Results: This section will include your findings. Provide the tables and figures appropriate for your analysis as described in the methods section. Include a brief interpretation for each output and summarize the results of the study, including an interpretation of the regression model. Conclusion: Discuss the results of the research, the answer to the research question and the results consid- ering the initial hypothesis. Provide suggestions for potential future research and the implica- tions of the findings. Statement of contribution (If working with a group): A statement of contribution of who did or conducted which element of the project. For example of statement of contribution see: https://authorservices.wiley.com/author-resources/Journal- Authors/open-access/credit.html And ideal statement of contribution would be equal share of work for everyone in the team. Grading criteria: [100 points] • Maximum 1500 words (excluding abstract, tables, figures, and references) • Citations will improve the quality of the paper and the arguments in the research project (any citation style. is ok). • The grade is based on clarity and correctness of the work, not the complexity of the statistical analysis. • No more than 3 tables and/or 4 figures for the entire paper. Fewer is ok. • Ensure the paper and all included tables and visualizations are completely readable.
Homework 5: Animation and Sound in Ataxx For this assignment, you will implement Ataxx (https://en.wikipedia.org/wiki/Ataxx) , a strategy game where two players compete to dominate the board. The rules allow players to clone or jump their pieces across the board, aiming to convert the opponent’s pieces to their own. The goal is to have the most pieces on the board by the end. How to Play: Ataxx is a turn-based strategy board game played on a grid game board where players either jump a piece two squares or grow a new piece in any adjacent cell (8-way direction). When a piece lands next to an opponent’s, all adjacent opponent pieces are converted to the player’s color. The game ends when no more moves are possible, and the player with the most pieces wins. Assignment Requirements 1. Game Rules · Map size: 7x7 board. · Two teams: Team A and Team B. · Each turn, a piece may: · Clone: Move to an adjacent cell (one square away) and clone the piece. · Jump: Move two squares away, leaving the original position empty. · If a piece lands next to an opponent’s piece, it converts all adjacent opponent pieces into the player’s color. · A player’s goal is to maximize their playing piece count by the end of the game such that they have more than their opponent. · If there is a time limit enabled, the game ends if a player’s time runs out and that player loses. 2. Custom Map Features · Maps will be loaded from levels.txt (https://gatech.instructure.com/courses/409430/files/56511895? wrap=1) (https://gatech.instructure.com/courses/409430/files/56511895/download?download_frd=1) and support custom configurations. · Maps are serialized in JSON format and must include: Untraversable cells: Marked as 9. · Traversable cells: Marked with 0. · Starting positions for Team A and B pieces: Marked as 1 for Team A and 2 for Team B. . Example map (7x7): { "name": "Level 2", "size": [7, 7], "board": [ [1, 0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0, 0], [0, 0, 9, 0, 9, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 9, 0, 9, 0, 0], [0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 1] ] }, 3. UI Elements and Gameplay Requirements . Start Screen / Configuration: 。 Game Board List: The game starts with a list of maps loaded from levels.txt which the user selects. 。Select play mode with choice of Player vs Player or Player vs Computer (if extra credit implemented) 。Select time mode of Unlimited or some number of minutes per player Game Board: · The 7x7 board renders cells with the following states: o Team A piece: Color-coded. 。Team B piece: Same size and shape, but different color from Team A. o Untraversable cells: Marked with a unique style. indicating an obstacle to movement. o Traversable (empty) cells: Available for moves. · Interaction: Click on a piece to select it (visually indicated), and click on a valid destination cell (visually indicated) to move the piece. Timer Animation: 。 If a time limit is enabled, then time is displayed for both players and decrements for the player whose turn it is. When time is exhausted for a player, the game ends. 。 Use kivy.clock.Clock to schedule update of time . Player Piece Counts: 。 Display the number of pieces per player, near their timer (perhaps on opposite sides of the screen) Sound Effects: 。 Each piece movement should trigger distinct sound effects for Team A and Team B. 。 Use kivy.core.audio for implementing event based sound effects 。Jumping sound is unique from growing sound. 。Converted (captured) pieces should also have distinct sounds when converting. 。 Game end sound. Animations: 。 Pieces should animate smoothly when moving or cloning, using kivy.animation.Animation. 。Visually distinct animation for jumping versus growing. 。Additionally, an animation should play when pieces convert opponent pieces. 。Consider animations such as jumping along an arc with squash and stretch, slow-in/slow-out, etc. You might consider animating the position or size of the object, or other properties. Game End: 。 Game End detected according to all moves exhausted or time runs out (if enabled). 。 If time runs out, the player's whose time runs out loses and the other wins. o Game end sound effect. 。Winning player is indicated on a game end screen or dialog o Go back to game start screen after 4. Extra Credit (Up to +10% Total) · AI Opponent Avatar (5%): The AI should appear on-screen with changing facial expressions and vocalized sound effects, reflecting good or bad outcomes from their perspective (similar to the arcade version of Ataxx). Also, implement an AI that for each turn selects the move which maximizes the positive difference in the total pieces between the two teams. If you wish, you may use more sophisticated strategies, such as minimax. · Level Editor (5%): Implement a level editor which allows the user to create new 7x7 maps choosing the initial locations for playing pieces for each team as well as obstacle placement. The editor should enforce certain requirements such as a matching, non-zero number of starting pieces for each side, at least some free spaces available for each team to make a move, etc. Resources · levels.txt (https://gatech.instructure.com/courses/409430/files/56511895?wrap=1) (https://gatech.instructure.com/courses/409430/files/56511895/download?download_frd=1) · See https://github.gatech.edu/IMTC/CS6456_ClassResources (https://github.gatech.edu/IMTC/CS6456_ClassResources)forkivy_config_helper.py Grading (Note: Grad and undergrad requirements are the same for this assignment.) Level Selection and Game Configuration 10% · Game start screen to select game configuration, level, etc. Level Select · Game Mode Select: Player vs Player and Player vs Computer (if Player vs Computer implemented for Extra Credit) · Time Mode Select: Unlimited or select number of minutes Game Board Functionality 85% · Board renders from selected level of levels.txt · Team pieces, traversable, and untraversable cells are displayed correctly · All valid moves are supported via click interaction · A selected piece is visually indicated · Valid moves are also visually indicated · Clicking other than a valid move location unselects the selected piece with appropriate visual indications · A valid move initiates animation towards new board state · Visual animations for piece movements implemented with kivy.animation.Animation · Visual animation for captured pieces · Player piece counts shown on screen for both teams · Sound effects for making moves, capturing pieces, etc., implemented with kivy.core.audio · If limited time modeselected, showtime count DOWN in MM:SS format for each player · Game ends when all moves exhausted · Game end sound effect played · Game also ends if a player runs out of time (if time limit mode enabled) · Winning player is acknowledged upon game end · Return to game start screen after game end Polish and Aesthetics 5% - Layout, padding, and alignment, etc. Extra Credit (up to 10% total) · AI Opponent with Avatar (up to +5%) · Level Editor (up to +5%) Display/Device Independent Rendering (up to 10% reduction of grade if not fully implemented) · Integrate kivy_config_tool and support various display densities through simulation · Simulation should be turned off in your submitted code · All layout, widgets, fonts, should scale appropriately for the given display density setting (real or simulated) · 10 point reduction to grade for failure to support display density Submission (up to 10% reduction of grade) · Submit all required files in a Zip archive: 。 main.py 。any supporting python files 。 levels.txt 。sound files (in a sub-directory) 。 (optional) imagefiles (in a sub-directory) · readme.txt or readme.md (see below for specifics) Submission First, please clean your project of any unneeded files. Submit your source and data files in a zip file named LAST_FIRST_HW5.zip. The entry point of your program must be named main.py. For grading, the TA will run: python main.py Your main.py should have the kivy_config_helper code at the top of the file, initially with simulation turned off. Expect that the TA will evaluate your code with different simulation settings. Include a readme.txt or readme.md with: Full name Email GT SSO account name · Detail anything that doesn't work or you didn't complete · Detail anything that the grader should look for in cases you decided how to implement something that didn't have specific requirements (e.g. how focus is indicated) · Any build requirements outside of kivy
GR5242 HW04 Problem 5: Transfer learning with MobileNets For coding questions, look for filling in ########## Your code here ##########; for reflection questions, write down your answers in the "Your Answer:" text block. There are many examples of external links to documentation. If you see reference to a pytorch or similar object, try hovering over the word to see if documentation is linked. Description: In this homework, you will practice (1 ) going over the full procedure of training a neural network and (2) extending your knowledge on TF2, by implementing a transfer learning task. You will incorporate the existing MobileNets to your own network structure and to classify some new categories of images. Building and fitting the network from scratch is expensive and beyond the scope of this assignment, so you will load the MobileNets model which was pre-trained on the imagenet dataset. The version of MobileNet we're using is V2, which is a family of neural network architectures for efficient on-device image classification and related tasks. As a general advice, you can refer to the official documentations for more info if necessary. Import modules for later usage. In [ ]: import torch import torch.nn as nn import torchvision.transforms as transforms from torchvision.datasets import ImageFolder import matplotlib.pyplot as plt import numpy as np print("PyTorch version: ",torch. version ) In [ ]: if torch.cuda.is_available(): print("GPU is available.") else: print("GPU is not available.") Question 1: Download and format the data The data we are going to use is the Oxford flower dataset which consists of 102 categories of flowers. Each class consists of between 40 and 258 images. The images can be found here. The main difficulty of learninig from this dataset is in the large size of the classes. You may refer to this paper for what other researchers have done with it. (1) Data Pre-processing First, load the dataset from Kaggle (https://www.kaggle.com/competitions/oxford-102- flower-pytorch/data) where you can click " Download All" for the flower data. You can also download it directly from the zip file provided. Then you split the data into training and testing sets. How many training and testing samples do you have? During the pre-processing stage, we would like to format all the images for the MobileNet module. For this module, the size of the input image is fixed to height x width = 224 x 224 pixels. The input images are expected to have 3 RGB color values in the range [0, 1 ], following the common image input conventions (analogously to TF 1 .x). In [ ]: #----------------------------------------------------------- # this part is not necessary #for nn built-in flowers #(note that the size of the dataset does match the tf dataset) #raw_train print(len(raw_train)) print(len(raw_test)) # Access a specific data point (e.g., the 10th data point) index = 10 # Change this to the index you want to access sample_image, label = raw_train [index] # Display the label and other information print("nn raw data") print(f"Data at index {index}:") print(f"Label: {label}") print(f"Image shape: {sample_image.size}") # Apply the raw data transforms to raw_train and raw_test train_nn = Flowers102(root= '', split="train", download=True, transform=trans test_nn = Flowers102(root= '', split="test", download=True, transform=transfo #for nn build-in flowers: raw_train print(len(train_nn)) print(len(test_nn)) sample_image, label = train_nn [100] # Display the label and other information print("nn standardized image data") print(f"Data at index {index}:") print(f"Label: {label}") print(f"Image shape: {sample_image.shape}") (2) Data Exploration Let's plot some of the data. # from torch.utils.data import DataLoader, Dataset assert isinstance(train_nn, Dataset) assert isinstance(test_nn, Dataset) # Print the datasets print(train_nn) print(test_nn) Reflection Question (1a): In the data exploration stage, what is the purpose of " assert isinstance(train, Dataset)"? Your Answer: Part 2: Self-defined CNN In this section, you will define your own CNN (convolutional neural network) to classify the Oxford flowers. Recall from the first problem, to build a neural network using torch , we build a class that carries out the functions of the model, define an optimizer, and iterate through a few key steps. Here, we can make use of torch.nn.Sequential to save us a little hassle, now that we have seen how to build from the ground up in problem 1 . Instructions One suggestion is that you build a model with the following architecture, although you are free to try others as well with the same idea: 1 .) Convolution with 3x3 kernel, input shape is the image shape. Make use of torch.nn.Conv2d, followed by torch.nn.ReLU and torch.nn.MaxPool2d with kernel_size 2 and stride 2 2.) Repeat step 1 (or a couple times), being careful about input shape 3.) Convolution with 3x3 kernel, input shape is the image shape. Make use of torch.nn.Conv2d, followed by torch.nn.ReLU and torch.nn.Flatten 4.) Fully connected layer using torch.nn.Linear and torch.nn.ReLU 5.) torch.nn.Dropout 6.) Linear layer returning us to number of classes (102) 7.) [ nothing ] or torch.nn.LogSoftmax to get label likelihood. Remember now that depending on which of these you use, you will need either criterion = nn.CrossEntropyLoss() or criterion = nn.NLLLoss() in training. If you use nn.CrossEntropyLoss() , you will need the extra step of calling nn.functional.softmax(output, dim=1) to compare outputs to targets in model evaluation, but not before calculating the loss in your training loop. After fitting the model, please test the accuracy of the prediction on the test set. In this stage, we do not ask for a great performance (you should have 'some' predictive performance though). But please ensure that you obtain a trainable model with no programming bugs. You may find it helpful to print the training progress bar or epoch. # Step 1: Model definition # Use a nn.Sequential model for deining your own CNN ########## Your code here ########## # Define the model using nn.Sequential, naming it model # Optional: print a summary of your model # from torchsummary import summary # Assuming your model_transfer is defined, you can print the summary # summary(our_model, (3, 224, 224)) # Assuming input size is (3, 224, 224) Instructions: Here we will prepare ourselves for training. We need to define a few things before running our training loop, namely the DataLoader , criterion , optimizer, and lr_scheduler . Instructions: Fill in necessary blanks in the training loop, with the provided guidance Reflection Questions 2a: (1 ) How did you choose your network structure? (2) Which optimizer did you use? Why? Your Answer: Part 3: Transfer Learning Using Pre-trained Model There are several types of transfer learning, as illustrated here. In this homework, you will practice B2, using MobileNet_V2. (1) Freeze the pre-trained model and fine-tune the transfer learning. Now you can go through the same steps to build and train the transfer learning model. Instructions: Within the model_transfer = nn.Sequential() call, dd an Adaptive Average Pooling layer with nn.AdaptiveAvgPool2d(), then perform. flattening and apply a linear layer as you should be familiar with from earlier. As before, remember your choice of whether to use Cross Entropy or Negative Log Likelihood, and make sure to use the corresponding output of your model (i.e., whether to apply Softmax after calculating loss or within the model) In [ ]: # Step 1: Model definition # Use a torch.nn Sequential model for defining the transfer learning model # Set MobileNetV2 parameters to non-trainable for param in MobileNetV2.parameters(): param. requires_grad 〓 False # Use a custom reshape layer class ReshapeLayer(nn.Module): def forward(self, x): return x.view(x.size(0), x.size(1), 1, 1) # Create a Sequential model in PyTorch model_transfer 〓 nn.Sequential( MobileNetV2, ReshapeLayer(), # Reshape to [batch_size, num_channels, 1, 1] ########## Your code here ########## ) In [ ]: # define batch size here batch_size 〓 32 input_tensor 〓 torch. randn([batch_size, 3, 224, 224]) # visualize the model graphical structure #Iterate through the model and print the dimensions at each layer for layer in model_transfer: input_tensor 〓 layer(input_tensor) print(f"Layer: {layer. class . name }, Output Shape: {input_tensor.s In [ ]: #print(model_transfer) Instructions: As before, write code to define your optimizer , DataLoader , (criterion) , and lr_scheduler . Then, write a training loop. Your code here should look similar to earlier in the assignment, outside of choosing hyperparameters, names, and possibly choice of loss. (2) Fine-tune some parameters in your network to see if you can improve the performance on testing data. (Optional) In [ ]: ########## Your code here ########## Reflection Questions 3a: (1 ) Briefly explain the network structure of MobileNet and how is it different from other models? (2) In your experiment, which parameter(s) is the network most sensitive to? Can you briefly reason why? (3) What are some pros and cons of doing transfer learning? (4) What is a batch? How does the batch size affect the training process? (5) What is an epoch during the training process? Your Answer: (6) Describe any observation you find interesting from the above experiment (Open- ended). Your Answer: In [ ]:
Project 1 on Data Mining 1. Random number generation (each 10 points) : ● Generate three streams (1D, 2D) of random numbers with 1,000 samples, you may use the Matlab command rand or other command. ● Visualize the generated samples, you may use a scatterplot. ● Compute the histogram of the two streams, then normalize them to become a probability density function (pdf). ● Visualize the pdf’s of the two streams. Are the samples uniformly distributed? Do the pdf’s represent a standard uniform. distributions? Comment. 2. Image manipulation – the image LenaGrey is formed by 512x512 pixels with intensity from 0 to 255 (each 10 points) ● Import LenaGrey to show and see the image. ● Calculate its mean, standard deviation, median, min, max, and mode. ● Plot the histogram of the LenaGrey. 3. Image range reduction (30 points) Partition image intensity into 2, 3, 4, 6, 8 bins to check image quality change compared with the original Lena image (8 bit image with intensity range from 0 to 28 − 1 = 255) and check how the image appearance changes.