In this assignment, you’ll use the observer design pattern to create a price watching application. Imagine a shopping trip to the mall to visit all your favorite stores. Customers are constantly looking for a way to monitor sales at these competing markets so that they can get the best deal. We are going to build a way to help customers monitor sales using the observer design pattern. When you’re finished with the assignment, you’ll be able to play a simple game from the command line by running the Main.main() method. You’ll have $100 to spend on products at the mall. Stores will periodically put products on sale, giving you the opportunity to buy at great prices—if you’re willing to wait for the deals. Novice We’re going to use the observer design pattern to notify customers whenever a sale event occurs in a store. However, there are multiple types of sale events that customers might care about. To model the different types of events, we’re going to create 5 different event classes which implement the StoreEvent interface. 1. BackInStockEvent – Represents the event where a product that was previously out of stock at a particular store is now available. 2. OutOfStockEvent – Represents the event where someone purchases the last copy of a product from a store, and the product is now out of stock. 3. PurchaseEvent – Represents the event where someone purchases a copy of a product from a store. 4. SaleEndEvent – Represents the event where a store ends their sale for a particular product. 5. SaleStartEvent – Represents the event where a store announces a sale for a particular product. Create these five classes in the com.comp301.a08shopping.events package. Each class should implement the StoreEvent interface and should encapsulate a Product field and a Store field, representing the product and the store that the event pertains to. Each class should be immutable, and should have a constructor that initializes the fields. For example, here is the signature for the SaleStartEvent constructor. The order of the constructor parameters is important, and must match this example for the autograder to accept your event classes. java public SaleStartEvent(Product product, Store store) { // Constructor code goes here } Adept ProductImpl Create a class called ProductImpl that implements the Product interface. At the bare minimum, your ProductImpl class must encapsulate a private string field to represent the product’s name, and a private double field to represent the product’s base price. The constructor for the ProductImpl should have the following signature: java public ProductImpl(String name, double basePrice) For this assignment, $0.00 should not be a valid base price for any products. For the sake of simplicity, assume that the basePrice parameter will be to no more than 2 decimal places. StoreImpl Next, create a class called StoreImpl which implements the Store interface. The StoreImpl class represents a store at the mall, containing a list of products that occasionally go on sale. At the same time, StoreImpl also serves as the “subject” in the observer design pattern, and will notify its active observers whenever a sale event occurs (see the five StoreEvent types from the novice section). What fields to encapsulate? To implement the Store methods, you’ll need to encapsulate a few private instance fields in the StoreImpl class. At minimum, you’ll need these three fields: 1. A string field to represent the name of the store. 2. A list (or other collection type) of StoreObserver objects to represent the active observers of the store’s sale events. 3. A list (or other collection type) of Product objects to represent the products sold at the store. The StoreImpl constructor should have the following signature: java public StoreImpl(String name) Use the provided name parameter to initialize the store’s name field. Also remember to initialize any other data structure fields that you use to store product and observer information. Notifying observers Returning a receipt in purchaseProduct() Upon successful product purchase, purchaseProduct() should return a new ReceiptItem object representing a receipt of the transaction. Create an appropriate new ReceiptItemImpl object to return. This class is part of the starter code, and no changes to it are necessary. Jedi CustomerImpl The last class to create for this assignment is CustomerImpl, which implements the Customer interface. Since the Customer interface extends the StoreObserver interface, Customer instances can be registered as observers of store events. The CustomerImpl class represents the user who is playing the command-line game, searching for sales and purchasing products. CustomerImpl should have a constructor with the following signature: java public CustomerImpl(String name, double budget) Encapsulate a string field to represent the customer’s name, and a double field to represent the customer’s budget (i.e. the amount of money that the customer has left to spend). These fields should be initialized using the parameters passed to the constructor. In addition, the CustomerImpl class should also encapsulate a List field to store a list of all purchases that the customer makes. Every time purchaseProduct() is called on the customer, the ReceiptItem object returned by the store should be added to the customer’s purchase list. Again, for the sake of simplicity, assume that the budget parameter will be to 2 decimal places. update() method Since CustomerImpl is a StoreObserver, you’ll also need to implement an update() method. This method will be executed by the Store objects whenever a StoreEvent occurs to update the customer about the event. The customer’s update() method should simply print out a statement to the console explaining which type of event occurred. Here are examples of the statements that should be printed for each event type: 1. BackInStockEvent – If a product with name “Watch” is back in stock in store “Macy’s”, then the update() method should print “Watch is back in stock at Macy’s” 2. OutOfStockEvent – If a product with name “Watch” is out of stock in store “Macy’s”, then the update() method should print “Watch is now out of stock at Macy’s” 3. PurchaseEvent – If a product with name “Watch” is purchased in store “Macy’s”, then the update() method should print “Someone purchased Watch at Macy’s” 4. SaleEndEvent – If the sale for a product with name “Watch” ends in store “Macy’s”, then the update() method should print “The sale for Watch at Macy’s has ended” 5. SaleStartEvent – If a new sale starts for a product with name “Watch” in store “Macy’s”, then the update() method should print “New sale for Watch at Macy’s!” Main class Once you’ve finished making the classes described above, you can try running the Main method to play the game! However, in order to receive the sale event updates, you’ll need to add a couple of lines of code to the main() method to register/deregister the customer as an observer to the stores. See the TODO comments in the Main class for details.
In this assignment, you’ll use the creational design patterns singleton, multiton, and factory method to control instantiation of some classes. Imagine the process of ordering a pizza at a local pizza shop. What information does a customer need to provide so that they get the pizza they want? 1. What size should the pizza be? 2. What kind of crust should the pizza have? 3. What kind of cheese should be used? 4. What kind of sauce should be used? 5. What toppings should go on the pizza? This assignment revolves around designing a series of classes that model the process of ordering pizza. In novice, you’ll create classes to represent the ingredients that go in a pizza. In adept, you’ll create a class to represent a pizza. And in jedi, you’ll create factory methods which are responsible for creating different pizza objects. Novice Let’s start by designing some classes to model pizza ingredients. IngredientImpl Check out the Ingredient interface. An ingredient is an object that encapsulates the following information: 1. The name of the ingredient, which is a string value. 2. A boolean value representing whether the ingredient is vegetarian or not. 3. A boolean value representing whether the ingredient is vegan or not. Make a new class, IngredientImpl, which implements the Ingredient interface and encapsulates the above information. The IngredientImpl class should be immutable. Add a suitable constructor to initialize the encapsulated fields using initial values passed in as parameter values. Note: The order or type of the constructor’s parameters don’t matter to the autograder Next, we’re going to create special subclasses of IngredientImpl to represent four different categories of pizza ingredients: crust, sauce, cheese, and toppings. Crust Create a new subclass of IngredientImpl, called Crust. This new class will use a variant of the multiton design pattern, so give it a private constructor. Now let’s create and store a few Crust instances inside the Crust class. The instances we create will represent the different types of pizza crust that are available at the pizza shop. The pizza shop offers customers their choice of three types of crust: | name | is vegetarian? | is vegan? | field name | |————-|—————-|———–|————-| | hand-tossed | yes | yes | HAND_TOSSED | | thin | yes | yes | THIN | | deep dish | yes | yes | DEEP_DISH | Using the field names and data values listed above, add three public static final fields to the Crust class. These fields will store references to the three types of crust offered by the pizza shop. For example, one of the field declarations might look like this: java public static final Crust HAND_TOSSED = new Crust(“hand-tossed”, true, true); Note: Your Crust constructor arguments might be different, depending on how you wrote the constructor In accordance with the singleton and multiton design patterns, we would traditionally mark the HAND_TOSSED, THIN, and DEEP_DISH fields private, and expose them through a static factory method. However, since Crust instances are immutable, and the fields in question are final, it’s okay to expose them directly as constant values by simply assigning them the public access modifier. Sauce Add another subclass of IngredientImpl, called Sauce. This new class will be similar to Crust, except it represents the pizza sauce choices offered by the pizza shop. Make the constructor of Sauce private, and include public static final Sauce fields for the following sauce options: | name | is vegetarian? | is vegan? | field name | |————-|—————-|———–|————-| | tomato | yes | yes | TOMATO | | barbecue | yes | yes | BARBECUE | | pesto | yes | yes | PESTO | | alfredo | yes | no | ALFREDO | | ranch | yes | no | RANCH | Cheese Add another subclass of IngredientImpl, called Cheese. This new class will be similar to Crust and Sauce, except it represents the pizza cheese choices offered by the pizza shop. Make the constructor of Cheese private, and include public static final Cheese fields for the following cheese options: | name | is vegetarian? | is vegan? | field name | |————-|—————-|———–|————-| | mozzarella | yes | no | MOZZARELLA | | blend | yes | no | BLEND | | vegan | yes | yes | VEGAN | Topping Finally, add one more subclass of IngredientImpl, called Topping. This new class will be similar to Crust, Sauce, and Cheese, except it represents the pizza topping choices offered by the pizza shop. Make the constructor of Topping private, and include public static final Topping fields for the following toppings: | name | is vegetarian? | is vegan? | field name | |——————|—————-|———–|——————| | tomato | yes | yes | TOMATO | | garlic | yes | yes | GARLIC | | mushrooms | yes | yes | MUSHROOMS | | pineapple | yes | yes | PINEAPPLE | | olives | yes | yes | OLIVES | | green pepper | yes | yes | GREEN_PEPPER | | spinach | yes | yes | SPINACH | | onion | yes | yes | ONION | | jalapeno | yes | yes | JALAPENO | | sun-dried tomato | yes | yes | SUN_DRIED_TOMATO | | pepperoni | no | no | PEPPERONI | | ground beef | no | no | GROUND_BEEF | | sausage | no | no | SAUSAGE | | bacon | no | no | BACON | | buffalo chicken | no | no | BUFFALO_CHICKEN | | ham | no | no | HAM | | anchovies | no | no | ANCHOVIES | Adept Now it’s time to create a class to represent a pizza. PizzaImpl Start by taking a look at the Pizza interface. A pizza is an object that encapsulates the following information: 1. The size of the pizza (either small, medium, or large), represented by a Size enum field 2. The type of crust on the pizza, represented by a Crust instance 3. The type of sauce on the pizza, represented by a Sauce instance 4. The type of cheese on the pizza, represented by a Cheese instance 5. The toppings on the pizza, represented by a Topping list or array Make a new class, PizzaImpl, which implements the Pizza interface and encapsulates the above information. The PizzaImpl class should be immutable. Add a suitable constructor to initialize the encapsulated fields using initial values passed in as parameter values. Note: The order or type of the constructor’s parameters don’t matter to the autograder Most of the Pizza methods should be self-explanatory in terms of implementation. One exception, however, is getPrice(). The getPrice() method should be a derived getter which calculates and returns the price of the pizza as a double value based on the pizza size and number of toppings. If the pizza is small, its price should be $7.00 plus $0.25 per topping. If it is medium, its price should be $9.00 plus $0.50 per topping. If it is large, its price should be $11.00 plus $0.75 per topping. Jedi The last step of the assignment is to write a series of static factory methods which will instantiate special types of pizza. Add a new class, PizzaFactory, to your project. PizzaFactory will contain the factory methods that handle pizza instantiation. inside the PizzaFactory class, add the following factory methods. Cheese pizza Add a factory method to the PizzaFactory class to instantiate a cheese pizza. The factory method should have the following signature: java public static Pizza makeCheesePizza(Size size) { // Your code here } The factory method should create and return a new Pizza instance with hand-tossed crust, tomato sauce, cheese blend, and no toppings. The returned Pizza object should also have the correct size as specified by the method’s parameter. Hawaiian pizza Add a factory method to the PizzaFactory class to instantiate a Hawaiian pizza. The factory method should have the following signature: java public static Pizza makeHawaiianPizza(Size size) { // Your code here } The factory method should create and return a new Pizza instance with hand-tossed crust, tomato sauce, cheese blend, and two toppings: ham and pineapple. The returned Pizza object should also have the correct size as specified by the method’s parameter. Meat lover’s pizza Add a factory method to the PizzaFactory class to instantiate a meat lover’s pizza. The factory method should have the following signature: java public static Pizza makeMeatLoversPizza(Size size) { // Your code here } The factory method should create and return a new Pizza instance with deep-dish crust, tomato sauce, cheese blend, and four toppings: pepperoni, sausage, bacon, and ground beef. The returned Pizza object should also have the correct size as specified by the method’s parameter. Veggie supreme pizza Add a factory method to the PizzaFactory class to instantiate a veggie supreme pizza. The factory method should have the following signature: java public static Pizza makeVeggieSupremePizza(Size size) { // Your code here } The factory method should create and return a new Pizza instance with thin crust, tomato sauce, cheese blend, and four toppings: sun-dried tomato, green peppers, mushrooms, and olives. The returned Pizza object should also have the correct size as specified by the method’s parameter. Daily special pizza Finally, add one more factory method to the PizzaFactory class to instantiate a daily special pizza. The factory method should have the following signature: java public static Pizza makeDailySpecialPizza() { // Your code here } The factory method should create and return a new Pizza instance, but this time you get to choose what type of pizza to create. Instantiate and return your favorite type of pizza! Notice that this time, there is no size parameter; this is because you get to choose what size to return.
Introduction This assignment gives practice with the decorator design pattern. To complete the assignment, you will create a series of base classes and decorator classes to collectively represent a digital image, like what you would see on Snapchat or Instagram. In this context, the decorator pattern will be used to add visual modifications to a starting image. For example, one decorator class you will make adds a border around an existing image; another decorator superimposes a configurable circle somewhere on the image. The order in which you add the decorators to the base image will determine the order in which the modifications will appear on the final result. Colors Painters like Bob Ross can create new colors of paint by combining three primary colors of paint in different proportions. Computers use the same approach to represent and display all the different colors you see on your screen. For a computer, the three primary colors are red, green, and blue. Every color on your screen is a combination of different proportions of red, green, and blue. Most computer systems represent a color using three numbers in the range 0-255. For example, (0, 255, 52) represents a greenish color. The first number corresponds to the amount of red present in the color, the second number corresponds to the amount of green, and the third corresponds to the amount of blue. This color therefore has no red, 255 green, and 52 blue. Since the color has the maximum amount of green, we could expect the color to be mostly green, mixed with a little blue. Java provides a built-in Color class for representing colors. The color class encapsulates a red, blue, and green value in the range 0-255. Here’s how to create a new Color instance: java Color greenish = new Color(0, 255, 52); Now greenish is an object representing the greenish color described above. Image interface Every class you will create for this assignment should implement the Image interface, which is already provided in the starter code. An Image object represents a digital image. Digital images are made up of a two-dimensional grid of “pixels”, which are essentially minuscule rectangles of color. Every Image has a width and a height, referring to the number of horizontal and vertical pixels in the image. The Image interface therefore has getWidth() and getHeight() getter methods for getting these values. To get the color of a pixel, use the getPixelColor() method. getPixelColor() takes an x and a y value as parameters, representing the location of the pixel to get. And getPixelColor() returns a Color object, representing the color of the requested pixel. The Image interface also has a numLayers() getter method for getting the number of “layers” in the image. Base images, which do not have any decorators, have only one layer. Each decorator added to an image (like a shape or a border) is another “layer” added to the image. So, for instance, if a base image has one border decorator and one square decorator, then the image has a total of 3 layers. Novice For the novice portion of the assignment, create two new classes implementing the Image interface: SolidColorImage, and PictureImage. These classes represent base images themselves—they do not decorate another image. SolidColorImage The SolidColorImage class represents a blank image that is a solid color, kind of like a background. This class is a good starting point for making images that consist mostly of decorators stacked on top of each other. Add a new class to your project called SolidColorImage which implements the Image interface. You’ll have to add getPixelColor(), getWidth(), getHeight(), and numLayers() methods in order to implement the interface. SolidColorImage should have only one constructor with the following signature: java public SolidColorImage(int width, int height, Color color) { // Constructor code goes here } Encapsulate width, height, and color as private fields in the class. They represent the width, height, and color of the image. Make sure to check for illegal values of height and width (negative values are illegal), and throw an IllegalArgumentException if an illegal value is detected. getWidth() and getHeight() should act as basic getter methods for their corresponding fields. getPixelColor() should retrieve and return the color of the pixel at the specified (x, y) location in the image. Since this class represents a solid color image, all pixel values have the same color. Therefore, getPixelColor() should return the same color for all pixel locations—that is, the color encapsulated as a private field. However, getPixelColor() should also check to make sure the specified coordinates are actually within the boundaries of the image. For example, if the provided x value is negative or if it is greater or equal to the width of the image, then the coordinate is invalid. If an invalid coordinate is detected, throw an IllegalArgumentException. Finally, the getNumLayers() method should always return 1, since base images only have one layer. You should now be able to create and use new instances of SolidColorImage. Test out your new class in the Main file by making and returning a new instance inside the static makeImage() method. Make an image that is 200 by 200 images large, and is the greenish color described above. Run the main method to see your image on the screen. PictureImage The other base image class to create for this assignment is PictureImage, which represents an existing image from your computer. This class is a good starting point for adding decorators on top of an existing image. PictureImage should implement the Image interface, and should have a single constructor with the following signature: java public PictureImage(String pathname) throws IOException { // Constructor code goes here } The pathname parameter represents the path of an image stored on your computer. You should be able to complete the implementation for the entire PictureImage class by encapsulating only one field, which stores a BufferedImage object. In the constructor, use the pathname parameter to create a BufferedImage object, and store it in a private field. A BufferedImage represents an image from your computer which has been read into memory. You can read more about it here. In particular, you’ll have to use BufferedImage’s getWidth(), getHeight(), and getRGB() methods to complete the PictureImage class. When you’re done, test out your PictureImage class by making and returning an instance of PictureImage from the makeImage() static method located in the Main.java file. If you use “img/kmp.jpg” as the pathname argument, you should see a picture of kmp when running the main() method. Adept Now it’s time to start making decorator classes for the Image interface. Remember, decorator objects need to encapsulate an instance of the same interface that they implement. That means all the decorator classes created for this assignment should both implement Image, and they should encapsulate an instance of an Image object as a private field. SquareDecorator This decorator class should superimpose a configurable square on top of an existing image. The constructor should have the following signature: java public SquareDecorator(Image image, int squareX, int squareY, int squareSize, Color color) { // Constructor code goes here } Parameters squareX and squareY represent the coordinates of the top left of the square. Parameter squareSize represents the side length of the square. The color parameter represents the color of the square. Finally, the image parameter represents the underlying image that is being painted over. Make sure to check for illegal argument values in the constructor, and throw an IllegalArgumentException if one occurs. In particular, if image is null or if the square size is negative, these are considered illegal arguments. When getPixelColor() is called, the specified (x, y) coordinates should be checked to see if they are within the bounds of the square. If they are inside the square, then the returned color should be the designated square color (regardless of the underlying image’s pixel value at that location). If the coordinates are outside the square, then the pixel’s color should be unaffected by the decorator. In this case, simply return the underlying image’s pixel value at that location. Note: Digital images, including the ones in this assignment, traditionally use a coordinate system with an inverted y-axis. In other words, pixel (0, 0) is the top-left-most pixel in the picture; pixels to the right of that pixel have positive x-coordinate values, and pixels below the pixel have positive y-coordinate values. Here is an article with more information about the coordinate system for digital images. CircleDecorator This decorator is very similar to SquareDecorator, except it decorates the underlying image with a circle instead of with a square. The constructor should have the following signature: java public CircleDecorator(Image image, int cx, int cy, int radius, Color color) { // Constructor code goes here } The center of the circle should be located at position (cx, cy) in the image, should have radius radius, and should have color color. A pixel should be considered “in the circle” (and should therefore be painted with the color stored in color) if its (x, y) location is strictly less than radius units away from the center, (cx, cy). You can use the distance formula to calculate how close a pixel is from the center of the circle. Negative radius values should not be allowed (i.e., a IllegalArgumentException should be thrown if one is detected). Jedi This section involves creating two more Image decorator classes: BorderDecorator, and ZoomDecorator. BorderDecorator The BorderDecorator class decorates an image by surrounding it with a solid-color border. The class should implement Image and should have the following constructor signature: java public BorderDecorator(Image image, int thiccness, Color borderColor) { // Constructor code goes here } thiccness represents the thickness of the border, and borderColor represents the color of the border. Negative values of thiccness should not be allowed, and if one is detected, an IllegalArgumentException should be thrown. BorderDecorator should expand the height and width of the underlying image to account for the border being added. For example, if thiccness is 10, that means 20 pixels should be added to the width of the image—10 pixels for the left border, and 10 pixels for the right border. A similar computation should take place for the top and bottom borders. ZoomDecorator The ZoomDecorator class decorates an existing image by scaling the image so that it appears larger. ZoomDecorator should provide two constructors. The first constructor has the following signature: java public ZoomDecorator(Image image, int multiplier) { // Constructor code goes here } Here, multiplier is a positive integer referring to the factor by which the image should be scaled. A multiplier of 1 indicates that the image should not be scaled at all. A multiplier of 2 means the width and height should be doubled; a multiplier of 3 means the width and height should be tripled, and so on. Invalid values of multiplier should throw an IllegalArgumentException. The other constructor should omit the multiplier parameter, and instead should use a default multiplier value of 2. Use constructor chaining to accomplish this. In addition to simply increasing the width and height of the image, this class should also stretch the original image to fit the new size. This modification should take place in the getPixelColor() method. For example, if the original image has a height and width of 2, and the zoom multiplier is 2, then the decorated image should have a height of 4 and a width of 4, but the underlying pixels should be scaled so that getPixelColor(0, 0), getPixelColor(0, 1), getPixelColor(1, 0), and getPixelColor(1, 1) all return the same pixel color—that is, they return the same color as the pixel located at position (0, 0) in the original picture. In other words, each pixel value in the original pixel should be mapped to four pixels in the scaled image. Putting it all together Finally, in Main.java, adjust the makeImage() method so that it creates and returns an Image object using the decorator pattern with the following properties: The base image should be img/kmp.jpg The red border is color (255, 0, 0) and has a thickness of 5 (before scaling) The blue border is color (0, 0, 255) and has a thickness of 50 (before scaling) The yellow circle is color (255, 255, 0), has radius 40 (before scaling), and is at position (50, 50) in the final, unscaled image The orange square is color (200, 80, 10), has size 40 (before scaling), and is at position (100, 100) in the final, unscaled image After applying these decorators, add one last ZoomDecorator with a multiplier of 2, to make the image bigger You can see an example of the final image in img/jedi.png.
Introduction Imagine you are a customer ready to use a ride share service like Uber or Lyft. When you open the app, the system accesses your location and uses that information to retrieve a collection of the nearby, available drivers. In this assignment, you will create three classes that implement the Iterator interface. Your iterator classes will provide access to the available drivers logged into the app, one at a time, in a specific order, through the next() and hasNext() methods. For novice, the iterator that you create will act as a filter, identifying and iterating through only the drivers that are near the customer. For adept, your iterator will search for nearby drivers using an increasing search range; the closest drivers will be iterated through first, and drivers which are farther away will be iterated through later. Finally, for jedi, your iterator will interleave multiple collections of drivers together, providing a single iterator that goes through the drivers in each of the collections. To get started, read through the code already provided. The interfaces Position, Driver, and Vehicle, and their implementations PositionImpl, DriverImpl, and VehicleImpl, are complete, and you should not have to modify them in any way for this assignment. Interfaces Distance calculation Driver pools The collection of Driver objects to iterate through represents the pool of drivers currently available on the app. Generally, the pool of available drivers will be passed into the constructor of your iterator class in the form of an Iterable object. Your iterator class will use this object to access the available Driver objects. How can you use an Iterable object to access the available drivers? One way is to call the iterator() method, which creates and returns an iterator object. You can then call next() on that iterator object repeatedly to get access to the Driver objects. In summary, each of your iterator classes for this assignment will implement the Iterator interface, but they will also encapsulate another instance of Iterator. Your iterator class will use the encapsulated iterator to access the Driver objects. It will rearrange or filter the Driver objects, and finally will return them in next() one at a time, in the new order. Novice The first iterator class to create for this assignment will act as a filter on the pool of available Driver objects. It will not modify the order of the drivers; instead, it will only iterate over the drivers which are close enough to the customer’s position. Create a class called ProximityIterator that implements the interface Iterator. You’ll have to add the next() and hasNext() methods to the class in fulfillment of the interface requirements. The constructor for the class should be declared with the following signature. java public ProximityIterator(Iterable driverPool, Position clientPosition, int proximityRange) Here is a description of the constructor’s parameters: * driverPool – Represents the available pool of Driver objects. Call driverPool.iterator() to receive an iterator object for the underlying collection of available drivers. * clientPosition – Represents the static position of the customer/client. * proximityRange – Represents the range to use when deciding whether to include a Driver object in the iterator. Only Driver objects located within proximityRange units from clientPosition should be included by your iterator. Your ProximityIterator class should iterate only through the Driver objects in the collection that have a Manhattan distance to clientPosition that is less than or equal to proximityRange. If next() is called but there are no more eligible drivers, throw a NoSuchElementException. Tips In your constructor, use the iterator() method of driverPool to create an iterator for all of the Driver objects in the collection. Store this iterator in an instance field. Use an instance field to store the next driver that is within the proximity range from the client. Initialize this to null in your constructor. Add a private instance method which loads the next driver that is within the proximity range into the “next driver” field. If the “next driver” field is already set (i.e., if it is already non-null), this method should do nothing. Otherwise, it should retrieve drivers from the driver pool iterator until either an appropriate driver is found, or until no more drivers are in the pool. If an appropriate driver is found, store it in the “next driver” instance field. Otherwise, leave the “next driver” field null, because no next driver exists. To implement hasNext(), first make sure that a driver has been loaded into the “next driver” field, by calling your private method. Then, if a driver was successfully loaded in, return true; otherwise, return false. To implement next(), first call hasNext(). If false, throw a NoSuchElementException. If true, then you know that the next eligible driver must be in your “next driver” instance field. Copy this to a local variable. Reset your “next driver” field to be null so that you don’t keep returning the same driver. Now return the value of the local variable that is storing the next driver. Adept The second iterator class to create for this assignment will scan through the pool of Driver objects multiple times, using a gradually increasing search range each time. The first time through the driver pool, only drivers within 1 unit from the client will be selected. The second time through the driver pool, the search range for finding drivers will increase by a configurable amount. The third time, the search range will increase again. This process continues until all drivers in the pool are visited. Create a class called ExpandingProximityIterator that implements the interface Iterator. You’ll have to add the next() and hasNext() methods to the class in fulfillment of the interface requirements. The constructor for the class should be declared with the following signature. java public ExpandingProximityIterator(Iterable driverPool, Position clientPosition, int expansionStep) Here is a description of the constructor’s parameters: * driverPool – Represents the available pool of Driver objects. Call driverPool.iterator() to receive an iterator object for the underlying collection of available drivers. * clientPosition – Represents the static position of the customer/client. * expansionStep – Represents the amount by which to increase the range when searching for available drivers. An ExpandingProximityIterator should first iterate through all of the Driver objects in the collection that have a Manhattan distance to clientPosition that is less than or equal to 1. After all such drivers have been exhausted, the iterator should start back at the beginning of the pool and iterate through drivers that have a distance that is greater than 1 but less than or equal to 1 + expansionStep. After all of these drivers have been exhausted, the iterator should start at the beginning of the pool again and iterate through drivers that have a distance that is greater than 1 + expansionStep but less than or equal to 1 + 2 * expansionStep. After these have been exhausted, go through drivers that are greater than 1 + 2 * expansionStep but less than or equal to 1 + 3 * expansionStep. This process should continue until there are no more drivers left to process. At that point, hasNext() should return false. Tips You will need to encapsulate driverPool as an instance field, so that you can use it to create a new iterator each time you run out of drivers for a particular “ring” size. You will need to detect when you have run out of drivers completely so that hasNext() returns false eventually. There are a couple of different ways to do this. One way is to maintain a boolean flag that is set whenever a driver is encountered that is outside of the current ring while looking for the next driver. Then, when you have run out of drivers at the current ring size, you can check this flag to make sure that at least one driver is still outside of the current ring, and you know if you should keep expanding. Be sure to reset the flag each time you expand. Another way to do this is to keep track of the total number of drivers in the driver pool. Then, keep track of the number of times next() has been successfully called. When this count is equal to the size of the driver pool, you know that every driver has been found at some ring size already and that expanding the ring won’t help (i.e., there are no more drivers). Jedi (extra credit) The last iterator class to create for this assignment will interleave the drivers from multiple different driver pools together into one iterator. Create a class called SnakeOrderAcrossPoolsIterator that implements the interface Iterator. The constructor for this class should be declared with the following signature: java public SnakeOrderAcrossPoolsIterator(List driverPools) Unlike novice and adept, the constructor of this iterator is given a list of driver pools. This version of the iterator should retrieve the next driver from each pool, one at a time, in “snake order”. “Snake order” means first going from first-to-last and then reversing and going from last-to-first. For example, let’s say there are 4 driver pools in the driverPools list. The first driver retrieved should come from pool 0, followed by the next driver from pool 1, then pool 2, then pool 3, then pool 3 again, then pool 2, then pool 1, then pool 0, then pool 0 again, then pool 1, and so on. Tips In your constructor, use the list of driver pools provided to create a corresponding list of driver iterators for each pool; store this list as an instance field. Encapsulate an integer instance field to store an index representing which pool iterator to pull from the next time next() is called. Grading This assignment is worth 15 points. Novice: 10 points Adept: 5 points Jedi: 5 points
This assignment is a little different from the rest of the assignments in COMP 301. In most other assignments, you are given a description of a class or algorithm, and your job is to write code that implements the class. Most of your work inevitably goes into the src/main folder. In this assignment, you are still given a description of a class, but you are not required to write code that implements it. Instead, you are asked to write unit tests to verify if an arbitrary implementation of the class is correct. Since you’ll be writing unit tests, most of your work will go in the src/test folder. Each of Novice, Adept, and Jedi below describes a different class or classes for which you should write unit tests. When you submit your work to Gradescope, the autograder will run your unit tests on a series of different (hidden) implementations of the classes. Your tests must correctly identify which implementations are correct and which ones contain a bug. Again, you are not required to implement the classes described below for this assignment. The goal of this assignment is to give you practice writing unit tests with JUnit 4. Novice The first class you should write tests for is called Alphabetizer. Write unit tests for Alphabetizer in the src/test/java/com/comp301/a04junit/NoviceAlphabetizerTests file. An empty, unimplemented version of the class can be found in src/main/java/com/comp301/a04junit/alphabetizer/Alphabetizer.java. You should test this class file when writing unit tests. This class file is the one you should test when writing unit tests. The unit tests you write should verify that Alphabetizer matches the algorithm specification given below. The Alphabetizer class is intended to sort an array of String values alphabetically and process the sorted strings one at a time. Constructor The Alphabetizer class has a constructor with the following signature: public Alphabetizer(String[] arr) When creating a new Alphabetizer instance, the constructor takes in an unsorted array of String values as an argument. The Alphabetizer instance keeps a reference to the provided array internally, and must never modify or manipulate the array. next() method Once an instance of Alphabetizer has been created, it can be used to process the elements in the array, one at a time, in alphabetized order. This can be accomplished by repeatedly calling the next() method. Each time next() is called, a different string from the array is returned. Strings are returned in alphabetized order. After every string from the array has been returned once, next() should throw a NoSuchElementException if it is called again. hasNext() method Instead of relying on catching a NoSuchElementException to check if there are still remaining strings left to process, another option is to use the hasNext() method. hasNext() returns a boolean value which is true if there are still strings left, and false if there are no more strings left. In other words, hasNext() will only return false if the object is in a state where a call to next() would throw a NoSuchElementException. Example usage Here is an example usage of the Alphabetizer class. Imagine a new Alphabetizer object is created for the array { “b1”, “a1”, “c1” }. Calling next() on the object for the first time will return “a1”. The second time next() is called, it will return “b1”; and the third time it is called, it will return “c1”. After the third time, any future calls to next() will throw a NoSuchElementException. Adept In adept, you should write unit tests for the ItemImpl and PositionImpl classes that you designed for assignment a02-adventure. Write unit tests for ItemImpl in the src/test/java/com/comp301/a04junit/AdeptItemTests file, and tests for PositionImpl in src/test/java/com/comp301/a04junit/AdeptPositionTests. Empty, unimplemented versions of these two classes can be found in src/main/java/com/comp301/a04junit/adventure. These class files are the ones you should be testing when writing unit tests. The unit tests you write should verify that ItemImpl and PositionImpl match the algorithm specification given in a02-adventure. Refer to that assignment write-up for details about the exact algorithm specification. Jedi In adept, you should write unit tests for the InventoryImpl and PlayerImpl classes that you designed for assignment a02-adventure. Write unit tests for InventoryImpl in the src/test/java/com/comp301/a04junit/JediInventoryTests file, and tests for PlayerImpl in src/test/java/com/comp301/a04junit/JediPlayerTests. Empty, unimplemented versions of these two classes can be found in src/main/java/com/comp301/a04junit/adventure. These class files are the ones you should be testing when writing unit tests. The unit tests you write should verify that InventoryImpl and PlayerImpl match the algorithm specification given in a02-adventure. Refer to that assignment write-up for details about the exact algorithm specification. Points Novice – The unit tests you write for the Alphabetizer class are worth a total of 4 points. Adept – The unit tests you write for the ItemImpl and PositionImpl classes are worth 4 points each, for a total of 8 points. Jedi – The unit tests you write for the InventoryImpl and PlayerImpl classes are worth 4 points each, for a total of 8 points. Style – Conforming to the Google style guide is worth 1 point. Important note about grading: When calculating your grade percent for this assignment, a point value of 11 or less will be considered a 0% on the assignment, while a grade of 21 will be considered a 100%. Any grade between 11 and 21 will be linearly scaled between 0% and 100%. You can calculate your grade percent with the following formula: Math.max(p – 11, 0) / 10, where p is the number of points that the autograder gave you. Why such a weird grading policy? Because submitting the starter code gives you an 11/21 on the assignment. This is because the empty starter code unit tests pass no matter what, which means they correctly identify the properly implemented classes (but not the bugged classes). You could equivalently change the starter code so that it fails no matter what, and then it would correctly identify the bugged classes (but not the correct classes). The crucial part of writing unit tests is not to universally pass or fail, but instead to pass and fail at the right time.
This assignment is a series of exercises where you can practice using exceptions in Java. To get started, open source code files Novice.java, Adept.java, and Jedi.java. Each of these files contains a series of empty methods with comment blocks explaining what code to write inside of them. To complete this assignment, fill out the methods with code as directed by the commented instructions. Grading The assignment is worth a total of 9 points, allocated as follows: Novice: 3 points Adept: 4 points Jedi: 2 points
Introduction In this assignment, you will design and implement a text-based, directional adventure video game that can be played in the console. The player will explore a two-dimensional, gridded map in search of treasures. The player will navigate through the world by entering keyword inputs such as “go north” or “go east” into the console. Each input will return a message based on what the player chose to do and their current surroundings. Some locations in the map will have “chests” containing items; the player can “open” a chest and take the items inside. The goal of the game is to find all the treasure in the map. Text-based adventure games were first popularized in the late 1970’s and early 1980’s. Zork, which you can read about here or play here, is a classic example of a text-based adventure game like the one we will be creating for this assignment. The environment that the player will navigate through is two-dimensional, so let’s assume a 2D, integer Cartesian coordinate system. This means the player’s current position on the map can be modeled by two integers representing their x and y location. The player should be able to move north (i.e. in the positive-y direction), south (i.e. in the negative-y direction), east (i.e. in the positive-x direction), and west (i.e. in the negative-x direction) through the environment. To model the game, we will design a Game object. However, as you can probably guess, the game will require a lot of functionality—and a lot of code—to work properly! To make our lives easier (and to make the resulting code more flexible), we’re going to use composition to split the Game class behavior into the following smaller components: Item – An interface that represents an item in the game. The objective of the game is to search for and collect different items as the player navigates through the game environment. In a more complex game, there might be multiple implementations of Item, each having unique behavior within the game. For example, there might be Furniture items, Weapon items, Clothing items, Tool items, etc. To keep it simple, for this assignment we’re just going to create one implementation of the Item interface: ItemImpl. The ItemImpl class will encapsulate a single instance field: a String to represent the name of the item. Inventory – An interface that represents a collection of Items. For this assignment, the Player object will have an Inventory to store the items that they have collected. As the player finds more items in the game, they will add the items to their inventory. Additionally, some locations on the map will contain “chests” that store items for the player to find. Each chest will be represented by anInventory instance. Player – An interface representing the player of the game. At all times, the player is located at a particular Position and has a personal Inventory full of the Items they have collected. Thus, this object will be an aggregation of these two objects. Cell – An interface representing the contents of an (x, y) location in the environment. Each accessible location in the environment will encapsulate a name and a description, so these will be String values stored in the Cell object. Some Cells will contain a chest (represented by the Inventory object). Ultimately, the game environment will be represented as a 2D array of Cell objects. Map – This interface encapsulates a two-dimensional array of Cell objects that represent the environment that the player will explore. Game – This interface represents the composition of a Player together with a Map, allowing the game to be played! Do you see how composition is used here to break down the game functionality into smaller, independent pieces? As software engineers, our job is to always be looking for ways to break down larger problems into smaller pieces. Before starting to write code, check out the Item, Position, Inventory, Cell, Player, Map, and Game interfaces that have been created for you as part of the starter code. Read the method descriptions in each interface, and begin to build a mental model for what the object do and how they interact. Novice The “novice” portion of this assignment is to create three new classes that implement provided interfaces: ItemImpl, PositionImpl, and InventoryImpl. Together, these classes will represent the basic building blocks for our adventure game. In the “adept” and “jedi” sections, we will be composing and aggregating these objects together to construct larger classes. ItemImpl The implementation class for the Item interface should be called ItemImpl. The ItemImpl class should encapsulate a private String field to store the name of the item. The ItemImpl class should be immutable. There should only be one constructor for ItemImpl, and it should look like this: java public ItemImpl(String name) { // Constructor code goes here } null values for the name parameter should not be allowed by the constructor; if one is encountered, an IllegalArgumentException should be thrown. Notice how the Item interface overrides the equals() and toString() methods? That’s because every class in Java is actually a descendant of a built-in superclass, called “Object”. The Object superclass defines a few useful methods for every Java object, like equals() and toString(). Since Object is the superclass to every class, that means every Java object has these methods. Programmers can override them, if necessary, to supply a subclass-specific version of the method. In the ItemImpl class, you should override both equals() and toString() to provide more suitable implementations for both of these methods (see the comments in the Item interface for more details). InventoryImpl The implementation class for the Inventory interface should be called InventoryImpl. InventoryImpl should encapsulate a single private field: a List list of items. The constructor of InventoryImpl should take no arguments, and simply construct the list of items. An ArrayList is a suitable List implementation to use, but any valid List implementation would work. PositionImpl The implementation class for the Position interface should be called PositionImpl. The PositionImpl class should encapsulate a position in the environment, in the form of an (x, y) pair of integer coordinates. The PositionImpl class should provide a single constructor which takes two integer arguments and looks like this: java public PositionImpl(int x, int y) { // Constructor code goes here } Adept In the “adept” portion of the assignment, you will begin to compose and aggregate the classes you created in “novice” together to create more complicated objects. CellImpl Create a CellImpl class which implements the Cell interface. The CellImpl class should provide two constructors. The first should look like this, and should throw an IllegalArgumentException for null values of name or description: java public CellImpl(int x, int y, String name, String description) { // Constructor code goes here } The x and y coordinates should immediately be stored in an encapsulated Position field. The name and description Strings should also be encapsulated in fields. The second constructor should take in only the x and y coordinates as parameters, and initialize the other two fields to empty strings (“”). You should use constructor chaining to implement these two constructors. Some (but not all) CellImpl instances will hold a chest. A chest will be represented by an Inventory instance. Therefore, the Cell class should also encapsulate a field to store the (optional) chest, and expose getter and setter methods for this field. Finally, the CellImpl object should also provide a way to check whether the player has visited the Cell before. You should encapsulate a boolean flag to track whether the cell has been visited. All CellImpl objects should start out with a “visited” value of false. Once the visit() method is called, the flag should be permanently switched to true. PlayerImpl Create a PlayerImpl class which implements the Player interface. The PlayerImpl class should provide a single constructor, which should look like this and should throw an IllegalArgumentException for null values of name: java public PlayerImpl(String name, int startX, int startY) { // Constructor code goes here } A Player object should encapsulate a name, a Position, and an Inventory. When the move() method is called, the player object should replace its private Position field with a new Position according to the indicated direction of the movement. Hint: use the getNeighbor() method. Jedi In the “jedi” portion of the assignment, you will continue to compose and aggregate the classes you created in “novice” and “adept” by creating MapImpl and GameImpl objects. MapImpl Create a MapImpl class which implements the Map interface. The MapImpl class represents a 2D grid of Cell objects, together with an integer representing the initial number of items hidden in the map that the player needs to find. You should therefore encapsulate these two ideas as two instance fields within the class. The MapImpl class should provide one constructor: java public MapImpl(int width, int height, int numItems) { // Constructor code goes here } Here, width and height indicate the dimensions of the 2D Cell grid. The MapImpl should provide getter methods for the map height, the map width, and each individual Cell. Initially, all Cell locations in the grid should be initialized to null. However, users of the class can instantiate grid locations as desired by using the initCell() method. GameImpl Finally, the last class to create for this assignment is GameImpl, which implements the Game interface. A Game is an aggregation of a Map object and a Player object, so you should encapsulate these as instance fields. The GameImpl constructor should look like this, and should throw an IllegalArgumentException if either map or player is null: java public GameImpl(Map map, Player player) { // Constructor code goes here } Write appropriate implementations for the methods required by the Game interface. You should be able to fill in all of these methods simply by manipulating the Player and Map object that is encapsulated by the Game. Playing the Game The starter code also includes the classes MapUNC and Main, which have been commented out. Once you have finished the “jedi” portion of the assignment, these can be used to play a short treasure hunting game that uses the UNC-CH campus as a map! Feel free to play it as is, make modifications, or create an entirely new game! To play, open the Main class file and hit run (the small green icon next to the line numbers at the top of the class)
First, read the comments in the code for the following interfaces defined in package a1 to understand the abstractions for ingredients, ingredient portions, and sushi: * Ingredient * IngredientPortion * Sushi Novice Create eight classes which implement the Ingredient interface called Avocado, Crab, Eel, Rice, Yellowtail, Seaweed, Shrimp, and Tuna. The characteristics of these classes are given in the following table: | Class Name | Name | Price/Oz. | Calories/Oz. | isVegetarian? | hasRice? | hasShellfish? | |————|——|———–|————–|————|——-|————| | Avocado | “avocado” | $0.24 | 42 | true | false | false | | Crab | “crab” | $0.72 | 37 | false | false | true | | Eel | “eel” | $2.15 | 82 | false | false | false | | Rice | “rice” | $0.13 | 34 | true | true | false | | Yellowtail | “yellowtail” | $0.74 | 57 | false | false | false | | Seaweed | “seaweed” | $2.85 | 105 | true | false | false | | Shrimp | “shrimp” | $0.65 | 32 | false | false | true | | Tuna | “tuna” | $1.67 | 42 | false | false | false | All of these classes should provide a constructor without any parameters. For example, for the Avocado class, the constructor should look like this: public Avocado() { // Constructor code goes here } You should employ inheritance to implement these classes. The easiest way to do this is to create a single parent class implementing the interface that encapsulates all of the information about an ingredient as private fields. You can then create individual subclasses for each specific ingredient. The constructor of each ingredient subclass should simply call the superclass constructor, passing the appropriate values from the table as arguments. Next, create eight new classes that implement IngredientPortion, called AvocadoPortion, CrabPortion, EelPortion, RicePortion, YellowtailPortion, SeaweedPortion, ShrimpPortion, and TunaPortion. Each of these classes should provide a constructor that accepts a single parameter, indicating the amount of the portion in ounces. For example, for the AvocadoPortion class, the constructor should look like this: public AvocadoPortion (double amount) { // Constructor code goes here } The constructor should throw an IllegalArgumentException if the amount specified is less than 0. Each of these classes should encapsulate an instance of Ingredient, representing the ingredient that it is a portion of. For example, AvocadoPortion should use an instance of Avocado as its ingredient. The IngredientPortion classes should also implement the combine method to use the appropriate subclass according to which ingredient it is. For example, combining an instance of AvocadoPortion with another instance of AvocadoPortion should return a new instance of AvocadoPortion. Again the easiest way to do this is to first create a parent class that implements an ingredient portion, and then create subclasses that simply provide the appropriate constructor and any subclass-specific method implementations that can not be provided generally (HINT: you’ll need a subclass specific version of combine). As you implement the IngredientPortion classes, think about whether or not you can reuse the same ingredient instance for every ingredient portion of the same type. This is not necessary for full points but is just a challenge. (HINT: Think about immutability) Adept Create the following three classes which implement the Sushi interface. Sashimi A piece of sashimi is comprised of 0.75 ounces of some type of seafood. There are five types of sashimi: tuna, yellowtail, eel, crab, and shrimp. The Sashimi class should define a public enumeration called SashimiType with the following definition: public enum SashimiType {TUNA, YELLOWTAIL, EEL, CRAB, SHRIMP}; The Sashimi class should have a constructor with the following signature: public Sashimi(SashimiType type) The value of type passed to the constructor indicates what type of sashimi is being made. The name associated with a Sashimi object should be the name of the underlying seafood ingredient followed by the word “sashimi”. For example, a tuna sashmi object should be produce the value “tuna sashimi” as the result of the getName method. Nigiri A piece of nigiri is comprised of 0.75 ounces of some type of seafood and 0.5 ounces of rice. There are five types of nigiri: tuna, yellowtail, eel, crab, and shrimp. The Nigiri class should define a public enumeration called NigiriType with the following definition: public enum NigiriType {TUNA, YELLOWTAIL, EEL, CRAB, SHRIMP}; The Nigiri class should have a constructor with the following signature: public Nigiri(NigiriType type) The value of type passed to the constructor indicates what type of nigiri is being made. The name associated with a Nigiri object should be the name of the underlying seafood ingredient followed by the word “nigiri”. For example, a tuna nigiri object should be produce the value “tuna nigiri” as the result of the getName method. Roll public Roll(String name, IngredientPortion[] roll_ingredients) Specifically do NOT use inheritance for these classes (i.e., Sashimi, Nigiri, and Roll). Implement each one as a separate class that implements the Sushi interface without using a common parent class. Be careful about working with arrays as parameters to and from constructors and methods. in particular, your Roll constructor should not just blindly copy the array reference passed in to a private field encapsulated in your Roll class. Instead, you should use the clone method of the array to make a copy that you can store safely. Similarly, you should not simply return an encapsulated array reference in order to implement the getIngredients method. You should create a new array to return each time. Jedi Amend your Roll class to add the following functionality: The constructor should detect if a particular ingredient type is repeated and combine the separate portions of a repeated ingredient type into a single portion. The constructor should always include at least 0.1 ounces of SeaweedPortion as a component ingredient portion to represent the roll wrapper if the ingredient portion array passed to the constructor does not already include at least this much seaweed. If the ingredient portions passed to the constructor already have at least this much seaweed, you should not include any more. Grading Novice: 4 points Adept: 4 points Jedi: 2 points Style guide: 2 points
Creating Weights The excel sheet titled roadtrip is what you need to fill in with numbers that you wanna assign each factor. link: https://docs.google.com/spreadsheets/d/1mB565mYrsWRLblfatBxrCXQe-3W9pQlL9fs46IYI_pE/edit?usp=sharing *IMPORTANT* In order to create a graph (in Main.java), you must pass in to the contstructor the path for where your csv file is stored. If you pass in the incorrect path you will get a FileNotFoundException. How to find your file path: Mac: Locate the file in your finder and right click on it. Hold down the option key and select ‘Copy “roadtrip.csv” as Pathname’. The absolute path of your file is now copied to your clipboard. Windows: Locate the file in your file explorer, shift + right click on file, then select “Copy as path” The calculateWeight method is where you create your algorithm using 4 factors to produce a single weight for your edge. However, make sure you are not doing any illegal math operations. For example if you divide a number by traffic, make sure you never pass in 0 for traffic since you cannot divide by 0. You can also choose to emphasize certain factors over others. For instance if your car gets really bad gas mileage, you could give distance more weight as opposed to scenery. Also be sure that your weights are positive. Dijkstra’s algorithm does NOT work with negative values. Once you have completed this part, Write 1 paragraph explaining your reasoning behind your scores for each category, and how your algorithm works. Write this paragraph in the Explanation.txt file provided. Implementing Dijkstra’s Algorithm Part 2 of this project is to implement Dijkstra’s algorithm, using a priorty queue. The package minBinHeap contains the code for a Minimum Binary Heap that you will be using for your algorith (do not edit anything in that folder). The Dijkstra method in Graph.java should return a Map with they key being the name of the city, and the value being the total weight that it takes to reach that city from your starting point. Once you are confident your algorithm works, add to your Explanation.txt file an overview of your roadtrip. Give us 1 paragraph explaining what cities you are going to hit between Chapel Hill and LA, the weight of each path you take and what attractions you’re planning to visit on the way (this doesn’t necessarily have to be the ones list below). Attractions Chicago – The Bean – Wrigley Field – Deep Dish Pizza! Nashville – Country Music Capital – Grand Ole Opry – Centennial PArk Dallas – Six Flags – Dallas Arboretum and Botanical Garden – Sixth Floor Museum at Dealey Plaza (museum about the JFK assassination) Las Vegas – Las Vegas Strip – Red Rock Canyon – Bellagio Hotel and Casino Phoenix – Desert Botanical Garden – Camelback Mountain – Papago Park Denver – Red Rocks Park and Amphitheatre – Great Skiing Resorts – Denver Art Museum San Francisco – Golden Gate Bridge – Alcatraz Island – Fisherman’s Wharf Los Angeles – Potential Celebrity Citings – DisneyLand – Santa Monica Pier Road Information CH – Nashville: Scenery: Nice, you drive through the Pisgah National Forest Traffic: No traffic CH – Chicago Scenery: Mostly highway but a nice drive through the West Virginia mountains Traffic: Low CH – Dallas Scenery: Pretty drive through hills and forests Traffic: Heavy Vegas – San Francisco Scenery: Goes through Death Valley National Park Traffic: Average traffic Dallas – Phoenix Scenery: Mostly farms and fields Traffic: Heavy traffic Dallas – Denver Scenery: Desert scenery, mainly flat Traffic: Moderate traffic Denver – Chicago Scenery: Midwestern Scenery Traffic: Low Denver – Nashville Scenery: Most of drive is through forests and open fields Traffic: No traffic Chicago – Vegas Scenery: Pass through 4 states with changing scenery, from fields to desert Traffic: Medium traffic Chicago – San Francisco Scenery: Some national forests on the way Traffic: None Vegas – Phoenix Scenery: Desert scenery Traffic: High Phoenix – LA Scenery: Desert scenery Traffic: Low traffic Phoenix – Denver Scenery: Many national forests Traffic: Moderate LA – San Francisco Scenery: Incredible ocean views on Pacific Coast Highway Traffic: Light
In this assignment you will be implementing a version of a HashMap in order to create your own password manager. A password manager is an application designed to store and manage someone’s passwords. The #1 rule of password security is to not reuse passwords, we all know that whenever safari or chrome recommends those strong password filled with random letters and numbers, no one actually uses them. However with a password manager, you can use strong passwords because you don’t have to remember them. All it takes is 1 master password for the password manager, and then you can access all of your stored passwords. HashMap Input Output The interface for the password manager will be a command line application that uses a Scanner to read inputs. The code for the input output logic should all go in the main method in Main.java. The Scanner and Password Manager object are already created for you. Upon running your program, your password manager should print “Enter Master Password”. Change the value of the variable MASTER_PASSWORD in PasswordManager.java to any String of your choosing. If the entered password does not match the password saved in the MASTER_PASSWORD variable, reprint “Enter Master Password” until the correct password is entered. Once they are given access, the user should be able to enter one of the following phrases: “New password”, “Get password”, “Delete account”, “Check duplicate password”,”Get accounts”, “Generate random password”, or “Exit”. If something other than these 7 phrases are entered, print “Command not found” and wait for another command. After each case, excluding “exit”, they can enter another phrase. If they enter exit, they get reprompted to enter the master password. Here is a link to a control flow diagram to help visualize the logic: https://drive.google.com/file/d/1XqckgFA8S3Zo1TPz826N5InO0JAGLk3/view?usp=sharing Based on which phrase is entered, you should call one of the methods in your password manager using the entered parameters. For each command, the user should be able to input the command name, and the needed parameters in the correct order. Here are the guidelines for using commands with parameters. “Get accounts” and “Exit” do not have any parameters. New password: input: New password Website Name Password output: New password added Get password input: Get password Website name output: Password does not exist || the account’s password Delete account input: Delete Account Website name output: Account deleted || Account does not exist Check duplicate password input: Check duplicate password password output: No account uses that password || Websites using that password: website1 website2 Get accounts input: Get accounts output: Your accounts: account1 account2 account 3 etc. Generate random password input: Generate random password Length of password (should be an int) output: generated password Below is an example of the expected inputs and outputs, where the master password is password123. The bold represents what is printed and the normal text is what the user enters. Enter Master Password password Enter Master Password password123 New password facebook mypassword New password added New passsword instagram mypassword New password added fake command Command not found Get password facebook mypassword Get password twitter Account does not exist Check duplicate password mypassword Websites using that password: facebook instagram Check duplicate password password789 No account uses that password Generate random password 10 Zq9CZ9noe4 New password facebook Zq9CZ9noe4 New password added Get accounts Your accounts: facebook instagram Delete account facebook Account deleted Delete account snapchat Account does not exist Exit Enter Master Password
Your task in A7 is to implement an AVL tree as an implementation of the interface SelfBalancingTree. A skeleton AVLTree class has been provided. You must at least provide a constructor that takes no arguments and creates an empty AVLTree. You can either use a null element value to indicate that a tree is empty or explicitly keep track of whether a tree is empty with a boolean field. You can assume that null is not otherwise a valid value for inserting into a tree as an element. The skeleton also declares private rotateLeft and rotateRight methods. You should provide the code to implement these operations and then use them as necessary in your implementation of insert and remove.
A nearby has been struggling to efficiently manage their emergency room and has brought you in to help. They want to be able to tend to the sickest people first, but their current system has been too slow in doing this and those that are the sickest end up having longer wait times. Part 1: Old System Patient.java represents a patient coming into the ER. There are two constructors for a patient, one that takes in only a value (the order which they came in) and a priority. The other only takes in a value and randomly assigns a priority. The lower the priority value is, the more severe their injuries are, and therefore they should be treated sooner. For example a patient with priority 2 is sicker than one with priority 3. SimpleEmergencyRoom.java represents the current way that the hospital’s database manages the ER. Currently, the patients are stored in an ArrayList in the order they come in. All the methods are filled in for you except the dequeue method. TODO: 1a) Fill in the dequeue method to find the patient with the smallest priority using a For-each loop. Return that patient and remove them from the list. 1b) In Main.java under the “Part 1” comment, create a SimpleEmergencyRoom object and call fillER() with the object you created as an argument. The fillER method adds 100,000 patients to your ER. (100,000 patients is definitely an exaggeration for how many fit in an ER room but we need a large number in order to get better times). Now dequeue from the list 10 times, and find the average amount of time it takes to do 1 dequeue, in nanoseconds (hint: use a for loop). Record your average time in data.txt. The data.txt file is where you will keep track of the times you calculate in order to prove to the hospital that your new implementation is more efficient. Write your average time in data.txt. Part 2: Improved System You recently learned about a really cool data structure called a Binary Heap in your COMP 210 course and figured it would apply great to this situation! Since the patients with lower priority are the ones we want to help first, you will be creating a Minimum Binary Heap. BinaryHeap.java is the interface that outlines all the methods you will need to implement in MinBinHeapER.java. MinBinHeapER has an overloaded constructor. For now you can ignore the second one (the one that takes in an array), we will get back to it in part 3. TODO: 2a) Fill in the methods in MinBinHeapER.java according to the specifications in BinaryHeap.java. The enqueue method is overloaded in MinBinHeaER but the functionality behind the two is the same. The only difference is that in enqueue(V value, P priority) you create a Patient using the constructor that takes in both a value and priority, and in enqueue(V value) you create the Patient using only the value. 2b) Now let us see how much faster the Heap is compared to the List used earlier. In Main.java under the “Part 2” comment, you will do the same as you did in part 1 but with a MinBinHeapER object. Create the object then call fillER with that object as a parameter (notice that there are 2 fillER methods, one for each type of Emergency Room). Dequeue from the list 10 times and find the average amount of time it takes to do 1 dequeue, in nanoseconds. Record down this number in data.txt. Now calculate the percent decrease between the 2 numbers and add it to the .txt file. Part 3: Hospital Transfers Sometimes, another hospital down the street is overflowing with patients and transfers them to your ER. These new patients are represented by a Patient[] in the database. You need to add functionality to your heap in order to turn this array of patients into a Minimum Binary Heap. TODO: Fill in the second constructor in MinBinHeapER.java to build a heap when given an initial array of Prioritized objects. An example of how you can test this is shown in Main.java under the Part 3 comment.
5/5 - (2 votes)
In this assignment your task is to complete a series of algorithms using linked lists. The method signatures and their explanations that you need to implement are provided at the top of LinkedList.java. The algorithms increase in difficulty as you go down the page. An example of the input and expected output is also provided. For these algorithms you should NOT be creating a new list and returning it, you should only be manipulating the list object that the method is called on (the object that the this keyword represents). The a4 package also contains the code for an implementation of a Linked List. The Node class is how we represent a Node that makes up the List and the LinkedList class has a full implementation of the LinkedList. You should not be changing any of the completed methods at the bottom, only edit the first 8 methods at the top of the file. Look over and understand the contents of this package before starting on the algorithm solutions. An example of how to test your code is provided in Main.java. A toString method is provided in LinkedList.java to display the contents of the list.
The package a3 contains a Java interface for the complex number abstract data type. Refer here for a refresher on complex numbers: https://en.wikipedia.org/wiki/Complex_number Complete the implementation for the data type started in ComplexNumberImpl. The ADT is being modeled as an immutable type which means that the multiply and add methods should create new instances to return as their result. Use the statically defined EQUALS_EPSILON as the epsilon bound for testing equality of the real and imaginary parts in your implementation of equals. The named constant I is also defined for your convenience if you should need it. The functional specification of the ADT is as follows: create: DOUBLE x DOUBLE => COMPLEX Canonical operation for creating a new complex number given the magnitudes of its real and imaginary parts. real: COMPLEX => DOUBLE Returns the magnitude of the real part. imag: COMPLEX => DOUBLE Returns the magnitude of the imaginary part. absolute: COMPLEX => DOUBLE Absolute value (see wikipedia page) add: COMPLEX x COMPLEX => COMPLEX Addition (see wikipedia page) multiply: COMPLEX x COMPLEX => COMPLEX Multiplication (see wikipedia page) equals: COMPLEX x COMPLEX => BOOLEAN Equality test. Two complex numbers are equal if both their real and imaginary parts are within EQUALS_EPSILON of each other. In a3test, complete the tests for the following axiomatic analysis (you’ll need to come up with the right hand sides): real(create(A,B)) = ???? imag(create(A,B)) = ???? absolute(create(A,B)) = ???? add(create(A,B), C) = ????? add(C, create(A,B)) = ????? multiply(create(A,B), C) = ????? multiply(C, create(A,B)) = ????? equals(create(A,B), C) = ????? equals(C, create(A,B)) = ????? You are encouraged to make each test as complete as you can think of, testing several different values and trying to cover corner cases. Feel free to add additional tests if you would like.
Like Assignment 1, this assignment is intended to further warm-up your basic programming skills and can be done without any object-oriented programming using built-in data types and arrays with loops and conditional execution. A2Novice This program reads in a list of ingredients used by a restaurant and prints out information derived from the list. The first input to the program will be an integer number that indicates the number of ingredients. Following this, for each ingredient will be a line with the form: Ingredient_Name Price_Per_Ounce Is_Vegetarian Calories_Per_Ounce Ingredient_Name is a single word token naming the ingredient. Price_Per_Ounce will be a real value indicating the cost of the ingredient in dollars per ounce. Is_Vegetarian will be the token “true” or “false” indicating whether the ingredient is vegetarian. Calories_Per_Ounce will be an integer indicating the caloric content of the ingredient per ounce. The program should count the number of vegetarian ingredients and report which ingredients provide the highest and lowest ratios of calories per dollar. The output should be formatted as follows: Number of vegetarian ingredients: Highest cals/$: Lowest cals/$: where the angle bracketed items are placeholders for the actual answers. For example, the following input: 6 Rice 0.12 true 37 Seaweed 2.95 true 113 Avocado 0.22 true 45 Salmon 1.77 false 48 Yellowtail 0.53 false 41 Eel 2.18 false 84 Should produce the following output: Number of vegetarian ingredients: 3 Highest cals/$: Rice Lowest cals/$: Salmon A2Adept This program first reads in a list of ingredients as specified for A2Novice and then a list of menu item recipes and prints out information about the menu items. The input to this program starts with the ingredient list in the same form as for A2Novice. Following this will be an integer indicating the number of menu item recipes followed by that many recipes. Each menu item recipe will start with a single word token name for the menu item. Following the name will be an integer indicating how many ingredients are in the recipe. Then there will be a line for each ingredient with the ingredient name followed by the number of ounces of this ingredient required for the menu item. For each menu item, the program should produce output describing the number of calories in the menu item, the total cost of the ingredients used, and an indication whether that menu item is “Vegetarian” or “Non-Vegetarian”. A menu item is vegetarian if all of its component ingredients are vegetarian. The output for each menu item should be formatted as follows (again, bracketed items are placeholders for values to be determined by the program): : calories $ CalorieCount should be rounded to the nearest integer. Cost should be rounded to two decimal places. To round a double to the nearest integer as an int, use the following expression (assume dval is the value that needs to be rounded): ((int) (dval + 0.5)) To print a double to two decimal places, use the following expression to produce the appropriate string: String.format(“%.2f”, value) For example, the following input: “` 6 Rice 0.12 true 37 Seaweed 2.95 true 113 Avocado 0.22 true 45 Salmon 1.77 false 48 Yellowtail 0.53 false 41 Eel 2.18 false 84 4 Avocado_Roll 3 Rice 0.5 Avocado 0.5 Seaweed 0.1 Unagi_Nigiri 2 Rice 0.75 Eel 0.75 KMP_Roll 4 Eel 0.6 Rice 0.4 Seaweed 0.2 Avocado 0.3 Salmon_Sashimi 1 Salmon 0.8 “` Should produce the following output: Avocado_Roll: 52 calories $0.47 Vegetarian Unagi_Nigiri: 91 calories $1.73 Non-Vegetarian KMP_Roll: 101 calories $2.01 Non-Vegetarian Salmon_Sashimi: 38 calories $1.42 Non-Vegetarian A2Jedi This program reads in a list of ingredients and menu item recipes as specified for A2Adept and then a list of menu items that are part of an order. It should produce an account of how much of each ingredient will be needed to fulfill the whole order. The first part of the input is the same as A2 Adept. This is followed by a sequence of menu item names that are part of the order. An item can appear more than once or not at all. There will be at least one item. The end of the order will be signalled by the word “EndOrder” The program should produce an accounting for the total amount of each ingredient required for the order. The ingredients should be listed in the same order as they were provided in the initial ingredient list input and have the following format: The order will require: ounces of ounces of ounces of … ounces of Note, the “…” above simply indicates possible additional lines of the same form. Ingredient amounts should be printed rounded to two decimal points. For example the following input: “` 6 Rice 0.12 true 37 Seaweed 2.95 true 113 Avocado 0.22 true 45 Salmon 1.77 false 48 Yellowtail 0.53 false 41 Eel 2.18 false 84 4 Avocado_Roll 3 Rice 0.5 Avocado 0.5 Seaweed 0.1 Unagi_Nigiri 2 Rice 0.75 Eel 0.75 KMP_Roll 4 Eel 0.6 Rice 0.4 Seaweed 0.2 Avocado 0.3 Salmon_Sashimi 1 Salmon 0.8 Avocado_Roll Unagi_Nigiri Unagi_Nigiri Unagi_Nigiri KMP_Roll Salmon_Sashimi Avocado_Roll KMP_Roll EndOrder “` should produce the following output: The order will require: 4.05 ounces of Rice 0.60 ounces of Seaweed 1.60 ounces of Avocado 0.80 ounces of Salmon 0.00 ounces of Yellowtail 3.45 ounces of Eel
Congratulations! If you’re seeing this, then presumably you’ve managed to: * Install Java * Install IntelliJ IDEA * Install Git * Created a GitHub account * Accepted the A1 assignment link. If you haven’t done one or more of those things, please do. This repository should be a “private” repository and access to it is limited to yourself, KMP, and the COMP 210 team. Now it’s time to create an IntelliJ project based on this repository. From the IntelliJ splash screen, simply select “Get From Version Control” and then provide the git clone URL for this repository. Or, if you are not on the IntelliJ splash screen, select menu item File -> New -> Project From Version Control… and again, provide the git clone URL for this repository. Demonstrated in this YouTube video: https://youtu.be/xx9GLxo6Y9M The first thing we’ll do is make sure you’re able to run a program in IntelliJ and provide input from the keyboard to that program. Follow this video and follow along: https://youtu.be/S2caecQkWSI Did you get your first point of the assignment? If yes, then congratulations. If not, better go work it out eventually, but you could also keep going with the assignment. Now things are set up, here is the rest of the assignment. Scanner This assignment requires you to make use of a Scanner object. You can read the documentation for Scanner here: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Scanner.html A Scanner object is associated with a source of input. In our case, this will be keyboard input from the console. By default, a Scanner object will parse input as whitespace-separated tokens and provides methods for parsing the next available token as a particular type. For example, the method next() will retrieve the next token (i.e., word) as a String. Similarly, the method nextInt() interprets and returns the value of the next token as an integer while nextDouble() will interpret the next token as a double value. For this assignment, you shouldn’t have to use any Scanner methods other than next(), nextInt(), and nextDouble(). In particular, you should avoid using nextLine(). Do not assume that the input is organized into lines. All of the input could be on a single line or each word might be on a different line or something in between. Do not make any assumptions about the input being organized into lines. For this assignment, you can assume that the input will always be valid and conform to the description below. In other words, you do not have to worry about validating the input or being able to deal with unexpected input. A1Novice This program will read in data that represents shopping orders from a number of customers and report the total amount spent on a per customer basis. The input provided will have the following form: The first input will be an integer indicating the total number of customers. Then, for each customer, the input will be comprised of: The first name of the customer The last name of the customer The number of items bought by the customer. For each item bought, the input will then contain: An integer quantity of the item bought The name of the item (you can assume these will be single words) The price of the item as a double For each customer, your program should print one line of ouptut in the following form: F. LAST: TOTAL Where F. represents the first letter initial of the first name of the customer, LAST represents the last name of the customer, and TOTAL is the total cost of the items purchased to two decimal places. For example, the following input: 3 Carrie Brownstein 3 2 Banana 0.75 1 Orange 1.25 2 Milk 3.15 Corin Tucker 2 3 Banana 0.75 2 Sponge 1.15 Janet Weiss 1 5 Salami 2.50 Should produce the following output: C. Brownstein: 9.05 C. Tucker: 4.55 J. Weiss: 12.50 A1Adept This program will also read in shopping order data but now provided in a slightly different form and will produce output that reports the customers that were the biggest and smallets spenders as well as the average bill for all customers. Input to the program will have the following form: An integer count of the number of items in the store. Then for each item in the store… The name of each item (a single word) The price of the item An integer count of the number of customers Then for each customer… The first name of the customer The last name of the customer An integer count of the number of items the customer bought. For each of the items bought… The quantity of the item bought The name of the item The output of the program should be exactly three lines in the following form: Biggest: FIRST LAST (AMOUNT) Smallest: FIRST LAST (AMOUNT) Average: AVERAGE … where FIRST and LAST are the first and last names of the biggest and smallest spenders as appropriate, AMOUNT is the amount spent, and AVERAGE is the average amount spent. For example, the following input: 6 Apple 0.25 Banana 0.75 Milk 3.15 Orange 1.25 Salami 2.50 Sponge 1.15 3 Carrie Brownstein 3 2 Banana 1 Orange 2 Milk Corin Tucker 2 3 Banana 2 Sponge Janet Weiss 1 5 Salami Should produce the following output: Biggest: Janet Weiss (12.50) Smallest: Corin Tucker (4.55) Average: 8.70 A1Jedi This program will read in data with the same form as A1Adept and as output will report for each item how many different customers bought that item and the total quantity of the item bought by all customers. Each item should be reported in the same order as specified in the beginning of the input. Each report line should have the form: NUMBER customers bought TOTAL ITEM … where NUMBER is the number of customers that bought the item, TOTAL is the total quantity of the item bought by all customers and ITEM is the item name. If no customers bought an item, then the report for that item should be in the form: No customers bought ITEM For example, the same input provided as an example for A1Adept above should produce the following output for A1Jedi: No customers bought Apple 2 customers bought 5 Banana 1 customers bought 2 Milk 1 customers bought 1 Orange 1 customers bought 5 Salami 1 customers bought 2 Sponge Hints In order to convert a double (let’s call it “value”) to a String with two decimal places, use the following expression: String.format(“%.2f, value) 6 Apple 0.25 Banana 0.75 Milk 3.15 Orange 1.25 Salami 2.50 Sponge 1.15 3 Carrie Brownstein 5 1 Banana 1 Orange 1 Milk 1 Banana 1 Milk Corin Tucker 3 1 Banana 2 Sponge 2 Banana Janet Weiss 3 2 Salami 2 Salami 1 Salami You should also be sure to only use next, nextInt, and nextDouble as methods of the Scanner object in order to read the next expected input word as either a String, int, or double without trying to process the input as lines. You should not assume any sort of line structure to the input. In other words, the following is a valid equivalent to the example input provided above: 6 Apple 0.25 Banana 0.75 Milk 3.15 Orange 1.25 Salami 2.50 Sponge 1.15 3 Carrie Brownstein 5 1 Banana 1 Orange 1 Milk 1 Banana 1 Milk Corin Tucker 3 1 Banana 2 Sponge 2 Banana Janet Weiss 3 2 Salami 2 Salami 1 Salami
Description This project is based partly off of your previous project. As the Flask docs so elegantly say, “Something that is untested is broken.” We’re sorry we have been making you all develop broken apps for the entire semester, but you’ll learn how to make actually-functional apps with this project. This project has most of the functionality of project 4 implemented, excluding profile pictures. The emphasis on this project is testing (and blueprints, to a lesser extent). Setup The setup of your API key should be complete from project 3. Activate your virtual environment (we recommend using the same one you’ve used for other projects, you don’t need a new one). Then to install all necessary packages, run pip3 install -r requirements.txt For this project we’ll be using the – requests – Flask – Flask-MongoEngine – Flask-WTF – Flask-Bcrypt – Flask-Login – pythondotenv – pytest libraries Project This is the p5/ directory structureTo run this project, stay in the p5/ directory and use the flask run command. This project is run the same way as project 4. The application fully works as it is given. In __init__.py, apps are now created by calling the create_app() function. Optionally, a test_config parameter can be passed in so that the application will be configured with the desired settings for testing. We create the db, login_manager, and movie_client objects and initialize them using the init_app() function of these extensions. Then we register the main blueprint (you’ll change this later) and set a global 404 error handler function. The configuration is loaded from config.py. Although we don’t have many configuration values for this project, this kind of pattern is the best practice for when your apps might get more complicated and have lots of configuration values. routes.py In this file, you’ll notice that there is a main blueprint. This is the blueprint that contains all of the routes, and it was registered to our application in __init__.py. You have to reorganize the project to make it more modular. It doesn’t make sense to have the functions concerned with user management side by side with the functions concerned with entering or viewing reviews. So you’ll see that we created two directories that each have a routes.py inside of them. To complete this part of the project, you’ll need to 1. Create blueprints inside of users.routes and movies.routes named users and movies, respectively. 2. Put all user management view functions into the users blueprint. These are: 3. register, 4. login, 5. account, 6. logout 7. Put all other view functions into the movies blueprint. These are: 8. index 9. query_results 10. movie_detail 11. user_detail 12. Rename routes from main.some_route to users.some_route or movies. some_route as appropriate. These changes will need to happen in the template files and in the function bodies as needed. 13. Register these blueprints with the main Flask object. tests In the tests/ directory, you’ll notice four files. The conftest.py file is provided with everything fully implemented. We’ll go into detail about how this code works: @pytest.fixture indicates that the return value of the function will be passed as a parameter to any test_* function that has a parameter with the same name as the function. For example, we create the app fixture and we pass it in as a parameter to the client fixture further down in the code. app() configures the Flask application with custom testing settings, clears the database, pushes an app context, and returns the app. client() returns a test client for the application AuthActions consists of convenience methods to help you register, login, and log out of your application. It’s used in auth() below. auth() is a fixture that provides authentication actions. The test_factory.py file is provided with implemented tests so you can see how we test that our configuration values are properly set. You’ll have to implement some tests in test_movies.py and test_users.py. test_movies.py – Implement test_search_input_validation(client, query, message) with pytest.mark.parametrize – Test that with an empty query, you get the error “This field is required.” – Test that with a very short string, you get the error “Too many results” – Test that with some gibberish (maybe a random string?) you get the error “Movie not found” – Test that with a string that’s too long, you get the error “Field must be between 1 and 100 characters long.” – Implement test_movie_review(client, auth) – A beginning implementation is already provided to check if the movie detail page for the ‘Guardians of the Galaxy’ page will show up. The choice of this id is arbitrary, and you can change it to something else if you want. – Register and login – Submit a movie review with a randomly generated string (to make sure that you’re adding a truly unique review) – Test that the review shows up on the page – Test that the review is saved in the database – Implement test_movie_review_redirects(client, movie_id, message) with pytest.mark.parametrize – This test refers to navigating to movies at a certain /movies/ url. – Test that with an empty movie_id, you get a status code of 404 and that you see the custom 404 page. – Test that with (1) a movie_id shorter than 9 characters, (2) a movie_id exactly 9 characters (but an invalid id), and (3) a movie_id longer than 9 characters, the request has a status code of 302 and the error message “Incorrect IMDb ID” is displayed on the page you’re redirected to. – Implement test_movie_review_input_validation(client, auth, comment, message) with pytest.mark.parametrize – This test checks whether the proper validation errors from MovieReviewForm are raised when you provide incorrect input. – Test that with an empty string, you get the error “This field is required” – Test that with (1) a string shorter than 5 characters and (2) a string longer than 500 characters, you get the error “Field must be between 5 and 500 characters long.” – Hint: ‘a’ * 10 == ‘aaaaaaaaaa’ – You can use any movie id here, just make sure it’s valid or your test will fail. test_users.py – Implement test_login_input_validation(auth, username, password, message) with pytest.mark.parametrize – Test that if you try to log in with an empty (1) username or (2) password, you get the error “This field is required” – Test that when you successfully register but have (1) a bad username or (2) a bad password, you get the error message “Login failed. Check your username and/or password” – Implement test_logout(client, auth) – Register, login, check that you successfully logged in, and then logout, and check that you successfully logged out – Implement test_change_username(client, auth) – Test that the account page loads successfully and that you can successfully change the username of the logged-in user. – Test that the new username shows up on the account page – Test that the new username change is reflected in the database – Implement test_change_username_taken(client, auth) – Test that if we try to change the username to a different user’s username, then we get the error message “That username is already taken” – Implement test_change_username_input_validation(client, auth, new_username) – Test that if we pass in an empty string, we get the error “This field is required.” – Test that if we pass in a string that’s too long, we get the error “Field must be between 1 and 40 characters long.” There are a total of 21 tests. Each case in the input validation tests counts as a different test. For the input validation tests, you have to figure out what to put inside the function. Then you can adjust the parameters being passed in according to the specifications above, and you will cover all cases for validating that input! Testing blueprints Try to perform all of the usual functions on the website, such as registration, login, going to your account, changing your username, performing movie queries, posting reviews, going into your user detail page, etc. Also try navigating to the account page when you’re not logged in, or try some other bad actions to make sure that your blueprints are working. If you implement the tests part of the project first, you can probably avoid checking that your blueprints are correct manually. tests Make sure you’ve covered every test case as detailed above. When you’re in the p5/ directory, run python -m pytest. This will say “4 failed, 9 passed, 5 skipped” when you start your project. By the end, it should be “30 passed”. Submission For submission, submit the zipped p5/ directory. The directory, along with its contents, should be zipped, not the contents of the directory. In other words, when we unzip your file, we should see the p5/ directory. If you have any questions on how to submit, please contact us. Also make sure that you don’t include your virtual environment in the submission. It makes your submissions much larger, and we don’t need them in order to grade. Grading If you don’t use MongoDB or don’t use the packages mentioned in Setup, then you will get a zero on this project. This will be graded on (1) correctness and (2) robustness You will have to implement 21 tests. There will be 30 tests in total and each will be worth 5 points for a total of 150 points for writing tests. 45 of these points are given in the tests that were already passing when you got this project. Every test that passes gives you 5 points. For blueprints, you will get – 5 points for creating each blueprint (2 total) – 5 points for correctly separating each of the 8 functions into the two blueprints. If we get an error related to your view functions being improperly configured in the blueprints, then you’ll lose points. In total, there are 200 points. Robustness: Refer to the syllabus for the robustness requirement for all projects. The syllabus has been updated with this information, since it will be common to all projects.