Assignment Chef icon Assignment Chef

Browse assignments

Assignment catalog

33,401 assignments available

[SOLVED] Comp1210 project: ring torus with junit tests – part 1

Overview: This project consists of two classes: (1) RingTorus is a class representing a RingTorus object and (2) RingTorusTest is a JUnit test class which contains one or more test methods for each method in the RingTorus class. Note that there is no requirement for a class with a main method in this project. You should create a new folder to hold the files for this project. After you have created your RingTorus.java file, you should create a jGRASP project and add your RingTorus.java file; you should see it in the Source Files category of the Project section of the Browse tab. With this project is open, your test file, RingTorusTest.java, will be automatically added to the project when it is created; you should see it in the Test Files category. If RingTorusTest.java appears in source File category, you should right-click on the file and select “Mark As Test” from the right-click menu. You will then be able to run the test file by clicking the JUnit run button on the Open Projects toolbar. A ring torus is made by revolving a small circle with radius r along a line made by a larger circle with radius R as shown below. Variables in formulas: �: radius of large circle (or large radius) �: radius of small circle (or small radius) A: surface area V: volume D: ring diameter D = 2 (R + r) � = (2��) (2��) � = (2��) (��!) Project: Ring Torus with JUnit Tests – Part 1 Page 2 of 5 Page 2 of 5 • RingTorus.java Requirements: Create a RingTorus class that stores the label, small radius, and large radius where the small radius is less than the large radius and both are positive. The RingTorus class also includes methods to set and get each of these fields, as well as methods to calculate the outside diameter, surface area, and volume of a RingTorus object, and a method to provide a String value that describes a RingTorus object. The RingTorus class includes a one static field (or class variable) to track the number of RingTorus objects that have been created, as well appropriate static methods to access and reset this field. And finally, this class provides a method that JUnit will use to test RingTorus objects for equality as well as a method required by Checkstyle. Design: The RingTorus class has fields, a constructor, and methods as outlined below. (1) Fields: Instance Variables – label of type String, large radius of type double, and small radius of type double. Initialize the String to “” and the double variables to 0 in their respective declarations. These instance variables should be private so that they are not directly accessible from outside of the RingTorus class, and these should be the only instance variables (fields) in the class. Class Variable – count of type int should be private and static, and it should be initialized to zero in the declaration. (2) Constructor: Your RingTorus class must contain a public constructor that accepts three parameters (see types of above) representing the label, large radius, and small radius. Instead of assigning the parameters directly to the fields, the respective set method for each field (described below) should be called since they are checking the validity of the parameter. For example, instead of using the statement label = labelIn; use the statement setLabel(labelIn); After setLabel is called be sure to call setLargeRadius before calling setSmallRadius. The constructor should increment the class variable count each time a RingTorus is constructed. Below are examples of how the constructor could be used to create RingTorus objects. Note that although String and numeric literals are used for the actual parameters (or arguments) in these examples, variables of the required type could have been used instead of the literals. RingTorus ex1 = new RingTorus (“Small Example”, 9.5, 1.25); RingTorus ex2 = new RingTorus (” Medium Example “, 35.1, 10.4); RingTorus ex3 = new RingTorus (“Large Example”, 134.28, 32.46); (3) Methods: Usually a class provides methods to access and modify each of its instance variables (known as get and set methods) along with any other required methods. The methods for RingTorus, which should each be public, are described below. See the formulas in the figure above and the Code and Test section below for information on constructing these methods. Project: Ring Torus with JUnit Tests – Part 1 Page 3 of 5 Page 3 of 5 o getLabel: Accepts no parameters and returns a String representing the label field. o setLabel: Takes a String parameter and returns a boolean. If the String parameter is not null, then the “trimmed” String is set to the label field and the method returns true. Otherwise, the method returns false and the label is not set. o getLargeRadius: Accepts no parameters and returns a double representing the large radius field. o setLargeRadius: Takes a double parameter and returns a boolean. If the double parameter is positive and is greater than the current small radius, then the parameter is assigned to the large radius field and the method returns true. Otherwise, the method returns false and the large radius field is not set. o getSmallRadius: Accepts no parameters and returns a double representing the small radius field. o setSmallRadius: Takes a double parameter and returns a boolean. If the double parameter is positive and is less than the current large radius, then the parameter is assigned to the small radius field and the method returns true. Otherwise, the method returns false and the small radius field is not set. o diameter: Accepts no parameters and returns a double representing the diameter of the RingTorus. See formula in figure on page 1. o surfaceArea: Accepts no parameters and returns the double value for the surface area of the RingTorus. See formula in figure on page 1. o volume: Accepts no parameters and returns the double value for the volume of the RingTorus. See formula in figure on page 1. o toString: Returns a String containing the information about the RingTorus object formatted as shown below, including decimal formatting (“#,##0.0##”) for the double values. Newline and tab escape sequences should be used to achieve the proper layout within the String but it should not begin or end with a newline. In addition to the field values (or corresponding “get” methods), the following methods should be used to compute appropriate values in the toString method: diameter(), surfaceArea(), and volume(). Each line should have no trailing spaces (e.g., there should be no spaces before a newline ( ) character). The toString value for ex1, ex2, and ex3 respectively are shown below (the blank lines are not part of the toString values). RingTorus “Small Example” large radius = 9.5 units small radius = 1.25 units diameter = 21.5 units surface area = 468.806 square units volume = 293.004 cubic units RingTorus “Medium Example” large radius = 35.1 units small radius = 10.4 units diameter = 91.0 units surface area = 14,411.202 square units volume = 74,938.248 cubic units Project: Ring Torus with JUnit Tests – Part 1 Page 4 of 5 Page 4 of 5 RingTorus “Large Example” large radius = 134.28 units small radius = 32.46 units diameter = 333.48 units surface area = 172,075.716 square units volume = 2,792,788.867 cubic units o getCount: A static method that accepts no parameters and returns an int representing the static count field. o resetCount: A static method that returns nothing, accepts no parameters, and sets the static count field to zero. o equals: An instance method that accepts a parameter of type Object and returns false if the Object is a not a RingTorus; otherwise, when cast to a RingTorus, if it has the same field values (ignoring case in the label field) as the RingTorus upon which the method was called, it returns true. Otherwise, it returns false. Note that this equals method with parameter type Object will be called by the JUnit Assert.assertEquals method when two RingTorus objects are checked for equality. Below is a version you are free to use. public boolean equals(Object obj) {if (!(obj instanceof RingTorus )) { return false; } else { RingTorus rt = (RingTorus ) obj; return (label.equalsIgnoreCase(rt.getLabel()) && (Math.abs(largeRadius – rt.getLargeRadius()) < .000001) && (Math.abs(smallRadius – rt.getSmallRadius()) < .000001)); } } o hashCode(): Accepts no parameters and returns zero of type int. This method is required by Checkstyle if the equals method above is implemented. Code and Test: As you implement the methods in your RingTorus class, you should compile it and then create test methods as described below for the RingTorusTest class. When using the setSmallRadius and setLargeRadius, the values of the current smallRadius and largeRadius must be considered to decide the order in which you invoke the associated set methods. For setSmallRadius, the “new” small radius must be positive and smaller the current large radius, and for setLargeRadius, the “new” large radius must be positive and larger the current small radius. For example, a new RingTorus object has its smallRadius and largeRadius fields initialized to zero in the field declaration, which is default initial value for doubles. However, this means in the constructor, you must invoke the setLargeRadius before the setSmallRadius. If you wanted a small radius of 2.5 and attempt to set it first, it would not be set since it will not be less than largeRadius, which is initially zero. Thus, you invoke setLargeRadius first since any positive value will be greater than the smallRadius which is initially zero. Project: Ring Torus with JUnit Tests – Part 1 Page 5 of 5 Page 5 of 5 Therefore, in general you need to consider the current value the smallRadius and largeRadius to decide the order you invoke the associated set methods. • RingTorusTest.java Requirements: Create a RingTorusTest class that contains a set of test methods to test each of the methods in RingTorus. Design: Typically, in each test method, you will need to create an instance of RingTorus , call the method you are testing, and then make an assertion about the expected result and the actual result (note that the actual result is commonly the result of invoking the method unless it has a void return type). You can think of a test method as simply formalizing or codifying what you could be doing in jGRASP interactions to make sure a method is working correctly. That is, the sequence of statements that you would enter in interactions to test a method should be entered into a single test method. You should have at least one test method for each method in RingTorus, except for associated getters and setters which can be tested in the same method. Collectively, these test methods are a set of test cases that can be invoked with a single click to test all the methods in your RingTorus class. Code and Test: Since this is the first project requiring you to write JUnit test methods, a good strategy would be to begin by writing test methods for those methods in RingTorus that you “know” are correct. By doing this, you will be able to concentrate on the getting the test methods correct. That is, if the test method fails, it is most likely due to a defect in the test method itself rather the RingTorus method being testing. As you become more familiar with the process of writing test methods, you will be better prepared to write the test methods as new methods are developed. Be sure to call the RingTorus toString method in one of your test methods and assert something about the return value. If you do not want to use assertEquals, which would require the return value match the expected value exactly, you could use assertTrue and check that the return value simply contains the expected value. For example, for RingTorus ex3: Assert.assertTrue(ex3.toString().contains(“”Large Example””)); Also, remember that you can set a breakpoint in a JUnit test method and run the test file in Debug mode. Then, when you have an instance in the Debug tab, you can unfold it to see its values or you can open a canvas window and drag items from the Debug tab onto the canvas. The Grading System When you submit RingTorus.java and RingTorusTest.java, the grading system will use the results of your test methods and their level of coverage of your source files as well as the results of our reference correctness tests to determine your grade. In this project, your test file should provide at least method coverage. That is, each method must be called at least once in a test method.

$25.00 View

[SOLVED] Comp1210 project: hexagonalprism list menu app

Overview: You will write a program this week that is composed of three classes: the first class defines HexagonalPrism objects, the second class defines HexagonalPrismList objects, and the third, HexagonalPrismListMenuApp, presents a menu to the user with eight options and implements these: (1) read input file (which creates a HexagonalPrismList object), (2) print report, (3) print summary, (4) add a HexagonalPrism object to the HexagonalPrismList object, (5) delete a HexagonalPrism Project: HexagonalPrism List Menu App Page 2 of 11 Page 2 of 11 object from the HexagonalPrismList object, (6) find a HexagonalPrism object in the HexagonalPrismList object, (7) Edit a HexagonalPrism in the HexagonalPrismList object, and (8) quit the program. [You should create a new “Project 6” folder and copy your Project 5 files (HexagonalPrism.java, HexagonalPrismList.java, HexagonalPrism_data_1.txt, and HexagonalPrism_data_0.txt) to it, rather than work in the same folder as Project 5 files.] • HexagonalPrism.java (assuming that you successfully created this class in the previous project, just copy the file to your new project folder and go on to HexagonalPrismList.java on page 4. Otherwise, you will need to create HexagonalPrism.java as part of this project.) Requirements: Create a HexagonalPrism class that stores the label, edge, and height. The HexagonalPrism class also includes methods to set and get each of these fields, as well as methods to calculate the surface area, lateral surface area, base area, and volume of a HexagonalPrism object, and a method to provide a String value of a HexagonalPrism object (i.e., a class instance). Design: The HexagonalPrism class has fields, a constructor, and methods as outlined below. (1) Fields (instance variables): label of type String, edge of type double, and height of type double. Initialize the String to “” and the doubles to zero in their respective declarations. These instance variables should be private so that they are not directly accessible from outside of the HexagonalPrism class, and these should be the only instance variables in the class. (2) Constructor: Your HexagonalPrism class must contain a public constructor that accepts three parameters (see types of above) representing the label, edge, and height. Instead of assigning the parameters directly to the fields, the respective set method for each field (described below) should be called. For example, instead of the statement label = labelIn; use the statement setLabel(labelIn); Below are examples of how the constructor could be used to create HexagonalPrism objects. Note that although String and numeric literals are used for the actual parameters (or arguments) in these examples, variables of the required type could have been used instead of the literals. HexagonalPrism ex1 = new HexagonalPrism (“Ex 1″, 3.0, 5.0); HexagonalPrism ex2 = new HexagonalPrism (” Ex 2 “, 21.3, 10.4); HexagonalPrism ex3 = new HexagonalPrism (“Ex 3”, 10.0, 204.5); (3) Methods: Usually a class provides methods to access and modify each of its instance variables (known as get and set methods) along with any other required methods. The methods for HexagonalPrism, which should each be public, are described below. See formulas in Code and Test below. o getLabel: Accepts no parameters and returns a String representing the label field. Project: HexagonalPrism List Menu App Page 3 of 11 Page 3 of 11 o setLabel: Takes a String parameter and returns a boolean. If the string parameter is not null, then the label field is set to the “trimmed” String and the method returns true. Otherwise, the method returns false, and the label field is not set. o getEdge: Accepts no parameters and returns a double representing the edge field. o setEdge: Accepts a double parameter and returns a boolean as follows. If the parameter is greater than zero, sets the edge field to the double passed in and returns true. Otherwise, the method returns false, and the edge field is not set. o getHeight: Accepts no parameters and returns a double representing the height field. o setHeight: Accepts a double parameter and returns a boolean as follows. If the parameter is greater than zero, sets the height field to the double passed in and returns true. Otherwise, the method returns false, and the height field is not set. o surfaceArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. o lateralSurfaceArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. o baseArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. o volume: Accepts no parameters and returns the double value for the volume calculated using the using the formula above. o toString: Returns a String containing the information about the HexagonalPrism object formatted as shown below, including decimal formatting (“#,##0.0##”) for the double values. Newline escape sequences should be used to achieve the proper layout. In addition to the field values (or corresponding “get” methods), the following methods should be used to compute appropriate values in the toString method: lateralSurfaceArea(), baseArea(), surfaceArea(), and volume(). Each line should have no leading and no trailing spaces (e.g., there should be no spaces before a newline ( ) character). The results of printing the toString value of ex1, ex2, and ex3 respectively are shown below. HexagonalPrism “Ex 1” has 8 faces, 18 edges, and 12 vertices. edge = 3.0 units height = 5.0 units lateral surface area = 90.0 square units base area = 23.383 square units surface area = 136.765 square units volume = 116.913 cubic units HexagonalPrism “Ex 2” has 8 faces, 18 edges, and 12 vertices. edge = 21.3 units height = 10.4 units lateral surface area = 1,329.12 square units base area = 1,178.721 square units Project: HexagonalPrism List Menu App Page 4 of 11 Page 4 of 11 surface area = 3,686.562 square units volume = 12,258.7 cubic units HexagonalPrism “Ex 3” has 8 faces, 18 edges, and 12 vertices. edge = 10.0 units height = 204.5 units lateral surface area = 12,270.0 square units base area = 259.808 square units surface area = 12,789.615 square units volume = 53,130.659 cubic units Code and Test: As you implement your HexagonalPrism class, you should compile it and then test it using interactions. For example, as soon you have implemented and successfully compiled the constructor, you should create instances of HexagonalPrism in interactions (e.g., copy/paste the examples above on page 2). Remember that when you have an instance on the workbench, you can unfold it to see its values. You can also open a viewer canvas window and drag the instance from the Workbench tab to the canvas window. After you have implemented and compiled one or more methods, create an HexagonalPrism object in interactions and invoke each of your methods on the object to make sure the methods are working as intended. You may find it useful to create a separate class with a main method that creates an instance of HexagonalPrism then prints it out. This would be similar to the HexagonalPrismApp class you will create below, except that in the HexagonalPrismApp class you will read in the values and then create and print the object. • HexagonalPrismList.java – extended from the previous project by adding the last six methods below. (Assuming that you successfully created this class in the previous project, just copy HexagonalPrismList.java to your new Project folder and then add the indicated methods. Otherwise, you will need to create all of HexagonalPrismList.java as part of this project.) Requirements: Create an HexagonalPrismList class that stores the name of the list and an ArrayList of HexagonalPrism objects. It also includes methods that return the name of the list, number of HexagonalPrism objects in the HexagonalPrismList, total surface area, total volume, average surface, and average volume for all HexagonalPrism objects in the HexagonalPrismList. The toString method returns a String containing the name of the list followed by each HexagonalPrism in the ArrayList, and a summaryInfo method returns summary information about the list (see below). Design: The HexagonalPrismList class has two fields, a constructor, and methods as outlined below. (1) Fields (or instance variables): (1) a String representing the name of the list and (2) an ArrayList of HexagonalPrism objects. These are the only fields (or instance variables) that this class should have, and both should be private. Project: HexagonalPrism List Menu App Page 5 of 11 Page 5 of 11 (2) Constructor: Your HexagonalPrismList class must contain a constructor that accepts a parameter of type String representing the name of the list and a parameter of type ArrayList representing the list of HexagonalPrism objects. These parameters should be used to assign the fields described above (i.e., the instance variables). (3) Methods: The methods for HexagonalPrismList are described below. o getName: Returns a String representing the name of the list. o numberOfHexagonalPrisms: Returns an int representing the number of HexagonalPrism objects in the HexagonalPrismList. If there are zero HexagonalPrism objects in the list, zero should be returned. o totalSurfaceArea: Returns a double representing the total surface area for all HexagonalPrism objects in the list. If there are zero HexagonalPrism objects in the list, zero should be returned. o totalVolume: Returns a double representing the total volume for all HexagonalPrism objects in the list. If there are zero HexagonalPrism objects in the list, zero should be returned. o averageSurfaceArea: Returns a double representing the average surface area for all HexagonalPrism objects in the list. If there are zero HexagonalPrism objects in the list, zero should be returned. o averageVolume: Returns a double representing the average volume for all HexagonalPrism objects in the list. If there are zero HexagonalPrism objects in the list, zero should be returned. o toString: Returns a String (does not begin with ) containing the name of the list followed by each HexagonalPrism in the ArrayList. In the process of creating the return result, this toString() method should include a while loop that calls the toString() method for each HexagonalPrism object in the list (adding a before and after each). Be sure to include appropriate newline escape sequences. For an example, see lines 3 through 28 in the output below from HexagonalPrismListApp for the HexagonalPrism_data_1.txt input file. [Note that the toString result should not include the summary items in lines 30 through 36 of the example. These lines represent the return value of the summaryInfo method below.] o summaryInfo: Returns a String (does not begin with ) containing the name of the list (which can change depending on the value read from the file) followed by various summary items: number of HexagonalPrism objects, total surface area, total volume, average surface area, and average volume. Use “#,##0.0##” as the pattern to format the double values. For an example, see lines 30 through 36 in the output below from HexagonalPrismListApp for the HexagonalPrism_data_1.txt input file. The second example below shows the output from HexagonalPrismListApp for the HexagonalPrism_data_0.txt input file which contains a list name but no HexagonalPrism data. The following six methods are new in Project 6: o getList: Returns the ArrayList of HexagonalPrism objects (the second field above). o readFile: Takes a String parameter representing the file name, reads in the file, storing the list name and creating an ArrayList of HexagonalPrism objects, uses the list name and the ArrayList to create a HexagonalPrismList object, and then returns the HexagonalPrismList object. See note #1 under Important Considerations for the Project: HexagonalPrism List Menu App Page 6 of 11 Page 6 of 11 HexagonalPrismListMenuApp class (last page) to see how this method should be called. The readFile method header should include the throws FileNotFoundException clause. o addHexagonalPrism: Returns nothing but takes three parameters (label, edge, and height), creates a new HexagonalPrism object, and adds it to the HexagonalPrismList object. o findHexagonalPrism: Takes a label of a HexagonalPrism as the String parameter and returns the corresponding HexagonalPrism object if found in the HexagonalPrismList object; otherwise returns null. This method should ignore case when attempting to match the label. o deleteHexagonalPrism: Takes a String as a parameter that represents the label of the HexagonalPrism and returns the HexagonalPrism if it is found in the HexagonalPrismList object and deleted; otherwise returns null. This method should use the String equalsIgnoreCase method when attempting to match a label in the HexagonalPrism object to delete. o editHexagonalPrism: Takes three parameters (label, edge, and height), uses the label to find the corresponding the HexagonalPrism object. If found, sets the edge and height to the values passed in as parameters, and returns true. If not found, simply returns false. Note that this method should not set the label. Code and Test: Remember to import java.util.ArrayList, java.util.Scanner, java.io.File, java.io.FileNotFoundException. These classes will be needed in the readFile method which will require a throws clause for FileNotFoundException. Some of the methods above require that you use a loop to go through the objects in the ArrayList. You may want to implement the class below in parallel with this one to facilitate testing. That is, after implementing one to the methods above, you can implement the corresponding “case” in the switch for the menu described below in the HexagonalPrismListMenuApp class. • HexagonalPrismListMenuApp.java (replaces HexagonalPrismListApp class from the previous project) Requirements: Create a HexagonalPrismListMenuApp class with a main method that presents the user with a menu with eight options, each of which is implemented to do the following: (1) read the input file and create a HexagonalPrismList object, (2) print the HexagonalPrismList object, (3) print the summary for the HexagonalPrismList object, (4) add a HexagonalPrism – object to the HexagonalPrismList object, (5) delete a HexagonalPrism object from the HexagonalPrismList object, (6) find a HexagonalPrism object in the HexagonalPrismList object, (7) Edit a HexagonalPrism object in the HexagonalPrismList object, and (8) quit the program. Design: The main method should print a list of options with the action code and a short description followed by a line with just the action codes prompting the user to select an action. After the user enters an action code, the action is performed, including output if any. Then the line with just the action codes prompting the user to select an action is printed again to accept the next code. The first action a user would normally perform is ‘R’ to read in the file and create a Project: HexagonalPrism List Menu App Page 7 of 11 Page 7 of 11 HexagonalPrismList object. However, the other action codes should work even if an input file has not been processed. The user may continue to perform actions until ‘Q’ is entered to quit (or end) the program. Note that your program should accept both uppercase and lowercase action codes (see items 3 and 4 in the Code and Test section below). Below is output produced by running HexagonalPrismListMenuApp and printing the action codes with short descriptions followed by the prompt with the abbreviated action codes waiting for the user to select from the menu. Example 1 Line # Program output 1 2 3 4 5 6 7 8 9 10 HexagonalPrism List System Menu R – Read File and Create HexagonalPrism List P – Print HexagonalPrism List S – Print Summary A – Add HexagonalPrism D – Delete HexagonalPrism F – Find HexagonalPrism E – Edit HexagonalPrism Q – Quit Enter Code [R, P, S, A, D, F, E, or Q]: Below shows the output after the user entered ‘r’ and then (when prompted) the file name. Notice the output from this action was “File read in and HexagonalPrism List created”. This is followed by the prompt with the action codes waiting for the user to make the next selection. You should use the HexagonalPrism_data_1.txt file from Project 5 to test your program. Example 2 Line # Program output 1 2 3 4 5 Enter Code [R, P, S, A, D, F, E, or Q]: r File name: HexagonalPrismList_data_1.txt File read in and HexagonalPrism List created Enter Code [R, P, S, A, D, F, E, or Q]: The result of the user selecting ‘p’ to Print HexagonalPrism List is shown below and next page. Example 3 Line # Program output 1 2 3 4 5 6 7 8 9 10 11 12 Enter Code [R, P, S, A, D, F, E, or Q]: p —– HexagonalPrism Test List —– HexagonalPrism “Ex 1” has 8 faces, 18 edges, and 12 vertices. edge = 3.0 units height = 5.0 units lateral surface area = 90.0 square units base area = 23.383 square units surface area = 136.765 square units volume = 116.913 cubic units Project: HexagonalPrism List Menu App Page 8 of 11 Page 8 of 11 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 HexagonalPrism “Ex 2” has 8 faces, 18 edges, and 12 vertices. edge = 21.3 units height = 10.4 units lateral surface area = 1,329.12 square units base area = 1,178.721 square units surface area = 3,686.562 square units volume = 12,258.7 cubic units HexagonalPrism “Ex 3” has 8 faces, 18 edges, and 12 vertices. edge = 10.0 units height = 204.5 units lateral surface area = 12,270.0 square units base area = 259.808 square units surface area = 12,789.615 square units volume = 53,130.659 cubic units Enter Code [R, P, S, A, D, F, E, or Q]: The result of the user selecting ‘s’ to print the summary for the list is shown below. Example 4 Line # Program output 1 2 3 4 5 6 7 8 9 10 Enter Code [R, P, S, A, D, F, E, or Q]: s —– Summary for HexagonalPrism Test List —– Number of HexagonalPrisms: 3 Total Surface Area: 16,612.943 square units Total Volume: 65,506.272 cubic units Average Surface Area: 5,537.648 square units Average Volume: 21,835.424 cubic units Enter Code [R, P, S, A, D, F, E, or Q]: The result of the user selecting ‘a’ to add a HexagonalPrism object is shown below. Note that after ‘a’ was entered, the user was prompted for label, edge, and height. Then after the HexagonalPrism object is added to the HexagonalPrism List, the message “*** HexagonalPrism added ***” was printed. This is followed by the prompt for the next action. After you do an “add”, you should do a “print” or a “find” to confirm that the “add” was successful. Example 5 Line # Program output 1 2 3 4 5 6 7 Enter Code [R, P, S, A, D, F, E, or Q]: a Label: New HP Edge: 22.2 Height: 77.7 *** HexagonalPrism added *** Enter Code [R, P, S, A, D, F, E, or Q]: Project: HexagonalPrism List Menu App Page 9 of 11 Page 9 of 11 Here is an example of the successful “delete” for a HexagonalPrism object, followed by an attempt that was not successful (i.e., the HexagonalPrism object was not found). Do “p” to confirm the “delete”. Example 6 Line # Program output 1 2 3 4 5 6 7 8 9 Enter Code [R, P, S, A, D, F, E, or Q]: d Label: Ex 2 “Ex 2” deleted Enter Code [R, P, S, A, D, F, E, or Q]: d Label: Ex 11 “Ex 11” not found Enter Code [R, P, S, A, D, F, E, or Q]: In the example below, there is a successful “find” for a HexagonalPrism object, followed by an attempt that was not successful (i.e., the HexagonalPrism object with label Fake was not found), and finally an invalid code Y was entered. Example 7 Line # Program output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Enter Code [R, P, S, A, D, F, E, or Q]: f Label: ex 3 HexagonalPrism “Ex 3” has 8 faces, 18 edges, and 12 vertices. edge = 10.0 units height = 204.5 units lateral surface area = 12,270.0 square units base area = 259.808 square units surface area = 12,789.615 square units volume = 53,130.659 cubic units Enter Code [R, P, S, A, D, F, E, or Q]: f Label: Not A Real Label “Not A Real Label” not found Enter Code [R, P, S, A, D, F, E, or Q]: Below is an example of the successful “edit” for a HexagonalPrism object, followed by an attempt that was not successful. To verify the edit, you should do a “find” for “ex 3” or you could do a “print” to see the whole list. Note the actual label, Ex 3, is shown on line 5 rather than ex 3 which was entered by the user. Edit does not modify the label. Example 8 Line # Program output 1 2 3 4 5 Enter Code [R, P, S, A, D, F, E, or Q]: e Label: ex 3 Edge: 5.555 Height: 7.777 “Ex 3” successfully edited Project: HexagonalPrism List Menu App Page 10 of 11 Page 10 of 11 6 7 8 9 10 11 12 13 Enter Code [R, P, S, A, D, F, E, or Q]: e Label: Also Not A Real Label Edge: 1.0 Height: 3.0 “Also Not A Real Label” not found Enter Code [R, P, S, A, D, F, E, or Q]: Entering a ‘q’ should quit the application with no message. Example 9 Line # Program output 1 2 Enter Code [R, P, S, A, D, F, E, or Q]: q Finally, if a code other than the ones in the “Enter Code” list is entered, the code is considered invalid and an appropriate message is printed, then the user is asked to enter a code again as shown below. Example 10 Line # Program output 1 2 3 4 Enter Code [R, P, S, A, D, F, E, or Q]: T *** invalid code *** Enter Code [R, P, S, A, D, F, E, or Q]: Code and Test: This class should import java.util.Scanner, java.util.ArrayList, and java.io.FileNotFoundException. Carefully consider the following important considerations as you develop this class. 1. At the beginning of your main method, you should declare and create an ArrayList of HexagonalPrism objects and then declare and create a HexagonalPrismList object using the list name and the ArrayList as the parameters in the constructor. This will be a HexagonalPrismList object that contains no HexagonalPrism objects. For example: String _______ = “*** no list name assigned ***”; ArrayList _________ = new ArrayList(); HexagonalPrismList _________ = new HexagonalPrismList(_________,_________); The ‘R’ option in the menu should invoke the readFile method on your HexagonalPrismList object. This will return a new HexagonalPrismList object based on the data read from the file, and this new HexagonalPrismList object should replace (be assigned to) your original HexagonalPrismList object variable in main. Since the readFile method throws FileNotFoundException, your main method needs to do this as well. 2. Very Important: You should declare only one Scanner on System.in for your entire program, and this should be done in the main method. That is, all input from the keyboard (System.in) must be done in your main method. Declaring more than one Scanner Project: HexagonalPrism List Menu App Page 11 of 11 Page 11 of 11 on System.in in your program will likely result in a very low score from Web-CAT. 3. After you read in the code as a String, you should invoke the toUpperCase() method on the code and then convert the first character of the String to a char as shown in the two statements below. code = code.toUpperCase(); char codeChar = code.charAt(0); 4. For the menu, your switch statement expression should evaluate to a char and each case should be a char. After printing the menu of actions with descriptions, you should have a do-while loop that prints the prompt with just the action codes followed by a switch statement that performs the indicated action. The do-while loop ends when the user enters ‘q’ to quit. You should strongly consider using a for-each loop as appropriate in the new methods that require you to search the list. You should be able to test your program by exercising each of the action codes. After you implement the “Print HexagonalPrism List” option, you should be able to print the HexagonalPrismList object after operations such as ‘A’ and ‘D’ to see if they worked. You may also want to run in debug mode with a breakpoint set at the switch statement so that you can step-into your methods if something is not working. In conjunction with running the debugger, you should also create a canvas drag the items of interest (e.g., the Scanner on the file, your HexagonalPrismList object, etc.) onto the canvas and save it. As you play or step through your program, you’ll be able to see the state of these objects change when the ‘R’, ‘A’, and ‘D’ options are selected. Although your program may not use all the methods in your HexagonalPrism and HexagonalPrismList classes, you should ensure that all your methods work according to the specification. You can run your program in the canvas and then after the file has been read in, you can call methods on the HexagonalPrismList object in interactions, or you can write another class and main method to exercise the methods. Web-CAT will test all methods to determine your project grade.

$25.00 View

[SOLVED] Comp1210 project: hexagonalprism list app

Overview: You will write a program this week that is composed of three classes: the first class defines HexagonalPrism objects, the second class defines HexagonalPrismList objects, and the third, HexagonalPrismListApp, reads in a file name entered by the user then reads the list name and HexagonalPrism data from the file, creates HexagonalPrism objects and stores them in an ArrayList of HexagonalPrism objects, creates an HexagonalPrismList object with the list name and ArrayList, Project: HexagonalPrism List App Page 2 of 8 Page 2 of 8 prints the HexagonalPrismList object, and then prints summary information about the HexagonalPrismList object. • HexagonalPrism.java (assuming that you successfully created this class in the previous project, just copy the file to your new project folder and go on to HexagonalPrismList.java on page 4. Otherwise, you will need to create HexagonalPrism.java as part of this project.) Requirements: Create a HexagonalPrism class that stores the label, edge, and height. The HexagonalPrism class also includes methods to set and get each of these fields, as well as methods to calculate the surface area, lateral surface area, base area, and volume of a HexagonalPrism object, and a method to provide a String value of a HexagonalPrism object (i.e., a class instance). Design: The HexagonalPrism class has fields, a constructor, and methods as outlined below. (1) Fields (instance variables): label of type String, edge of type double, and height of type double. Initialize the String to “” and the doubles to zero in their respective declarations. These instance variables should be private so that they are not directly accessible from outside of the HexagonalPrism class, and these should be the only instance variables in the class. (2) Constructor: Your HexagonalPrism class must contain a public constructor that accepts three parameters (see types of above) representing the label, edge, and height. Instead of assigning the parameters directly to the fields, the respective set method for each field (described below) should be called. For example, instead of the statement label = labelIn; use the statement setLabel(labelIn); Below are examples of how the constructor could be used to create HexagonalPrism objects. Note that although String and numeric literals are used for the actual parameters (or arguments) in these examples, variables of the required type could have been used instead of the literals. HexagonalPrism ex1 = new HexagonalPrism (“Ex 1″, 3.0, 5.0); HexagonalPrism ex2 = new HexagonalPrism (” Ex 2 “, 21.3, 10.4); HexagonalPrism ex3 = new HexagonalPrism (“Ex 3”, 10.0, 204.5); (3) Methods: Usually a class provides methods to access and modify each of its instance variables (known as get and set methods) along with any other required methods. The methods for HexagonalPrism, which should each be public, are described below. See formulas in Code and Test below. o getLabel: Accepts no parameters and returns a String representing the label field. o setLabel: Takes a String parameter and returns a boolean. If the string parameter is not null, then the label field is set to the “trimmed” String and the method returns true. Otherwise, the method returns false, and the label field is not set. Project: HexagonalPrism List App Page 3 of 8 Page 3 of 8 o getEdge: Accepts no parameters and returns a double representing the edge field. o setEdge: Accepts a double parameter and returns a boolean as follows. If the parameter is greater than zero, sets the edge field to the double passed in and returns true. Otherwise, the method returns false, and the edge field is not set. o getHeight: Accepts no parameters and returns a double representing the height field. o setHeight: Accepts a double parameter and returns a boolean as follows. If the parameter is greater than zero, sets the height field to the double passed in and returns true. Otherwise, the method returns false, and the height field is not set. o surfaceArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. o lateralSurfaceArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. o baseArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. o volume: Accepts no parameters and returns the double value for the volume calculated using the using the formula above. o toString: Returns a String containing the information about the HexagonalPrism object formatted as shown below, including decimal formatting (“#,##0.0##”) for the double values. Newline escape sequences should be used to achieve the proper layout. In addition to the field values (or corresponding “get” methods), the following methods should be used to compute appropriate values in the toString method: lateralSurfaceArea(), baseArea(), surfaceArea(), and volume(). Each line should have no leading and no trailing spaces (e.g., there should be no spaces before a newline ( ) character). The results of printing the toString value of ex1, ex2, and ex3 respectively are shown below. HexagonalPrism “Ex 1” has 8 faces, 18 edges, and 12 vertices. edge = 3.0 units height = 5.0 units lateral surface area = 90.0 square units base area = 23.383 square units surface area = 136.765 square units volume = 116.913 cubic units HexagonalPrism “Ex 2” has 8 faces, 18 edges, and 12 vertices. edge = 21.3 units height = 10.4 units lateral surface area = 1,329.12 square units base area = 1,178.721 square units surface area = 3,686.562 square units volume = 12,258.7 cubic units Project: HexagonalPrism List App Page 4 of 8 Page 4 of 8 HexagonalPrism “Ex 3” has 8 faces, 18 edges, and 12 vertices. edge = 10.0 units height = 204.5 units lateral surface area = 12,270.0 square units base area = 259.808 square units surface area = 12,789.615 square units volume = 53,130.659 cubic units Code and Test: As you implement your HexagonalPrism class, you should compile it and then test it using interactions. For example, as soon you have implemented and successfully compiled the constructor, you should create instances of HexagonalPrism in interactions (e.g., copy/paste the examples above on page 2). Remember that when you have an instance on the workbench, you can unfold it to see its values. You can also open a viewer canvas window and drag the instance from the Workbench tab to the canvas window. After you have implemented and compiled one or more methods, create an HexagonalPrism object in interactions and invoke each of your methods on the object to make sure the methods are working as intended. You may find it useful to create a separate class with a main method that creates an instance of HexagonalPrism then prints it out. This would be similar to the HexagonalPrismApp class you will create below, except that in the HexagonalPrismApp class you will read in the values and then create and print the object. • HexagonalPrismList.java Requirements: Create an HexagonalPrismList class that stores the name of the list and an ArrayList of HexagonalPrism objects. It also includes methods that return the name of the list, number of HexagonalPrism objects in the HexagonalPrismList, total surface area, total volume, average surface, and average volume for all HexagonalPrism objects in the HexagonalPrismList. The toString method returns a String containing the name of the list followed by each HexagonalPrism in the ArrayList, and a summaryInfo method returns summary information about the list (see below). Design: The HexagonalPrismList class has two fields, a constructor, and methods as outlined below. (1) Fields (or instance variables): (1) a String representing the name of the list and (2) an ArrayList of HexagonalPrism objects. These are the only fields (or instance variables) that this class should have, and both should be private. (2) Constructor: Your HexagonalPrismList class must contain a constructor that accepts a parameter of type String representing the name of the list and a parameter of type ArrayList representing the list of HexagonalPrism objects. These parameters should be used to assign the fields described above (i.e., the instance variables). (3) Methods: The methods for HexagonalPrismList are described below. o getName: Returns a String representing the name of the list. Project: HexagonalPrism List App Page 5 of 8 Page 5 of 8 o numberOfHexagonalPrisms: Returns an int representing the number of HexagonalPrism objects in the HexagonalPrismList. If there are zero HexagonalPrism objects in the list, zero should be returned. o totalSurfaceArea: Returns a double representing the total surface area for all HexagonalPrism objects in the list. If there are zero HexagonalPrism objects in the list, zero should be returned. o totalVolume: Returns a double representing the total volume for all HexagonalPrism objects in the list. If there are zero HexagonalPrism objects in the list, zero should be returned. o averageSurfaceArea: Returns a double representing the average surface area for all HexagonalPrism objects in the list. If there are zero HexagonalPrism objects in the list, zero should be returned. o averageVolume: Returns a double representing the average volume for all HexagonalPrism objects in the list. If there are zero HexagonalPrism objects in the list, zero should be returned. o toString: Returns a String (does not begin with ) containing the name of the list followed by each HexagonalPrism in the ArrayList. In the process of creating the return result, this toString() method should include a while loop that calls the toString() method for each HexagonalPrism object in the list (adding a before and after each). Be sure to include appropriate newline escape sequences. For an example, see lines 3 through 28 in the output below from HexagonalPrismListApp for the HexagonalPrism_data_1.txt input file. [Note that the toString result should not include the summary items in lines 30 through 36 of the example. These lines represent the return value of the summaryInfo method below.] o summaryInfo: Returns a String (does not begin with ) containing the name of the list (which can change depending on the value read from the file) followed by various summary items: number of HexagonalPrism objects, total surface area, total volume, average surface area, and average volume. Use “#,##0.0##” as the pattern to format the double values. For an example, see lines 30 through 36 in the output below from HexagonalPrismListApp for the HexagonalPrism_data_1.txt input file. The second example below shows the output from HexagonalPrismListApp for the HexagonalPrism_data_0.txt input file which contains a list name but no HexagonalPrism data. Code and Test: Remember to import java.util.ArrayList. Each of the four methods above that finds a total or average requires that you use a loop (i.e., a while loop) to retrieve each object in the ArrayList. As you implement your HexagonalPrismList class, you can compile it and then test it using interactions. However, it may be easier to create a class with a simple main method that creates an HexagonalPrismList object and calls its methods. • HexagonalPrismListApp.java Requirements: Create an HexagonalPrismListApp class with a main method that (1) reads in the name of the data file entered by the user and (2) reads list name and HexagonalPrism data from the file, (3) creates HexagonalPrism objects, storing them in a local ArrayList of HexagonalPrism objects; and finally, (4) creates an HexagonalPrismList object with the name of the list and the ArrayList of HexagonalPrism objects, and then prints the HexagonalPrismList object followed Project: HexagonalPrism List App Page 6 of 8 Page 6 of 8 summary information about the HexagonalPrismList object. All input and output for this project must be done in the main method. • Design: The main method should prompt the user to enter a file name, and then it should read in the data file. The first record (or line) in the file contains the name of the list. This is followed by the data for the HexagonalPrism objects. Within a while loop, each set of HexagonalPrism data (i.e., label, edge, and height) is read in, and then a HexagonalPrism object should be created and added to the local ArrayList of HexagonalPrism objects. After the file has been read in and the ArrayList has been populated, the main method should create a HexagonalPrismList object with the name of the list and the ArrayList of HexagonalPrism objects as parameters in the constructor. It should then print the HexagonalPrismList object, and then print the summary information about the HexagonalPrismList (i.e., print the value returned by the summaryInfo method for the HexagonalPrismList). The output from two runs of the main method in HexagonalPrismListApp is shown below. The first is produced after reading in the HexagonalPrism_data_1.txt file, and the second is produced after reading in the HexagonalPrism_data_0.txt file. Your program output should be formatted exactly as shown on the next page. Example 1 Line # Program output 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 Enter file name: HexagonalPrismList_data_1.txt —– HexagonalPrism Test List —– HexagonalPrism “Ex 1” has 8 faces, 18 edges, and 12 vertices. edge = 3.0 units height = 5.0 units lateral surface area = 90.0 square units base area = 23.383 square units surface area = 136.765 square units volume = 116.913 cubic units HexagonalPrism “Ex 2” has 8 faces, 18 edges, and 12 vertices. edge = 21.3 units height = 10.4 units lateral surface area = 1,329.12 square units base area = 1,178.721 square units surface area = 3,686.562 square units volume = 12,258.7 cubic units HexagonalPrism “Ex 3” has 8 faces, 18 edges, and 12 vertices. edge = 10.0 units height = 204.5 units lateral surface area = 12,270.0 square units base area = 259.808 square units surface area = 12,789.615 square units volume = 53,130.659 cubic units —– Summary for HexagonalPrism Test List —– Number of HexagonalPrisms: 3 Total Surface Area: 16,612.943 square units Total Volume: 65,506.272 cubic units Average Surface Area: 5,537.648 square units Average Volume: 21,835.424 cubic units Project: HexagonalPrism List App Page 7 of 8 Page 7 of 8 Example 2 Line # Program output 1 2 3 4 5 6 7 8 9 10 11 12 Enter file name: HexagonalPrismList_data_0.txt —– HexagonalPrism Empty Test List —– —– Summary for HexagonalPrism Empty Test List —– Number of HexagonalPrisms: 0 Total Surface Area: 0.0 square units Total Volume: 0.0 cubic units Average Surface Area: 0.0 square units Average Volume: 0.0 cubic units Code: Remember to import java.util.ArrayList, java.util.Scanner, and java.io.File, and java.io.FileNotFoundException prior to the class declaration. Your main method declaration should indicate that main throws FileNotFoundException. After your program reads in the file name from the keyboard, it should read in the data file using a Scanner object that was created on a file using the file name entered by the user. … = new Scanner(new File(fileName)); You can assume that the first line in the data file is the name of the list, and then each set of three lines contains the data from which an HexagonalPrism object can be created. After the name of the list has been read and assigned to a local variable, a while loop should be used to read in the HexagonalPrism data. The boolean expression for the while loop should be (_________.hasNext()) where the blank is the name of the Scanner you created on the file. Each iteration through the loop reads three lines. As each of the lines is read from the file, the respective local variables for the HexagonalPrism data items (label, edge, height) should be assigned, after which the HexagonalPrism object should be created and added to a local ArrayList of HexagonalPrism objects. The next iteration of the loop should then read the next set of three lines then create the next HexagonalPrism object and add it to the local ArrayList of HexagonalPrism objects, and so on. After the file has been processed (i.e., when the loop terminates after the hasNext method returns false), name of the list and the ArrayList of HexagonalPrism objects should be used to create an HexagonalPrismList object. Then the list should be printed by printing a leading and the HexagonalPrismList object. Finally, the summary information is printed by printing a leading and the value returned by the summaryInfo method invoked on the HexagonalPrismList object. Test: You should test your program minimally (1) by reading in the HexagonalPrism_data_1.txt input file, which should produce the first output above, and (2) by reading in the HexagonalPrism_data_0.txt input file, which should produce the second output above. Although your program may not use all the methods in the HexagonalPrismList and HexagonalPrism classes, you should ensure that all your methods work according to the specification. You can either user interactions in jGRASP or you can write another class and main method to exercise the methods. Web-CAT will test all methods to determine your project grade. Project: HexagonalPrism List App Page 8 of 8 Page 8 of 8 General Notes 1. All input from the keyboard and all output to the screen should done in the main method. Only one Scanner object on System.in should be created and this should be done in the main method. All printing (i.e., using the System.out.print and/or System.out.println methods) should be in the main method. Hence, none of your methods in the HexagonalPrism and HexagonalPrismList classes should do any input/output (I/O). 2. Be sure to download the test data files (HexagonalPrism_data_1.txt and HexagonalPrism_data_0.txt) and store them in same folder as your source files. It may be useful examine the contents of the data files. Find the data files in the jGRASP Browse tab and then open each data file in jGRASP to see the items that your program will be reading from the file. Be sure to close the data files without changing them.

$25.00 View

[SOLVED] Comp1210 project: hexagonalprism app

Overview: You will write a program this week that is composed of two classes: (1) HexagonalPrism, which defines right regular HexagonalPrism objects (base and top of prism are hexagons with all sides equal), and (2) HexagonalPrismApp, which has a main method that reads in data, creates an HexagonalPrism object, and then prints the object. The Hexagonal Prism is a prism with hexagonal base. This polyhedron has 8 faces, 18 edges, and 12 vertices. The formulas are provided to assist you in computing return values for the respective methods in the HexagonalPrism class described in this project. (Sources: “Google” Hexagonal Prism; https://en.wikipedia.org/wiki/Hexagonal_prism) Formulas for surface area (A), lateral surface area (��), base area (��), and volume (V) are shown below where � is the base edge length and h is height, both of which will be read in. � = 6�ℎ + 3√3 �! �” = 6�ℎ �# = 3√3 �! 2 � = 3 √3 2 �!ℎ Project: HexagonalPrism App Page 2 of 6 Page 2 of 6 • HexagonalPrism.java Requirements: Create a HexagonalPrism class that stores the label, edge, and height. The HexagonalPrism class also includes methods to set and get each of these fields, as well as methods to calculate the surface area, lateral surface area, base area, and volume of a HexagonalPrism object, and a method to provide a String value of a HexagonalPrism object (i.e., a class instance). Design: The HexagonalPrism class has fields, a constructor, and methods as outlined below. (1) Fields (instance variables): label of type String, edge of type double, and height of type double. Initialize the String to “” and the doubles to zero in their respective declarations. These instance variables should be private so that they are not directly accessible from outside of the HexagonalPrism class, and these should be the only instance variables in the class. (2) Constructor: Your HexagonalPrism class must contain a public constructor that accepts three parameters (see types of above) representing the label, edge, and height. Instead of assigning the parameters directly to the fields, the respective set method for each field (described below) should be called. For example, instead of the statement label = labelIn; use the statement setLabel(labelIn); Below are examples of how the constructor could be used to create HexagonalPrism objects. Note that although String and numeric literals are used for the actual parameters (or arguments) in these examples, variables of the required type could have been used instead of the literals. HexagonalPrism ex1 = new HexagonalPrism (“Ex 1″, 3.0, 5.0); HexagonalPrism ex2 = new HexagonalPrism (” Ex 2 “, 21.3, 10.4); HexagonalPrism ex3 = new HexagonalPrism (“Ex 3”, 10.0, 204.5); (3) Methods: Usually a class provides methods to access and modify each of its instance variables (known as get and set methods) along with any other required methods. The methods for HexagonalPrism, which should each be public, are described below. See formulas in Code and Test below. o getLabel: Accepts no parameters and returns a String representing the label field. o setLabel: Takes a String parameter and returns a boolean. If the string parameter is not null, then the label field is set to the “trimmed” String and the method returns true. Otherwise, the method returns false and the label field is not set. o getEdge: Accepts no parameters and returns a double representing the edge field. o setEdge: Accepts a double parameter and returns a boolean as follows. If the parameter is greater than zero, sets the edge field to the double passed in and returns true. Otherwise, the method returns false, and the edge field is not set. o getHeight: Accepts no parameters and returns a double representing the height field. o setHeight: Accepts a double parameter and returns a boolean as follows. If the parameter is greater than zero, sets the height field to the double passed in and returns true. Otherwise, the method returns false, and the height field is not set. o surfaceArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. Project: HexagonalPrism App Page 3 of 6 Page 3 of 6 o lateralSurfaceArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. o baseArea: Accepts no parameters and returns the double value for the surface area calculated using the formula above. o volume: Accepts no parameters and returns the double value for the volume calculated using the using the formula above. o toString: Returns a String containing the information about the HexagonalPrism object formatted as shown below, including decimal formatting (“#,##0.0##”) for the double values. Newline escape sequences should be used to achieve the proper layout. In addition to the field values (or corresponding “get” methods), the following methods should be used to compute appropriate values in the toString method: lateralSurfaceArea(), baseArea(), surfaceArea(), and volume(). Each line should have no leading and no trailing spaces (e.g., there should be no spaces before a newline ( ) character). The results of printing the toString value of ex1, ex2, and ex3 respectively are shown below. HexagonalPrism “Ex 1” has 8 faces, 18 edges, and 12 vertices. edge = 3.0 units height = 5.0 units lateral surface area = 90.0 square units base area = 23.383 square units surface area = 136.765 square units volume = 116.913 cubic units HexagonalPrism “Ex 2” has 8 faces, 18 edges, and 12 vertices. edge = 21.3 units height = 10.4 units lateral surface area = 1,329.12 square units base area = 1,178.721 square units surface area = 3,686.562 square units volume = 12,258.7 cubic units HexagonalPrism “Ex 3” has 8 faces, 18 edges, and 12 vertices. edge = 10.0 units height = 204.5 units lateral surface area = 12,270.0 square units base area = 259.808 square units surface area = 12,789.615 square units volume = 53,130.659 cubic units Code and Test: As you implement your HexagonalPrism class, you should compile it and then test it using interactions. For example, as soon you have implemented and successfully compiled the constructor, you should create instances of HexagonalPrism in interactions (e.g., copy/paste the examples above on page 2). Remember that when you have an instance on the workbench, you can unfold it to see its values. You can also open a viewer canvas window and drag the instance from the Workbench tab to the canvas window. After you have implemented and compiled one or more methods, create an HexagonalPrism object in interactions and invoke each of your methods on the object to make sure the methods are working as intended. You may find it useful to create a separate class with a main method that creates an instance of HexagonalPrism then prints it out. This would be similar to the HexagonalPrismApp class you will create below, except that in the HexagonalPrismApp class you will read in the values and then create and print the object. Project: HexagonalPrism App Page 4 of 6 Page 4 of 6 • HexagonalPrismApp.java Requirements: Create an HexagonalPrismApp class with a main method that reads in values for label, edge, and height. After the values have been read in, main creates an HexagonalPrism object and then prints a new line and the object. Design: The main method should prompt the user to enter the label, edge, and height. After a value is read in for the edge or height, if the value is less than or equal to zero, an appropriate message (see examples below) should be printed followed by a return statement. Assuming that the edge and height are positive, an HexagonalPrism object should be created and printed. Below is an example where the user has entered a negative value for edge followed by an example using the values from the first example above for label, edge, and height. Your program input/output should be exactly as follows. Example #0A Line # Program input/output 1 2 3 4 5 Enter label, edge, and height for a hexagonal prism. label: Ex 0A edge: -4.0 Error: edge must be greater than zero. Example #0B Line # Program input/output 1 2 3 4 5 6 Enter label, edge, and height for a hexagonal prism. label: Ex 0B edge: 4.0 height: 0.0 Error: height must be greater than zero. Example #1 Line # Program input/output 1 2 3 4 5 6 7 8 9 10 11 12 13 Enter label, edge, and height for a hexagonal prism. label: Ex 1 edge: 3.0 height: 5.0 HexagonalPrism “Ex 1” has 8 faces, 18 edges, and 12 vertices. edge = 3.0 units height = 5.0 units lateral surface area = 90.0 square units base area = 23.383 square units surface area = 136.765 square units volume = 116.913 cubic units Project: HexagonalPrism App Page 5 of 6 Page 5 of 6 Example #2 Line # Program input/output 1 2 3 4 5 6 7 8 9 10 11 12 13 Enter label, edge, and height for a hexagonal prism. label: Ex 2 edge: 21.3 height: 10.4 HexagonalPrism “Ex 2” has 8 faces, 18 edges, and 12 vertices. edge = 21.3 units height = 10.4 units lateral surface area = 1,329.12 square units base area = 1,178.721 square units surface area = 3,686.562 square units volume = 12,258.7 cubic units Example #3 Line # Program input/output 1 2 3 4 5 6 7 8 9 10 11 12 13 Enter label, edge, and height for a hexagonal prism. label: Ex 3 edge: 10.0 height: 204.5 HexagonalPrism “Ex 3” has 8 faces, 18 edges, and 12 vertices. edge = 10.0 units height = 204.5 units lateral surface area = 12,270.0 square units base area = 259.808 square units surface area = 12,789.615 square units volume = 53,130.659 cubic units Code: Your program should use the nextLine method of the Scanner class to read user input. Note that this method returns the input as a String, even when it appears to be numeric value. Whenever necessary, you can use the Double.parseDouble method to convert the input String to a double. For example, Double.parseDouble(s1) will return the double value represented by String s1, assuming s1 represents a numeric value. For the printed lines requesting input for label, edge, and height, use a tab “t” rather than three spaces. After reading in the values, create the new HexagonalPrism, say hp, then print it: System.out.println(“ ” + hp); Test: You should test several sets of data to make sure that your program is working correctly. Although your main method may not use all the methods in HexagonalPrism, you should ensure that all your methods work according to the specification. You can use interactions in jGRASP or you can write another class and main method to exercise the methods. The viewer canvas should also be helpful, especially using the “Basic” viewer and the “toString” viewer for an HexagonalPrism object. Web-CAT will test all the methods specified above for HexagonalPrism to determine your project grade. Project: HexagonalPrism App Page 6 of 6 Page 6 of 6 General Notes 1. All input from the keyboard and all output to the screen should done in the main method. Only one Scanner object on System.in should be created and this should be done in the main method. All printing (i.e., using the System.out.print and System.out.println methods) should be in the main method. Hence, none of your methods in the HexagonalPrism class should do any input/output (I/O). 2. When a method has a return value, you can ignore the return value if it is no interest in the current context. For example, when setEdge(3.5) is invoked, it returns true to let the caller know the edge field was set; whereas setEdge(-3.5) will return false since the edge field was not set. So, if the caller knows that x is positive, then the return value of setEdge(x) can safely be ignored since it can be assumed to be true. 3. Even though you may not be using the return value of a method, you can ensure that the return value is correct using interactions in jGRASP. 4. In a method with a void return type (e.g., main), the return statement (return;) can be used immediately return from the method. This is commonly used to exit the method when some condition is not met. For example, suppose a value for time is read in by main and should be greater than or equal to zero. If time is less than zero, an error message should be printed, and the program should immediately end by returning from main as shown in the code below. if (time < 0) { System.out.println(“Error: time must be non-negative.”); return;

$25.00 View

[SOLVED] Comp1210 project: using java api classes

Overview: You will write two programs this week. The first will solve for the result of a specified expression using methods from the Math class, and the second will read data for a coded box lunch order and then interpret and print the formatted order information. • RadicalFormula.java Requirements: Solve for the result of the expression in the formula below for a value x of type double which is read in from the keyboard, and save the result in a variable of the type double. You must use the pow, sqrt, and abs methods of the Math class to perform the calculation. You may use a single assignment statement with a single expression, or you may break the expression into appropriate multiple assignment statements. The latter may easier to debug if you are not getting the correct result. !(��� − ���)� + |��� − ���| Next, determine the number of characters (mostly digits) to the left and to the right of the decimal point in the unformatted result. [Hint: You should consider converting the type double result into a String using the static method Double.toString(result) and storing it into a String variable. Then, on this String variable invoke the indexOf(“.”) method from the String class to find the position of the period (i.e., decimal point) and the length() method to find the length of the String. Knowing the location of the decimal point and the length, you should be able to determine the number of digits on each side of the decimal point.] Finally, the result should be printed using the class java.text.DecimalFormat so that to the right of the decimal there are at most three digits and to the left of the decimal each group of three digits is separated by a comma in the traditional way. Also, there should also be at least one digit on each side of the decimal (e.g., 0 should be printed as 0.0). Hint: Use the pattern “#,##0.0##” when you create your DecimalFormat object. However, make sure you know what this pattern means and how to modify and use it in the future. Project: Using Java API Classes Page 2 of 5 Page 2 of 5 Design: Several examples of input/output for the RadicalFormula program are shown below. Example #1 Line # Program output 1 2 3 4 5 6 Enter a value for x: 1 Result: 1.4142135623730951 # digits to left of decimal point: 1 # digits to right of decimal point: 16 Formatted Result: 1.414 Example #2 Line # Program output 1 2 3 4 5 6 Enter a value for x: -2.5 Result: 4608.915111500769 # digits to left of decimal point: 4 # digits to right of decimal point: 12 Formatted Result: 4,608.915 Example #3 Line # Program output 1 2 3 4 5 6 Enter a value for x: 5.1 Result: 1372773.0387854169 # digits to left of decimal point: 7 # digits to right of decimal point: 10 Formatted Result: 1,372,773.039 Example #4 Line # Program output 1 2 3 4 5 6 Enter a value for x: 1234.567 Result: 1.618969128395518E25 # digits to left of decimal point: 1 # digits to right of decimal point: 18 Formatted Result: 16,189,691,283,955,180,000,000,000.0 When the characters to the right of the decimal in the unformatted result end with E followed by one or more digits (e.g., E25 indicates an exponent of 25), the ‘E’ should be included in the count of the characters to the right of the decimal point. Code: To receive full credit for this assignment, you must use the appropriate Java API classes and method to do the calculation and formatting. It is recommended as a practice that you do not modify the input value once it is stored. Project: Using Java API Classes Page 3 of 5 Page 3 of 5 Test: You will be responsible for testing your program, and it is important to not rely only on the examples above. Assume that the amount entered can be any positive or negative floating-point number. • BoxLunch.java Requirements: The purpose of this program is to accept coded box lunch order as input that includes the theme, the number of adult meals, price of adult meal, number of child meals, price of child meal, and name of the customer. Note that the four digits for the two price fields have an implied decimal point. The program should then print the user’s order information including the total, as well as a “lucky number” between 1 and 9999 inclusive that should always be printed as four digits (e.g., 1 should be printed as 0001). The coded input is formatted as follows: 0151895060695Pat Smith customer’s name (goes through last character in the code) price per child meal (0695 has an implied decimal point for 6.95) number of child meals price per adult meal (1895 has an implied decimal point for 18.95) number of adult meals theme (0 for Birthday, 1 for Graduation, other values for Holiday) Whitespace before or after the coded information should be disregarded (e.g., if the user enters spaces or tabs before or after the coded information, these should be disregarded). Your program will need to print the customer’s name, number of adult meals, price per adult meal, number of child meals, price per child meal, total, the theme, and a random “lucky” number in the range 1 to 9999 as shown in the examples below. If the user enters a code that does not have at least 13 characters, then an error message should be printed. [The 14th character if present is part of the customer’s name.] Design: Several examples of input/output for the program are shown below. The box lunch order code below is invalid since it does not include the required minimum of 13 characters. Example #1 Line # Program output 1 2 3 4 5 Enter order code: 123456789 *** Invalid Order Code *** Order code must have at least 13 characters. Project: Using Java API Classes Page 4 of 5 Page 4 of 5 Note that the order codes entered in the examples below result in the indicated output except for the prize number which is random. Example #2 Line # Program output 1 2 3 4 5 6 7 8 9 Enter order code: 0151895060695Pat Smith Name: Pat Smith Adult meals: 15 at $18.95 Child meals: 6 at $6.95 Total: $325.95 Theme: Birthday Lucky Number: 1008 Example #3 Line # Program output 1 2 3 4 5 6 7 8 9 Enter order code: 1091895020695Sam Jones Name: Sam Jones Adult meals: 9 at $18.95 Child meals: 2 at $6.95 Total: $184.45 Theme: Graduation Lucky Number: 3737 Example #4 The order code below has five leading spaces (be sure to trim the input code). Line # Program output 1 2 3 4 5 6 7 8 9 Enter order code: 7431550290425Becky’s Big Party Name: Becky’s Big Party Adult meals: 43 at $15.50 Child meals: 29 at $4.25 Total: $789.75 Theme: Holiday Lucky Number: 9645 Code: To receive full credit for this assignment, you must use the appropriate Java API classes and methods to trim the input string, to extract the substrings, conversion of substrings of digits to numeric values as appropriate, and formatting. These include the String methods trim, and substring, as well as wrapper class methods such Double.parseDouble and Integer.parseInt which can be used to convert a String of digits into a numeric value for price and number of meals. The Project: Using Java API Classes Page 5 of 5 Page 5 of 5 dollar amounts should be formatted so that both small and large amounts are displayed properly, and the prize number should be formatted so that seven digits are displayed including leading zeroes, if needed, as shown in the examples above. It is recommended as a practice that you not modify input values once they are stored. Test: You are responsible for testing your program, and it is important to not rely only on the examples above. Remember, when entering standard input in the Run I/O window, you can use the up-arrow on the keyboard to get the previous values you have entered. This will avoid having to retype the order code each time you run your program. Hints: 1. The order code should be read in all at once using the Scanner’s nextLine method and stored in a variable of type String. Then the individual values should be extracted using the substring method. The String value for the meal prices should be converted to type double (using Double.parseDouble) and the String value for number of meals should be converted to type int (using Integer.parseInt) so that these can be used to Total cost. When printing the values for meal prices, total, and prize number, they should be formatted properly by creating an appropriate DecimalFormat object (see patterns below) and calling its format method. To format meal prices and total, use the pattern “$#,##0.00” when you create your DecimalFormat object. The number of meals does not require formatting. For prize number, use the pattern “0000” when you create your DecimalFormat object. 2. Since all items in the order code other than the prices and number of meals will not be used in arithmetic expressions, they can be left as type String. Grading Web-CAT Submission: You must submit both “completed” programs to Web-CAT at the same time. Prior to submitting, be sure that your programs are working correctly and that they have passed Checkstyle. If you do not submit both programs at once, Web-CAT will not be able to compile and run its test files with your programs which means the submission will receive zero points for correctness. I recommend that you create a jGRASP project and add the two files. Then you will be able to submit the project to Web-CAT from jGRASP. Activity 1 (pages 5 and 6) describes how to create a jGRASP project containing both of your files.

$25.00 View

[SOLVED] Comp1210 project: introduction to java

Overview: You will write two programs this week. One will print your short-term, medium-term, and long-term life goals to standard output, and the other will display letter J as a large block letter. Because these are small programs, you will only need to have 1-2 sentences of description in your class and method Javadoc comments (don’t forget the @author and @version tags in the class-level comment in each file). • MyLifeGoals.java Requirements: Write the application MyLifeGoals that prints your name, your short-term, medium-term and long-term life goals. Design: Your program should contain a main method that prints the information listed under “Output” (i.e., your output should replace the text in Italics). Output: Your first and last name (separated by a space) (The second line should be blank) Describe your short-term life goals.(in one line) Describe your medium-term life goals. (in one line) Describe your long-term life goals. (in one line) Describe your life goals (if you have never thought about them, this is a good chance to think about them carefully). The actual output for each line of goals should be at least 100 characters not including spaces. Page 1 of Activity 1 shows how to break up a String literal in your program (where lines cannot exceed 80 characters) in order to print a longer line. Code and Test: The expected output for the program will vary from student to student, but it is important to follow output pattern described above, formatting requirements, and minimum character requirements. If you are not sure how many characters (no spaces) are in your output, you can copy your output into Microsoft Word then select the line (paragraph) of output. Then select the Word “Review” tab and click “Word Count” in the Proofing group on the far left. Project: Introduction to Java Page 2 of 2 Page 2 of 2 • JLetter.java Requirements: Write the application JLetter that displays letter J as a large block letter composed of the characters ‘J’, ‘A’, ‘V’, ‘A’ arranged in a pattern with a width of 12 characters and a height of 10 lines. Each line should begin in column 1 with appropriate leading spaces in lines 3, 4, 5, and 6. Trailing spaces at the end of each line should be avoided. Design: Your program should contain a main method that prints exact the same pattern as shown in Figure 1. You should have 10 lines of output with each line in the pattern indicated. JAVAJAVAJAVA JAVAJAVAJAVA JAVA JAVA JAVA JAVA J JAVA JA JAVA JAVAJAVA JAVAJA Figure 1. Output from JLetter programCode and Test: The expected output contains 10 lines of letters in the specified order. Note that the first line of output has no leading spaces. Make sure that you print the pattern exactly as it appears above. Grading Web-CAT Submission: Prior to submitting to Web-CAT, you should complete both programs and make sure that they appear to be working correctly. You will have 10 attempts to receive full credit for your two program files, but you should try to get everything right on the first submission. You must submit both programs files at the same time. If you only submit one of the files, the submission will receive zero points for correctness. Creating a jGRASP Project and adding the two files will make Web-CAT submission from jGRASP much more straightforward. [Instructions for creating a jGRASP project can be found in Activity 1 (p. 5-6).]

$25.00 View

[SOLVED] Comp1210 project: variables and expressions

Overview: You will write two programs this week. One will solve for the result of a specified formula after reading input values for x, y, and z, and the other will determine the number of miles, yards, feet, and inches for an input value of a raw distance in inches. • MySolver.java Requirements: A program is needed that inputs values of type double for x, y, and z and solves for the result of the indicated formula when z is not equal to zero. If z is equal to zero, then the result is zero. Design: The result should be calculated as follows: ������ = (8.5� + 6.1) (10� + 7.9) � for z ≠ 0 Special case: ������ �� ��������� for z = 0 Three examples of program output for the indicated input values are shown below. Note that lines 2 through 4 for the input values begin with tab which is equivalent to three spaces in jGRASP (i.e., your output should use the escape sequence for a tab). Example #1 Line # Program output 1 2 3 4 5 6 result = (8.5x + 6.1) (10y + 7.9) / z Enter x: 3.5 Enter y: 1.5 Enter z: 0.0 result is undefined Project: Variables and Expressions Page 2 of 3 Page 2 of 3 Example #2 Line # Program output 1 2 3 4 5 6 result = (8.5x + 6.1) (10y + 7.9) / z Enter x: 1 Enter y: 1 Enter z: 1 result = 261.34 Example #3 Line # Program output 1 2 3 4 5 6 result = (8.5x + 6.1) (10y + 7.9) / z Enter x: 23.5 Enter y: 35.8 Enter z: 10.0 result = 7532.0515 Code: Your numeric variables should be of type double. Use an if-else statement to determine if the divisor in the formula is zero. Note that in Example #1, the value of z is zero so the divisor is zero. Test: You are responsible for testing your program, and it is important to not rely only on the examples above. Remember that the input values are doubles, so be sure to test both positive and negative values (with and without a decimal point) for x, y, and z. You should use a calculator or jGRASP interactions to check your answers. • LaserMeasure.java Requirements: A digital laser measure manufacturer would like a program that accepts a raw distance measurement in inches (of type int) and then displays the distance as a combination of miles, yards, feet, and inches for both short and long distances (e.g., from onboard and an aircraft). When a negative raw distance measurement is entered, an appropriate message is printed as shown in the first example below. Design: The digital laser measure manufacturer would like the output to look as shown below when each of the indicated test values is entered as the raw distance for separate runs of the program. Example #1 Line # Program output 1 2 3 Enter the raw distance measurement in inches: -36 Measurement must be non-negative! Project: Variables and Expressions Page 3 of 3 Page 3 of 3 Example #2 Line # Program output 1 2 3 4 5 6 7 8 9 10 Enter the raw distance measurement in inches: 63409 Measurement by combined miles, yards, feet, inches: miles: 1 yards: 1 feet: 1 inches: 1 63409 in = 1 mi, 1 yd, 1 ft, 1 in Example #3 Line # Program output 1 2 3 4 5 6 7 8 9 10 Enter the raw distance measurement in inches: 1234567890 Measurement by combined miles, yards, feet, inches: miles: 19484 yards: 1712 feet: 1 inches: 6 1234567890 in = 19484 mi, 1712 yd, 1 ft, 6 in Your program must follow the above format with respect to the output. Note that lines 4 through 7 in two previous examples begin with tab (i.e., your output should use the escape sequence for a tab). Code: In order to receive full credit for this assignment, you must calculate the number of miles, yards, feet, and inches and store each of the values in separate variables. Create a Scanner object on System.in to read in the value for the raw distance using the nextInt() method. It is recommended as a practice that you do not modify input values once they are read in and stored. Test: You will be responsible for testing your program, and it is important to not rely only on the example above. Assume that the amount entered can be any integer less than or equal to 2,147,483,647 (the maximum value for a 32-bit int) and greater than or equal to -2,147,483,648 (the minimum value for a 32-bit int). Grading Web-CAT Submission: You must submit both “completed” programs to Web-CAT at the same time. Prior to submitting, be sure that your programs are working correctly and that have passed Checkstyle. If you do not submit both programs at once, the submission will receive zero points for correctness. Activity 1 describes how to create a jGRASP project containing both of your files.

$25.00 View

[SOLVED] program

Creative Audio-VisualApplicationDeveloping creative applications using contemporary techniquesFinal Submission: Blackboard. Thurs. 1st May 2025 | 13:59 Module: Introduction to Creative Coding (UFCF8L-30-1) Semester 2: 27th January 2025 – 23rd May 2025(Easter vacation 7th April 2025 – 25th April 2025) Task: Creative Audio-Visual ApplicationWeighting: 60%Contact Time: 3 hrs per week Reading/Coursework preparation: 5 hrs per week Module Teaching email: [email protected] Digital Media BSc, University of the West of England //2024-2025//Assignment Overview (image from bork Doy: https://medium.com/@borkdoy/generative-art-triangles-with-p5-js-f1c9e3f50739)This assignment is designed so that you can build on the feedback you received from the first coursework and create an awesome interactive web piece for your portfolio. It will facilitate your independent learning of programming, creative and critical thinking that you have undertaken throughout this term. Your task is to produce a single cohesive interactive audio- visual piece of work which can focus on one of these three themes: audio-visual artwork, AI experience or game.In order to do this, you will carry out the following activities individually:• Activity A – Conduct research into contemporary web based interactive art/AI experiences/games.• Activity B – Design and program a creative, interactive artwork/AI experience/game with a minimum of two different states, scenes or levels.• Activity C – Write a design and evaluation report that synthesises research and reflections on practical work.• Activity D – Create and record a demonstration video, presenting your interactive work.2 Digital Media BSc, University of the West of England //2024-2025// DeliverablesThe following is a list of the specific deliverables that must be submitted in order to fulfil the requirements of the brief. You will submit and be assessed individually on:Interactive Audio-Visual Project (70%):• One web-based interactive audio-visual piece (i.e. artwork, AI experience or game) hosted online (e.g. on the panel server, codepen.io, editor.p5js.org etc).• All code must be submitted in the same folder structure as is hosted on the server. It must be submitted via Blackboard as a .zip file.• URL of the audio-visual piece needs to be submitted to Blackboard in a text file (.txt).Design and Evaluation Report (20%):• A three-page design and evaluation report with URL to your piece submitted as a PDF via Blackboard.Demonstration Video Presentation (10%):• 2-4 Minute demonstration video presentation. This should be hosted on a videoservice such as YouTube or Vimeo. Submitted as a URL via Blackboard. Important dates1st May 2025 at 13:59 – Blackboard submission.Deliverable SpecificationsAudio-visual ProjectYou may choose one of the following three options (please discuss with your module tutors which you think would be suitable):1. A web-based interactive audio-visual artwork with a minimum of two states/scenes.2. A web-based interactive experience using Artificial Intelligence (e.g. using ml5.js) with a minimum of two states/scenes.3. A simple web-based game with a minimum of two levels.Please be aware, games are generally more complex. The option that you pick will not affect your mark – complexity does not necessarily mean a higher mark. We are focusing not only on code structure but also the creativity on show.Further detail on the options:3 Digital Media BSc, University of the West of England //2024-2025//1. The audio-visual artwork should be a piece developed around an artistic or design theme. It could be exploring something abstract such as “Simple Harmonic Motion” by Memo Akten (https://www.memo.tv/simple-harmonic-motion/) or something more tangible like an interactive narrative, such as “Solace” by Evan Boehm (https://experiments.withgoogle.com/solace).2. The AI experience should make use of the ml5.js (https://ml5js.org/) library. For inspiration, please explore some of the creative projects made using this library in the community section (https://ml5js.org/community/).3. The game does not have to be hugely complex, in terms of gameplay and graphics. But it should involve some goal directed activity which involves multiple levels (minimum of two). Gameplay logic is more complex to program so please discuss with your module tutors if you are unsure about this option. Examples include: https://p5js.org/examples/interaction-snake-game.html and https://sub-tropic.itch.io/amoeba-blasterWhichever option you choose:- Your piece must be contained within one p5.js sketch and hosted online (e.g. on the panel server, codepen.io, editor.p5js.org etc).- There must be a minimum of two states/scenes/levels. This means two distinct but thematically related parts of the piece. This could mean combinations of changing colour schemes; difficulty level; interaction mechanics; animation style or other methods.- You may use standard and/or alternative methods of interaction. Standard in this context means keyboard and mouse. Alternative in this context means camera or microphone.- Your piece must contain some reactive sonic element. This may just be simple sound effects related to clicks, or may be something more complex such as being based on collision.Code Submission in .zipYou must submit exactly the same code in exactly the same folder structure as is running online (e.g. on the panel server, codepen.io, editor.p5js.org etc). This should be zipped up and submitted via Blackboard. We ask you to do this so that we can look through your code in a code editor where it is easier to read.ReportWrite a design and evaluation report. This should have two main sections: “Design” and “Evaluation”. The “Design” section should contain the most important parts of the research and inspiration you collated from looking at the different design work in Activity A. It should also contain a short explanation of the code to demonstrate understanding. 4 Digital Media BSc, University of the West of England //2024-2025//The “Evaluation” section should contain a brief analysis of what you felt was successful and what needs improvement about your work.You need to ensure that your report contains references to artistic/design work that has inspired you. You also must reference any code snippets you have taken from elsewhere. All references must make use of the UWE Harvard referencing style (https://www.uwe.ac.uk/study/study-support/study-skills/referencing).VideoThe video is a chance for you to show your piece in action. We ask you to this to ensure that you have done the work and can explain it in your own words. You do not have to show your face, it can just be a screen recording with you talking during the demonstration. Think about what you need to show the markers to demonstrate your understanding of the creative and technical elements of your work.You are not expected to do any editing in the video itself, it can be a single take. But do make sure you rehearse and that it is no longer than 4 minutes.Marking GuidanceA full rubric is provided at the end of this document.Creative Audio-visual Application (70%)- Code quality (35%)The functionality of your code, implementing all of the programming constructs taught on the module. Higher marks will be given for code that functions without any errors. Please ensure no errors are being displayed in the console.- Commenting (10%)- Detailed comments which to demonstrate understanding and explain functionality to others.- Creativity (25%)Use your visual ingenuity to create novel design pieces. Higher marks will be given for those who clearly use their research as inspiration and then build upon it to create something novel.Report (20%)- Design (5%)o Qualityofresearch:Have a variety of sources been used? Have books, websites and journal articles been read in detail?o Demonstrationofhowresearchinformeddesign: 5 Digital Media BSc, University of the West of England //2024-2025//How clear is it that the research has directly influenced the outputs? - Evaluation (15%)o Criticalanalysisofworkcreated:Reflect on whether the work was successful and why.o Thoughtsonhowtoimprovethework:Outline what you would do to make the work better in the future.Video (10%)- Video Demonstration of Understanding:o Demonstrationofallfeaturesofthepiece.o Clarityofpresentation.o Qualityoflinkagebetweenfeaturesandsectionsofcodei.ewhichpartsof the code do which parts of the experience.Study Support:The following links provide detailed information on study skill provision and UWE academic policy. In submitting your final submission for examination you agree that you have read the following guides linked to below:• Digital Media BSc Learning Policy:• UWE Study skills: http://goo.gl/NalwD5• UWE Word count policy: http://goo.gl/Qe8kbg• UWE Referencing policy (UWE Harvard): http://goo.gl/Iu3S3L• UWE Plagiarism policy: http://goo.gl/vAHWOp• UWE Academic appeal process: http://goo.gl/Tf1nv3Plagiarism Advice:The usual university strictures about plagiarism apply to this assignment. It is good practice in academic writing to reference correctly the work of others that you may draw upon for your own. Please help us to clearly distinguish your original efforts by so doing.If you use code from other sites, the sources must be referenced in your Bibliography. If you use any other site(s) as a source of ideas for your site, you must reference the source. If you copy code and/or ideas from another student's work, or even if you are helped by another student, you must reference/acknowledge the source.• UWE Plagiarism policy: http://goo.gl/vAHWOp 6 Digital Media BSc, University of the West of England //2024-2025//References:https://p5js.org/ p5, your best friend!https://ml5js.org/ Machine learning library.http://p5play.molleindustria.org/ p5 game engine Machine learning library. https://github.com/bitcraftlab/p5.gui p5 graphical user interface library. https://thecodingtrain.com/ The Coding Train – video tutorials with Dan Shiffman. http://www.creativeapplications.net/ Inspiration! 7Rubric Deliverable Deliverable Sub- section FAIL: Fails to achieve module outcomes.0-30% FAIL: Marginally fails to achieve module outcomes. 30-40% PASS: Achieves module outcomes.40-50% PASS: Achieves module outcomes.50-60% PASS: Achieves module outcomes.60-70% PASS: Achieves and exceeds module outcomes.70-100% Interactive Audio Visual Project (70%) Quality of Code (35%) Code is not present or does not function. Code is present but is not functional. Or functions for some time then crashes. Code is jumbled and messy, not formatted well and very difficult to read. Code functions with a lot of errors. JavaScript console fills up with errors very quickly. Code is jumbled and messy, not formatted well and very difficult to read. Code only implements basic techniques shown in class. Code functions with no errors in the JS console. Code is formatted to a satisfactory level, is legible and structured well. Code implements basic and more complex techniques shown in class.Code functions with no errors in the JS console. Code is formatted to a good level, is legible and structured very well. Goes above and beyond what is specified in the brief on at least one element. Code implements significant use of complex techniques shown in class. Some techniques taken from independent study implemented with limited success. Code functions with no errors in the JS console. Code is formatted to an excellent level, is legible and structured very well. Programming methods that have not been taught in class have been implemented successfully. Code implements significant use of complex techniques shown in class. Techniques drawn from independent study implemented successfully. Commenting (10%) No comments. Very few comments showing a deep lack of understanding. Very few comments showing limited understanding. Comments throughout, showing some understanding. Comments throughout, showing significantly developed understanding. Comments throughout, showing significantly developed understanding of concepts and methods shown both in class and through independent research. Creativity (25%) No code functionality to determine whether creativity has occurred. Very little code functionality to determine whether creativity has occurred. Generative drawing displays basic creativity with limited inspiration derived from the research. Generative drawing displays good creativity drawing some inspiration from the research to create a new piece. Generative drawing displays very good creativity drawing clear inspiration from the research to create a new piece. Generative drawing displays excellent creativity with explicit inspiration drawn from the research to create a novel and aesthetically rich artwork. Design and Evaluation Report (20%) No report submitted. Incoherent/unread able/illegible report submitted. Very basic design research undertaken. Unclear as to how it relates to the project. Very little evaluation, analysis Some design research undertaken. Basic links have been made relating it to the project. Some effort at evaluation, analysis and reflection is Good design research undertaken. Very clearly linked to the project. Good effort at evaluation, analysis and reflection is provided. Good number and range of sources provided. Excellent design research undertaken. Very clearly linked to the project. Deep and insightful evaluation, analysis and reflection is provided. Large number and range of relevant Digital Media BSc, University of the West of England //2024-2025// and reflection is provided. No sources provided.provided. Limited sources provided. number and range ofsources provided. Demonstration Video (10%) No video submitted. Video URL is submitted but cannot be accessed/is not viewable. Basic demonstration provided. Not clear that much of the creative or technical elements of the piece are understood by the student. Satisfactory demonstration provided with some good elements. Clarity of understanding is shown in parts, but other sections there are errors or lack of detail. Comprehensive demonstration provided with most elements shown and explained. Clarity of understanding is shown throughout. Outstanding demonstration provided with all elements shown and explained with rigor and in an articulate manner. Clarity of understanding is shown throughout explaining where you have gone above and beyond the brief. 9

$25.00 View

[SOLVED] program c/

DISTRIBUTED SYSTEMS APIDistributed Systems ACW2024/25You have been hired as a distributed systems programmer after Gribbald, their previous expert disappeared one foggy night. You’ve been promised that your first job for them won’t be very hard and, thankfully, it’s really not. The task is to develop a client/server, using ASP.NET Core Web API, which provides a number of extra secret security andencryption services... sort of.You’re lucky though. Gribbald was working on this project before you and has already created an outline solution with some ‘TODO’ regions, based on the original specification. They have also broken down the specification into tasks for you, which should make your life even easier!On your first day you were handed this specification:• The server must be able to handle multiple client requests simultaneously.• The server must use Entity Framework, Code First, to create and manage a local database of Users (that will,in the future be moved over to a production database).• The client must be able to get a TalkBack/Hello message from the server. The server will respond with “HelloWorld”.• The client must be able to send a TalkBack/Sort message as a get request to the server with an array ofintegers as parameters. The server will sort the integers into ascending order and return the sorted array tothe client, because – well, sorting data is tedious.• The client must be able to send a User/New get request to the server which has a username string as aparameter. The server must return a string identifying if the username already exists in the database.• The client must be able to send a User/New post request to the server which has a username string in the request body. The server must create a new user, generate a new GUID as an API Key, save the user to the database and return the API Key to the user. If this is the first user they should be saved as Admin role,otherwise just with User role.• The client must be able to send a User/RemoveUser delete request to the server with an API Key in the headerand a string username in the URI. If the server receives this request, it must check to see if the API Key is in the database and, if it is, it must check that the username and API Key are the same user and if they are, it must delete this user from the database.• The client must be able to send a User/ChangeRole Post request to the server with an API Key in the header which links to an Admin role user, a string username in the body and a string role in the body. If the server receives this request, it must check to see if the API Key is in the database and whether the role is Admin, if it is, it must update the role for the given username to the role provided (User or Admin)• The client must be able to send a Protected/Hello get request to the server with an API Key in the header. If the server receives this request, it must check to see if the API Key is in the database and, if it is, it must get the username associated with the API Key and send back “Hello ” (e.g. “Hello UserOne”).• The client must be able to send a Protected/SHA1 get request to the server with an API Key in the header and a string message as a parameter. If the server receives this request, it must check to see if the API Key is in the database and, if it is, it must compute the SHA1 hash of the message and return it in hexadecimal form to the client.• Somebody told the boss that SHA256 is more secure than SHA1 so the client must be able to send a Protected/SHA256 get request to the server with an API Key in the header and a string message as a parameter. If the server receives this request, it must check to see if the API Key is in the database and, if it is, it must compute the SHA256 hash of the message and return it in hexadecimal form to the client. 1• The client must be able to send a Protected/GetPublicKey get request to the server with an API Key in the header. If the server receives this request, it must check to see if the API Key is in the database and, if it is, it must send back its RSA public key.• The client must be able to send a Protected/Sign request with an API Key in the header and a string message as a parameter. If the server receives this request, it must check to see if the API Key is in the database and, if it is, it must digitally sign the message with its private RSA key and send the signed message back to the client. The client must then be able to verify that the server signed the message by using the server’s public RSA key.• Finally, the client must be able to send a Protected/Mashify get request to the server with an API Key in the header which links to an Admin role user, and three strings in the body comprising:o A string of text, encrypted using the server’s public RSA keyo A symmetric key (using AES encryption), encrypted using the server’s public RSA keyo An IV (initialization vector) for the symmetric key, also encrypted using the server’s public RSA keyIf the server receives this request, it must...o check to see if the API Key is in the database and whether the role is Admin,o if it is, it must decrypt all three parameters using its private RSA key.o It must then ‘mashify’ the string it was given (see task 14), encrypt the mashified string using theclient’s symmetric (AES) key and IV ando finally, it must send the newly encrypted string back to the client.The client must then be able to...o decrypt the string using its symmetric (AES) key and IV and o finally, output the new mashified string to the console.Your task is to follow the next instructions carefully and develop a console-based client and Web API-Based server with a Code First Entity Framework Database.➢ You must use the skeleton solution as your starting point, and➢ You must ensure that you carefully follow instructions on request types and names, parameter naming,responses and response types – if you do not conform to these instructions, some of the marking tools will not be able to find your code and you will receive a mark of 0 in affected areas.Please do not, under any circumstances, publish your work on a public source code repository – even after you leave the University. We have had issues in the past with students using public repositories (e.g. on GitHub) and their work being plagairised (e.g. by people doing reassessment). In these circumstances it becomes very difficult to ascertain who was cheating and both parties may be penalised for collusion under the academic misconduct policy, which can have severe academic consequences. Furthermore, the skeleton code remains the intellectual property of the University of Hull and you are not permitted to share this publicly. You may, however, use any of the solution (including the skeleton code) in your future work and share your solution privately (e.g. a repository set to private) with prospective employers, etc., as you wish. 2InstructionsDownload the skeleton solution from Canvas and unzip it. You may delete or modify any of the code that has already been written if you want, but for the most part you will only need to add to it. Note how there are a number of regions and comments that identify tasks by number – use these as a guide to identify where you might want to add your code.The ServerThe server that you have been given in the skeleton solution is an ASP.NET Web API. You may find it useful to refer to the Microsoft documentation on Web API. You should also recognise it from labs and lecture material.There are a few things you should look at before you start working on the server:1. Open TalkBackController.cs – Gribbald started writing this controller before they mysteriously disappeared. It will contain two get request actions for /API/TalkBack/Hello and /API/Talkback/Sort. Task1 will be to complete these methods, but they should also be a guide to help you get started – you may change any of the code you feel needs to be changed.2. Open Pipeline->Auth->CustomAuthenticationHandler.cs – this is custom authentication middleware that is added inside Program.cs. This means that whenever an HTTP request is made, this method will run before the request gets to your controller. You will need to modify this method in TASK5 to verify that the API Key in the header is correct and authenticate the user. There is a similar CustomAuthorizationHandler – middleware that runs immediately after authentication if the authentication succeeds. You will need to make changes to this code in TASK6. The use of these handlers is directly linked to the Authorize attribute.3. Notice the error handling middleware and filter inside Pipeline->ErrorHandling.4. Open BaseController.cs – you should note four things:a. This is an abstract class. You cannot make an instance of this controller.b. It inherits from ControllerBase and has the attribute ApiController – all Controllers need to descendfrom ControllerBase and have the attribute ApiController.c. It stores a protected instance of the Database Context that you’ll need to use for your data access.d. The route mapping has been changed to api/{controller}/{action} which will allow you to callactions inside your controller (e.g. /API/TalkBack/Hello, where TalkBack is the controller and Hellois the action).BaseController is an abstract base class you should inherit from to retain the above functionality in your controllers. If you open TalkbackController.cs you can see that it inherits from BaseController. To make your life easier use this as a template for any new controllers you create.Before you start working on your server, you may find it useful to use a tool which allows you to craft requests (with control over the header/body/URI/etc.) send them to your server for debugging purposes and receive RESTful responses. This means you won’t need to have a working client to test your server out. A suitable (and free) tool is PostMan: https://www.getpostman.com/apps Follow the module instructions on setting up a student account.Finally, make sure you use the test server. This server responds as per this coursework specification. If your server responds in exactly the same way as the test server then you are likely to get a good mark for the server elements of this coursework. If your client works properly with the test server then you can be confident it is working properly too. You may use Postman to analyse the responses from the test server before you start producing your server. There’s more info at the end of TASK10 but the test server can be accessed by pointing your client to:http://150.237.94.9//e.g. http://150.237.94.9/1234567/Api/TalkBack/HelloYour unique 7 digit code should have been distributed to you via email already but if you have not received this then email me: [email protected] 3TasksThe following tasks are designed to help you identify exactly what to do to meet the specification and they give a logical order for doing it too. You must ensure that your server and client respond exactly as specified to get the marks for that section, so read this specification very carefully. Most tasks also have a section dedicated to testing so that you can test your solution against expected results. If your server and client do not respond exactly as specified you will not receive marks for the corresponding marking criteria.Task1:When the client makes a get request for api/TalkBack/Hello or api/TalkBack/Sort, the talkback controller must handle the responses.Complete these methods so that they offer the responses detailed in the specification.Once you have created these methods, right-click the server project, select Debug and click Start New Instance. This should fire up IIS, open your browser and take you to a web page with an address similar to localhost:53415 where 53415 is your portnumber. Identify what this port number is as it will be required in your client and for testing.For your personal testing you can identify if your server is working by sending a get request with the URI (replace with your port number) of: For Hello: For Sort:Task2:In order to work with databases, you have been asked to use Entity Framework Core.Gribbald has already put all of the references, etc. that you will need into the project. You just need to define a User class.Open Models->User.cs, where you will find the Task2 region. Complete the User class with:• An empty constructor• A public string ApiKey property (which is the unique database key and is the API Key for the user)• A public string UserName property (which is the username of the user)• A public string or enum Role property (which saves the role of the user)UserContext.cs has been created for you already, but to create the database correctly you’ll need to generate a migration*.*You may first need to set the project directory in the Package Manager Consolelocalhost:/api/talkback/helloMust return "Hello World" in the body of the result with a status code of OK (200)localhost:/api/talkback/sort?integers=8&integers=2&integers=5 Must return [2,5,8] in the body of the result with a status code of OK (200)If there are no integers submitted, must return [] in the body with a status code of OK (200)If the submitted integers are invalid (e.g. a char is submitted) the server must return with a with a status code of BAD REQUEST (400) 4Task3:You should keep your controller classes only loosely coupled to the database access code. Ensuring your code is nicely abstracted is good coding practice as it will allow you to easily swap out the data access logic in the future without editing your controllers. You may like to create these data access functions now.For the next tasks, you may need database access such as:1. Create a new user, using a username given as a parameter and creating a new GUID which is saved as a string to the database as the ApiKey. This must return the ApiKey or the User object so that the server can pass the Key back to the client.2. Check if a user with a given ApiKey string exists in the database, returning true or false.3. Check if a user with a given ApiKey and UserName exists in the database, returning true or false.4. Check if a user with a given ApiKey string exists in the database, returning the User object.5. Delete a user with a given ApiKey from the databaseHint: The BaseController already contains an instance of UserContextConsider: What happens in your solution if two admin users simultaneously try to change a user’s role?Task4:When the client makes a api/User/New get request or api/User/New post request, the server must be able to handle them and provide a response.Create a new controller called UserController. The easiest way to do this is by right-clicking on Controllers and adding a new, Empty API Controller. You may want to inspect the existing TalkBack Controller to help set up your new controller – note it’s base type, constructor and routing.Both of these actions have the name ‘New’ but one is a GET request that takes its parameter from the URI and the other is a POST request that takes a JSON string parameter from the body. The POST request must use a content-type of application/json. Note the difference between a JSON string and a JSON Object with a string.For your personal testing you can identify if your server is working by sending a get request with the URI (replace with your port number) of: For GET:localhost:/api/user/new?username=UserOneIf a user with the username ‘UserOne’ exists in the database, the server must return "True - User Does Exist! Did you mean to do a POST to create a new user?" in the body of the result with a status code of OK (200)If a user with the username ‘UserOne’ does not exist in the database, the server must return "False - User Does Not Exist! Did you mean to do a POST to create a new user?" in the body of the result with a status code of OK (200).If there is no string submitted, the server must return "False - User Does Not Exist! Did you mean to do a POST to create a new user?" in the body of the result with a status code of OK (200).localhost:/api/user/new with only “UserOne” in the body of the requestShould create a new User with the username ‘UserOne’, generate a new GUID as the user’s API Key, and then add the new user to the database. Finally, the server must return the API Key as a string to the client with a status code of OK(200). If this is the first user they should be saved as Admin role, otherwise just with User role.If there is no string submitted in the body, the result should be "Oops. Make sure your body contains a string with your username and your Content-Type is Content-Type:application/json" with a status code of BAD REQUEST (400)If the username is alrady taken, the result should be "Oops. This username is already in use. Please try again with a new username." with a status code of FORBIDDEN (403)For POST:5Task5:The client now has the ability to ask for an API Key, so our server will now need to be able to determine if a request has a valid API Key in its header. A useful way to do this is to use an Authentication Scheme. Ours is a custom Authentication Scheme so we can investige its functionality. Return to CustomAuthenticationHandler.cs. You must add code to HandleAuthenticateAsync which tries to get the header ‘ApiKey’, and if it does exist, checks the database to determine if the given API Key is valid. You should use your UserDatabaseAccess class that you created in TASK3 to do the database access to loosen your coupling.If the API Key is valid, you must get the relevant User from your database and set up a:• Claim of type ClaimTypes.Name, using the user’s UserName as the string value• Claim of type ClaimTypes.Role, using the user’s Role as the string value• ClaimsIdentity with an authentication type of “ApiKey”, using an array containing both of your Claims• ClaimsPrinciple, using the ClaimsIdentity above.Finally, you must create an AuthenticationTicket using the ClaimsPrinciple and the scheme name (you can get this using the property: this.Scheme.Name). You can now use the ticket to create a Success AuthenticateResult and return as a Task.If this is working, you should be able to use attributes such as [Authorize(Roles = "Admin")] or [Authorize(Roles = "Admin, User")] to authorise requests which require a valid API key to be present.If a user is not found, return a Fail AuthenticateResult and pass a 401 error with the JSON string "Unauthorized. Check ApiKey in Header is correct." back to the user (see HandleChallengeAsync).Task6:So far we haven’t used any of our Roles. Before we can do this we’ll need to check that our users have the roles they are supposed to. We are already looking at whether or not they have a valid API key (Task5), and we’re using that easily by applying an attribute, so we’ll use a filter to modify the response.Most of the filter has already been written. Open CustomAuthorizationHandler.cs and modify the code so that, when the action requires a user to be in Admin role ONLY (e.g. [Authorize(Roles = "Admin")]) and the user does not have the Admin role, you return a Forbidden status (403) with the message: "Forbidden. Admin access only.". You will need the injected IHttpContextAccessor for this.Task7:Add to your UserController a method to handle an api/User/RemoveUser DELETE request.• A user with role User or Admin should be able to use this request.• The client must send its API Key in the header and a string username in the URI.If the server receives this request, it must extract the ApiKey string from the header to see if the API Key is in the database and, if it is, it must check that the username and API Key are the same user and if they are, it must delete this user from the database. You should probably use your UserDatabaseAccess class that you created in TASK3 to do the database access.This method must return a Boolean value only. If a user has been deleted, the server must return true, otherwise, the server must return false. In both cases, the server must return a status code of OK (200).For your personal testing you can identify if your server is working by sending a delete request with the URI (replace with your port number and with a username) of:RemoveUser: localhost:/api/user/removeuser?username= with an ApiKey in the header of the requestMust return true if the ApiKey and username match, are valid, and a user has been deleted or false if not. 6 Task8:Inside UserController Add the api/User/ChangeRole method.This method must only be accessible to users who are authorised by API key and have the role of Admin. Update the role for the given username to the role provided (User or Admin).The body should contain a JSON object in the form (where is the given username string and is the given role string):{ "username":, "role": }For your personal testing you can identify if your server is working by sending a post request with the URI (replace with your port number) of:ChangeRole: localhost:/api/user/changerole with an ApiKey in the header of the request, a string username in the body and a string role in the bodyIf success: Must return "DONE" in the body of the result, with a status code of OK (200)If username does not exist: Must return "NOT DONE: Username does not exist" in the body of the result, with a status code of BAD REQUEST (400)If role is not User or Admin: Must return "NOT DONE: Role does not exist" in the body of the result, with a status code of BAD REQUEST (400)In all other error cases: Must return "NOT DONE: An error occured" in the body of the result, with a status code of BAD REQUEST (400)Task9:Create a new ProtectedController. Add the api/Protected/Hello method, api/Protected/SHA1 method and api/Protected/SHA256 method.All of these requests must be authorised (User or Admin role) and all three must return strings to the client. You may use the .NET SHA1 and SHA256 types for SHA1 and SHA256 hashing respectively.Both SHA1 and SHA256 methods must take a string message from the URI and both must return the hexadecimal hash as a string with no additional characters (e.g. no delimiters like -)For your personal testing you can identify if your server is working by sending a get request with the URI (replace with your port number) of: For Hello:For SHA1:For SHA256: localhost:/api/protected/sha256?message=helloMust return "2CF24DBA5FB0A30E26E83B2AC5B9E29E1B161E5C1FA7425E73043362938B9824" in the body of theresult with a status code of OK (200)If there is no message string submitted, the result should be "Bad Request" with a status code of BAD REQUEST (400)localhost:/api/protected/hello with an ApiKey in the header of the requestMust return "Hello " in the body of the result, where UserName is the User’s UserName from the database, with a status code of OK (200). E.g. “Hello UserOne”.localhost:/api/protected/sha1?message=helloMust return "AAF4C61DDCC5E8A2DABEDE0F3B482CD9AEA9434D" in the body of the result with a status code of OK(200)If there is no message string submitted, the result should be "Bad Request" with a status code of BAD REQUEST (400)7Task10:If you have not already started, begin to write the client (in project DistSysAcwClient) now as the next server tasks are the most difficult and you should get the basic functionality of your client working before you attempt them.The client must be a console application. It would make sense to use System.Net.Http.HttpClient. You don’t need to use HttpClient but your client must be able to perform all of the same functions. Your client must request and expect a JSON response type. When your client is opened it should show: “Hello. What would you like to do?” and wait for user input. Below is what the client must be able to do... Input String from Console Window Example Example Request Response Client Function Output to Console Window TalkBack HelloTalkBack Sort User Get User Set TalkBack HelloTalkBack Sort [6,1,8,4,3]User Get UserOneUser Set UserOne 004b620d-a523-4b1b- 8bdc-857d8a5541b9localhost:/api/talkback/ hellolocalhost:/api/talkback/ sort?integers=6&integers=1&integers= 8&integers=4&integers=3localhost:/api/user/new ?username=UserOneNone – this function is only in the clientstring int[]stringn/aNone NoneNoneStore given API Key and username as variablesResponse stringResponse as a stringResponse string“Stored” User Post User Post UserOne localhost:/api/user/new with “UserOne” in the request body string Check status of response. Store API Key and username as variables if response: OK “Got API Key” if OK, else print response string. User Delete User Delete Client must get the locally stored username and ApiKey. If they don’t yet exist the console must print “You need to do a User Post or User Set first”.localhost:/api/user/remo veuser?username=(with in the URI)with ApiKey: in the header Boolean None “True” if delete succeeded, otherwise “False” User Role User Role UserOne AdminClient must get the locally stored ApiKey. If it doesn’t yet exist the console must print “You need to do a User Post or User Set firstlocalhost:/api/user/chan gerolewith ApiKey: in the header and with the JSON object:{“username” : “UserOne”, “role” : “Admin”}in the request body stringNone Response as a string Protected Hello Protected Hello Client must get the locally stored ApiKey. If it doesn’t yet exist the console must print “You need to do a User Post or User Set first”. string None Response string 8 localhost:/api/protected/ hellowith ApiKey: in the header Protected SHA1 Protected SHA1 Hello Client must get the locally stored ApiKey. If it doesn’t yet exist the console must print “You need to do a User Post or User Set firstlocalhost:/api/protected/ sha1?message=Hellowith ApiKey: in the header string None Response String Protected SHA256 Protected SHA256 Hello Client must get the locally stored ApiKey. If it doesn’t yet exist the console must print “You need to do a User Post or User Set first”.localhost:/api/protected/ sha256?message=Hellowith ApiKey: in the header string None Response StringIf an error is returned, from your server, you must write out the error to the console or write out the given error string if one is specified in the Output to Console Window column. The Console must output error messages and never crash.The client application should be asynchronous. The console must write “...please wait...” to the console window as the request is sent and then write the output once the asynchronous Task has been completed. After the output has been written, the console must write (on a new line) “What would you like to do next?”. When a new input is entered, the Console Window must be cleared.If the user enters “Exit” (without quotes), the console must close.Whilst you do not have to, you may wish to have the console read/write to a file to save a valid UserName and ApiKey, so that you don’t have to do a User Post or User Set every time you restart your application to test any of the requests that require a username or ApiKey. If you do this, you should ensure that the software will run on another computer.Hint: you may find some of the information on this page useful: https://docs.microsoft.com/en- us/dotnet/csharp/tutorials/console-webapiclient 9**TEST SERVER**As specified previously in this document, there is a test server from which to test your client and check that your server responds in the same way. This test server acts as the ‘gold standard’. If your server responds in the same way you can be certain that you will get the associated mark(s). You are very much encouraged to use the test server as you will receive no marks for client functionality which does not work against the test server (even if it works against your server).I would very much advise you to create a single place in your client-side code (e.g. a const) which stores the first part of your URL and then allows you to revert to using your server by changing only one line or config file.The test domain is: http://150.237.94.9// e.g. http://150.237.94.9/1234567/Api/TalkBack/HelloYour unique 7 digit code should have been distributed via email but if you have not received this or you find a bug in the test server prototype then please email me: [email protected]. I would recommend you don’t share your code as it provides data isolation - someone else editing your data may interfere with your testing.You should ensure that when you hand in your solution it is configured to access and use your local server, not the test server.➢ There is an additional useful command on the test server. You can run this command from any browser or from Postman so you don’t need to implement it into your Client:http://150.237.94.9//Api/Other/ClearThis command clears all users and logs from your account on the test server, refreshing it back to empty. This may help during testing. You do not need to replicate this command on your server/client unless you want to; there are no marks for other/clear. 10Task11:First, set up an RSA Crypto Service Provider which is configured once and the same across all threads. You must not make a new key pair for each client but you may generate a new key pair each time the server starts. The private RSA key must be stored securely (it would be a good idea to use the machine key store as we are using Windows).Now, returning the public key should be as simple as returning the XmlString created by your RSA Crypto Service Provider, containing the public RSA key for your server.This request must be authorised (User or Admin role).On receiving an api/Protected/GetPublicKey get request, the server must check to see if the API Key is in thedatabase and, if it is, it must send back its RSA public key.Remember not to send over the private key!!For your personal testing you can identify if your server is working by sending a get request with the URI (replace with your port number) of:GetPublicKey: localhost:/api/protected/getpublickey with an ApiKey in the header of the request Must return the XmlString containing the public key, which should look something like this:"rSJEEeLC4H452XFL+taho/473M5OKdfSC/PKNFk55xOx/M5HbDxG9ihoENpazG7OHsGit b0aXfn2qEVzhaaTtUJUKyO+sV2nQ6aaE0rwFUK0XxttFX1ann/d3qNTrlVxWdzygGq8ODn7qzvijcXjR/S2iyEguSNOuwhU O/M98sk=AQAB"Now add the functionality to your client which will allow it to store the public key. You can store the key however you like, but it must be usable when you need to encrypt something to send it to the server. Input String from Console Window Example Request Response Client Function Output to Console Window Protected Get PublicKey Protected Get PublicKey Client must get the locally stored ApiKey. If it doesn’t yet exist the console must print “You need to do a User Post or User Set first”.localhost:/api/protected/ getpubl

$25.00 View

[SOLVED] Review Questions AD/AS models Phillips Curve expectations

Review Questions – AD/AS models, Phillips Curve, expectations (1) Use the IS/LM framework to explain why the aggregate demand curve is downward sloping (2). In the sticky-price model, describe the aggregate supply curve in the following special cases. How do these cases compare to the short-run aggregate supply curve we discussed in Chapter 10? 1. All firms have sticky prices (s = 1). 2. The desired price does not depend on aggregate output (a = 0). (3). Suppose that an economy has the Phillips curve π = π−1 − 0.5(u − 5). 1. What is the natural rate of unemployment? 2. Graph the short-run and long-run relationships between inflation and unemployment. 3. How much cyclical unemployment is necessary to reduce inflation by 4 percentage points? Using Okun’s law, compute the sacrifice ratio. 4. Inflation is running at 6 percent. The central bank wants to reduce it to 2 percent. Give two scenarios that will achieve that goal. (4) for the following aggregate demand and aggregate supply curves, Case 1 Qd = 100/P Qs = 10 Case 2 Qd = 10 Qs = (P + 110)1/2 1. Contrast and algebraically discuss the equilibrium level of prices (and thereby output and employment) in the two cases above 2. Which demand curve shows money illusion 3. Which supply curve is classical and which is Keynesian? Why? (5) compare and contrast the perfect foresight, adaptive expectation, and rational expectation approach to forming expectations.

$25.00 View

[SOLVED] ENG5009 Advanced Control 5 Assignment

ENG5009 Advanced Control 5 Assignment Introduction This assignment is presented as a challenge within control engineering and is split into two parts: 1. Create a controller that can control a mobile robot to a selected waypoint, 2. Create a controller, or combine controllers, that can command a mobile robot to follow a series of waypoints while avoiding obstacles. You will be required to write a report on the approach you took to complete the tasks outlined. This should include: · A description of the controller used, or controllers and method of switching, · How the parameters for the control system were selected, · Highlight and describe any testing carried out, · Results should be provided and discussed, · Improvements, if any, should be highlighted. If you are not able to complete the waypoint path, then a detailed report on the approach you took, the debugging steps you undertook (with results), and the how you would work towards completing the challenge is acceptable. The report should be a MAXIMUM of 10 pages (not including appendices). A marking scheme is provided on the course Moodle page. For the report a standard engineering report structure could be followed a, for example: · Introduction · Methodology/Approach · Testing · Results · Discussion · Appendices All resources are provided on the course Moodle page, and you can ask for help in the laboratories and over email. You are also free to use the Fuzzy Logic Toolbox but ensure justification of the methods used is made. Task 1 Develop a controller that can drive the robot to a selected point. The position of the robot can be assumed to be accurately know via robot_x and robot_y. The first stage of developing this controller is to establish the direction that the robot is required to drive in. To achieve this, you can use the following function to work out the required heading: [booleanAtCheckpoint, newHeadingAngle] = ComputeHeadingAngle(currentLocation, checkpoint, tolerance) in which: currentLocation – the current coordinates of the robot, you can use state(timeStep,19:20) checkpoint – the coordinates of the checkpoint the robot is aiming for now tolerance – if the robot is within an x meter radius of the target it is considered at the waypoint (use x = 0.05) booleanAtCheckpoint – returns 1 if the robot reached the checkpoint and 0 if not newHeadingAngle – the heading angle to move towards the given checkpoint Once you have implemented the above controller, provide a plot showing the robot driving through  the points provided in Table 1 consecutively. Table 1: Points to travel through Point Y (x-axis) X (y-axis) Origin 0 0 1 -1 -1 2 -3 1 3 2 1 4 3 -3 5 -3 -3 Task 2 The final stage of the assignment is to create a controller based on either fuzzy logic, a Neural network or a combination of both, or any other suitable controller that can be justified, that is able to guide a robot to a particular point (within 0.05m radius of the point) while avoiding obstacles. Table 2 provides the point that are to be travelled too consecutively. Figure 1 provides the map in which the robot is to operate in. Code snippet 1 provides the required. It should be noted that the outer edge of the map is also considered an obstacle.  To add in the obstacles uncomment the relevant lines of code in the code file. Table 2: Points to travel through Point Y (x-axis) X (y-axis) Origin 0 0 1 -1 -1 2 1 -4 3 3 3 4 -4 4 5 -2 -4 Figure 1: Map of environment robot is to navigate in

$25.00 View

[SOLVED] ENT204TC Corporate Entrepreneurship CW2 2024-2025 Statistics

Entrepreneurship & Enterprise Hub ENT204TC Corporate Entrepreneurship Module Leader: Assoc. Prof. Pietro Borsano CW2: Individual Reflection Report Assessment Brief First Part of Semester 2 Academic Year 2024-2025 Assessment Task: Reflect on Course Work 1 and your learning experience in regards to corporate entrepreneurship and intrapreneurial projects, your individual contribution within the group work, and what you have learned from those experiences in this module. Specific tasks should include the following: 1.   Reflect on your learning experience in CW1, and your individual contribution 2.   Identify and analyse the challenges that the company face (Note: challenges related to CW1, therefore linked to 1) Entrepreneurial Orientation; 2) Leadership; 3) Organizational Structure) 3.   Reflect on how entrepreneurial leadership can be further developed and how this can be helpful for problem solving and secure a competitive advantage. 4.   Compare different forms of entrepreneurship (Note: Entrepreneurship here is broadly interpreted as Entrepreneurial Mindset & Behaviour as well as Entrepreneurial Orientation) and, based on the company case from your CW1, provide recommendations for the company to continue fostering and sustaining innovation. Learning Outcomes Tested: A.  Assess the entrepreneurial orientation of an organization and evaluate the company’s ability to deal with the opportunities and threats it faces. (Note: same as CW1) B.  Elaborate what is required to become an entrepreneurial leader and explain how entrepreneurial leadership can be developed and leveraged in existing organizations. (Note: same as CW1) C.  Appraise and recommend how an organizational architecture can be configured within an existing organization to secure a sustainable competitive advantage. (Note: same as CW1) D.  Compare and contrast different forms of corporate entrepreneurship. E.   Develop a way how an existing firm can organize its corporate entrepreneurship efforts directed at fostering and sustaining innovation, initiating strategic renewal. Coursework Assignment Submission Date: April 6, 23:59 CST. Fail to submit on LMO, will result to fail this class. Late submissions will get a 5% deduction for each day of delay up to five (5) days. Submissions beyond five (5) days, will be regarded as a  non-submission and will not be graded. Please note that the draft version on the LMO will not be accepted. Format Requirements: •      Maximum 1500 words, excluding References and Appendices. •      Must include the cover page with your student ID. Cover page is provided in the LMO. •      The cover page must be the first page in the assignment file. •      Name your word file with your student ID, e.g., 123456.docx, points will be deducted if the file is not named correctly. •      Penalties: Wrong file type -5 points, no cover page -5 points, more than one file -5 points. •      The word font should be ‘Arial’ or ‘Calibri’ and font size 12 with 1.5 spacing and 1-inch margin. The left and right margins should be ‘Justify’ . References no need to ‘Justify’. •      All assignments must be typed, proof-read, and professional in appearance (MS Word only).  

$25.00 View

[SOLVED] Assignment ST3074 AY2024-2025 Semester 2

Assignment ST3074 AY2024-2025 Semester 2 Instructions: • 100 marks are available. • Please answer both questions, each worth 50 marks. • Suggested time is 2 hours. • You must upload a completed report (word file/pdf), copying and pasting supporting calculations/output/code from Excel and R into the spaces provided. • You should also upload any accompanying excel files and R scripts with your report to Canvas. • Each uploaded file should be named with your name and student number, e.g. “Forename_Surname_123456789_Report” “Forename_Surname_123456789_Q1 Excel” “Forename_Surname_123456789_Q2 R” • This is an open book assignment. You are permitted the use of any notes, Canvas materials and the R help function. Q1. You are a trainee reserving actuary at XYZ Ltd, an established Irish insurance company. You are currently managing two Lines of Business (LoBs): • Employers' Liability Insurance (LoB X): A well-established LoB with multiple years of claims data. • Medical Malpractice Liability Insurance (LoB Y): A newer LoB with limited historical data. Claims for both lines are subject to inflation, and you have been provided with  historical inflation values as per the CPI Index. Your task is to estimate the required reserves as of year- end  2024, considering both lines of business. The necessary data are provided in  the accompanying excel file. (a)  Describe at least two examples (for each line of business) of events that could lead to claims for Employer’s Liability and Medical Malpractice. (b) You are provided with the incremental and cumulative incurred claims triangles for LoB X in the accompanying excel file. Calculate the Basic Chain Ladder Estimate of the reserves required for LoB X. Note any assumptions required. Cumulative Claims Development Year Accident Year 0 1 2 3 2021 1637 2292 2784 3200 2022 1400 2060 2570 2023 1200 1820 2024 1125 Incremental Claims Development Year Accident Year 0 1 2 3 2021 1637 655 492 416 2022 1400 660 510 2023 1200 620 2024 1125 (c)  You are provided with historical inflation data in the accompanying excel file. Research and  apply the Inflation-Adjusted Chain Ladder Method to estimate the required reserve.  Note any assumptions required.  Comment on  the impact of using the Inflation-Adjusted Chain Ladder Method versus the Chain Ladder Method to estimate the reserve. (d)  LoB Y is a new line of business with limited historical data (€2,000 of incurred claims in the current year). In order to establish a reserve, it should be assumed that the development pattern for LoB Y can be derived from   LoB X with appropriate adjustments. In an effort to modernise the company, XYZ has laid off its underwriting staff and replaced them with  an AI chatbot, arguing that the AI model has been appropriately trained on company data and can emulate a discussion with an underwriting expert accurately. Engage in a conversation with an AI chatbot (Chat GPT or similar) to determine reasonable assumptions for reserving LoB Y, including: •   The claims development assumptions. •    Inflation assumptions. •   Other relevant actuarial assumptions. Copy and paste below your conversation history with the AI chatbot. Without further discussion with the chatbot, provide a critical assessment of the chatbot’s responses. (e)  Based on your discussion in (d), document your assumptions and construct a reserve model in Excel for LoB Y. This model should apply the Inflation-Adjusted Chain Ladder Method to project the claims development for LoB Y to Ultimate and estimate the required reserves. (f)  The Chief Actuary has become concerned that the excel reserving model takes a long time to update. She has asked you to develop a model in R to implement the Inflation- Adjusted Chain Ladder Method for LoB X. Create an implementation that replicates your answer for part (c) above, pasting your code and output below. (g)  The Chief Actuary has further commented that the current model is limited in that it only provides a point estimate for the reserves and gives no indication as to their potential variability.  Extend your model from (e) to bootstrap the future inflation assumption from the historical inflation data to generate a  distribution of 50,000 reserve estimates. Report below: •   The best estimate (mean of the bootstrap distribution). •   The 99.5th percentile reserve estimate. •   An appropriate visualisation of the reserve distribution to illustrate the reserve variability by varying the inflation assumption. •   Comment on your results, using your actuarial judgement to suggest (with justification) the level at which the reserves should be set for LoB X. • Note:  to ensure reproducibility of the bootstrap reserves, the regulator requires that the R model uses the set.seed(100) command. Q2. You have joined a startup company which plans to sell Property Damage and Business Interruption Insurance Policies. The regulator has provided you with a dataset of 1,000 annual aggregate claims  (Gross of any reinsurance arrangement) expressed  in  2024 terms in the accompanying excel file Property_BI_Claims.csv. (a)  Read the data into R, generate appropriate visualisations and comment on the features of the data. (b) Your task is to parameterise a suitable model to assess the solvency of the business in 2025. The company’s reinsurance programme is as follows: •   The Property Damage LoB is reinsured via a Quota Share (QS) arrangement where 40% of each claim is transferred to the reinsurer. •   The Business Interruption LoB is reinsured via an individual Excess of Loss (XoL) arrangement with retention of 10,000. The insurer’s profit may be modelled as: profit = Initial capital + premiums — Net claims — Expenses •   Assume the initial Capital is €150,000 and the annual aggregate  premium intake is €70,000. •   Assume fixed expenses of €10,000 and that claims handling expenses are 5% of claims gross of reinsurance. •   Select (giving your rationale) a suitable model for the claims portfolio and use the regulator’s data to estimate its   parameters.  Hence create 50,000 simulations of the insurer’s profit. •   Assess the probability that the insurer will be solvent (have a profit greater than zero). (c)  The  regulator  has  asked for you to  provide sensitivity analysis to demonstrate the robustness of the company’s solvency. •    Produce a plot to illustrate the change in probability of solvency for a range of values of initial capital. •    How much capital would be required to ensure a 99.5% probability  of solvency? (d) Assess (with supporting statistical tests, calculations and output) the goodness of fit of your chosen claims model, commenting on your answer.

$25.00 View

[SOLVED] CS3243 Introduction to ArtificialIntelligence Project 3 Adversarial Search AY2024/2025 Semester

CS3243 Introduction to Artificial Intelligence Project 3: Adversarial Search AY2024/2025 Semester 2 Issued: 17 March 2025 Due: 13 April 2025, 2359hrs 1 Overview In this project, you will implement an adversarial search algorithm to find valid and good moves for a modified chess game. Specifically, you are tasked to implement the Alpha-Beta Pruning algorithm to play a modified game of chess. This project is worth 10% of your course grade, with an extra 2% bonus. 1.1 General Project Requirements The general project requirements are as follows: • Individual project: Discussion within a team is allowed, but no code should be shared • Python Version: ≥ 3.12 • Deadline: 13 April 2025, 2359hrs • Submission: Via Coursemology – for details, refer to the Coursemology Guide on Canvas 1.2 Academic Integrity and Late Submissions Note that any material that does not originate from you (e.g., is taken from another source) should not be used directly. You should do up the solutions on your own. Failure to do so constitutes plagiarism. Sharing of code between individuals is also strictly not allowed. Students found plagiarising will be dealt with seriously. For late submissions, there will be a 20% penalty for submissions received within 24 hours after the deadline, 50% penalty for submissions received between 24-48 hours after the deadline, and 100% penalty for submissions received after 48 hours after the deadline. For example, if you submit the project 30 hours after the deadline and obtain a score of 92%, a 50% penalty applies, and you will only be awarded 46%. 2 Background: Fairy Chess Fairy chess is a modified chess game that includes pieces with nonstandard movements1 . In this project, you will be creating an agent that can find the best move for a given fairy chess board position. Your agent must be implemented using the Alpha-Beta pruning algorithm. 2.1 Rules of the Game 2.1.1 Board For ease of implementation, we will not use standard chess board notation. Instead, squares on the chessboard will be represented as a Tuple[int,int], representing the row and column of the square. The top-most row is row 0, and the left-most column is column 0. An example chessboard is depicted in Figure 1 below. Figure 1: Chess board with labelled squares 2.1.2 Movement of Chess Pieces The classic chess pieces that will be used are as follows. • King: The king can move one square in any direction. • Rook: A rook can move any number of squares along a rank or file but cannot leap over other pieces. • Bishop: A bishop can move any number of squares diagonally but cannot leap over other pieces. • Knight: A knight moves in an “L”-shape, i.e., two squares vertically and one square horizontally, ortwo squares horizontally and one square vertically. Note that the knight can leap over other pieces. In addition to the standard chess pieces mentioned above, two other fairy chess pieces will be defined. • Squire: A squire can move to any square a Manhattan distance of 2 away. A squire can also leap over other pieces. • Combatant: When moving (without capturing), the combatant moves one square orthogonally in any direction (denoted by points in Figure 2). When capturing, the combatant captures one square diagonally in any direction (denoted by crosses in Figure 2). Figure 2: Chess piece movement 2.1.3 Winning Conditions In this variant, the game is won by capturing your opponent’s King; it is lost when your King is captured. Note that this means the concepts of check, checkmate, and stalemate do not apply. An agent may (either accidentally or being forced to) put its own King under attack, and if a King is under attack, an agent is not forced to defend it. The game ends when any King is captured, hence, if both Kings are under attack, the player that captures the opponent King first wins. With this modified winning condition, the concept of stalemate also does not apply. A stalemated King is forced to move into danger on the next move, resulting in a loss for the stalemated player. 2.1.4 Draws A draw will be declared if only Kings are left on the board. The game is drawn even if one King can capture the other on the very next move. 2.2 Getting Started You are given one python file (AB.py) with the recommended empty functions/classes to be implemented. Specifically, the following files are given. 1.studentAgent(gameboard): This function takes in a parameter gameboard and returns a move. More details on the output will be given in the later sections. DO NOT REMOVE THIS FUNCTION. 2.get_legal_moves(gameboard,color): This function takes in two parameters, gameboard and color. This function should return a list of moves. DO NOT REMOVE THIS FUNCTION. 3.ab(): Implement the Alpha-Beta Pruning algorithm here. (You may change/remove this function, as long as you keep the studentAgent(gameboard) function and return the required value(s).) 4.State: A classstoring information of the game state. (You may change/remove thisfunction as desired, as long as you keep the studentAgent(gameboard) function and return the required value(s).) 5.Board: A class storing information of the board. (You may change/remove this function as desired, as long as you keep the studentAgent(gameboard) function and return the required value(s).) 6.Piece: A class storing information of a game piece. (You may change/remove this function as desired, as long as you keep the studentAgent(gameboard) function and return the required value(s).) You are encouraged to write other helper functions to aid you in implementing the algorithms. Do note that during testing, the Autograder will call both studentAgent(gameboard) and get_legal_moves(gameboard,color). 2.3 Winning a Fairy Chess Game Using Alpha-Beta Pruning The objectives of this project are as follows. 1. To gain exposure in the implementation of the algorithms taught in class. 2. To learn how to apply the Minimax algorithm to games. 3. To learn the efficiency and importance of using Alpha-Beta Pruning. 3 Project 3 Task 1 Many years have passed since the last invasion and the people of CS3243 kingdom are living peacefully and happily. However, the council of CS3243 Kingdom detects an imminent threat from our enemy Kingdom, CS9999 and are fearful that a war may break out soon. In order to prepare for the war, the council seeks to recruit a strategic advisor. To assess the best candidate, the council decides to organise a fairy chess competition that anyone can join. The participants will compete against AI agents of various difficulty levels and the participant that wins against all the AI agents will be recruited as the strategic advisor. Being an avid fairy chess player in the kingdom, you decide to join the competition to challenge yourself! 3.1 Task 1: Alpha-Beta Pruning Algorithm Implement the Alpha-Beta pruning algorithm to find the best move for a given fairy chess board state. 3.1.1 Input The function studentAgent() takes in a parameter gameboard that is a list of all the pieces on the board. Each piece is represented by a tuple containing 3 elements. The first element is a string containing the name of the piece. The second element is either the string ’white’ or ’black’, and this element represents the colour of the piece. The last element is another tuple, representing the position of the piece using the notation defined in Figure 1. An example of the gameboard is given below. [(′King′,′white′,(7, 0)), (′King′,′black′,(0, 7)), (′Knight′,′white′,(3, 4))] 3.1.2 Output When the studentAgent() function is executed, your code should return a valid move in the following format. (pos1, pos2) To be more precise, your studentAgent() function should return a tuple containing two other tuples. The first tuple represents the starting position of the piece you intend to move. The second tuple represents the position you intend to move the piece to. Both positions are denoted using the notation in Figure 1. Note that captures are not denoted differently from other moves, if pos2 is occupied by an opponent piece, it is guaranteed that the piece at pos2 is captured after the move. In addition, you are tasked to define a get_legal_moves(gameboard,color) function. This function should take in a gameboard as described above, and the string ’black’ or ’white’. This function should return a list all the legal moves available to the player whose colour is specified. An example is shown below. Assume that the following is executed. gameboard = [ (′King′,′white′,(7, 0)),                        (′King′,′black′,(0, 7)),                        (′Knight′,′white′,(3, 4)) ] print(get_legal_moves(gameboard,’white’)) print(studentAgent(gameboard)) Consequently, the sample output representing your Knight at (3,4) moving to (5,5) is as follows. # output of get_legal_moves: [ ((7,0),(7,1)), ((7,0),(6,0)), ((7,0),(6,1)), ((3,4),(5,5)),    ((3,4),(4,6)), ((3,4),(1,5)), ((3,4),(2,6)), ((3,4),(5,3)),    ((3,4),(4,2)), ((3,4),(1,3)), ((3,4),(2,2)) ] # output of studentAgent: ( (3,4),(5,5) ) 3.1.3 Assumptions In your implementation, you may assume the following. • Both players will have a King on the board. • With the exception of the first four test cases (where the get_legal_moves function is evaluated), every other test case is a board position such that one move is clearly better than all other moves (i.e., only one move leads to a forced win or leads to winning material2 ). • In the board position given, you will only play as “white”. You may assume that the opponent plays optimally. 3.2 Grading (Total: 10 marks + 2 bonus marks) 3.2.1 Evaluating Your Agent Your agent will not be playing a game. Instead, your agent will be tasked to find the best move for several given board positions. However, do feel free to let your agent play against itself to view the performance of your agent in a real game. The test cases will test for the following: • Test cases b1 - b4: Find all the legal moves for a given board position. • Test cases m1_1 - m1_2: Find the best move for a board position where there is a forced win in one move (i.e., you may capture the black King in one move). • Test cases m3_1 - m3_4: Find the best move for a board position where there is a forced win in three moves (i.e., two moves by white, one move by black). • Test cases m5_1 - m5_4: Find the best move in a board position where there is a forced win in five moves (i.e., three moves by white, two moves by black). • Test cases e3_1 - e3_2: Find the best move in a board position where there is a guaranteed way to win material in three moves. • Test cases e5_1 - e5_4: Find the best move in a board position where there is a guaranteed way to win material in five moves. • Bonus test cases e5_5 - e5_6: Find the best move in a board position where there is a guaranteed way to win material in five moves (note: these are very tricky test cases). 3.2.2 Marks Distribution The grading rubrics are as follows: • Test cases b1 - b4 (to test the get_legal_moves function): 0.5m each [total: 2m] • Test cases m1_1 - e5_4: 0.5m each [total: 8m] • Bonus test cases e5_5 - e5_6: 1m each [total bonus: 2m] 4 Submission 4.1 Details for Submission via Coursemology Refer to Canvas > CS3243 > Files > Projects > Coursemology_guide.pdf for submission details. 5 Appendix 5.1 Allowed Libraries The following libraries are allowed: • Data structures: queue, collections, heapq, array, copy, enum, string • Math: numbers, math, decimal, fractions, random, numpy • Functional: itertools, functools, operators • Types: types, typing 5.2 Tips and Hints • IMPORTANT: Do not spend too much time optimising the heuristic! A simple weighted sum of piece values is sufficient. Evaluation of more complicated heuristics may slow down your code significantly due to the frequency with which the evaluation function is called. You may search online to determine how to define a good evaluation function. • With an average computer, you may expect the slowest test cases to run in under 2 seconds (locally). • ChatGPT is quite useful for generating the skeletal code for minimax, as well as the piece movements. You may use that as a starting point. For Project 3, you are allowed to use ChatGPT to assist you.

$25.00 View

[SOLVED] Empirical Finance BU232640W1SP24 Assignment 1 Event Driven Backtesting for Small-Cap Bio

Assignment 1 - Event Driven Backtesting for Small-Cap Bio Stock Empirical Finance  (BU.232.640.W1.SP24) April 11, 2023 Assignment Objectives: •    Source PDUFA and Phase 3 catalyst event data for small cap biotech stocks. •    Develop a robust investment strategy and analyze the summary statistics of the strategy. •    Discuss whether the “Sell the News” phenomenon is evident in the data. •    Strategize for the upcoming PDUFA and Phase 3 catalyst events in the second half of 2024 and develop an investment strategy. Source PDUFA and Phase 3 catalyst event data for small cap biotech stocks I have sourced PDUFA and Phase 3 catalyst event data from the following websites: • https://www.fdatracker.com/fda-calendar/ • https://www.biopharmcatalyst.com This is an example of the data from www.fdatracker.com: FDATracker provides the PDUFA dates for all biotech stocks going back around 10 years. The only problem with the data is that the FDA decision needs to be sourced from company news announcements. I have manually sourced the FDA decision for a small sample of companies. Biopharmcatalyst.com has a very comprehensive database on Phase 3 clinical trials. This is an example of the data: Zoomed in view: Biopharmcatalyst.com provides information on whether the company has met endpoints or surpassed targets set for the Phase 3 trial.  I have manually assigned positive and negative ratings based on whether end points have been achieved. I also used Bloomberg to calculate the market capitalization of all companies and only retained companies with a market capitalization below $2 billion. Investopedia (n.d.) considered companies to be small cap if their market cap is between $250 million and $2  billion. I included companies with a market capitalization below $250 million as they tend to be more sensitive to news events and relevant to this study. This is a small sample of my data which can be found in the Phase3_And_PDUFA_Data.xlsx spreadsheet: I have collected data on 204 catalyst events categorized as either PDUFA events or Phase 3 clinical trial results. My data has 101 negative news events and 103 positive news events. Structuring the Data and Collecting Stock Data I used a python script linked to the Bloomberg API to download the stock data for all companies listed in the Phase3_And_PDUFA_Data.xlsx spreadsheet: The stock data had 132 different companies. Although I had 204 catalyst events some companies had more than one catalyst event on different dates. Methodology for Structuring the Data I wrote a python script. Empirical Finance Project - Equity Curves - Mark Tanzer.py which outputs a spreadsheet  titled Structured_Stock_Event_Data. This workbook has two sheets called Returns and Prices. The Returns sheet calculates the percentage returns 5, 10, 30, and 60 days before and after the catalyst event date. The python script is flexible and outputs percentage returns specified by the user. There is no limit on the number of columns which can be output. This is  a small sample of the data: The Prices sheet goes through every csv file and locates closing price stock data around the catalyst event date. It then outputs the daily closing price stock data for 90 days before the event and 90 days after the event. I could not display 180 columns and have just taken a picture of the output 5 days before and 5 days after the event date below: The following screenshots show the  python script is extracting the correct closing  price stock data (highlighted in red below): The structured output data is consistent with the highlighted closing price stock data above: I progressed to write a python script. called Empirical Finance Project - Equity Curves - Mark Tanzer.py. This script outputs an excel workbook titled  Equity_Curves.xlsx. It  has 4 sheets titled All  Returns, Individual Daily Returns, Cumulative Returns and Summary Statistics. The All_Returns sheet calculates the daily returns 90 days before and 90 days after the trade event: Day_0_Return defines the trade event and represents holding a trade at the close of the day before the trade event to the closing price on the trade event. One notices large percentage changes for the first 4 stocks on the catalyst event date. Sometimes a catalyst event doesn’t have a large percentage change. In my data there were around 30 events with a move between -5% and 5%. All other events were outside this range which is considered reasonable for this project. The All_Returns sheet aims to  identify stock price changes around catalyst event dates. This is not however sufficient to construct an equity curve as the individual returns need to be allocated to a full list of dates extending the entire data set. These returns should also reflect the trade entry date and the trades holding period. This is a very difficult piece of code to design  because a strategy trading on day 5 and holding 2 days needs to find the date corresponding to the Day_-5_Return and the Day_-4_Return and then allocate it to the full list of dates. It needs to do this for all securities with a catalyst event date and for all holding periods. The Individual Daily Returns sheet was able to achieve this result for different trade entry dates and holding periods (defined by Days_offset and Holding): Let’s, check the data for one stock security, namely CERS. The Day_-5_Return of -2.28% represents a daily return calculated from holding the stock from the close on day -6 to the close on day -5.  It is allocated to 14 March 2024 which is 5 days before the trade event. But AQSTand OPTN have an overlap with the dates and -1.6% and -3.5% returns on 14  March 2024 need to be added to the -2.28%. This gives 7.38% (-2.28% - 1.6% - 3.5%) and the difference is  because of rounding.  Similarly, the same process is done for Day_-4_Return, Day_-3_Return, Day_-2_Return and Day_-1_Return which match exactly with the previous  individual  daily  returns  calculated.  Note:  the  column heading  specifies a Days_offset = 5 days (5 days in the past) and Holding = 5 (hold the trade for 5 days). Compounding these individual returns then gives the cumulative equity curve or cumulative returns of the trades. This is output into the Cumulative_Returns sheet based on a notional investment of 100,000 . The full notional investment plus capital gains and losses are assumed to be invested in each trade. This means that if any investment falls 90% it is almost impossible for the equity curve to recover. Here is a screenshot of the Cumulative_Returns sheet: Finally , for every equity curve, I calculate summary trade statistics which are output into the sheet called Summary_Statistics. This is a small sample of the output and most spreadsheets have a large number of columns extending hundreds of columns. Backtesting Methodology The previous section explained the methodology for calculating equity curves for different holding periods. I used a brute force approach to simulate thousands of different equity curves and then filter by highest return and highest Sharpe ratio to select my top 8 strategies. The equity curves have been simulated for the following scenarios: •    Only trade before the catalyst event (Before) •    Only trade after the catalyst event (After) •    Only trade after the catalyst event with positive news from the company ( After – Positive News) •    Only trade after the catalyst event with negative news from the company ( After – Negative News) •    Only trade after the catalyst event with positive news and positive momentum ( After – Positive News – Positive Momentum) •    Only trade after the catalyst event with positive news and negative momentum ( After – Positive News – Negative Momentum) •    Only trade after the catalyst event with negative news and positive momentum ( After – Negative News – Positive Momentum) •    Only trade after the catalyst event with negative news and negative momentum ( After – Negative News – Negative Momentum) Positive momentum is defined as a +10% total return from 20 days before the catalyst event to the stocks closing price on the catalyst event date . Negative momentum is defined as a -10% returns from 20 days before the catalyst event to the stock’s closing price on the catalyst event date. The plot of all the individual equity curves can be found in the following folders which accompany this report: These are the output excel spreadsheets from running all the simulations: This is a picture of the python code supporting this project (python code submitted with this report): Top Selected Equity Curves and Trade Summary Statistics The previous section described how I calculated thousands of equity curves and then filtered by highest return and highest Sharpe ratio to determine the top 8 strategies.  The top strategies  are summarized below: It should be noted that for backtesting “After” scenarios, days ffset = X and holding period = Y means the trader should go X days in the future and then backY days. A trade is placed on the date corresponding to  Y and then held until date corresponding to  X. This approach was adopted because I needed a consistent methodology for “Before” events and “After” events with flexibility to change the backtest scenario. In the case of a “Before” scenario, days offset = X and holding period = Y means the trader should enter the trade X days in the past and then hold for Y days in the future. A trade would be entered on the date corresponding to date X and held till date corresponding to date Y. The top trading strategies were selected from thousands of equity curves and generally show positive news with negative momentum or negative news with positive  momentum.  This suggests “Sell the News” s an effective strategy in the market. The following plot displays all equity curves next to each other  as shown in the trade statistics summary table above. The strategies go from top left to top right, then a sequential move down one row starting from the left column. The plot is small because I have combined all the equity curves on the same pane. This does however, provide a high-level overview of the structure of the equity curves for each strategy.  Please refer to the Appendix for enlarged screenshots of these equity curves. Future Catalyst Events and Trading Strategy for H2 of 2024 I have selected strategies 5, 6, 7 and 8 for trading H2 of 2024. I have eliminated strategies 1 and 3 from inclusion as a sample size of 12 is very small. Strategies 2 and 4 are subsets of strategies 5 and 6 which suggests some robustness around these strategies.  Strategies 5 and 6 show a nice shaped positive performance from the beginning of 2023 which suggests there may be an edge. The sample size  is however small (28) which means there will not be  many trades taken based on these strategies. Strategies 7 and 8 have a much bigger trade sample which means there is more statistical significance related to the results. Their equity curves are upwards sloping. There are some sharp drawdowns which suggest there could be events not captured in the backtest data. I would advise carefully checking for unforeseen catalyst events which could impact trading results  in the future. I would also suggest setting a stop loss  of around  13% on all trades.  This is close to the max loss percentage on the different strategies and will not change the distribution of the equity curves while still providing downside protection. In the Appendix section titled Future Catalyst Events I have taken screenshots of an additional 72 future catalyst events. The below is an illustration of 10 potential trade entries and exits. For all of the strategies the trader would need to wait for the news release. If momentum is a trading rule in the strategy then it would also involve checking if there is a 10% positive momentum or -10% negative momentum from exactly 20 days before the catalyst event through to the closing price on the day of the catalyst event.

$25.00 View

[SOLVED] ELEC7310 MODULE I POWER SYSTEM STABILITY AND DYNAMICS Assignment4

ELEC7310, MODULE I: POWER SYSTEM STABILITY AND DYNAMICS (SECURITY) Assignment#4: Static Voltage Stability Analysis Submission Date: May 2, 2025 The main objective of the assignment is to study the static voltage stability of the WSCC 9 bus test system. Fig. 1. A single-line diagram of 3-machine WSCC system. The test system can be found as “d_009” in “tests” folder of PSAT. Note that number assignments to the buses are not as same as in Fig. 1. Use Power System Analysis Toolbox (PSAT) and MATLAB to produce all  the simulation results and hence answer to the following questions. Questions: Direct method, repeated power flow a)   Increase the loading level of the system step by step, run a load flow and see whether you are getting convergence or not, report the maximum loading level. For loading “direction,” assume all the loads are increased by the same ratio, and only generator at bus one is allowed to dispatch required additional real power. b)  Plot the voltage against the total load at all the load buses; Find out which load bus having the highest dV/dPTotal  at the point closer to divergence? c)  Form. the power flow Jacobian at several loading levels up to the divergence point and plot the following curves. (i)      Smallest  Singular value of power flow Jacobian against the total load in the system. (ii)      Minimum eigenvalue of the power flow Jacobian against the total load in the system. (iii)      Condition number of power flow Jacobian against the total load in the system. (iv)      At the divergence point check the reactive power limits  of the other two generators (other than swing bus). Continuation Power Flow Method a)  Run the continuation power flow (use same generation and loading direction as direct method) to obtain the static voltage stability margin of the system. Compare the results obtained in question 1 and comment on the results. b)  Run the continuation power flow and produce PV curve assuming only load at bus 9 is allowed to be increased. Total mark: 8

$25.00 View

[SOLVED] Philosophy Process and Portfolio StatementR

Philosophy, Process, and Portfolio Statement Overview The purpose of this investment policy statement is to establish guidelines for the management of a balanced and diversified portfolio. Over nine weeks we have been entrusted to manage a financial portfolio worth one million dollars for potential clients. The objective is to ensure steady market returns for the investor while maintaining an approach suitable for their preferences. Investment Philosophy Based upon the low-risk preference of the potential client, the philosophy of the investments follows a balanced approach, focusing mainly on investments like exchange-traded funds and bonds, with some cash on hand to be used wherever seen best fit. With these investment instruments, the portfolio will be diversified across the entire world, ensuring that concentration risk is minimized. Diversification includes investments in the North American, European, and emerging markets. Due to the current economic conditions, less focus will be placed on Canadian investments due to the uncertainty of market conditions and potential tariffs by the United States. The portfolio is expected to earn a similar return to the total market, acknowledging that it is not reasonable to consistently beat the market without extraordinary luck. The low-risk tolerance of the potential client explains why a reasonable amount of the portfolio was placed in low-risk investments such as corporate and treasury bonds, while some was held in cash. Not only will cash be useful to make trades over the nine weeks, but it will also grow at the interest rate, ensuring that it is still accumulating a return for the investor. Investment Process In selecting the specific assets to invest in, the goal was to avoid investments with high management expense ratios, such as mutual funds. This is the reason why a large part of the portfolio has been invested in exchange-traded funds. Exchange-traded funds allow the portfolio to be diversified with hundreds and even thousands of stocks within a single fund. The funds we  have chosen span across many countries and sectors, reducing the overall risk of the portfolio. In addition, individual stocks were purchased when value had significantly dipped, providing confidence that they were bought at a discounted price and would rise throughout the portfolio management. The low-risk assets were chosen as United States treasury bonds and an index of highly rated corporate bonds. Additional strategies have also been put into place to manage risk. Initially, the maximum amount of the portfolio invested into a specific asset has been capped at ten percent. This allows  us the security to know that a specific asset will not be overinvested into and risk losing significant amounts of the portfolio in one area. The asset classes were intentionally mixed between equities, bonds, and cash to further diversify the portfolio. As well, stop-loss and exit strategies will be implemented to mitigate losses and maintain the overall health and return of the portfolio. The trading strategy will consist of a minimum of two trades per week to ensure an active trading strategy that will maximize returns for the client. Short-term investments will be paired with long-term investments to prevent liquidity issues and further diversify the portfolio. Throughout the portfolio management market trends will change, making it a necessity to adjust our investing tactics based on the landscape of the markets. Exhibit: Portfolio Allocation & Initial Positions The portfolio is structured with a mix of equities, bonds, and cash, as follows: Initial Holdings: Security Shares/Units     Allocation VOO (Vanguard S&P 500)                               179 shares          ~10% VWO (Vanguard Emerging Markets ETF)     2272 shares        ~10% NVDA (NVIDIA)                                           391 shares          ~5% T-BOND 6.000% 15-FEB-2026                      97 units              ~10% VGK (Vanguard Europe ETF)                         1483 shares        ~10% Cash                                                                -                         ~20% IGIB (Blackrock Corporate Bond ETF)          1927 shares        ~10% META. (Meta. Platforms)                                  71 shares            ~5% COIN (Coinbase)                                             175 shares          ~5% TSLA (Tesla)                                                    126 shares          ~5% GOOGL (Google)                                           250 shares          ~5% SPY (S&P 500 ETF)                                       100 shares          ~5%

$25.00 View

[SOLVED] CMT654 DevOps 2024-25

Assessment Proforma 2024-25 Key Information Module Code CMT654 Module Title DevOps Assessment Title Portfolio Assessment Number 1 Assessment Weighting 100% Assessment Limits Pipeline, pipeline report (1200 words), Performance analysis report (300 words), research report (1000 words). Total 2500 words + pipeline The Assessment Calendar can be found under ‘Assessment & Feedback’ in the COMSC-ORG-SCHOOL organisation on Learning Central. This is the single point of truth for (a) the hand out date and time, (b) the hand in date and time, and (c) the feedback return date for all assessments. Additional Demo of Pipeline in class Monday Week 11. Learning Outcomes The learning outcomes for this assessment are as follows: 1.  Use and troubleshoot a range of leading-edge DevOps tools for continuous integration (i.e. automated building, packaging, testing and deployment), and justify the rationale for doing so. 2.  Use a range of Cloud tools and platforms, critically appraising the benefits of their use. 3.  Use of a range of appropriate tools and techniques to measure performance of various system components and investigate issues. 4.  Scale real systems to obviate performance issues, and overcome resource constraints critically analysing the rationale behind design decisions with respect to Reliability, Availability and Performance. 5.  Discuss security implications of cloud solutions, utilising mechanisms to mitigate their effects. Submission Instructions The coversheet can be found under ‘Assessment & Feedback’ in the COMSC-ORG- SCHOOL organisation on Learning Central. All files should be submitted via Learning Central.  The submission page can be found under ‘Assessment & Feedback’ in the DevOps module on Learning Central.  Your submission should consist of multiple files: Description Type Name Coversheet Compulsory One PDF (.pdf) file Coversheet.pdf Scripts Compulsory All scripts associated with the deployment pipeline and other parts of the coursework. These must be within a zipped folder named Scripts Scripts_[student number].zip Report Compulsory Report with 3 sections: 1) Pipeline Report 2) Performance Report 3) Research Report Report_[student number].pdf There will also be an in-class demonstration during Week 11’s session where you will be required to demonstrate your working pipeline. If you are unable to submit your work due to technical difficulties, please submit your work via e-mail to [email protected] and notify the module leader. Assessment Description This is an individual assignment. There are no aspects of team submission. For the purposes of this assignment, you will be working with the Spring Boot Client Application that you worked on last semester. This assignment will not assess the Client Application’s functionality but must include connectivity to a MySQL / MariaDB Database that you deploy. You may use any branch from the Client Application to start from and if you really believe that using your Client Application rather than another team’s will put you at a disadvantage please come and see me and I will get you access to another team’s application. You must not deploy the client project to any external service outside university hosted platforms (if in any doubt, speak to staff). The work is split into four related sections: 45% Deploy your application to the School’s OpenStack cluster, creating a repeatable process (scripted)  that creates a Linux (Rocky or Debian. Debian will get more marks) test environment and uses Jenkins to pull your project from your Gitlab repository and trigger a build and test of the application. The pipeline should include the build, installation and configuration of all required software to enable the application to run and to enable the application to be tested according to Dev Ops best practices. The pipeline should leave the application running on a separate server and accessible via a browser via the University’s network. During an in-class demonstration session (week 11) you will be asked to open and run the application in the Dev environment (Intellij) make a simple change to the project, push that change to Gitlab and then demonstrate the deployment pipeline. 25% Write a brief report (1200 words) on your pipeline discussing the decisions behind creation of the environment, the testing schedule and the resources used (e.g. web sites used to find instructions). In this report, you should reflect on your choice of methods used in the construction of the pipeline (do not discuss decisions that you did not make e.g., you did not choose to use OpenStack – this was a specified part of the project). You should also reflect on the use of the pipeline during the week 11 group exercise and it’s limitations. 10% Run performance analysis on the deployed project using a range of appropriate tools as discussed in the sessions and worksheets (must include J Meter). Produce a report (300 words, maximum 3 images) on your findings detailing your methods, what they hope to show and showing screen shots of tests you have run. DO NOT!!!  run high load testing on the openstack instances. If you wish to run high user and loop tests, run them on your local machine. 20% Research report on transfer of project to the Google Cloud platform (1000 words): Your company is negotiating for VC investment for a rapid expansion. Your OpenStack server is now running out of power for the increasing client base and the application is rapidly expanding its feature set. Your company wishes to migrate to a Google Cloud offering. Write a recommendation on the technologies that you will use, discussing the options and the justifications for your choice. Tips: 1)  An image showing the architecture of your proposed solution (similar to the one in the notes for the current OpenStack solution may help). 2)  Stating assumptions on usage numbers may help with your costing estimates. 3)  Ensure that you have a final, cohesive, solution proposed. Please note that this is a migration of the development / deployment pipeline not just a migration of the application. Considerations for: Cost, Reliability, Security, Best Practice, Lock-in and Agile Development should all be considered.

$25.00 View