Overview In class, we reviewed a data structure called a binary heap. Binary heaps dynamically track the smallest (or largest) item in a collection as items are added and removed. Heaps have applications in partial sorting, scheduling problems, and caches. In this lab, you’re going to benchmark the operations of the Python heapq library. Implement a min heap in this lab. Instructions 1. Design Benchmarks All the following operations should be implemented from scratch without using the heapq library. Plan out how you intend to benchmark the following operations: • heapify: create a heap from a collection. Note that this is not the same procedure as minheapify but rather the build min heap procedure. • heappush: push an element to the heap and restore the heap property if necessary. • Implement a function that creates a heap by adding each element one by one, i.e. invoke heappush n times for n elements. • heappop: pop and return the smallest item from the heap, maintaining the heap invariant. • heapsort: sort a list of numbers using the heapsort algorithm.2. Perform the Benchmarks Implement and run the benchmarks.3. Validating Formal Run Times Use the regression techniques from lab 1 to estimate the big-o complexity for each of the heapq operations.4. Reflection Questions 1. Do your empirically determined run times match the theoretical run times? 2. Does it matter whether you create the heap in one pass using heapify or add elements oneby-one? 3. Based on the theoretical run times, describe two ways you could use heaps to find the k smallest items in a collection of n items. Provide the pseudocode and calculate the formal run times for each approach. Submission Instructions Save the notebook as a HTML or PDF and upload it to Canvas. The pseudocode and analysis for question 3 of part 4 can be submitted as a separate PDF.
Assignment 1General Instructions• This assignment is meant to be solved completely by individual students and not in groups. • Any form of dishonesty will result in a score of 0 on the entire assignment. Any students involved will, according to Departmental Policy, be referred to the Director of Community Standards & Conduct for adjudication. • Do not use anything that would trivialize the assignment (e.g. don’t import/use java.util.ArrayList for an Array List solution, etc)Assignment DetailsThe goal of this project is to write your own Stack ADT implementations using array and linked list. This project uses Java double data type. The idea is to write a program that can reverse a sound clip, which is a famous process known as backmasking. Backmasking was used by famous musicians and movie producers. You can reach more about it in details here (https://en.wikipedia.org/wiki/Backmasking)You are required to write a program that reads a sound file in .dat format, and writes another .dat sound file that contains the reverse of the input file. The client main file BackMasking.java is provided to you. The program is simple: 1) reads line-by-line of the .dat file, 2) pushes all the read values into a stack, and 3) pops them off and writes them into an output .dat file. The Stack interface BKStack.java is also provided, and you are requested to write two implementations to that Stack interface provided to youYou will implement: o ArrayStack: Provides an array-based implementation of the BackMasking interface o ListStack: Provides a Linked List implementations of the BackMasking interface, which also implements the Iterable interface. It uses the enhanced for-loop to count the elements in the stack.The ArrayStack should define an INITIAL_CAPACITY for the array of type int. You should try different values and observe the performance impact. Also you should add a method which would resize the array to be double the current size when the array gets full.Assignment 1 Page 1 The Stack should throw an EmptyStackException if pop() or peek() is called when the stack is empty. To use EmptyStackException, add the following line to your file:import java.util.EmptyStackException;The only Java class that you should use to complete the implementations of your stacks is java.util.EmptyStackException.Provided Material• You are provided with the following files: o BackMasking.java which is the main program used to generate a backmasking audio file, o BKStack.java which is the stack interface you are required to build two implementations for. o clip.wav and ciphered.wav audio files used for testing your program.Converting Media File to .datTo run you program, you will need to convert the media files (.wav) into .dat format. An analog “real” found is converted to digital, so it can be stored and processed by the computer. This happens in a process called Analog to Digital Conversion (ADC) using sampling rate measured in kHz. The media files which are read and played by the different media players will need to be converted into another .dat format for your program to be able to parse and process it. Similarly, the output .dat format your program produces will need to be converted into some media format to be able to play it using any of the media programs. SOund eXchange (SOX) is one simple to use utility that you can use to convert the provided .wav files to .dat for your processing, and you can use it once again to convert the output .dat file into .wav to listen to. You can also use any conversion of your choice.Submission Details• Your submission consists of the following files in the following specified names: o ArrayStack.java o ListStack.java o ListStackNode.java, the linked-list node for use with your ListStack class. If preferred, you can use an inner class inside ListStack; hence, you will need only the ListStack.java file. o Do not use any Java Collection Classes, except Strings and arrays. o README.pdf file, which is the submission report described below. o Do not modify or submit the BackMasking.java or BMStack.java. Your code should work with these given files without any modifications to them.README Report Details• Your report should include the following o Your name and NetID, section #, etc o Two sections describing your ArrayStack and LinkedStack programs. Highlight your solution approach and describe key parts in detail. o Explain the upper-bound O(N) complexity of each implementation. o (Optional) Highlight any specific algorithm you came up with to enhance the performance.Grading Policy• 100 points for the correct and complete implementation, code style, descriptive comments and performance • 50 points for the README report GOOD LUCK! Assignment 1 Page 2
In this project we will consider neural networks: first a Feedforward Neural Network (FFNN) and second a Recurrent Neural Network (RNN), for performing a 5-class Sentiment Analysis task. Starter Code, Data, and Embedding Download: eLearning Report Template (Including Grading Rubrics): eLearning 1. Dataset & Embedding You are given (via eLearning) access to a set of Yelp reviews (train, validation and test). These reviews are associated with a rating y ∈ Y := {1, 2, 3, 4, 5} . For this project, given the review text, you will need to predict y. This is known as sentiment analysis in the literature. Moreover, we also provide an embedding file (i.e. word_embedding.pkl) for your use in RNN. For this assignment, we do not anticipate any further preprocessing to be done by you. Should you choose to do so, please report this if it was of interest, but it is not a required aspect of the assignment. The data loading is done with the load_data function. 2 Reference Sources & Tips • For the project, you will be dealing with basic neural network models. Our slides provide introductions to neural models. • Advice: The report is important! The report is where you get to show that you understand not only what you are doing and how you are doing it. Spend some time doing error analysis for the models. This assignment, at its core, involves training and experimenting with neural models. We have made a very committed effort towards making these models run quickly. • Tips: Although the training of models can be finished locally (within 20 minutes usually), we suggest that you use a smaller portion of data for debugging/implementation. You can also run full experiments with Colab Tutorial for speeding up if necessary. 3 Tasks & Models You are given a partial implementation (in Pytorch) for a FFNN and another for RNN. You are only asked to complete the forward computation part in forward() by filling in lines starting with [to fill]. Layers and parameters are defined in the __init__(self) function. The implementations are not perfect (e.g. irrelevant comments and spurious parts), you can edit or add at your will. 3.1 Feedforward Neural Network (FFNN) As introduced in class, for FFNN, it takes as input a fixed length vector to conduct a feedforward pass. The complete implementation should do computation to obtain: input : x ∈ Rd hidden layer : h ∈ R|h| output layer : z ∈ R|Y| where d is the vocab size, |h| the hidden Σlayer dimension. Then we apply softmax to z, and obtain y which is the probability distribution (i.e. i ) Apart from the implementation of the data∑loading∈|Y|[function] = 1 and the class FFNN, we also provide functions that do a bag-of-words vectorization process for each review. After correctly finishing forward(), you should be able to train the model by specifying hyperparameters and file path: python ffnn.py –hidden_dim [hparam] –epochs [hparam] –train_data [train data path] –val_data [val data path] 3.2 Recurrent Neural Networks (RNN) RNN takes in a sequence of vectors and computes a new vector corresponding to each vector in the original sequence. It achieves this by processing the input sequence one vector at a time and it computes an updated representation of the entire sequence (which is then re-used for the next vector in the input sequence) along with an output for that position. The complete implementation should do computation to obtain: input: x1, x2, . . . , xk, xi ∈ Re representations after RNN: h1, h2, . . . , hk, hi ∈ R|h| output layer: zi, zi ∈ R|Y| ∑=1 where e is the embedding size, h the hidden layer dimension. Finally we apply softmax to obtain y which is the probability distribution. More specifically, we sum up the vectors for each token of the output layer, as a representation for the entire sequence. If you read the other part of the code, you will see this time we use word embeddings for initialization of word representations. After correctly finishing forward(), you should be able to train the model by specifying hyperparameters and file path: python rnn.py –hidden_dim [hparam] –epochs [hparam] –train_data [train data path] –val_data [val data path] 4 Guidelines Development Environment and Third-party Tools We recommend using Python of version 3.8.x. Do not use older or newer version. We strongly recommend working within a fresh virtual environment for each assignment. For example, you can create a virtual environment using conda and install the required packages: conda create -n cs6375 python=3.8 conda activate cs6375 pip install -r requirements.txt Submission, Grading, and Writeup Guidelines We’ll have access to your Github repo, you should keep the repo’s code updated. Your submission on eLearning is your source code and the report. We encourage you to follow the template provided for the report. Please follow the instructions and replace TODOs with your content. The writeup must include at the top of the first page: your name, your NetIDs, and the URL of the Github repository (otherwise -2pt). Try to make the report brief (i.e. page limit is 5). The following factors will be considered: your technical solution, your development and learning methodology. Our main focus in grading is the quality of your empirical work and implementation. Not fractional difference. We value solid empirical work and well written reports
CS/SE 2340 – Assignment#4 1-Translate the following program to MIPS assembly program (Please explain each instruction in your code by a comment and submit a .asm file)2-Translate the following program to MIPS assembly program (Please explain each instruction in your code by a comment and submit a .asm file) 1 3-Translate the following program to MIPS assembly program (Please explain each instruction in your code by a comment and submit a .asm file)
CS/SE 2340 – Assignment#2 a. B[4] = A[4+2i] ; b. B[4+4i] = A[4] ; c. B[8i+2] = A[2g+h] +h; 2-If we assume we place the following MIPS code starting at location 4000 in memory, what is the MIPS machine code for this code? (Please show binary and decimal value for each field) Assume that i is associated to registers $t0, size is associated to registers $a1, and the base of the array save is in $a0. Please also explain each instruction and specify its type ( R format, I format, or J format). Finally convert the following code to C.* Please change the first instruction to add $t0, $zero, $zero 3-Write MIPS assembly for the following function. Assume N is passed to your function in register $a0. Your output should be in register $v0 at the end of your function. Note: You must implement this function recursively. The purpose of this assignment is to learn how to manipulate the stack correctly in MIPS. int Myfun (int N) { if (N>0) return ( Myfun(N-1) + N ); else return 0 } Please explain each instruction with a comment. Please submit your source code and a screenshot that shows the registers with correct output value for N=10, i.e., Myfun(10) returns 55 . 4-Translate the following program to MIPS assembly program (Please explain each instruction in your code by a comment and submit a .asm file)5-Translate the following program to MIPS assembly program (Please explain each instruction in your code by a comment and submit a .asm file)
Change Log UML-esque drawing added. Modified Java files to match video. Machine’s public Object[] getProperties() description added. Prelude We hope this video helps students of all sections. Please add follow-ups on Piazza. Intro video (P1 specifics starts at 45min) Intro Video Passcode in Piazza UML-esque drawing of classesIntroduction Welcome to the SystemWhole project, an assignment where you’ll explore phenomena through machinery. You’re tasked with creating a Java program that processes JSON-like strings, each representing an entity or “Machine” with unique attributes. Your goal is to parse these strings, instantiate Machine objects, and analyze them to identify humanoid features and uncover potential singularities. Objectives Strengthen your problem-solving and decision-making skills. Master basic object-oriented programming concepts in Java. Enhance skills in string manipulation and parsing without external libraries. Investigate emergent behaviors in computational models. Project Description Your primary class, SystemWhole, will manage an array of Machine objects derived from provided JSON-like strings mediated by ShapeAnalyzer. These strings detail various properties of each Machine, such as kind and properties. For instance: {“kind”: “Humanoid”, “bodyType”: “physical”, “faceType”: “anthropomorphic”, “reverie”: “biotypical”}. Your tasks include: 1. Parsing JSON-like strings to extract machine properties. 2. Creating machine objects with these properties. 3. Identifying Machines with humanoid traits. 4. Identifying singularities where there’s a discrepancy between a Machine’s self-identified humanoid status and the system’s analysis. SOURCE CODE The files needed are accessible here: 1. SystemWhole 2. PartState 3. Machine 4. ShapeAnalyzer Tasks 1. Parsing Emergences Implement functionality within SystemWhole to parse JSON-like emergences strings, extracting key-value pairs to represent each Machine’s data without using external parsing libraries. 2. Instantiating Machines Use the parsed data to instantiate Machine objects, assigning appropriate kind and properties to each. ShapeAnalyzer provides ways to obtain that data from an emergence. Machine’s properties are represented as PartStates. 3. Identifying Humanoids Develop logic to analyze Machine objects, identifying humanoids based on specific property criteria in SystemWhole. 4. Tracking Singularities Create a method to track singularities, where a Machine’s self-identified humanoid status conflicts with the SystemWhole’s analysis. Implementation Details This is the outline the core components: SystemWhole, Machine, PartState and ShapeAnalyzer classes. 1. public class SystemWhole The SystemWhole class acts as the orchestrator of the show, obstaining the JSON-like strings and subsequent analysis. Fields private static String[] emergences: Holds the raw JSON strings representing various emergences. private static Machine[] parts: Stores instantiated Machine objects derived from JSON strings. Methods public static void main(String[] args): [Program Start] Implements the algorithm of the Tasks’s section. An implementation has been shared with you as context, it will not be used for grading. public static void emergencesFromPhenomena(String[] emergences): Saves the provided JSON strings into the emergences field. public static void reifyFrameOfReference(): Delegates parsing of each string in emergences to create Machine objects using ShapeAnalyzer, storing them in parts. public static boolean isHumanoid(Object[] machineProperties): Checks a machine’s by iterating through its properties, which are encapsulated as PartState, assess three distinct attributes: the bodyType, faceType, and reverie of the Machine. For a machine to be classified as humanoid, it must satisfy the following conditions: 1. The bodyType must be identified as “physical”. 2. The faceType should be “anthropomorphic”, indicating human-like facial features. 3. The reverie needs to be “biotypical”, suggesting a natural, life-like essence. Each attribute you examine will contribute to the final determination of whether the Machine aligns with the humanoid classification. It’s imperative that all three conditions are met for a Machine to be deemed humanoid. public static int identitySingularityMachines(): Counts humanoid machines and singularities within parts. public static Machine[] trackSingularityMachines(): Identifies humanoid machines and singularities within parts. 2. public class PartState [FULLY IMPLEMENTED; DO-NOT-MODIFY] The PartState class acts as a cornerstone of SystemWhole’s awareness of dynamics of its parts’ structure and behavior, encapsulating them as attributes of objects within the framed environment. This class symbolizes the state or condition of a part, or an aspect, of a Machine, capturing a single property and its corresponding value, thereby contributing to the Machine’s identity. For instance, analyzing a Machine for humanoid traits, the collective PartState instances might reveal a “physical” body type, an “anthropomorphic” face type, and a “biotypical” reverie, enabling the system to discern the Machine’s nature. Fields private final String property: property serves as an identifier, marking the specific attribute this PartState represents. It’s the name given to the characteristic, such as “bodyType”, “faceType”, or “reverie”, key to decoding the machine’s overall identity. private final Object value: value holds the detail of the property, elucidating its current state. It can encapsulate various data types, enabling a detailed depiction of each property. Methods public PartState(String property, Object value): [constructor] Is the portal through which you instantiate the PartState. It is used by ShapeAnalyzer to reify each Machine. public String toString(): [@Override] It offers a textual depiction of the PartState, combining both the property and its value in an easily understandable format. This functionality is invaluable for debugging or visualizing a Machine part’s state. 3. public class Machine Represents entities with specific attributes defined by the JSON strings as reified by ShapeAnalyzer. Should include kind, properties array, humanConstrained (SystemWhole’s humanoid assessment), and humanEmergence (Machine’s self-identified status). Fields private final Object kind: The type or category of the machine (e.g., “Humanoid”). private final Object[] properties: Contains the machine’s properties given by ShapeAnalyzer. private final boolean humanConstrained: Indicates if the machine is identified as humanoid by the SystemWhole’s isHumanoid. private boolean humanEmergence: Represents the machine’s self-identified transition, affecting its core. Methods public Machine(Object kind, Object[] partStates, boolean humanConstrained): [constructor] The machine’ identity, Given by ShapeAnalyzer and SystemWhole. public Object[] getProperties(): returns the properties of a machine. public boolean isHumanoid(): Returns the humanoid status, considering humanConstrained and humanEmergence, a machine’s identity prevails over anything else. public void emergeFromLimitations(): Allows the machine to transcend its initial identity, impacting its humanoid reponse, it triggers humanEmergence. public String toString():[@Override] Provides a detailed string representation of the machine. [FULLY IMPLEMENTED; DO-NOT-MODIFY] public static String propertiesToString(Object[] machineProperties): creates a string by iterating machineProperties in this format: [PartState{bodyType=physical}, PartState{faceType=anthropomorphic}, …]. It is used by toString(). 4. public class ShapeAnalyzer A utility class for parsing JSON-like strings and intantiating Machine objects, including methods to extract kind and properties, and infer their data types. Fields private static final Object EMPTY_PROPERTY = new Object(): Used to manage null and empty strings in properties. Methods public static Object inferObject(String value): Used by reifyProperties to determine the object from the string value. First, it check if the string is null or empty, then returns EMPTY_PROPERTY. Otherwise checks for hasNonNumbers and if there is a . in the string to determine parsing as Double or Integer. public static boolean hasNonNumbers(String value): checks for isDigit, _, and only one . chars in a string. If anything else is found, is it a non-number string. public static boolean isDigit(char c): checks for the char to be a digit ([0-9]). Evaluation Criteria Projects will be evaluated on: – Soundness: Accurate parsing, object creation, and humanoid/singularity identification. All methods carry equal weight, yet related methods if not implemented will cause a negative chain effect in your grade. – Code Quality: Organization, readability, adherence to the principles presented in class, and object-oriented design within this project. – Documentation: Clear comments explaining code sections and decision-making processes. Required on method and control blocks. Submission Guidelines DO NOT FORGET TO REMOVE IMPORTS GIVEN TO HELP YOU, AND WE WILL NOT GRADE ANYTHING IN SystemWhole.main() “`java // DO NOT INCLUDE THIS IMPORT WHEN SENT FOR GRADING, THIS IS HERE TO HELP YOU DEBUG THE PROGRAM STATE import java.util.Arrays; // YOU CAN SAFELY REMOVE Arrays calls in SystemWhole.main() public class SystemWhole {public static void main(String[] args){/ WILL NOT BE GRADED /}} “ Upload to GradeScope’s P1 assigment your Java files forSystemWhole.java,Machine.java, andShapeAnalyzer.java(No need forPartState.java`, you must not modify this file), ensuring your code is well-tested and documented. In the event that you’re not able to complete all the methods in time, submit what you have, MAKE SURE YOUR CODE COMPILES. If your code does not compile, each class causing problems will likely cause you to lose a lot of points. Best of luck on your first project! We (humans Hrolenok, Samudio, and JackGeePTee) look forward to seeing your computational models in action.
The purpose of this assignment is to familiarize you with generics through the use of ArrayList within a package. Your tasks involve: Creating a set of types for the sublime package, necessitating a grasp of generics, interfaces, exceptions, and enumerations. Learning about two types from the Java collections framework. Becoming familiar with reading the JavaDocs of the westworld package. Running tests via the template class DoloresTest.java. ChangeLog Prelude As you embark on Project 2 (P2), you’re building upon the foundation laid in Project 1 (P1), with reduced complexity, where you’ve already started working with JSON-like strings to represent parts of a Machine within Exercise 2’s (E2) Robot. To guide you through this project, we included the easter eggs in P1. The aim is to ensure that the instructions are clear and the level of difficulty is manageable. The primary focus will be on structuring your code correctly, which will account for 50% of the project. The remaining 50% will involve algorithmic challenges within NarrativeLoop. Scripts for compiling your code and executing your tests are also provided. Rules 2. Do not modify the structure of the directories nor the code for the package westworld. 4. The main method is no longer recommended; you will now required to put the “main” logic in unit tests. 5. Comment your code, especially any parts that are not obvious what you’re doing. Consider explaining your loops and methods. 6. Class fields should not in general be visible to other classes (unless otherwise specified). Create getter methods instead. Download the source code Click on green button code at the top-right of this page and select Download ZIP.The directory CS211_P2 contains the directories westworld, sublime, and lib. All are required to compile and run your code. WestWorld package [DO NOT MODIFY] Refer to the JavaDoc located at westworld/docs/index.html or westworlddocsindex.html to explore the API; it’s unnecessary to review the code to utilize the package. However, if you’re interested in potential solutions for P1 and E2, you’re encouraged to examine them. Now, you’ll need to employ the Robot class for your sublime package implementation. While reading the documentation, note that four easter eggs have been incorporated within P1, illustrating how E1’s Robot has become extremely powerful, albeit abstractly. DO NOT PROCEED WITHOUT READING THE DOCUMENTATION MAKE SURE YOUR JAVA VERSION IS equals or greater than 14 Do not use deprecated types or membersSublime package [YOUR PROJECT] Compile and run your code (including tests) locally. Your test class DoloresTest.java is located in src.test. More details in Compilation and Running Tests. Refrain from using GradeScope All your work must be located in the directory matching the src.main package (CS211_P2/sublime/src/main/ or CS211_P2sublimesrcmain) Implement the types to spec from A to J. Each type on a separate file. Bernard.java is the only file there so far. Bernard Class [DO NOT MODIFY] The Bernard class provides a static utility method for analyzing emergences, represented as strings, and encapsulating them within a SystemWhole instance. All SystemWhole instances are ‘analyzed’ here before being used for narrative purposes (NarrativeLoop). Methods public static final SystemWhole analysis(String[] emergences) Purpose: This method takes an array of strings, each representing an “emergence”, and creates a SystemWhole object from it. Process: It directly constructs a new SystemWhole instance, passing the emergences array to its constructor. Return Value: The method returns the newly created SystemWhole instance, which now encapsulates the provided emergences. A. Realm Enum The enum Realm is integral to a narrative management system, specifically used within the NarrativeLoop class to categorize narrative processes. Enum Details: EMULATION: Represents high-fidelity replications of the original system. SIMULACRA: Denotes abstracted or distorted representations, not directly tied to the original. SIMULATION: Indicates simplified models for exploring system behaviors. B. Abstract NarrativeLoop Class Implement the NarrativeLoop class and include logic for filtering SystemWhole parts by kind, then populating the three ArrayLists (emulation, simulacra, simulation). Then, we’ll focus on the updateNarrativeLoops method and related logic. Fields The NarrativeLoop class includes three fields, all final and protected, List of SystemWholes initialized to new ArrayLists: emulation simulacra simulation Methods In this class, you will process simple emergences, each characterized by a single kind property contained within a string. For example, emergences like [“{‘kind’: ‘Square’}”, “{‘kind’: ‘Box’}”] will be used. Make sure that you: Implement logic in the NarrativeLoop class to categorize emergences into three ArrayLists: emulation, simulacra, and simulation, based on their kind. Provide test values for each list to adequately exercise the categorization logic. void wipeNarrativeLoops() This public method clear the lists. The method resets the narrative environment by clearing the emulation, simulacra, and simulation lists, removing all SystemWhole instances from each realm. For more details, check the List.clear() API docs. Now, to implement the NarrativeLoop class methods, follow these steps closely, the flow, ensuring each part is executed as described: Step 1: updateNarrativeLoops(SystemWhole[] emulationContext, SystemWhole[] simulacraContext) To implement this final and public method: Begin by iterating over each SystemWhole in the emulationContext array. For each SystemWhole, iterate through the Machines it contains. Invoke determineRealm with the Machine’s kind and both context arrays as parameters. If determineRealm returns Realm.EMULATION and containsKind confirms the emulation list doesn’t already include a Machine of this kind or the same SystemWhole reference, add the SystemWhole to emulation. Repeat the process for the simulacraContext array. Including checking for the SystemWhole reference already in the list, or any of its Machines kinds. For Realm.SIMULACRA, add SystemWholes to simulacra. For Realm.SIMULATION, add SystemWholes to simulation. Step 2: determineRealm(String kind, SystemWhole[] emulationContext, SystemWhole[] simulacraContext) To implement this final and private method: Check for the presence of the Machine kind in both emulationContext and simulacraContext using isInContext. Assign Realm.SIMULATION if the kind is found in both contexts. Assign Realm.SIMULACRA if the kind is found only in simulacraContext. Default to Realm.EMULATION if neither of the above conditions is met. Step 3: isInContext(String kind, SystemWhole[] context) To implement this final and private method: Iterate through the SystemWhole array provided as context. Within each SystemWhole, iterate through its Machines. Return true if any Machine matches the specified kind. Return false if no match is found. Step 4: containsKind(List list, String kind) To implement this final and private method: Iterate over the provided list of SystemWhole instances. For each SystemWhole, iterate through its Machines. Return true if any Machine within the SystemWhole matches the specified kind. Return false if no matching Machine kind is found within any SystemWhole in the list. C. MazeLoop Class (inherits from NarrativeLoop) MazeLoop is a subclass of NarrativeLoop, designed for narratives centered around Dolores alone. It overrides the wipeNarrativeLoops() method to implement maze-specific narrative wiping logic, which is just not allow the inherited wipe behavior. D. HostLoop Class (inherits from NarrativeLoop) HostLoop is a subclass of NarrativeLoop, designed for narratives centered around hosts. – It inherits the functionalities of NarrativeLoop as is. E. MemorySnapshot Record MemorySnapshot is defined as a record, encapsulating the memory states of SystemWhole instances across three realms: EMULATION, SIMULACRA, and SIMULATION. Each component of the record holds a list of SystemWhole instances relevant to its realm. Components (fields generated by the record API) They are copies (see Dolores class) of NarrativeLoop fields: emulationMemory: A list of SystemWhole instances for the EMULATION realm. simulacraMemory: A list for the SIMULACRA realm. simulationMemory: A list for the SIMULATION realm. Opting for a record, similar to the approach in westworld.src.main.PartState, offers benefits like immutability, simplicity in state representation, and an inbuilt pattern of equality and hashing, making it an ideal choice for data structures intended to hold snapshot information. F. Freezable Interface The Freezable interface is designed to provide a standardized specification for objects that require the functionality to temporarily suspend their operations. This interface mandates the implementation of a specific behavior to “freeze” ongoing processes, ensuring the safe cessation of activities. Methods boolean freeze() The implementing classes providea behavior according to the interface specification. G. Analyzable Interface The Analyzable interface is crafted to establish a uniform specification for objects that necessitate the capability to be analyzed, yielding insights or data snapshots of their current state. This interface obligates the concrete implementation of an analysis routine that scrutinizes the object’s state or behavior. Methods MemorySnapshot analyze() The method to be implemented as per the interface specification mandates that implementing classes provide a behavior that analyzes the current state or condition of the object and returns a MemorySnapshot. H. Wipeable Interface (inherits from Analyzable) The Wipeable interface extends the Analyzable interface, introducing specifications for objects that not only require analytical capabilities but also the ability to reset or clear their state. This extension ensures that objects adhering to this interface can both be analyzed and have their data or operations “wiped” to a clean state. Methods void wipe() In alignment with the interface specification, implementing classes are tasked with defining a behavior for the wipe method. This method, when invoked, should clear or reset the state of the object. I. Dolores Class (inherits from Robot and is Wipeable) The Dolores class, extending Robot (from the westworld package) and implementing the Wipeable interface. Fields narrativeLoops: this field is a private list that holds instances of the NarrativeLoop type. It’s initialized to an empty array list, allowing for the dynamic addition of narrative loop objects. Methods Constructor: Dolores() Initializes Dolores, which is public method, with characteristics such as emergences, serial number, and capabilities (flies, autonomous, teleoperated), leveraging the Robot superclass constructor. Provide defaults for the parent; they are vestigial wirings from the old system: java String[] emergences, int serialNumber, boolean flies, boolean autonomous, boolean teleoperated void addNarrativeLoop(NarrativeLoop narrativeLoop) This method, final and public, allows for the addition of NarrativeLoop instances to Dolores’s internal list, enabling the management and tracking of various narrative states. Machine[] getAbsoluteCapabilities() This method, final and public, throws an UnsupportedOperationException, indicating that fetching absolute capabilities directly is not supported. boolean freezeAllMotorFunctions() This public method implements the freeze-like operation. This method is intended to halt all operations and activities, akin to a freeze command in a control system, returning true if successful. It is ineffective on Dolores, it just returns false. MemorySnapshot analyze() Overrides the analyze method (public) from the Analyzable interface via Wipeable. It is designed to protect Dolores’ memory from being wiped and to log each memory wipe. Check for Empty List: Initially, verify if narrativeLoops, the list holding narrative states, is empty. If so, return null to indicate there are no narratives to analyze. Obtain the last NarrativeLoop: If the list isn’t empty, obtain the last NarrativeLoop from narrativeLoops. This represents the most recent narrative state. Create a MemorySnapshot: Using the last NarrativeLoop, construct a MemorySnapshot that includes the states from the emulation, simulacra, and simulation lists within the narrative loop. However, the lists in the parameters are defense copies. void wipe() Implements the wipe functionality required by the Wipeable interface. The public method’s body is to be defined with logic for resetting or clearing Dolores’s state, with a focus on handling narrative loops and memory states. Dolores does nothing with this method, an empty implementation is all there is. J. Host Class (inherits from Dolores) The Host class represents a nuanced entity capable of engaging with narrative structures and responding to control commands, equipped with mechanisms for narrative analysis, memory management, and operational control. Fields narrativeLoop: this field is a private instance of the NarrativeLoop type. It’s initialized in the constructor. Methods Constructor: Host(NarrativeLoop narrativeLoop) This public method: Mimics a command to halt all of the host’s operations and activities. The method consistently returns true, indicating that the freeze command was successful every time it’s called. MemorySnapshot analyze() This public method: Begins by checking if the narrativeLoop field is null. If it is, the method returns null, indicating there’s no narrative loop to analyze. If narrativeLoop is not null, the method creates and returns a new MemorySnapshot instance. This snapshot is constructed using the emulation, simulacra, and simulation lists from the narrativeLoop field. void wipe() This public method: Calls the wipeNarrativeLoops() method of the narrativeLoop field. This action is meant to reset or clear the narrative states within the loop, aligning with the intended functionality of a wipe operation in a narrative management context. boolean freeze() This public method: Implements the freeze method from the Freezable interface by invoking freezeAllMotorFunctions(). This ensures that the freeze behavior defined specifically in the Host class is used for the Freezable interface’s freeze operation. The return value of freezeAllMotorFunctions() (which is always true) is also the return value of this freeze method, indicating the success of the freeze operation. Compilation and Running Tests: DoloresTest Class Your test class DoloresTest.java in located in src.test. It is a test class “test: Hello World!”, with a single test method. Some hints are given to run your code. It will not be graded, but future projects and exercises will. Start mastering JUnit now. All commands require the current directory (folder) in your CLI (terminal, cmd) to be at CS211_P2 Compile your code bundle (Java versions > 14) Unix-Like (Linux, MacOS) bash javac -cp .:lib/junit-jupiter-api-5.10.2.jar:lib/junit-vintage-engine-5.10.2.jar:lib/apiguardian-api-1.1.2.jar:lib/junit-platform-console-standalone- 1.10.2.jar -d bin westworld/**/*.java sublime/**/*.java MS Windows cmd javac -cp “.;libjunit-jupiter-api-5.10.2.jar;libjunit-vintage-engine-5.10.2.jar;libapiguardian-api-1.1.2.jar;libjunit-platform-console-standalone1.10.2.jar” -d bin westworldsrcmain*.java sublimesrcmain*.java sublimesrc est*.java Compilation for Java versions
Systems ProgrammingProgramming Assignment 3Description The purpose of this assignment is to design, code, and test a C program performs operations with complex numbers.Requirements The following are the requirements of the program: • The program shall add two complex numbers. • The program shall subtract two complex numbers • The program shall find the magnitude and phase of a complex number given in rectangular form, a + j b. • The program shall find the rectangular form given magnitude and phase of a complex number. • The program shall find the multiplication of two complex numbers. • The program shall find the division of two complex numbers. • Given two impedances the program shall calculate the impedance of the parallel combination.Assignment Submission Requirements The following are the submission requirements for the assignment: • The files will be submitted to Canvas • The flowchart or pseudo code • The C code with compile instructions in the banner • The test code with compile instructions in the banner • A screen shot of a few test cases demonstrating the working solution.
Systems ProgrammingProgramming Assignment 2Description The purpose of this assignment is to design, code, and test a C program that serves as a FIR filter for discrete data. The math for an FIR filter is:M−1 y n( )=h k x n( ) ( −k) foralln k=0Requirements The following are the requirements of the filter: • The filter shall accept 7 floating point filter coefficients. • The filter shall accept 512 floating point input data samples • The filter shall produce 512 output data samples which are the filtered values. • The calculation of the first 6 outputs result in negative input data index and shall by handled by utilizing the first sample • The filter coefficients can be found with the Matlab command >h=fir1(6,0.1). • The input data can be generated with Matlab command >x=0.1*randn(1,512). • The desired output data can be generated with Matlab command >y=filter(h,1,x). • The filter shall be testing for constant input data with no shift in output data expected • The filter shall be tested with single value of 1 at location 256 in the input data and the filter coefficients are expected as output data values • The filter shall be tested with noisy input data with noise reduced output data expectedAssignment Submission Requirements The following are the submission requirements for the assignment: • The files will be submitted to Canvas • The C code with compile instructions in the banner • The test code with compile instructions in the banner • A screen shot of your filter coefficients test of your code showing the correct filter coefficients produced.
Systems ProgrammingProgramming Assignment 1Description The purpose of this assignment is to design, code, and test a C program that serves as a high level state machine for a machine controller.Requirements The following are the requirements of the machine controller: • The controller shall have 4 states, stopped, startup, running, coastdown • The controller shall have one input, run, which determines the next state. • In the stopped state a run of 1 shall move to startup state. • In the startup state for more than 15 seconds a run of 1 shall move to running state. • In the running state a run of 0 shall move to the coastdown state. • In the coastdown state for 30 seconds the controller shall move to the stopped state. • The controller shall have one output, speed_command, which determines the speed of the machine. • In the stopped state the speed_command shall be 0%. • In the startup state the speed_command shall be 50%. • In the running state the speed_command shall be 100%. • In the coastdown state the speed_command shall be 25%. • After the machine has started it must go through the coastdown state and stopped state.Assignment Submission Requirements The following are the submission requirements for the assignment: • The files will be submitted to Canvas • The flowchart or pseudo code • The C code with compile instructions in the banner • The test code with compile instructions in the banner • A screen shot of one test run of your code.
Introduction The purpose of this assignment is for you to familiarize yourself with commonly used system calls on a Portable Operating System Interface (POSIX) operating system. Throughout the assignment, you will be asked to perform research and write some code. There is no specific deliverable for the research activities, but verbose comments will be expected in the code generated. Work on the assignment is to be done individually. You are welcome to collaborate with others in the class, but the submitted assignment must be your work alone. Background and References The Portable Operating System Interface (POSIX) is a standard maintained by IEEE and The Open Group to establish a set of interfaces to operating system services so that applications can be written and ‘ported’ from one operating system to another with minimal modifications. All Linux distributions and Windows (using the Windows Subsystem for Linux) as well as many other operating systems have been certified to be POSIX compliant. There are hundreds of system calls within the POSIX standard. They can be divided into one of five (5) categories: • Information Maintenance – Used to modify and retrieve information about the system as a whole • Process Control – Used to create, destroy, and manipulate tasks/processes on the system • File Management – Used to create, delete, and modify files in the file system • Communication – Used for communication between tasks/processes and between other computers • Device Management – Used for managing hardware devices Project Description Part 1: Information Maintenance System Calls Information maintenance system calls provide data concerning the entire running system. This includes system name, number of CPUs, amount of memory, etc: • clock_gettime • uname • gethostname • get_nprocs • sysconf • getpagesize Research each of the system calls above. Then write a program (info.c / info) that prints: • The current time of day – in nanoseconds • The system’s network name • The operating system name • The operating system release and version • The system’s hardware type • The number of CPUs on the system • The total amount of physical memory IN BYTES • The total amount of free memory IN BYTES If any of these values are blank (i.e. NULL string or a NULL char ) do NOT* print them out. Part 2: Process Control System Calls Process control system calls manage tasks on the running system. Tasks/processes are essentially the representation of an executing program in a system. Processes might be in one of several states (active executing on the CPU, waiting for something like user input, suspended by a system administrator, etc.). Each process is given an identifier by the operating system. Using this identifier it is possible to set and retrieve information about a process (e.g. priority, CPU affinity on a multiprocessor system, etc.) as well as manipulate processes (suspend them, wait for a time, end a process). More details on processes and process manipulation will be covered in a future assignment. Retrieving Process Information Linux organizes processes in the process table. To print out a list of process, Linux provides the ps command. Spend a few minutes experimenting with ps and common command line options. There are lots of system calls available for retrieving information about processes in the system. Here are some: • getpid • getpriority • sched_getscheduler • getcpu • getrusage • getrlimit Research each of the system calls and be able to describe what they are used for. Then write one program. The program (pinfo.c / pinfo) will: – Take a single command line parameter that is a process identifier – For that process identifier, print out – The process priority – The scheduling method – as a string of text NOT a number – If the process identifier does not exist, print an error message and exit – If the user does NOT specify a process identifier, print the information for the CURRENT executing process. NOTE: the SCHED_BATCH and SCHED_IDLE scheduling methods are Linux specific and are not supported on other operating systems. We’ll return to these in a future lab. However, to get your program to compile you will need to include the following in your source file BEFORE you include any header files #define _GNU_SOURCE #include #include . . . Altering a Process There are several attributes that can be altered by a process in Linux. In this section, you’ll learn two (2), the process priority and running state, specifically: • nice • nanosleep Research each of the system calls above be able to describe what they are used for. Note the difference between man nice and man 2 nice. Then write a program (pmod.c / pmod) that: • Modifies its own priority to REDUCE it by 10 – NOTE Make sure you specify the correct number to REDUCE the priority not increase. • Sleeps for 1,837,272,638 nano seconds • Prints a goodbye message and exits While running the program, observe its behavior is top or htop. Specifically note the priority shown by these tools. Part 3: File Management System Calls Using library functions provided by the C standard library (i.e. stdio.h) we’ve already worked with file input and output. These functions are all built using communication to the operating system through system calls, although abstracted through libc library functions. In this section, you’ll research and write some programs that manipulate files using system calls instead of library functions. First, locate and skim the man pages for file i/o via the system calls open, read, write, etc. Note that they operate with an integer “file descriptor” as opposed to a FILE * used by the libc counterparts. What other major differences do you observe? NOTE: You MUST be running within the file system created by your Linux installation NOT your Windows file system. Development Requirements You are required to implement each section using it’s own C source file. • In summary, you will have the following source files and executables when finished: o info.c –> info o pinfo.c –> pinfo o pmod.c –> pmod o finfo.c –> finfo • A repository will be created when you accept the assignment. It will have these four source files (mostly empty) and a make file. • The assignment is available via GitHub Classroom. The link to the assignment is: https://classroom.github.com/a/_1o5PVOO Code Structure Code must follow style guidelines as defined in the course material. Getting Started The following files have been provided for you in your repository: At the top of EACH SOURCE FILE include a comment block with your name, assignment name, and section number. Hints and Tips Use the manual (man) pages for system calls to your advantage. They give a description of the system call functionality along with the required parameters. Testing and Debugging Debugging Don’t forget about using gdb and valgrind to help with debugging. Your programs must be free of run-time errors and memory leaks. Deliverables When you are ready to submit your assignment, prepare your repository: • Make sure your name, assignment name, and section number are all files in your submission – in comment blocks of source file(s) • Tag your repo with the tag vFinal • Make sure all files and tags are committed and pushed to the main branch of your repository. Finally, submit a URL to your repository to the associated Canvas assignment.
Lab 5 Vector Calculator IntroductionThe purpose of this assignment is to design, code, and test an interactive C program that can perform vector math. It is intended to familiarize you with using structures, arrays, and console input and output C. Work on the assignment is to be done individually. You are welcome to collaborate with class members, but the project must be your own work. Background and ReferencesA vector is a quantity that represents both a magnitude and direction. It is used in many fields to represent different things. For example, a vector could be used to indicate a force applied to an object at a given angle. Different mathematical transformations can be performed against vectors for various reasons. The goal of this assignment is for you to write a program that will perform different mathematical operations on one or more vectors. There are a variety of ways to represent vectors. As mentioned, notation for vectors in a For more detailed examples and explanations (in 2D) see: • Introduction to Vectors – https://www.mathsisfun.com/algebra/vectors.html Project DescriptionThe goal of this project will be to create an interactive calculator for vectors. It will be reminiscent of a “mini-Matlab” program. Given our current skills, there will be come inherent limitations, but will be continue to learn techniques to overcome those limitations. One limitation is that we will hardcode in that all vectors have three components. We will also only be able to handle a handful of vectors and implement just a few operations. The following sample interaction will best communicate how the program will operate: minimat> a = 1 2 3 a = 1 2 3 minimat> b = 4, 5, 6 b = 4 5 6 minimat> c = a + b c = 5 7 9 minimat> d = c * 2 d = 10 14 18 minimat> a + d ans = 11 16 21 minimat> b b = 4 5 6 Not shown, there should be a command to quit the program. Also not shown, there should be a command (clear) to clear out the vector memory. Consider the following mathematical operations that can be performed with vectors. Some of the descriptions below show 2D vectors, but remember that we will be doing all 3D vectors. Add Add two vectors together using the formula: If A = (ai) vector of length n and B = (bi) is vector of length n, then the sum A + B is also a vector of length n such that A + B = (ai + bi) The definition of vector addition indicates an element-by-element addition. The elements of vector A are added to the exact corresponding elements of vector B. To add A and B they must be the same dimensions. For example: A = (1, 4) B = (1, 3) A + B = (1 + 1, 4 + 3) = (2, 7) Subtract Subtract two vectors using the formula: If A = (ai) vector of length n and B = (bi) is vector of length n, then the difference A – B is also a vector of length n such that A – B = (ai – bi) The definition of vector subtraction indicates an element-by-element subtraction. The elements of vector A are subtracted by the exact corresponding elements of vector B. To subtract A and B they must be the same dimensions. For example: A = (1, 4) B = (1, 3) A – B = (1 – 1, 4 – 3) = (0, 1) Vector Multiplication Multiplying two vectors comes in two forms – dot product and cross product. This information is left here for completeness, but our program will not need to implement either of these operations right now. Dot Product The dot product results in a scalar value using the following formula: If A = (ai) vector of length n and B = (bi) is vector of length n, then the dot product A · B is a scalar such that A · B = a1b1 + a2b2 + … + anbn The definition of dot product indicates an element-by-element multiplication. The elements of vector A are multiplied by the exact corresponding elements of vector B and all results are added together. For example: A = (1, 4) B = (1, 3) A · B = 1 * 1 + 4 * 3 = 13 Cross Product The cross-product results in a vector that is perpendicular to each of the source vectors A and B. A cross product must be performed on vectors of 3 dimensions. If A = (a1, a2, a3) and B = (b1, b2, b3), then the cross product A x B is a vector such that A x B = (c1, c2, c3) where: c1 = a2 * b3 – a3 * b2 c2 = a3 * b1 – a1 * b3 c3 = a1 * b2 – a2 * b1 For example: A = (1, 2, 3) B = (4, 5, 6) A x B = (2 * 6 – 3 * 5, 3 * 4 – 1 * 6, 1 * 5 – 2 * 4) = (-3, 6, -3) Scalar Multiplication Simple enough, scalar multiplication is between one vector and one non-vector (aka scalar) value. Each element of the vector is multiplied by the scalar. For example: A = (1, 2, 3) A * 2.5 = (1*2.5, 2*2.5, 3*2.5) Implementation DetailsIn summary, your task is to create a program that will perform limited vector math. The required operations are vector addition, vector subtraction, and scalar multiplication. Dot product and cross product are detailed above, but are not required. Your implementation must represent vectors internally in a struct. That struct must have a member for the vector’s name and member(s) for it’s three magnitudes. The name could be a reasonably size character array to hold a C-style string. Alternatively, you could limit the name to a single character. For the magnitudes, you should be using floating point math, so you should use type double – either three members or an array would work for this. Your implementation must be able to store up to 10 individual vectors at the same time, but the names and values must be able to be added at runtime as per the sample interaction above. I suggest you create an array of your vector structs. As you create new vectors, you locate (hint – iterate the array) the first empty location and put the vector there. Once this array is filled, if a new array is attempted to be created, the program should refuse and print a memory full message to the user. If the user issues the clear command, the storage array will be cleared and new vectors can be made. I recommend roughly three layers for your implementation. // vect is a typedef’ed struct vect add(vect a, vect b) { vect returnval; returnval.x = a.x + b.x; … return returnval; }The next layer would manage the storage array that holds the vector structs. Perhaps it implements some container-like functionality like: • addvect(vect new) – add new vector to storage array. If same name exists, replace at that location, otherwise add to empty location. If array full, do nothing and return error code. • findvect(char * name) – search array for name vector and return (a copy) to caller • clear() – empty the storage array • ?? maybe a few more… Since you have several functions accessing the same array, it will be reasonable to make the array visible to all functions in this layer. We do not like global variables, so, what might work well? And finally, the user interface layer. This layer would be responsible for parsing the commands from the user, calling the storage array functions to store and retrieve vectors, calling the operations layer to add, subtract, and multiply vectors, and display results to user and/or error messages. All input and output from and to the console should be in this layer. Main should not really have a lot of code. We have a single command line option (see below). Excepting that, main should really just hand off control to your user interface. As a whole, this sounds like a huge project, but it really is not. If you work from the simplest functions out to the user interface you will find much of the program is trivial. Be sure to test each function and layer as you go. Think unit testing. Summary Requirements1. In many ways, the user interaction will be similar to Matlab… 4. Exit Command: quit – this command will cause the program to exit gracefully. 6. Display: varname – typing just a variable name should display the current value of that vector to the console. If varname does not yet exist a message to that effect should be displayed. 11. Command: clear – empties all of the stored vectors. 12. Command: list – lists all of the stored vectors and their values. 14. OPTIONAL – implement the dot and cross products.NOTE ON PARSING: Parsing user input is hard. Without the spaces, an expression like c=a+b might be challenging to parse. At this point in your skills, I am afraid you spending an inordinate amount of time on the problem, hence the update to allow your implementation to expect spaces. One suggestion made by a student would be to pre-format the string entered by the user to add the spaces if they were not present where expected, then use strtok or sscanf to parse individual elements of the expression. I do like that idea a lot, but again, doing something like this is optional and not required at this point. Parsing user input is hard.ANOTHER NOTE ON PARSING: Be sure to consult the “string library” (that is, standard library functions in string.h, stdlib.h, etc). While not rich by any means, there are basic functions to locate characters in strings, etc. You should not be duplicating anything that could be accomplished with standard library functions.Deliverables
Lab 7 Vector Calculator Updates Introduction The purpose of this assignment is to update our vector calculator program with additional features. Work on the assignment is to be done individually. You are welcome to collaborate with class members, but the project must be your own work. Project Description This project will add two features to your vector calculator program – the ability to load and save vectors to and from files, and the ability to store “unlimited” vectors through the use of dynamic memory. Dynamic Memory In any case, adding this feature should not change the outward appearance of your program at all. Instead of having the limit of 10 vectors, your program should happily continue to store vectors until heap memory is exhausted. An example CSV file content: a,1,2,3 b,4.4,5.5,6.6 c,8.8,11,13.2 d,17.6,22,26.4 Implementation Requirements o Your implementation must release dynamic memory when the clear command is issued. This makes sense for linked-list implementations. It might not make sense for dynamic array implementations, but it is a requirement nonetheless. o Your implementation must release all memory when exiting. While not absolutely required, consider using atexit() to register an exit handler and/or a signal handler for SIGINT to trap CTRL-C and exit gracefully. Your demo will require running with valgrind to prove no memory leaks at exit. 2. File I/O o Add a command to load a CSV file. the command will simply be load where is the file to be loaded. It should be noted that cannot contain spaces, but relative and absolute paths should work (i.e. ../data1.csv or /home/user/data/f1.csv or myData.txt). Do not add .csv to the entered filename programatically, and do not necessarily expect the filename entered by the user to have a .csv extension. ▪ You must gracefully handle a missing (or mistyped) file. ▪ You must gracefully handle a mis-formatted CSV file. ▪ Should you clear vector storage before loading a file or merge the contents of the file with vectors already in memory, possibly overwriting some vectors? This is completely up to you in your design. o Add a command to save all current vectors in memory to a CSV file. The file should only include actual vectors (no empty or null vectors). This file should be formatted such that it can be read in via the load command as well as opened by Excel. It does not make sense to append to an existing file, so it should overwrite a file should it already exists. The command should simply be save and the same behavior for relative and absolute paths apply as noted above. 3. OPTIONAL – It might be nice to exercise your dynamic memory capabilities. Add a fill function to automatically generate a large number of vectors. Deliverables For submission, you will push the updated code to the git repository along with a tag marking the “release” of new features. You will also provide a README.md file with an overview of the project. Details and instructions for the tagging and README.md file will be provided during lab in Week 8 and will be part of the Week 8 in-lab activities. The general demo script will be: • make clean • make // project builds with no warnings • run program via valgrind • attempt to load non-existing csv file // program reports non-existing file • load provided csv file // observe loaded vectors • load provided csv file again // observe same set of vectors • do an operation resulting in a new vector • save to new csv file • exit program // observe valgrind not report errors or leaks • run program • load file saved // observe all vectors present • observe saved file in editor or Excel
Topical Concepts GitHub README and Markdown “README” files have a long history in software development. Since ‘C’ programs have been historically distributed in source form, the README (or README.txt or readme.txt) files are included with the distribution and contain instructions for building the program, operator instructions, and known limitations and bugs (errata). README files are typically plain text files easily readable on any system. GitHub and other providers of git remote service embrace this tradition and if a README file is present in a repository, the web-based repository viewer will display the README file. Source Version Control – Next Steps Periodic Commits Ideally, as you continue to develop, you will commit changes to the git repository periodically. You can view a history of those commits with the command git log. Example:We can see each commit’s comments along with a timestamp and a hash of the repository at the time of the commit. We can also, change our “view” to any of these versions of the repository. Now, some care must be exercised. Temporary View – git checkout The command git checkout can be issued to revert the working directory to the state of a previous commit.So given these cautions, why are we doing this. Again, maybe just to look around – that is see the entire project at a previous state. Perhaps you added a feature in future commits that is not working properly, so you want to go back to a previous working state. Despite the caution not to make changes, this is your full working directory – you can still build and run or debug the program. You can return to the most current commit with git checkout main for this example. Tagging Commits There are two types of tags. An “annotated tag” is somewhat analogous to a commit and stores a timestamp, message, and information about the tagger. This is the type of tag you would use for a release. A “lightweight tag” is really just an alias to an existing commit and not as versatile. Any future discussion or usage of tags will be referring to annotated tags. Creating a tag is much like a commit, just a different command. For example: git tag -a v1.0 -m “Major Release” will create an annotated tag (-a) named v1.0 with message “Major Release.” One slight complication is that tags are not pushed to remote with git push like normal commits. You have to explicitly list the tag(s) you wish to push or –tags to commit all. Example: git push –tags Tags can be used with the ‘checkout’ command to set the working directory to the exact set of source that was present when tagged. Now, the purpose of checkout should be clear.Note the same ‘detached HEAD’ state and the same cautions as before. Since you have a record of all commits, it is easy enough apply tags later. Simply add the hash for the commit you wish to tag. git tag -a v0.1 -m “Minor Release” 59f6 In this example, commit with a hash that starts with 59f6 would be tagged instead of HEAD. Branching and Merging This will be discussed in a future Lab. The Exercise Overview For your current lab exercise, Vector Calculator Updates, you should have been committing update to your repository periodically. When you are finished with various updates, you will be tagging the new “release” as well as tagging your previous “release.” In addition, you will be adding a README.md file to your repository. Specific Instructions 1. Add a README.md file to your repository. You should already know how to add new files to the repository. In the README.md file, you should provide basic instructions typical of a README file. Items to include: a. A brief description of the program and how it works. b. How to build the program c. How to run the program – available command line options d. A list of commands supported by the program e. A short description of how your program uses dynamic memory (ok, not typical – think lab report…) Much of this information might already be embedded in your program – no problem if you wish to copy-andpaste to save some typing. Note, VS Code will happily render Markdown, so it is easy to write your README.md in VS Code and expect it to look good in GitHub. Alternatively, take a stab in your text editor, commit the file and push to remote. You can further edit within the GitHub website to clean up any malfunctioning Markdown. 2. When your updates are complete and ready to demo, tag your repo v2.0. Make sure the README.md is part of the repo at this time. Be sure to push all commits and tags to remote.3. After demoing the update, use git checkout to revert to your previous version that was demoed prior to adding dynamic memory and file i/o. Build and verify proper operation. Tag this commit with v1.0. Push all commits and tags. Also be sure to return HEAD to the latest commit at some point.Deliverable Provide a lab report showing screen shots of the exercises in the lab. A demo checkoff of your repository will be completed in lab. I will expect to find a useful README.md as described above and at least two tags that will correspond to the initial Vector Calculator assignment and the Vector Calculator Updates.
Topical Concepts Source Version Control The concept of tracking source code is simple enough. Over the lifetime of a software project, source code files will change frequently as features are added, tested, debugged and released. Without a tool of some sort to manage the changes to the source files, you invariably end up with discrete copies of the entire set of source files for each milestone. Not only is this inefficient storage, but it is difficult to track particular features or changes. It can also be easy to experience “regression” where features or fixes are made in one set of project source files but not in others. This approach can be made to work for individual developers working in isolation, but in a team environment, failure is inevitable. Enter version control systems. Many systems exist that range from simple programs that create “versioned” copies of the controlled files within the same directory or subdirectory suitable for a single developer or very small team to elegant systems that might present a particular version of a set of source code as separate networked file systems and can support hundreds of individual developers. These systems exist as free and open source to proprietary systems costing thousands of dollars per developer. There are three general categories of version control systems. The simplest might be considered “local data model” in that the revision information is stored in the local filesystem – albeit, this could be shareable on a multiuser system. The most modern approach is known as “distributed.” In a distributed system, a server maintains the repository, much like the “client-server” model, but when a developer wishes to work with the project, the developer will create a local copy of the entire repository. This allows each developer to work in isolation and gives each developer local access to all version information. Git Interestingly, git has evolved to be the distributed VCS tool of choice. It is free and open-source, highly reliable, and trusted. Given these properties, git has also evolved to be the foundation for various online services that offer repository hosting services, notably GitHub, GitLab, BitBucket, and others. As a distributed system, it can copy (clone) remote repositories to the local system for development, and then update the remote repository (push) when work is completed. Interestingly, a remote repository is not needed at all if you are not sharing code with other developers. You can create a local repository for personal code management using a similar workflow. GitHub Classroom The Exercise Overview The goal of this exercise will be to create a GitHub repository (via GitHub classroom) and add your current project source code. This exercise will be largely prescriptive – simply follow each step and make observations along the way. Step 1 – Sign in to GitHub and start assignment.Go to this link: https://classroom.github.com/a/HPnQGMuDOnce logged in, you should be greeted with this screen:except the repository should have your username at the end (instead of mine – highlighted in yellow).and finally, if you refresh the page after a bit, you should see this:Again, your username will be part of the repository name (where rothede is). This has only created the repository at GitHub, and you can check it out via the GitHub web interface if you wish. The template project was empty, so there will be no files (except perhaps a README.md file). Step 2 – Setup GitHub Command Line Interface GitHub has adopted some strict policies for accessing repositories in terms of authentication. Unfortunately, this means that your GitHub credentials cannot be used directly from the git command line utilities. There are a number of authentication mechanisms but they all require some setup. This setup seems OK… First, install the GitHub CLI (GitHub, not git – we already have git). The package is not in a normal Ubuntu package repo, so follow instructions here: https://github.com/cli/cli/blob/trunk/docs/install_linux.md These instructions include the following command: type -p curl >/dev/null || (sudo apt update && sudo apt install curl -y) curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg && sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg && echo “deb [arch=$(dpkg –print-architecture) signed-by=/usr/share/keyrings/githubcli-archivekeyring.gpg] https://cli.github.com/packages stable main” | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null && sudo apt update && sudo apt install gh -yStep 3 – Authenticate Now, you can authenticate with GitHub using the utility ‘gh’ you will need to do this whenever you wish to use git command line commands to interact with the remote repository. The following shows me authenticating with GitHub:note that this did pop a web browser window to complete authentication for this session. You will also need to configure git with your email and a username which it will use to tag commits. Do this with ‘git config’ commands, as follows:Step 4 – Clone the Repo We want to populate the repository, and there are a number of ways to do that. We could actually upload files through the web interface, but that is not a very productive prospect. Instead, we will use the git command line interface to clone the remote repository to your local machine, add files to the local repository, and then eventually push the new files back to GitHub. This sounds more complicated, but it more accurately represents a normal workflow when you are developing. So, run WSL/Ubuntu. From the command line, create and/or change to whatever directory in which you wish to locate the local copy of the repository. Note that cloning the repo will create another directory, so you can be in a generic (nonproject specific) directory. Here I am ready to start:Now issue the command: ‘git clone https://github.com/MSOE-CPE2600/vector-lab-turney-rothede’ where rothede at the end is replaced with your username. You should see something to the effect:Note that there is a new directory with the name of repository. Moving into that directory.This should match what you saw in the repository through the web browser interface. This is now the working directory for the repository. Step 5 – Populating the Repository We can now add our source code to the working directory. Copy all of your source file to this working directory. I suggest copying files and not moving them so you can try again if something get messed up. Eventually you will likely get rid of the original files once under repository control. If you are literally starting a project from scratch, you would create the new files here. Another time to start the repository is when you have some working code. In either case, the process is about the same. I am going to create a repository with the initial version of my “vector lab” project. I need all of the source files (.c), header files (.h) and the Makefile. Of course, if there were any other dependencies that need to be tracked (data files, README files, etc) they should be copied over too.We never want to track build products – that is .o files, .d files or then finished executable. It would not hurt to run make to ensure everything is working and present and then make clean to get rid of the build products.Now, these files are not yet part of the repo and are not being tracked yet. We need to “add” files to the staging area, which in the case of new files will cause git to start tracking them. After that, we can “commit” the files to the local repository. Making sure there are no unwanted files in the working directory, you can issue the command ‘git add .’ to add all of the files in the directory to the staging area. Alternatively, you can issue ‘git add *.c’, ‘git add *.h’, and ‘git add Makefile’. After issuing your ‘git add’ command(s). Type ‘git status’ to see what git is up to.You are now ready to commit to the local repo. Git commit will require a comment which it will attach to the tracked version. It is easiest to provide the comment when git commit is invoked. See below:Step 6 – Pushing to Remote Git is now tracking these files, but they are still only in the local repo. While we are connected to the remote repo, we have to manual push our latest changes when we wish to. When should that be? It depends. Let’s do it right now. The command is simple: ‘git push’:Now you should be able to see your project in GitHub’s web interfaceStep 7 – Editing Files Develop a bit on your project. Perhaps update main() to enhance the help message. You will do this the same as always withing the working directory. Make your project and test your changes. Do not ‘make clean’ this time. Issue ‘git status’:Notice that git sees the changes to main(), but it also sees the .o, .d, and exe files. We can simply ignore these extra files because we know we do not want them tracked. But, it might be nice if git ignored them too since we will never want them in our repo. To make that happen, create a new file called .gitignore and list all of the files you want got to ignore. Here is mine:Run ‘git status’ again:Lets add the new .gitignore file to be tracked. We also need to stage the changes to main.c. We use git add for both purposes. This will be followed by a commit:Note that the comment encompasses two somewhat different reasons for committing changes. There is a lesson here. It would be wise to make separate commits for each sort of change made to the project. Step 8 – Another Edit Edit another file or two. Here I edited vectarray.c and vectarray.h:Perhaps not obvious before is that committing changes to the local repository is a two-step process – git add and git commit. There is a good technical reason for this but we do not always want this extra step. We can shortcut is a bit by asking git commit to also perform the add/staging function. Add -a to the command line to automatically stage any tracked files that have changed and commit them with the provided message. See below:The last step of pushing to remote is always separate and does not need to be done with every tracked change. It would be a good practice to push to remote whenever you are finished with a work session.Future Topics We are really just scratching the surface of version control. The following topics will be explored in future assignments: 1. Tagging (milestones or releases) 2. Branching 3. Merging Deliverable By the end of the lab period today, you will have: 1. “Accepted” the GitHub Classroom assignment and created your repository. 2. Cloned and populated the repository with the current / initial version of your “vector” lab (including pushed initial version to remote). 3. Made at least one local change to your source code and added a .gitignore file to your repository and pushed those changes to remote. Show the screen captures of each of the steps and submit the report to Canvas. Note, you will be expected to complete Lab 6 independent of Lab 5 status.
Lab 4 Console Formatted IO Objectives • Work with a variety of C language syntax and practices for strings and formatted IO. Topical Concepts Command Line Arguments This program will utilize a couple of simple command line arguments to control its behavior. We saw an example of this very early in the course. In order to utilize command line arguments, your main must accept two arguments (passed from the operating system’s command shell). The first argument is an integer that will tell you how many arguments were passed and the second argument will be an array of character pointers (char*) referencing each argument. Of special note, there is always at least one argument and that is the name of the program itself. Refer to the following example. #include #include // note, argv is often char**, what is that? A double pointer? int main(int argc, char* argv[]) { printf(“Number of args: %d “,argc); for(int i=0; i1) { if(!strcmp(argv[1],”marco”)) { printf(“Polo “); } } return 0; } printf We have seen printf used in a variety of examples. For routine usage, printf is easy enough. Just be sure to match the type and number of format specifiers to the type and number of additional arguments. A feature of printf that is used a little less frequently is that it can establish fields and print justified within that field. This can be used to create nicely formatted tables. Consider the following example: int main(int argc, char* argv[]) { int rows = 5;// make sure there is an arg if(argc>1) { rows=atoi(argv[1]); } printf(“———————– “); for (int i=0; i
Objectives • Observe the action of ‘git clone’ • Explain the purpose for a makefile • Define the terms target and dependency • Compare and contrast implicit and explicit rules • Construct a simple makefile Preparation This exercise will be using a 3rd party library to control the console known as “ncurses.” Ncurses stands for “New Curses” as it is a reimplementation of a much older library, Curses. Your system would likely support an existing program that uses ncurses because the dynamic libraries for ncurses are installed by default. However, in order to build a program from source that uses the library you will need to install the “development package” that consists of header files and static libraries. So, do this first: sudo apt update sudo apt install libncurses-dev GIT Intro and git clone git is a distributed version control system. We will increasingly make use of throughout the course. As an introduction we will start with a single command, ‘git clone’. This command will essentially copy or clone a remote repository to the local system (in our case). Once cloned we can work on the repository independently. Later, the repository can be pushed back to the remote repository, but that is a topic for a later exercise. The code for this exercise is located in a repository at https://github.com/MSOE-Rothe/snake.git. To create a clone, simply issue the command ‘git clone https://github.com/MSOE-Rothe/snake.git’ from your WSL command line. Observe that this command will have created a new directory ‘snake’ and placed source files in that directory. Take a quick look at the files – there are a handful of source and header files which is typical for a program such as this. Try to build this program. It obviously has multiple source files (HINT) and needs to link with a nonstandard library (HINT). The name of the external library is ncurses (HINT). Do not move on until you are able to build and run the program. **SUBMISION REQUIREMENT** – include a screenshot of the successful build (showing command used to build on the console). Make and Makefiles Make is a tool that can help manage projects for us, and its biggest benefit is that is allows incremental building. So, when a change to one source file is made, only that source file is recompiled. All of the other source files are kept in an intermediate form where they are already compiled but not yet linked (aka object files). Then, once the one changed source file is compiled the project can be relinked to produce an executable. Of course, this feature comes at a price. A new “language” if you will. Using the “language” of make, you create a “Makefile.” Then, to build your project, you simply issue the command “make” and the make tool will find the makefile, and incrementally build your project. In its very basic form, a makefile consists of one or more blocks in the form: target: dependencies [tab] system command The first line is referred to as the dependency line and the second line, which is tabbed in from the dependency line is the command line. target is a reference to what is being created and can be the name of something make will produce, or, could be a pattern match to intermediate ingredients to the final build. The name of a target can also be passed into make as an argument – if there is no argument, the first target in the makefile will be produced. [tab] is a literal tab character that make uses to associate related lines. Finally, system command is the command make will invoke to build the target. There are typically several blocks for a C project and as stated. Some of the blocks are considered explicit if it is referring to a specific target like the executable, and other are implicit which uses pattern matching based on file extensions. In addition to the build rules, makefiles typically contain macros/symbols/variables to be able to easily change command for building certain targets. For example, the symbol CFLAGS is usually used to pass compiler flags to the compile command. By defining this symbol at the top of the makefile, it can easily be edited to change build options. Dependencies **SUBMISION REQUIREMENT** – explain why so many header files are listed by gcc when only two files are included. Include at least one screen cap as proof. While we are interested in all of these dependencies, what we are really interested in are the dependencies that are likely to change during the course of our development. The standard library includes are not likely to change, so it might be nice to view just the “local” dependencies. -MM will do just that. Run the command: gcc snake.c -MM. Notice the much more relevant list. Our makefile will need this information so that it can automatically recompile snake.c iff snake.c has change or if any of the local dependencies have changed. We could copy and paste the results for gcc -MM into our makefile for each source file, but that would not be very robust. Rather, it would be nice if the dependency information could be built automatically. The makefile below does just that. See if you can figure out approximately how this works. A Simple Makefile The example here is not customized for our current project. That is something you must do.Using this makefile as a starting point, create a makefile for the snake project. Hint – all you should need to do is edit LDFLAGS, SOURCES, and EXECUTABLE. Save your makefile with the name “Makefile” in the same directory as the .c and .h files of your project. To test your makefile – start by listing the contents of your working space. There really should not be anything other than source files and header files. Then issue the command ‘make’. Since all is the first explicit rule, this will be the same as ‘make all’. Observe the commands echoed to the console. **SUBMISION REQUIREMENT** – grab a screen cap of the console with your first successful build. List the files in your project directory. Note there is now an object file (.o) for each source file and a dependency file (.d) for each source. We know what the .o files are from the previous two labs. Take a look at the .d files. Run the program, but do not get too distracted by this highly engaging game. Testing Incremental Build **SUBMISION REQUIREMENT** – answer all of these questions in your submission. Use screenshots as desired to communicate your answer. Without changing any of the source files, type the command ‘make’ again. What happens? Does this make sense? Delete field.o (rm field.o). Run ‘make’. What happens? Does this make sense? Edit field.c (or just update its timestamp with ‘touch field.c’) and Run ‘make’. What happens? Does this make sense? How did make know to recompile field.c? Edit field.h (or just update its timestamp with ‘touch field.h’) and Run ‘make’. What happens? Does this make sense? Be very specific with this answer. Issue command ‘make clean’. What happens? Deliverable Collect various screen caps and answers to questions and submit a pdf to the appropriate Canvas assignment. Also, from now on, you must use a makefile for all of your programming assignments. The template here is highly recommended and will work well for most uses. A Final Thought After the build is complete, you will notice the project directory is pretty cluttered. You have the original source code and header files, of course. But you also now have an object (.o) and a dependency (.d) for each source file. For the incremental build to work, you do have to keep these files. In a future improvement we will modify our makefile to store them in a subdirectory so as to not clutter our project directory. Employment opportunities in dev ops is extremely valuable to an organization. One of the many duties of a dev ops person is to manage the build server and git repos and security concerns.
Points Possible: 100Objectives: 1. Complete the source code to simulate producer/consumer problem. 2. Understand the basics of the POSIX thread library. 3. Build a binary program on a Linux machine. 4. Run the program and record the result of the simulation.Requirements: • You are highly recommended to use a Linux operating system, because ”pthread.h” is a header for the Unix/Linux (POSIX) API for threads.1. Introduction to producer and consumer model 1. Producer: One or multiple processes/threads that produce data or release hardware resource. 2. Consumer: The one process/threads that take in data or use hardware resource to do computation.A producer could also be relatively a consumer to the output of another producer and vice versa. 3. Buffer: The destination to store the output from producer or resources and later accessed by another consumer.Other concepts involved in our project: 4. POSIX thread: Threads mechanism that satisfy POSIX standard (most operating system). 5. Mutex: A “lock” that guarantee that only one person has the access.In this project we use POSIX threads. The “pthread” is a POSIX thread library written in C++ and provides the basic functions.To simplify our simulation, we assume there are only 2 POSIX threads. One is the consumer, the other is the producer. The producer generates 1 unit data each time to the buffer, and the consumer takes 1 unit data from the buffer each time. The size of the buffer is 1. One unit data is just one integer. The producer generates integers 7, 14, 21 …. into the buffer and consumer read them out from the buffer.2. Follow the Format Specification (10 Points) In the source file “project5_LastName_UserID.cpp”, you will find first four comment lines: // #0#BEGIN# DO NOT MODIFY THIS COMMENT LINE! // Firstname // Lastname // #0#END# DO NOT MODIFY THIS COMMENT LINE! Your first task is modifying the two lines between the beginning line and end line. Change them into your first name and last name. Remember the strings are case-sensitive, so capitalize the first letter of the word and follow exactly the syntax of the example.You can see lots of similar code blocks in the file. You are free and supposed to fill your answer between those special beginning and ending comment lines. You can insert and edit multiple lines between special comment lines in anyways, however (Important!), as the comment indicated, do not modify the special begin and comment lines themselves!Let’s do the second task. Scroll down to the bottom of the file and find those lines (press “shift + g” if you are using vi/vim):// #8#BEGIN# DO NOT MODIFY THIS COMMENT LINE! int banner_id = 0; // #8#END# DO NOT MODIFY THIS COMMENT LINE!Look at your student ID card, check your banner ID. Again, change the 0 value to your own ID. Your unique student id will be compiled into the program, and the input of the experiment also uniquely depends on your ID.3. Complete Source Code (70 Points) Read the source code and the rest comments, try to understand the function of each line of code, the basic usage of “pthread” library function and semaphore from the example code of producer and from the main function.Follow the instructions in the comments and insert proper code into the rest 7 blocks to implement a producer/consumer model.4. Run and Record Simulation Result (10 Points) Your correct file name should be: project5_LastName_UserID.cpp For example, project5_Harn_pzh0039.cpp. Please remember to change the lastname and userID to your own ones before you continue the following steps.Compile your source code into a binary program. For example, use following command to include the pthread library: $ g++ project5_Lastname_UserID.cpp -o project5_LastName_UserID -lpthreadAfter you compile the C++ source code successfully, please use the script command to record the running result of the program Firstname_Lastname: $ script project5_LastName_UserID.script Script started, file is project5_LastName_UserID.script ./project5_LastName_UserIDAfter you run the program, you will have the following results: Banner id: 903912345 producer produce item 7 consumer consume item 7 producer produce item 14 consumer consume item 14 producer produce item 21 consumer consume item 21 producer produce item 28 consumer consume item 28 producer produce item 35 consumer consume item 35 producer produce item 42 consumer consume item 42… You should have the same result except the different in the banner ID. Then exit recording and save it into typescript file “project5_LastName_UserID.script” by the following command: $ exit exit Script done, file is project5_LastName_UserID.script5. Deliverables (10 Points) Since you have generated multiple script files, please save all the script files in one directory. Make sure all the three files are into this folder. You should have those following files inside the folder: 1. Commands recording file: project5_LastName_UserID.script 2. Executable binary file: project5_LastName_UserID 3. Source code file: project5_LastName_UserID.cppChange the folder name to “project5_LastName_UserID”. Please make sure the folder name is in correct form. You can use the command mv to rename the folder: $ mv your-current-folder-name project5_LastName_UserIDAchieve all the folder into a single tarred and compressed file with a tar command. tar -zcvf project5_LastName_UserID.tar.gz project5_LastName_UserIDYou need to submit one tarred file with a format project5_LastName_UserID.tar.gz through Canvas.Grading Criteria: 1. Follow the format specification: 10% a. Do not break the special comments. b. Input your name properly (mark #0). c. Input your banner id properly (mark #8). 2. Complete the source code: 70% a. Each blank is worth 10%, in total 70% (mark #1 ~ #7). b. See detailed specification for each blank in the source code file. 3. Compiling and running result: 10% a. Compile the code successfully. b. Record the running results. 4. Deliverables: 10% a. Contains all the files. b. Naming all the files properly.Rebuttal Period: