proj6/Collision.javaproj6/Collision.javapackage proj6;
import java.util.ArrayList;
/**
* Collision objects represent individual collisions occuring on NYC streets.
* Each object contains information regarding the time, location, number
* of injuries and fatalities and types of involved vehicles.
* @author Joanna K.
*
*/
publicclassCollisionimplementsComparable<Collision>{
staticprivateSortOrder sortOrder =SortOrder.ZIP;
privateString date;
privateString time;
privateString borough;
privateString zip;
privateint personsInjured;
privateint personsKilled;
privateint pedestriansInjured;
privateint pedestriansKilled;
privateint cyclistsInjured;
privateint cyclistsKilled;
privateint motoristsInjured;
privateint motoristsKilled;
privateString vehicleCode1;
privateString vehicleCode2;
privateString uniqueKey;
/**
* Creates a Collision object given an array of entries.
* There should be 21 string entries in the following order:
* date
* time
* borough
* zip
* lattitude^
* longitude ^
* on street name^
* cross street name ^
* personsInjured
* personsKilled
* pedestriansInjured
* pedestriansKilled
* cyclistsInjured
* cyclistsKilled
* motoristsInjured
* motoristsKilled
* contributing factor vehicle 1^
* contributing factor vehicle 2^
* uniqueKey
* vehicleCode1
* vehicleCode2
* The entries indicated with ^ are not used.
*
* @param entries an array of entries containing information about the
* collision
* @throws IllegalArgumentException when the Collision object cannot be created
* due to errors or incompleteness of the entries parameter
*/
publicCollision(ArrayList<String> entries )throwsIllegalArgumentException{
date = entries.get(0);
time = entries.get(1);
borough = entries.get(2);
zip = entries.get(3);
if(!verifyZip(zip)){
thrownewIllegalArgumentException("invalid zip");
}
try{
personsInjured =Integer.parseInt(entries.get(8));
personsKilled =Integer.parseInt(entries.get(9));
pedestriansInjured =Integer.parseInt(entries.get(10));
pedestriansKilled =Integer.parseInt(entries.get(11));
cyclistsInjured =Integer.parseInt(entries.get(12));
cyclistsKilled =Integer.parseInt(entries.get(13));
motoristsInjured =Integer.parseInt(entries.get(14));
motoristsKilled =Integer.parseInt(entries.get(15));
}
catch(NumberFormatException ex ){
thrownewIllegalArgumentException( ex.getMessage());
}
uniqueKey = entries.get(18);
vehicleCode1 = entries.get(19);
vehicleCode2 = entries.get(20);
}
/*
* Verifies accuracy of the zip code.
* @param zip the zip code to be verified
* @return true if zip is a valid zip code, false otherwise
*/
privateboolean verifyZip (String zip ){
if( zip.length()!=5)returnfalse;
for(int i =0; i < zip.length ...
import java.util.;import acm.program.;public class FlightPla.pdfanushasarees
import java.util.*;
import acm.program.*;
public class FlightPlanner extends ConsoleProgram {
/* Private instance variables */
private FlightDB flights; //creates a new database
private ArrayList enteredCities = new ArrayList(); //keeps track of entered cities
private String firstCity; //keeps track of the first city entered by the user
public void init() {
//passes the text file to the database to read and parse
flights = new FlightDB(\"flights.txt\");
}
public void run() {
welcome();
askForFistCity();
askForMoreCities();
printFinalRoute();
}
/* Welcomes the user */
private void welcome() {
println(\"Welcome to Flight Planner\");
println(\"Here is a list of all the cities in our database\");
Iterator it = flights.getCities();
while(it.hasNext()) {
println(\" \" + it.next());
}
println(\"Let\'s plan a round-trip route!\");
}
/* asks the user for the starting city and prints out
* all the possible destination cities for that city */
private void askForFistCity() {
while(true) {
firstCity = readLine(\"Enter the starting city: \");
if(flights.ContainsKey(firstCity)) {
enteredCities.add(firstCity);
break;
}
else{
println(\"You can\'t get to that city by a direct flight.\");
println(\"Here is a list of all the cities in our database\");
Iterator it = flights.getCities();
while(it.hasNext()) {
println(\" \" + it.next());
}
}
}
println(\"From \" + firstCity + \" you can fly directly to:\");
Iterator it = flights.findRoute(firstCity);
while(it.hasNext()) {
println(\" \" + it.next());
}
}
/* asks the user for the cities he/she wants to fly to,
* and prints out possible destination cities for each city
* until the user enters the starting city */
private void askForMoreCities() {
String city = firstCity;
String lastCity = city;
while(true) {
city = readLine(\"Where do you want to go from \" + city + \"? \");
if(city.equals(firstCity)) {
break;
}
if(flights.ContainsKey(city) == true) {
lastCity = city;
enteredCities.add(city);
}
else{
city = lastCity;
println(\"You can\'t get to that city by a direct flight.\");
}
println(\"From \" + city + \" you can fly directly to:\");
Iterator it = flights.findRoute(city);
while(it.hasNext()) {
println(\" \" + it.next());
}
}
}
/* prints out the chosen route */
private void printFinalRoute() {
println(\"The route you\'ve chosen is\");
String route = enteredCities.get(0);
for(int i = 1; i \" + enteredCities.get(i);
}
route += \" -> \" + enteredCities.get(0);
println(route);
}
}
import acm.program.*;
public class FlightPlanner extends ConsoleProgram {
/* Private instance variables */
private FlightDB flights; //creates a new database
private ArrayList enteredCities = new ArrayList(); //keeps track of entered cities
private String firstCity; //keeps track of the first city entered by the user
public void init() {
//passes the text file to the database to read and parse
flights = new FlightDB(\"flights.txt\");
}
public void run() {
welcome();
askForFistCity();
askForMoreCities();
printFinalRoute();
}
/* Welcomes the use.
ONLY EDIT CapacityOptimizer.java, Simulator.java, and TriangularD.pdfvinodagrawal6699
ONLY EDIT CapacityOptimizer.java, Simulator.java, and TriangularDistribution.java (add
exception handling only)
Simulator.java
/**
* @author Mehrdad Sabetzadeh, University of Ottawa
*
*/
public class Simulator {
/**
* Length of car plate numbers
*/
public static final int PLATE_NUM_LENGTH = 3;
/**
* Number of seconds in one hour
*/
public static final int NUM_SECONDS_IN_1H = 3600;
/**
* Maximum duration a car can be parked in the lot
*/
public static final int MAX_PARKING_DURATION = 8 * NUM_SECONDS_IN_1H;
/**
* Total duration of the simulation in (simulated) seconds
*/
public static final int SIMULATION_DURATION = 24 * NUM_SECONDS_IN_1H;
/**
* The probability distribution for a car leaving the lot based on the duration
* that the car has been parked in the lot
*/
public static final TriangularDistribution departurePDF = new TriangularDistribution(0,
MAX_PARKING_DURATION / 2,
MAX_PARKING_DURATION);
/**
* The probability that a car would arrive at any given (simulated) second
*/
private Rational probabilityOfArrivalPerSec;
/**
* The simulation clock. Initially the clock should be set to zero; the clock
* should then be incremented by one unit after each (simulated) second
*/
private int clock;
/**
* Total number of steps (simulated seconds) that the simulation should run for.
* This value is fixed at the start of the simulation. The simulation loop
* should be executed for as long as clock < steps. When clock == steps, the
* simulation is finished.
*/
private int steps;
/**
* Instance of the parking lot being simulated.
*/
private ParkingLot lot;
/**
* Queue for the cars wanting to enter the parking lot
*/
private Queue incomingQueue;
/**
* Queue for the cars wanting to leave the parking lot
*/
private Queue outgoingQueue;
/**
* @param lot is the parking lot to be simulated
* @param steps is the total number of steps for simulation
*/
public Simulator(ParkingLot lot, int perHourArrivalRate, int steps) {
throw new UnsupportedOperationException("This method has not been implemented yet!");
}
/**
* Simulate the parking lot for the number of steps specified by the steps
* instance variable
* NOTE: Make sure your implementation of simulate() uses peek() from the Queue interface.
*/
public void simulate() {
throw new UnsupportedOperationException("This method has not been implemented yet!");
}
public int getIncomingQueueSize() {
throw new UnsupportedOperationException("This method has not been implemented yet!");
}
}
CapacityOptimizer.java
public class CapacityOptimizer {
private static final int NUM_RUNS = 10;
private static final double THRESHOLD = 5.0d;
public static int getOptimalNumberOfSpots(int hourlyRate) {
throw new UnsupportedOperationException("This method has not been implemented yet!");
}
public static void main(String args[]) {
StudentInfo.display();
long mainStart = System.currentTimeMillis();
if (args.length < 1) {
System.out.println("Usage: java CapacityOptimizer ");
System.out.println("Example: java CapacityOptimizer 11");
return;
}.
operating system linux,ubuntu,Mac Geometri.pdfaquadreammail
//operating system linux,ubuntu,Mac
/*********************GeometricObject.java**********************/
public abstract class GeometricObject {
private String color = \"white\";
private boolean filled;
// default constructure
public GeometricObject() {
super();
// TODO Auto-generated constructor stub
}
// construct a Geometric Object
// parameterized constructure
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
/** Getter method for color */
public String getColor() {
return color;
}
/** Setter method for color */
public void setColor(String color) {
this.color = color;
}
/**
* Getter method for filled. Since filled is boolean, so the gret method
* name is isFilled
*/
public boolean isFilled() {
return filled;
}
/** Setter method for filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/** Abstract method for FindArea */
public abstract double findArea();
/** Abstract method for findPerimeter */
public abstract double findPerimeter();
}
/*****************************Octagon.java**************/
public class Octagon extends GeometricObject implements Cloneable, Comparable {
private double side;
/** construct a Octagon with specified side */
public Octagon(double side) {
super();
this.side = side;
}
/** Implement the abstract method findArea in GeometricObject */
@Override
public double findArea() {
double area = (2 + 4 / Math.sqrt(2)) * side * side;
return area;
}
/** Implement the abstract method findArea in findPerimeter */
@Override
public double findPerimeter() {
double perimeter = 8 * side;
return perimeter;
}
/** Implement the compareTo method in Comparable interface */
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/*******************App.java*******************/
public class App {
public static void main(String[] args) {
Octagon a1 = new Octagon(5);//creating object of octagon
System.out.println(\"Area of a1 is \" + a1.findArea());
System.out.println(\"Perimeter of a1 is \" + a1.findPerimeter());
Object a2;
try {
a2 = a1.clone();
String result = (a1.compareTo(a2) == 0) ? \"a1 and its clone a2 have the same area\"
: \"a1 and its clone a2 have different areas\";
System.out.println(\"Compare a1 and its clone a2:\ \\t \" + result);
System.out.println(\"Hashcode of a1: \" + a1.hashCode());
System.out.println(\"Hashcode of a2: \" + a2.hashCode());
System.out.println(\"Displaying a1: \" + a1);
System.out.println(\"Displaying a2: \" + a2);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
/*****************output***************/
gopal@gopal:~/Desktop/chegg$ javac GeometricObject.java
gopal@gopal:~/Desktop/chegg$ javac Octagon.java
gopal@gopal:~/Desktop/chegg$ javac App.java
gopal@gopal:~/Desktop/chegg$ java App
Area of a1 is 120.71067811865476
Perimeter of a1 is 40.0
Compare a1 and its clone a2:
a1 and its clone a2 have the same area
.
For the following questions, you will implement the data structure to.pdfarjunhassan8
For the following questions, you will implement the data structure to store information used by a
local car dealer. Each car has some information and stored in a text files called cars: Write a
main program for all questions to let the user enter, delete, search for information, and print
current cars stored in the data structure. Cars formatted so car records separated by a blank line.
Each record contains (in order, each in a single line): Make (manufacturer). Model, Year,
Mileage, Price. Implement a double linked-list to store cars data. Write a double linked-list class
including search, delete, append (to the head and tail), and remove (from the head and tail).
Implement a FIFO queue of car data using the double linked-list. You can use the double linked
list you wrote in Q1. Implement a max-heap of cars data that can extract the car with the highest
price. Write a max-heap class including heapify, build heap, extract, and insertion. Implement a
binary search tree of car data. Write a BST class including search, insertion, and deletion.
Solution
Cars.java
package pacages;
public class Cars {
String make;
String model;
int year;
double mileage;
double price;
// Setters and getters for the Cars member variables
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getMileage() {
return mileage;
}
public void setMileage(double mileage) {
this.mileage = mileage;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString()
{
return \"Make: \"+getMake()+ \" Model: \"+getModel()+ \" Year: \"+getYear() + \"
Mileage: \"+getMileage() + \" Price: \"+getPrice();
}
}
DoublyLinkedList.java
package pacages;
class Node
{
protected Cars data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = null;
}
/* Constructor */
public Node(Cars d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(Cars d)
{
data = d;
}
/* Function to get data from node */
public Cars getData()
{
return data;
}
}
/* Class linkedList */
public class DoublyLinkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public DoublyLinkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of list */
public.
I have compilation errors that I'm struggling with in my code- please.pdfColinjHJParsonsa
I have compilation errors that I'm struggling with in my code, please can you help me fix the
errors. I'm trying to make a road map, where each place is a vertex and each road between two
places is an edge. Each edge stores a number indicating the length of the road. Assume that there
is at most one road directly connecting two given places, so that there is at most one edge
between two vertices. The map is loaded in via a text file that starts with a line that contains the
number of vertices and the number of edges. After the line mentioned, there are two sections of
content. The initial section holds details regarding the vertices, where each line represents a
single vertex. The information stored for each vertex includes its name and the availability of
charging stations, represented as an integer with 1 indicating availability and 0 indicating
unavailability. The second section stores information about the edges, with each line
corresponding to one edge. Each line contains three numbers: the first two are 0-based indices of
its two incident vertices within the places array; the last number is the edge length. An example
of the map input would look like this as a txt file:
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
private ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
}
// A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map an.
This C++ program defines classes to represent railroad cars and a string of coupled cars. The Car class stores attributes of individual cars like reporting mark, number, type, load status, and destination. Derived classes Cs112 and PassinjirKarr represent specific car types. The StringOfCars class models a string of cars using a dynamic array of Car pointers. It provides functions to add/remove cars and output the string. The main() function tests creating Car objects, passing them to StringOfCars, and printing the string.
(In java language)1. Use recursion in implementing the binarySearc.pdfrbjain2007
(In java language)
1. Use recursion in implementing the binarySearch method
2. Use Generics in implementing different methods
3. Use the attached driver. Do not modify the driver
Please put answers into the skeleton / complete the following given skeleton with the code in
java language:
import java.util.ArrayList;
public class MyGenerics{
//Declarations
//****************************************************************************
//No-argument constructor:
//****************************************************************************
public MyGenerics (){
}//end of constructor
//****************************************************************************
//max: Receives a generic one-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[] list){
return null;
}//end of max
//****************************************************************************
//max: Receives a generic two-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[][] list) {
return null;
}
//****************************************************************************
//largest: Receives a generic arrayList and returns the maximum
// value in the array.
//****************************************************************************
public > E largest(ArrayList list) {
return null;
}
//****************************************************************************
//binarySearch: Receives a generic one-dimensional array and a generic key
// and returns the location of the key (positive) or
// a negative location if not found.
//****************************************************************************
public > int binarySearch(E[] list, E key) {
int low = 0;
int high = list.length - 1;
return binarySearch (list, key, low, high);
}
public > int binarySearch(E[] list, E key, int low, int high) {
return -99; // update
}
//****************************************************************************
//sort: Receives a generic arrayList and returns nothing.
//****************************************************************************
public > void sort(ArrayList list) {
}
//****************************************************************************
//sort: Receives a generic one-dimensional array and returns nothing.
//****************************************************************************
public > void sort(E[] list) {
}
//****************************************************************************
//displayOneDList: Receives a generic one-dimensional array and displays its contents
//****************************************************************************
public void displayOneDList(E[] list, String listName){
}
//****************************************************************************
//displayTwoDList: Receives a generic two-dimensional array & a string .
import java.util.;import acm.program.;public class FlightPla.pdfanushasarees
import java.util.*;
import acm.program.*;
public class FlightPlanner extends ConsoleProgram {
/* Private instance variables */
private FlightDB flights; //creates a new database
private ArrayList enteredCities = new ArrayList(); //keeps track of entered cities
private String firstCity; //keeps track of the first city entered by the user
public void init() {
//passes the text file to the database to read and parse
flights = new FlightDB(\"flights.txt\");
}
public void run() {
welcome();
askForFistCity();
askForMoreCities();
printFinalRoute();
}
/* Welcomes the user */
private void welcome() {
println(\"Welcome to Flight Planner\");
println(\"Here is a list of all the cities in our database\");
Iterator it = flights.getCities();
while(it.hasNext()) {
println(\" \" + it.next());
}
println(\"Let\'s plan a round-trip route!\");
}
/* asks the user for the starting city and prints out
* all the possible destination cities for that city */
private void askForFistCity() {
while(true) {
firstCity = readLine(\"Enter the starting city: \");
if(flights.ContainsKey(firstCity)) {
enteredCities.add(firstCity);
break;
}
else{
println(\"You can\'t get to that city by a direct flight.\");
println(\"Here is a list of all the cities in our database\");
Iterator it = flights.getCities();
while(it.hasNext()) {
println(\" \" + it.next());
}
}
}
println(\"From \" + firstCity + \" you can fly directly to:\");
Iterator it = flights.findRoute(firstCity);
while(it.hasNext()) {
println(\" \" + it.next());
}
}
/* asks the user for the cities he/she wants to fly to,
* and prints out possible destination cities for each city
* until the user enters the starting city */
private void askForMoreCities() {
String city = firstCity;
String lastCity = city;
while(true) {
city = readLine(\"Where do you want to go from \" + city + \"? \");
if(city.equals(firstCity)) {
break;
}
if(flights.ContainsKey(city) == true) {
lastCity = city;
enteredCities.add(city);
}
else{
city = lastCity;
println(\"You can\'t get to that city by a direct flight.\");
}
println(\"From \" + city + \" you can fly directly to:\");
Iterator it = flights.findRoute(city);
while(it.hasNext()) {
println(\" \" + it.next());
}
}
}
/* prints out the chosen route */
private void printFinalRoute() {
println(\"The route you\'ve chosen is\");
String route = enteredCities.get(0);
for(int i = 1; i \" + enteredCities.get(i);
}
route += \" -> \" + enteredCities.get(0);
println(route);
}
}
import acm.program.*;
public class FlightPlanner extends ConsoleProgram {
/* Private instance variables */
private FlightDB flights; //creates a new database
private ArrayList enteredCities = new ArrayList(); //keeps track of entered cities
private String firstCity; //keeps track of the first city entered by the user
public void init() {
//passes the text file to the database to read and parse
flights = new FlightDB(\"flights.txt\");
}
public void run() {
welcome();
askForFistCity();
askForMoreCities();
printFinalRoute();
}
/* Welcomes the use.
ONLY EDIT CapacityOptimizer.java, Simulator.java, and TriangularD.pdfvinodagrawal6699
ONLY EDIT CapacityOptimizer.java, Simulator.java, and TriangularDistribution.java (add
exception handling only)
Simulator.java
/**
* @author Mehrdad Sabetzadeh, University of Ottawa
*
*/
public class Simulator {
/**
* Length of car plate numbers
*/
public static final int PLATE_NUM_LENGTH = 3;
/**
* Number of seconds in one hour
*/
public static final int NUM_SECONDS_IN_1H = 3600;
/**
* Maximum duration a car can be parked in the lot
*/
public static final int MAX_PARKING_DURATION = 8 * NUM_SECONDS_IN_1H;
/**
* Total duration of the simulation in (simulated) seconds
*/
public static final int SIMULATION_DURATION = 24 * NUM_SECONDS_IN_1H;
/**
* The probability distribution for a car leaving the lot based on the duration
* that the car has been parked in the lot
*/
public static final TriangularDistribution departurePDF = new TriangularDistribution(0,
MAX_PARKING_DURATION / 2,
MAX_PARKING_DURATION);
/**
* The probability that a car would arrive at any given (simulated) second
*/
private Rational probabilityOfArrivalPerSec;
/**
* The simulation clock. Initially the clock should be set to zero; the clock
* should then be incremented by one unit after each (simulated) second
*/
private int clock;
/**
* Total number of steps (simulated seconds) that the simulation should run for.
* This value is fixed at the start of the simulation. The simulation loop
* should be executed for as long as clock < steps. When clock == steps, the
* simulation is finished.
*/
private int steps;
/**
* Instance of the parking lot being simulated.
*/
private ParkingLot lot;
/**
* Queue for the cars wanting to enter the parking lot
*/
private Queue incomingQueue;
/**
* Queue for the cars wanting to leave the parking lot
*/
private Queue outgoingQueue;
/**
* @param lot is the parking lot to be simulated
* @param steps is the total number of steps for simulation
*/
public Simulator(ParkingLot lot, int perHourArrivalRate, int steps) {
throw new UnsupportedOperationException("This method has not been implemented yet!");
}
/**
* Simulate the parking lot for the number of steps specified by the steps
* instance variable
* NOTE: Make sure your implementation of simulate() uses peek() from the Queue interface.
*/
public void simulate() {
throw new UnsupportedOperationException("This method has not been implemented yet!");
}
public int getIncomingQueueSize() {
throw new UnsupportedOperationException("This method has not been implemented yet!");
}
}
CapacityOptimizer.java
public class CapacityOptimizer {
private static final int NUM_RUNS = 10;
private static final double THRESHOLD = 5.0d;
public static int getOptimalNumberOfSpots(int hourlyRate) {
throw new UnsupportedOperationException("This method has not been implemented yet!");
}
public static void main(String args[]) {
StudentInfo.display();
long mainStart = System.currentTimeMillis();
if (args.length < 1) {
System.out.println("Usage: java CapacityOptimizer ");
System.out.println("Example: java CapacityOptimizer 11");
return;
}.
operating system linux,ubuntu,Mac Geometri.pdfaquadreammail
//operating system linux,ubuntu,Mac
/*********************GeometricObject.java**********************/
public abstract class GeometricObject {
private String color = \"white\";
private boolean filled;
// default constructure
public GeometricObject() {
super();
// TODO Auto-generated constructor stub
}
// construct a Geometric Object
// parameterized constructure
public GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
/** Getter method for color */
public String getColor() {
return color;
}
/** Setter method for color */
public void setColor(String color) {
this.color = color;
}
/**
* Getter method for filled. Since filled is boolean, so the gret method
* name is isFilled
*/
public boolean isFilled() {
return filled;
}
/** Setter method for filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/** Abstract method for FindArea */
public abstract double findArea();
/** Abstract method for findPerimeter */
public abstract double findPerimeter();
}
/*****************************Octagon.java**************/
public class Octagon extends GeometricObject implements Cloneable, Comparable {
private double side;
/** construct a Octagon with specified side */
public Octagon(double side) {
super();
this.side = side;
}
/** Implement the abstract method findArea in GeometricObject */
@Override
public double findArea() {
double area = (2 + 4 / Math.sqrt(2)) * side * side;
return area;
}
/** Implement the abstract method findArea in findPerimeter */
@Override
public double findPerimeter() {
double perimeter = 8 * side;
return perimeter;
}
/** Implement the compareTo method in Comparable interface */
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
/*******************App.java*******************/
public class App {
public static void main(String[] args) {
Octagon a1 = new Octagon(5);//creating object of octagon
System.out.println(\"Area of a1 is \" + a1.findArea());
System.out.println(\"Perimeter of a1 is \" + a1.findPerimeter());
Object a2;
try {
a2 = a1.clone();
String result = (a1.compareTo(a2) == 0) ? \"a1 and its clone a2 have the same area\"
: \"a1 and its clone a2 have different areas\";
System.out.println(\"Compare a1 and its clone a2:\ \\t \" + result);
System.out.println(\"Hashcode of a1: \" + a1.hashCode());
System.out.println(\"Hashcode of a2: \" + a2.hashCode());
System.out.println(\"Displaying a1: \" + a1);
System.out.println(\"Displaying a2: \" + a2);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
/*****************output***************/
gopal@gopal:~/Desktop/chegg$ javac GeometricObject.java
gopal@gopal:~/Desktop/chegg$ javac Octagon.java
gopal@gopal:~/Desktop/chegg$ javac App.java
gopal@gopal:~/Desktop/chegg$ java App
Area of a1 is 120.71067811865476
Perimeter of a1 is 40.0
Compare a1 and its clone a2:
a1 and its clone a2 have the same area
.
For the following questions, you will implement the data structure to.pdfarjunhassan8
For the following questions, you will implement the data structure to store information used by a
local car dealer. Each car has some information and stored in a text files called cars: Write a
main program for all questions to let the user enter, delete, search for information, and print
current cars stored in the data structure. Cars formatted so car records separated by a blank line.
Each record contains (in order, each in a single line): Make (manufacturer). Model, Year,
Mileage, Price. Implement a double linked-list to store cars data. Write a double linked-list class
including search, delete, append (to the head and tail), and remove (from the head and tail).
Implement a FIFO queue of car data using the double linked-list. You can use the double linked
list you wrote in Q1. Implement a max-heap of cars data that can extract the car with the highest
price. Write a max-heap class including heapify, build heap, extract, and insertion. Implement a
binary search tree of car data. Write a BST class including search, insertion, and deletion.
Solution
Cars.java
package pacages;
public class Cars {
String make;
String model;
int year;
double mileage;
double price;
// Setters and getters for the Cars member variables
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getMileage() {
return mileage;
}
public void setMileage(double mileage) {
this.mileage = mileage;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString()
{
return \"Make: \"+getMake()+ \" Model: \"+getModel()+ \" Year: \"+getYear() + \"
Mileage: \"+getMileage() + \" Price: \"+getPrice();
}
}
DoublyLinkedList.java
package pacages;
class Node
{
protected Cars data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = null;
}
/* Constructor */
public Node(Cars d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(Cars d)
{
data = d;
}
/* Function to get data from node */
public Cars getData()
{
return data;
}
}
/* Class linkedList */
public class DoublyLinkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public DoublyLinkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of list */
public.
I have compilation errors that I'm struggling with in my code- please.pdfColinjHJParsonsa
I have compilation errors that I'm struggling with in my code, please can you help me fix the
errors. I'm trying to make a road map, where each place is a vertex and each road between two
places is an edge. Each edge stores a number indicating the length of the road. Assume that there
is at most one road directly connecting two given places, so that there is at most one edge
between two vertices. The map is loaded in via a text file that starts with a line that contains the
number of vertices and the number of edges. After the line mentioned, there are two sections of
content. The initial section holds details regarding the vertices, where each line represents a
single vertex. The information stored for each vertex includes its name and the availability of
charging stations, represented as an integer with 1 indicating availability and 0 indicating
unavailability. The second section stores information about the edges, with each line
corresponding to one edge. Each line contains three numbers: the first two are 0-based indices of
its two incident vertices within the places array; the last number is the edge length. An example
of the map input would look like this as a txt file:
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
private ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
}
// A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map an.
This C++ program defines classes to represent railroad cars and a string of coupled cars. The Car class stores attributes of individual cars like reporting mark, number, type, load status, and destination. Derived classes Cs112 and PassinjirKarr represent specific car types. The StringOfCars class models a string of cars using a dynamic array of Car pointers. It provides functions to add/remove cars and output the string. The main() function tests creating Car objects, passing them to StringOfCars, and printing the string.
(In java language)1. Use recursion in implementing the binarySearc.pdfrbjain2007
(In java language)
1. Use recursion in implementing the binarySearch method
2. Use Generics in implementing different methods
3. Use the attached driver. Do not modify the driver
Please put answers into the skeleton / complete the following given skeleton with the code in
java language:
import java.util.ArrayList;
public class MyGenerics{
//Declarations
//****************************************************************************
//No-argument constructor:
//****************************************************************************
public MyGenerics (){
}//end of constructor
//****************************************************************************
//max: Receives a generic one-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[] list){
return null;
}//end of max
//****************************************************************************
//max: Receives a generic two-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[][] list) {
return null;
}
//****************************************************************************
//largest: Receives a generic arrayList and returns the maximum
// value in the array.
//****************************************************************************
public > E largest(ArrayList list) {
return null;
}
//****************************************************************************
//binarySearch: Receives a generic one-dimensional array and a generic key
// and returns the location of the key (positive) or
// a negative location if not found.
//****************************************************************************
public > int binarySearch(E[] list, E key) {
int low = 0;
int high = list.length - 1;
return binarySearch (list, key, low, high);
}
public > int binarySearch(E[] list, E key, int low, int high) {
return -99; // update
}
//****************************************************************************
//sort: Receives a generic arrayList and returns nothing.
//****************************************************************************
public > void sort(ArrayList list) {
}
//****************************************************************************
//sort: Receives a generic one-dimensional array and returns nothing.
//****************************************************************************
public > void sort(E[] list) {
}
//****************************************************************************
//displayOneDList: Receives a generic one-dimensional array and displays its contents
//****************************************************************************
public void displayOneDList(E[] list, String listName){
}
//****************************************************************************
//displayTwoDList: Receives a generic two-dimensional array & a string .
package reservation; import java.util.; For Scanner Class .pdfanitasahani11
package reservation;
import java.util.*; //For Scanner Class
import java.time.*; //For LocalDate
import java.time.format.*; //For DateTimeFormatter
public class Reservation
{
double perNight = 105.00, finalAmt;
long noDays;
int m, d, y;
LocalDate std, end;
//Sets the Arrival date inputed by the user
void setArrivalDate(LocalDate arrivalDate)
{
std = arrivalDate;
}
//Sets the Departure date inputed by the user
void setDepartureDate(LocalDate departureDate)
{
end = departureDate;
}
//Returns the Arrival date
LocalDate getArrivalDate()
{
return std;
}
//Returns the Departure date
LocalDate getDepartureDate()
{
return end;
}
//Formats the Arrival date as per the requirement given question
String getArrivalDateFormatted()
{
String stdFormat;
stdFormat = \"Arrival Date: \" + std.getMonth() + \" \" + String.valueOf(std.getDayOfMonth())
+ \", \" + String.valueOf(std.getYear());
return stdFormat;
}
//Formats the Departure date as per the requirement given question
String getDepartureDateFormatted()
{
String stdFormat;
stdFormat = \"Departure Date: \" + end.getMonth() + \" \" +
String.valueOf(end.getDayOfMonth()) + \", \" + String.valueOf(end.getYear());
return stdFormat;
}
//Returns the Price per night as per the format
String getPricePerNightFormatted()
{
String pr = \"Price: $\" + String.valueOf(perNight) + \" per night\";
return pr;
}
//Returns the number of nights
long getNumberOfNights()
{
//toEpochDay() returns number of days
noDays = end.toEpochDay() - std.toEpochDay();
return noDays;
}
//Calculates final Amount to be paid
double getTotalPrice()
{
finalAmt = (double)getNumberOfNights() * perNight;
return finalAmt;
}
//Returns the Total amount to be paid as per the format given in the question
String getTotalPriceFormatted()
{
String finA = \"Total price: $\" + String.valueOf(getTotalPrice()) + \" for \" +
String.valueOf(getNumberOfNights()) + \" night\" ;
return finA;
}
//Accepts the Arrival date and Departure date from console
void accept()
{
//Creates object of LocaleDate
LocalDate std1, end1;
//Creates the Date Time Formater object and applies Format Style
//SHORT in mm/dd/yy format
DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
//Creates Scanner class object to accept data from console
Scanner s = new Scanner(System.in);
System.out.println(\"Enter starting date mm/dd/yyyy: \");
System.out.println(\"Enter the arrival month (1-12):\");
m = s.nextInt(); //Accept data in integer format
System.out.println(\"Enter the arrival day (1-31):\") ;
d = s.nextInt();
System.out.println(\"Enter the arrival year:\") ;
y = s.nextInt();
//Initializes the LocalDate object for Arrival date
std1 = LocalDate.of(y, m, d);
//Sets the SHORT date format
fmt.format(std1);
//Assigns Arrival date to class data member
setArrivalDate(std1);
System.out.println(\"Enter ending date mm/dd/yyyy: \");
System.out.println(\"Enter the departure month (1-12):\");
m = s.nextInt(); //Accept data in integer format
System.out.println(\"Enter the departur.
This C++ program defines a Car class with private member variables and public member functions. The main function gets user input, creates a Car object, calls its setUp member function to set the object's variables, and then calls its output member function to display the variable values. A non-member input function gets data from the user and a main function handles program flow, creating and calling the Car object.
The document describes an implementation of the simulated annealing algorithm to solve the traveling salesman problem. It defines a City class to represent locations with name, coordinates, and derived Metro class to add remarks. It includes functions to calculate distance between cities, total route distance, and acceptance probability for simulated annealing. The main function gets user input for cities, runs simulated annealing to optimize the route, and outputs results.
자프링(자바 + 스프링) 외길 12년차 서버 개발자가 코프링(코틀린 + 스프링)을 만난 후 코틀린의 특징과 스프링의 코틀린 지원을 알아가며 코프링 월드에서 살아남은 이야기…
코드 저장소: https://github.com/arawn/kotlin-support-in-spring
import java-util--- import java-io--- class Vertex { -- Constructo.docxBlake0FxCampbelld
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public Vertex(String placeName, boolean hasChargingStataion) {
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
public void setVisited(boolean b) {
}
public Edge[] getAdjacentEdges() {
return null;
}
public boolean isVisited() {
return false;
}
public boolean isChargingStationAvailable() {
return false;
}
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Edge(Vertex vtx1, Vertex vtx2, int length2) {
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
public Vertex getEnd() {
return null;
}
}
//A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map and determine if two places are connnected by a path with charging stations:");
System.err.println(" java RoadMap -c <MapFile> <StartVertexIndex> <EndVertexIndex>");
System.err.println(" - Load a map and determine the mininmum number of assistance cars required:");
System.err.println(" java RoadMap -a <MapFile>");
}
public static void main(String[] args) throws Exception {
if (args.length == 2 && args[0].equals("-i")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Error in reading map file");
System.exit(-1);
}
System.out.println();
System.out.println("Read road map from " + args[1] + ":");
map.printMap();
System.out.println();
}
else if (args.length == 2 && args[0].equals("-a")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Err.
Create a system to simulate vehicles at an intersection. Assume th.pdfarchanacomputers1
\"Create a system to simulate vehicles at an intersection. Assume that there is one lane going in
each of four directions, with stoplights facing each direction. Vary the arrival average of vehicles
in each direction and the frequency of the light changes to view the \"behavior\" of the
intersection.\"
You canNOT use the Java built-in Queue or Deque class. Use an Array or Linked List
implementation of a queue as explained in the text. This means a jsjf package containing
QueueADT.java file with CircularArrayQueue.java or LinkedQueue.java and LinearNode.java.
Include user-defined exceptions and javadoc comments.
Be sure to test thoroughly, and document your results.
Be sure to label your outputs so that when I run your code I can readily understand what you\'re
doing.
Determine what is the optimal light-change time to maximize car throughput.
WANT KNOW HOW CAN I MAKE IT RUN!
import java.lang.Math;
import java.io.*;
import jsjf.*;
import jsjf.exceptions.*;
import java.util.*;
import java.net.*;
import java.io.*;
/**
*This class is where all action resides. It contains all the queues that represent the lanes at the
intersection.
* It also contains all methods that pertain to populating the intersection and moving the vehicles
in their
* retrospective directions.
*/
public class Simulator {
/** This queue will hold only vehicle objects that enter in the left lane on Main Street headed
East. */
private LinkedQueue EMainL = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the right lane on Main Street headed
East. */
private LinkedQueue EMainR = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the left lane on Main Street headed
West. */
private LinkedQueue WMainL = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the right lane on Main Street headed
West. */
private LinkedQueue WMainR = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the left lane on Church Street
headed North. */
private LinkedQueue NChurchL = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the right lane on Church Street
headed North. */
private LinkedQueue NChurchR = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the left lane on Church Street
headed South. */
private LinkedQueue SChurchL = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the right lane on Church Street
headed South. */
private LinkedQueue SChurchR = new LinkedQueue();
/** This integer value will keep track of the current time during the simulation.*/
int time = 0;
/** This integer value will be used to make sure only two vehicles move during each light
change for each lane. */
int i = 0;
/** This integer value will keep track of the vehicle numbers of the cars that arrive at the
intersection. */
int vehicleNum = 1;
/** This creates a filewriter object that allows us for the ability to write streams o.
The document discusses Java serialization and the Externalizable interface. It provides examples of how to serialize and deserialize objects to allow their state to be written to a stream and restored later. The key points covered include:
- Using the Serializable interface to allow object serialization
- Implementing Externalizable for more control and better performance than Serializable
- Techniques for serializing singletons, enums, and collections for Externalizable
- Performance comparisons showing Externalizable can provide significant speed improvements over Serializable
// PersonData.h
#ifndef PersonData_h
#define PersonData_h
#include
#include
#include
using namespace std;
class PersonData {
protected:
//member variables
string lastName; //holds the users last name
string firstName; //holds the users first name
string address; //holds the users address
string city; //holds the users city
string state; //holds the users state
int zip; //holds the users zip code
int phone; //holds the users phone number
public:
//constructors and destructor
PersonData(); //default constructor
PersonData( string ln , string fn , string addr , string c , string s , int z , int p); // overloaded
constructor
~PersonData(){ /*cout << \"The object has been deleted.\" << endl ;*/ } //destructor
//member functions
//returns the users lastName
string getLastName();
//sets the users lastName
void setLastName( string lastN );
//returns the users firstName
string getFirstName();
//sets the users firstName
void setFirstName( string firstN );
//returns the users address
string getAddress();
//sets the users address
void setAddress( string addr );
//returns the users city
string getCity();
//sets the users city
void setCity( string city );
//returns the users state
string getState();
//sets the users state
void setState( string state );
//returns the users zip
int getZip();
//sets the users zip
void setZip( int zip );
//returns the users phone
int getPhone();
//sets the users phone
void setPhone( int phone );
};
#endif /* PersonData_h */
// PersonData.cpp
#include
#include \"PersonData.h\"
using namespace std;
//constructors and destructor
PersonData::PersonData(){
//defining arbitrary values for member variables
string lastName = \"\"; //holds the users last name
string firstName = \"\"; //holds the users first name
string address = \"\"; //holds the users address
string city = \"\"; //holds the users city
string state = \"\"; //holds the users state
int zip = 0; //holds the users zip code
int phone = 0; //holds the users phone number
}//default constructor
PersonData::PersonData( string strln , string name , string stradd , string liveingcity , string
livingstate , int code , int number){
// user defined values for member variables
string lastName = strln; //holds the users last name
string firstName = name; //holds the users first name
string address = stradd; //holds the users address
string city = liveingcity; //holds the users city
string state = livingstate; //holds the users state
int zip = code; //holds the users zip code
int phone = number; //holds the users phone number
}// overloaded constructor
//member functions
//returns the users lastName
string PersonData::getLastName(){
return lastName;
}
//sets the users lastName
void PersonData::setLastName( string lastN ){
lastName = lastN;
}
//returns the users firstName
string PersonData::getFirstName(){
return firstName;
}
//sets the users firstName
void PersonData::setFirstName( string firstN ){
firstName = firstN;
}
//returns the users address
string PersonData::getAddress(){
retur.
C#i need help creating the instance of stream reader to read from .pdfajantha11
C#
i need help creating the instance of stream reader to read from a file the using statement will also
close the StreamReader
the txt files are \"NumofAutos.txt\" which is 5
and the txt files for \"AutoData.txt\"
which is Corolla
2013
23000
6
FORD
F150
2012
31000
8
BMW
328XI
2009
42000
3
CHEVY
Volt
2013
39000
5
NISSAN
Cube
2012
17500
5
this is the code that i have
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutoInventory
{
//Class that holds the entire information related to Auto
class Auto
{
//Attributes
private string maker;
private string model;
private int year;
private double price;
private int inStock;
private double inventoryCost;
public static double totalInventoryCost = 0;
//Constructor
public Auto(string maker, string model, int year, double price, int inStock)
{
this.maker = maker;
this.model = model;
this.year = year;
this.price = price;
this.inStock = inStock;
}
//Setter methods
public void setMaker(string maker)
{
this.maker = maker;
}
public void setModel(string model)
{
this.model = model;
}
public void setYear(int year)
{
this.year = year;
}
public void setPrice(double price)
{
this.price = price;
}
public void setInStock(int stock)
{
this.inStock = stock;
}
//Getter Methods
public string getMaker()
{
return maker;
}
public string getModel()
{
return model;
}
public int getYear()
{
return year;
}
public double getPrice()
{
return price;
}
public int getInStock()
{
return inStock;
}
//Readonly Property
public double getInventoryCost()
{
return inventoryCost;
}
//Method that updates inventory
public void calcInventoryCost()
{
inventoryCost = price * inStock;
totalInventoryCost += inventoryCost;
}
}
//Main class
class Program
{
static void Main(string[] args)
{
//Getting number of autos
int count = getCount();
//Creating an array with size obtained
Auto[] autos = new Auto[count];
//Loading data
loadData(autos);
//Displaying and reading menu options
int option = menuOptions();
//Loop till user quits
while (true)
{
//Calling appropriate function
switch (option)
{
case 1: displayData(autos); break;
case 2: addAuto(autos); break;
case 3: sellAuto(autos); break;
case 4: saveExit(autos); Environment.Exit(0); break;
default: Console.WriteLine(\"\ \ Invalid Option.... \ \ \"); break;
}
option = menuOptions();
}
}
//Function that fetches the number of autos from file
public static int getCount()
{
int count = 0;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(\"c:/NumofAuto.txt\"))
{
string line;
//Reading count value
while ((line = sr.ReadLine()) != null)
{
count = Convert.ToInt32(line);
}
}
}
catch (Exception e)
{
//Handling exceptions
Console.WriteLine(\"The file could not be read:\");
Console.WriteLine(e.Message);
}
return count;
}
//Method that loads data from file to array
public static void loadData(Auto[] autos)
{
int i, length = autos.Length;
try
{
/.
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
Kotlin is a programming language developed by JetBrains that targets multiple platforms including the JVM, JavaScript, and native binaries. A year ago it has been adopted as an officially supported language for Android development. Kotlin offers clean and concise syntax, interoperability, both object-oriented and functional code constructs, and a lot of other cool features with little or no overhead. Let's find out together why developers love this language and how it helps them to be productive and have fun!
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdfaioils
Please do Part A, I'll be really grateful
The main.c is the skeleton code, the content of main.c is given below:
#include
#include
/* a rtpkt is the packet sent from one router to
another*/
struct rtpkt {
int sourceid; /* id of sending router sending this pkt */
int destid; /* id of router to which pkt being sent
(must be an directly connected neighbor) */
int *mincost; /* min cost to all the node */
};
struct distance_table
{
int **costs; // the distance table of curr_node, costs[i][j] is the cost from node i to node j
};
/*****************************************************************
***************** NETWORK EMULATION CODE STARTS BELOW ***********
The code below emulates the layer 2 and below network environment:
- emulates the transmission and delivery (with no loss and no
corruption) between two physically connected nodes
- calls the initializations routine rtinit once before
beginning emulation for each node.
You should read and understand the code below. For Part A, you should fill all parts with
annotation starting with "Todo". For Part B and Part C, you need to add additional routines for
their features.
******************************************************************/
struct event {
float evtime; /* event time */
int evtype; /* event type code */
int eventity; /* entity (node) where event occurs */
struct rtpkt *rtpktptr; /* ptr to packet (if any) assoc w/ this event */
struct event *prev;
struct event *next;
};
struct event *evlist = NULL; /* the event list */
struct distance_table *dts;
int **link_costs; /*This is a 2D matrix stroing the content defined in topo file*/
int num_nodes;
/* possible events: */
/*Note in this lab, we only have one event, namely FROM_LAYER2.It refer to that the packet
will pop out from layer3, you can add more event to emulate other activity for other layers. Like
FROM_LAYER3*/
#define FROM_LAYER2 1
float clocktime = 0.000;
/********************* EVENT HANDLINE ROUTINES *******/
/* The next set of routines handle the event list */
/*****************************************************/
void rtinit(struct distance_table *dt, int node, int *link_costs, int num_nodes)
{
/* Todo: Please write the code here*/
}
void rtupdate(struct distance_table *dt, struct rtpkt recv_pkt)
{
/* Todo: Please write the code here*/
}
void main(int argc, char *argv[])
{
struct event *eventptr;
/* Todo: Please write the code here to process the input.
Given different flag, you have different number of input for part A, B, C.
Please write your own code to parse the input for each part.
Specifically, in part A you need parse the input file and get num_nodes,
and fill in the content of dts and link_costs */
dts = (struct distance_table *) malloc(num_nodes * sizeof(struct distance_table));
link_costs = (int **) malloc(num_nodes * sizeof(int *));
for (int i = 0; i < num_nodes; i++)
{
link_costs[i] = (int *)malloc(num_nodes * sizeof(int));
}
for (int i = 0; i < num_nodes; i++)
{
rtinit(&dts[i], i, link_costs[i], num_nodes);
}
whil.
Complete skeletonimport java.util.ArrayList; public class My.pdfarhamnighty
**Complete skeleton**
import java.util.ArrayList;
public class MyGenerics{
//Declarations
//****************************************************************************
//No-argument constructor:
//****************************************************************************
public MyGenerics (){
}//end of constructor
//****************************************************************************
//max: Receives a generic one-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[] list){
return null;
}//end of max
//****************************************************************************
//max: Receives a generic two-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[][] list) {
return null;
}
//****************************************************************************
//largest: Receives a generic arrayList and returns the maximum
// value in the array.
//****************************************************************************
public > E largest(ArrayList list) {
return null;
}
//****************************************************************************
//binarySearch: Receives a generic one-dimensional array and a generic key
// and returns the location of the key (positive) or
// a negative location if not found.
//****************************************************************************
public > int binarySearch(E[] list, E key) {
int low = 0;
int high = list.length - 1;
return binarySearch (list, key, low, high);
}
public > int binarySearch(E[] list, E key, int low, int high) {
return -99; // update
}
//****************************************************************************
//sort: Receives a generic arrayList and returns nothing.
//****************************************************************************
public > void sort(ArrayList list) {
}
//****************************************************************************
//sort: Receives a generic one-dimensional array and returns nothing.
//****************************************************************************
public > void sort(E[] list) {
}
//****************************************************************************
//displayOneDList: Receives a generic one-dimensional array and displays its contents
//****************************************************************************
public void displayOneDList(E[] list, String listName){
}
//****************************************************************************
//displayTwoDList: Receives a generic two-dimensional array & a string name
// and displays its contents
//****************************************************************************
public void displayTwoDList(E[][] list, String listName){
}
//****************************************************************************
//displayArray.
Production.javapublic class Production { Declaring instance.pdfsooryasalini
The document defines classes for different types of productions - Production, Film, Play, and Musical. Production is the parent class that defines common properties like title, director, writer. Child classes like Film add properties specific to that type - box office gross for Film. The main method creates objects of each type and prints their details.
JavaScript for Unleashed a game about a robbery in London and its pretty long i do not know why you would want it but here have it :P also this is not pro its just for school because i am a loner like that and i have nothing better to do
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docxAdamq0DJonese
/* Task 2: Debugging a program with stacks, queues, and doubly-linked lists There are a number of errors in the following program. All errors are located in main() and structure definitions. Function declarations and definitions are correct! Locate all errors, fix them (as shown below), run the program and save its output as a comment at the end of the source file. Example: int num = 10; int *ptr; num = &ptr; // <== Error: Comment the line and write the correct line below // Write a short justification where appropriate // num = &ptr; // Error #1 ptr = # Name: */ #include #include #include #include #define DUMMY_TRAILER '\177' // octal ASCII code of the // last character in the ASCII table #define NUM_CITIES 10 typedef struct { char name[12]; int temperature[5]; } CITY; // Stack and Queue Node typedef struct node NODE; struct node { CITY city; node *next; }; // Doubly Linked List Node typedef struct d_node D_NODE; struct d_node { CITY city; NODE *forw; NODE *back; }; // Stack Functions NODE *push(NODE *stack, const CITY *pStu); NODE *pop(NODE **stack); // Queue Functions void enqueue(NODE **queue, NODE **rear, const CITY *pStu); NODE *dequeue(NODE **queue, NODE **rear); // Doubly Linked List Functions D_NODE *init_list(void); int insert(D_NODE *list, const CITY *pStu); void traverse_forw(D_NODE *list); void traverse_back(D_NODE *list); // Other Functions void printCity(const CITY *pCity); int main (void) { CITY cList[NUM_CITIES] = { {"Cupertino", {88, 89, 87, 85, 89}}, {"Flagstaff", {81, 80, 88, 89, 89}}, {"Los Angeles", {87, 88, 89, 89, 90}}, {"Philadelphia", {96, 99, 99, 90, 95}}, {"Phoenix", {106, 109, 109, 100, 105}}, {"Portland", {89, 90, 85, 89, 90}}, {"Reno", {108, 105, 109, 100, 108}}, {"Salem", {85, 90, 85, 89, 90}}, {"Tucson", {107, 100, 109, 100, 108}}, {"Yreka", {101, 109, 100, 108, 109}} }; NODE *stack = NULL; NODE *top = NULL; NODE *queue = NULL, *rear = NULL; NODE *front; D_NODE *list; list = init_list(); // build stack and queue with data from an array of CITY structures srand((unsigned int)time(NULL)); int count = rand() % 10; for ( int n = 0; n < count; n++) { int i = rand() % NUM_CITIES; int duplicate = insert(list, &cList[i]); if(duplicate) { // already in the list! push(stack, &cList[i]); enqueue(&queue, &rear, cList[i]); } } // display list printf("\nLIST contents (forwards):\n"); traverse_forw(list); printf("\nLIST contents (backwards):\n"); traverse_back(list); // display stack if (top) { printf("\nSTACK contents from top to bottom:\n"); while ((top = pop(stack))) { printCity(top->city); } } else printf ("Empty Stack!\n"); // display queue if (front) { printf("\nQUEUE contents from front to rear:\n"); while ((front = dequeue( queue, rear))) { printCity(front->city); } } else printf ("Empty Queue!\n"); return 0; } /*************************************************** Displays the fileds of a CIS_CLASS structure Pre pCls - a pointer to a CIS_CLASS structure Post */ void printCity(const CITY *pCity) { printf("%-20s %3d\n",.
infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!Infoshare
The document discusses values for software development such as individuals and interactions over processes and tools, working software over comprehensive documentation, and responding to change over following a plan. It emphasizes valuing craftsmanship over poor quality code and building the right system through testing, code ownership, and collaboration.
C346_PA3_W12/src/common/BaseThread.javaC346_PA3_W12/src/common/BaseThread.javapackage common;
import java.util.Random;
/**
* Class BaseThread
* Simply one customized base class for many of our own threads
*
* An attempt to maintain an automatic unique TID (thread ID)
* among all the derivatives and allow setting your own if needed.
* Plus some methods for the sync exercises.
*
* $Revision: 1.2 $
* $Last Revision Date: 2010/10/24 $
*
* @author Serguei A. Mokhov, mokhov@cs.concordia.ca
*/
publicclassBaseThreadextendsThread
{
/*
* ------------
* Data members
* ------------
*/
/**
* Preserves value across all instances
*/
publicstaticint siNextTID =1;
/**
* Our Thread ID
*/
protectedint iTID;
/**
* TID of a thread to proceed to the phase II
*/
privatestaticint siTurn =1;
/*
* ------------
* Constructors
* ------------
*/
/**
* Default
*/
publicBaseThread()
{
setTID();
}
/**
* Assigns name to the thread and places it to the specified group
*
* @param poGroup ThreadGroup to add this thread to
* @param pstrName A string indicating human-readable thread's name
*/
publicBaseThread(ThreadGroup poGroup,String pstrName)
{
super(poGroup, pstrName);
setTID();
}
/**
* Sets user-specified TID
*/
publicBaseThread(finalint piTID)
{
this.iTID = piTID;
}
/**
* Retrieves our TID
* @return TID, integer
*/
publicfinalint getTID()
{
returnthis.iTID;
}
/**
* Sets internal TID and updates next TID on contruction time, so it's private.
*/
privatefinalvoid setTID()
{
this.iTID = siNextTID++;
}
/**
* Just a make up for the PHASE I to make it somewhat tangeable.
* Must be atomic.
*/
protectedsynchronizedvoid phase1()
{
System.out.println(this.getClass().getName()+" thread [TID="+this.iTID +"] starts PHASE I.");
System.out.println
(
"Some stats info in the PHASE I:\n"+
" iTID = "+this.iTID +
", siNextTID = "+ siNextTID +
", siTurn = "+ siTurn +
".\n Their \"checksum\": "+(siNextTID *100+this.iTID *10+ siTurn)
);
System.out.println(this.getClass().getName()+" thread [TID="+this.iTID +"] finishes PHASE I.");
}
/**
* Just a make up for the PHASE II to make it somewhat tangeable.
* Must be atomic.
*/
protectedsynchronizedvoid phase2()
{
System.out.println(this.getClass().getName()+" thread [TID="+this.iTID +"] starts PHASE II.");
System.out.println
(
"Some stats info in the PHASE II:\n"+
" iTID = "+this.iTID +
", siNextTID = "+ siNextTID +
", siTurn = "+ siTurn +
".\n Their \"checksum\": "+(siNextTID *100+this.iTID *10+ siTurn)
);
System.out.println(this.getClass().getName()+" thread [TID="+this.iTID +"] finishes PHASE II.");
}
/**
* Test-and-Set for the iTurn variable.
*
* Use to proceed to the phase II in the correct order.
* Must be atomic.
*
* @param pcIncreasingOrder true if TIDs are in increasing order; false otherwis ...
assignmentTwo/Car.javaassignmentTwo/Car.javapackage assignmentTwo;
// incomplete starter code for assignment two programming 1, sem 2 2014
// author: Kathleen Keogh version 1, incomplete. September 2014
publicclassCarextendsVehicle{
// instance variables
privateint numSeats, numDoors;
privateboolean hatch, tintedWindows;
publicCar(){
}
publicCar(int _numSeats,int _numDoors,boolean _hatch,boolean _tintedWindows){
// insert appropriate initialisation code here based on the parameters provided
}
// get and set methods for each car instance variable
publicint getNumSeats(){
return numSeats;
}
publicboolean setNumSeats(int _numSeats){
returntrue;// change this based on validation
}
publicint getNumDoors(){
return1;// change this to return appropriate value
}
publicvoid setNumDoors(){
}
publicboolean getHatch(){
returntrue;// change this to return the appropriate value
}
publicvoid setHatch(boolean _hatch){
}
publicboolean getTintedWindows(){
returntrue;// update this to return the appropriate value
}
publicvoid setTintedWindows(boolean _tintedWindows){
}
// toString method
publicString toString(){
// insert code here to appropriately return a string of data for this car, use superclass methods where appropriate
return("Car. Make "+ getMake());// change this to return more than just the make
}
}
assignmentTwo/Garage.javaassignmentTwo/Garage.javapackage assignmentTwo;
// Author, Version 1. Starter Code: Kathleen Keogh September 2014
// Author, Version 2. :
// Garage class is for a garage that contains a number of vehicles
publicclassGarage{
//instance variables
Vehicle vehicleList[];
int maxVehicles=10;// default maximum number of vehicles is 10
int currsize;
publicGarage(){// constructor with no parameters
vehicleList =newVehicle[maxVehicles];
currsize=0;
}
publicGarage(int _numMaxVehicles){// constructor with one parameter - maximum number of vehicles for garage
maxVehicles = _numMaxVehicles;
vehicleList =newVehicle[maxVehicles];
currsize =0;
}
// TODO: add get and set methods
// TODO: add toString() method
// TODO: add other methods including addVehicle, sortVehicles
}
assignmentTwo/Rectangle.javaassignmentTwo/Rectangle.javapackage assignmentTwo;
publicclassRectangleextendsShapes{
double length, width;// extra instance variables associated with Rectangle particularly
publicRectangle(){// constructor to create an 'empty' triangle
super("","",0,0);
length =0.0;//initialise length and width to zero for new rectangle
width =0.0;
}
publicRectangle(double initLength,double initWidth,String initName,String initColour,double xCoord,double yCoord){
super(initName, initColour, xCoord, yCoord);// use constructor from super class: Shapes
setLength(initLength);// initialise length to provided value
setWidth(initWidth);
}
publicboolean setLength(double _length){// mutator method to set length to new value
if(_length >0.0){// validate length is positi ...
Modify the bouncing ball example demonstrated/tutorialoutletCleasbyz
FOR MORE CLASSES VISIT
tutorialoutletdotcom
COIS 2240 Assignment#3 Question#1
Modify the bouncing ball example demonstrated in class to include a rectangle as shown in the
figure here: The width of the rectangle should be equal to radius*4, while the height should be equal to the
radius.
A class that automates conversion from a C++ recursive function to an iterative function. It allow the recursive function to preserve its structure by reproducing the "call stack" on an std::stack. The examples use combinatorics to illustrate usage.
Melissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docxwkyra78
Melissa Hinkhouse
Week 3-Original Post
NURS 6050: Policy and Advocacy for Improving Population Health
Walden University
In 2010 The Affordable Care Act (ACA) was enacted; the hope was to expand access to medical care, make coverage more affordable, and decrease the number of people without medical insurance. The Affordable Care Act (ACA) expanded and improved health insurance coverage in two primary ways. First, the number of individuals receiving insurance coverage grown by increasing access to coverage through Medicaid expansion and providing subsidies to purchase private insurance on the health care exchanges. Second, the ACA upgraded the quality and scope of coverage by improving benefit design, including implementing the essential health benefits (Willison & Singer, 2017). People who did not have coverage through their employer or Medicaid were required to purchase insurance through the Marketplace. The Marketplace was created as a one-stop-shop for people to view multiple plans and purchase insurance. Just because you have access to health care insurance does not mean you are going to receive quality health care (Teitelbaum, 2018).
Both parties have asked that the ACA be repealed or replaced for multiple reasons. Every Republican presidential candidate for 2016 has called for the repeal of the ACA. Some, but not all, Republican candidates have proposed health policies that they would like to put in place after repeal, but there is no broad agreement on a replacement for the ACA (Buettgens & Blumberg, 2016). The federal government would spend $90.9 billion less on health care for the nonelderly in 2021 if the ACA were repealed (Buettgens & Blumberg, 2016). State governments as a whole would spend $5.2 billion more on health care for the nonelderly in 2021 if the ACA were repealed (Buettgens & Blumberg, 2016). Healthcare is a priority to many Americans for obvious reasons; it was more costly for those with preexisting conditions before the ACA to obtain Medical Insurance. With the ACA the income guidelines for Medicaid where changed so additional people qualified that didn’t prior. As a Behavioral Health Nurse, I am a fan of anyone and everyone having access to Healthcare Services. I have seen to many times my patient not have the money for their medications because insurance was canceled so they go off their medications, they become unstable and ended up in the Emergency Department and admitted Inpatient, costing more money, hurting themselves and their loved ones.
Politicians are aware that election time is the best time to play the tug of war game with the heavy ticket items to capture someone votes. Republicans ran hard on promises to get rid of the law in every election since it passed in 2010. But when the GOP finally got control of the House, the Senate and the White House in 2017, Republicans found
they could not reach agreement
on how to "repeal and replace" the law (Kaiser Health News, 2018). And political strategists s.
Melissa Hinkhouse
Advanced Pharmacology NURS-6521N-43
Professor Dr. Vicki Gardin
Discussion Board Week 1-Original Post
11/30/2020
I have worked in an outpatient behavioral health clinic for the past seven years with many different providers. I live in a rural community, many patients wait six to twelve months to be seen. Patients being treated for Attention Deficit Disorder must be officially tested before being seen by a Psychologist. For this discussion board post, I have changed the name of my patient to Paul to ensure patient confidentially. The provider I worked with this particular patient will also be referred to as PMHNP to ensure provider confidentiality.
Paul was a ten-year-old Caucasian male referred to our clinic diagnosed per DSM criteria, confirmed via Psychologist testing with ADHD. When he saw the Psychologist, he was also diagnosed with mild depression and anxiety. He struggled with concentration, hyperactivity, impulse control, and disorganization. He presented to his appointment with his mother and father, clean, well-nourished, pleasant, interactive with staff, reported no medication allergies, current medication Zyrtec for seasonal allergies. Paul just had his well-child exam and is current on vaccinations and his primary care provider completed lab work to include CBC, CMP, TSH, Vit D, B12, and A1C, all have returned normal. Family history reported father has a history of ADHD (never medicated), brother has a history of depression and anxiety (never medicated treating with psychotherapy), no other significant family history to report. Paul’s current weight at his appointment was 30kg.
PMHNP spent one hour with Paul and his parents for the initial new patient appointment (Thursday). It was decided Paul would be prescribed Strattera (atomoxetine) 40mg once a day for one week then increase to 80mg once a day. I returned to work on Monday and received a call from Paul’s mom, she said he was acting strange. He was tearful, had been in his room with the door closed for most of the weekend, she stated on Sunday she went into his room and he was crying and said he was just thinking about dying and his parents dying. She stated he had already had his meds Sunday so she kept him with her that entire day and made Sunday night a campout night in the Livingroom so he would think it was fun and she could keep a close eye on him. I had a cancelation that morning for him to come to see PMHNP and he was in to see her within twenty minutes and removed from Strattera. His parents decided medications were no longer the route they wanted to try for treatment and a referral was made for psychotherapy.
The only medication Paul takes on occasion is Zyrtec which is in an antihistamine drug class, Strattera is a selective norepinephrine reuptake inhibitor; there is no known drug interaction between the two medications. Reflecting on his age and the medication, Strattera has a black box labeled for suicidal ideation with adolescents dia.
More Related Content
Similar to proj6Collision.javaproj6Collision.javapackage proj6;import.docx
package reservation; import java.util.; For Scanner Class .pdfanitasahani11
package reservation;
import java.util.*; //For Scanner Class
import java.time.*; //For LocalDate
import java.time.format.*; //For DateTimeFormatter
public class Reservation
{
double perNight = 105.00, finalAmt;
long noDays;
int m, d, y;
LocalDate std, end;
//Sets the Arrival date inputed by the user
void setArrivalDate(LocalDate arrivalDate)
{
std = arrivalDate;
}
//Sets the Departure date inputed by the user
void setDepartureDate(LocalDate departureDate)
{
end = departureDate;
}
//Returns the Arrival date
LocalDate getArrivalDate()
{
return std;
}
//Returns the Departure date
LocalDate getDepartureDate()
{
return end;
}
//Formats the Arrival date as per the requirement given question
String getArrivalDateFormatted()
{
String stdFormat;
stdFormat = \"Arrival Date: \" + std.getMonth() + \" \" + String.valueOf(std.getDayOfMonth())
+ \", \" + String.valueOf(std.getYear());
return stdFormat;
}
//Formats the Departure date as per the requirement given question
String getDepartureDateFormatted()
{
String stdFormat;
stdFormat = \"Departure Date: \" + end.getMonth() + \" \" +
String.valueOf(end.getDayOfMonth()) + \", \" + String.valueOf(end.getYear());
return stdFormat;
}
//Returns the Price per night as per the format
String getPricePerNightFormatted()
{
String pr = \"Price: $\" + String.valueOf(perNight) + \" per night\";
return pr;
}
//Returns the number of nights
long getNumberOfNights()
{
//toEpochDay() returns number of days
noDays = end.toEpochDay() - std.toEpochDay();
return noDays;
}
//Calculates final Amount to be paid
double getTotalPrice()
{
finalAmt = (double)getNumberOfNights() * perNight;
return finalAmt;
}
//Returns the Total amount to be paid as per the format given in the question
String getTotalPriceFormatted()
{
String finA = \"Total price: $\" + String.valueOf(getTotalPrice()) + \" for \" +
String.valueOf(getNumberOfNights()) + \" night\" ;
return finA;
}
//Accepts the Arrival date and Departure date from console
void accept()
{
//Creates object of LocaleDate
LocalDate std1, end1;
//Creates the Date Time Formater object and applies Format Style
//SHORT in mm/dd/yy format
DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
//Creates Scanner class object to accept data from console
Scanner s = new Scanner(System.in);
System.out.println(\"Enter starting date mm/dd/yyyy: \");
System.out.println(\"Enter the arrival month (1-12):\");
m = s.nextInt(); //Accept data in integer format
System.out.println(\"Enter the arrival day (1-31):\") ;
d = s.nextInt();
System.out.println(\"Enter the arrival year:\") ;
y = s.nextInt();
//Initializes the LocalDate object for Arrival date
std1 = LocalDate.of(y, m, d);
//Sets the SHORT date format
fmt.format(std1);
//Assigns Arrival date to class data member
setArrivalDate(std1);
System.out.println(\"Enter ending date mm/dd/yyyy: \");
System.out.println(\"Enter the departure month (1-12):\");
m = s.nextInt(); //Accept data in integer format
System.out.println(\"Enter the departur.
This C++ program defines a Car class with private member variables and public member functions. The main function gets user input, creates a Car object, calls its setUp member function to set the object's variables, and then calls its output member function to display the variable values. A non-member input function gets data from the user and a main function handles program flow, creating and calling the Car object.
The document describes an implementation of the simulated annealing algorithm to solve the traveling salesman problem. It defines a City class to represent locations with name, coordinates, and derived Metro class to add remarks. It includes functions to calculate distance between cities, total route distance, and acceptance probability for simulated annealing. The main function gets user input for cities, runs simulated annealing to optimize the route, and outputs results.
자프링(자바 + 스프링) 외길 12년차 서버 개발자가 코프링(코틀린 + 스프링)을 만난 후 코틀린의 특징과 스프링의 코틀린 지원을 알아가며 코프링 월드에서 살아남은 이야기…
코드 저장소: https://github.com/arawn/kotlin-support-in-spring
import java-util--- import java-io--- class Vertex { -- Constructo.docxBlake0FxCampbelld
import java.util.*;
import java.io.*;
class Vertex {
// Constructor: set name, chargingStation and index according to given values,
// initilaize incidentRoads as empty array
public Vertex(String placeName, boolean chargingStationAvailable, int idx) {
name = placeName;
incidentRoads = new ArrayList<Edge>();
index = idx;
chargingStation = chargingStationAvailable;
}
public Vertex(String placeName, boolean hasChargingStataion) {
}
public String getName() {
return name;
}
public boolean hasChargingStation() {
return chargingStation;
}
public ArrayList<Edge> getIncidentRoads() {
return incidentRoads;
}
// Add a road to the array incidentRoads
public void addIncidentRoad(Edge road) {
incidentRoads.add(road);
}
public int getIndex() {
return index;
}
private String name; // Name of the place
ArrayList<Edge> incidentRoads; // Incident edges
private boolean chargingStation; // Availability of charging station
private int index; // Index of this vertex in the vertex array of the map
public void setVisited(boolean b) {
}
public Edge[] getAdjacentEdges() {
return null;
}
public boolean isVisited() {
return false;
}
public boolean isChargingStationAvailable() {
return false;
}
}
class Edge {
public Edge(int roadLength, Vertex firstPlace, Vertex secondPlace) {
length = roadLength;
incidentPlaces = new Vertex[] { firstPlace, secondPlace };
}
public Edge(Vertex vtx1, Vertex vtx2, int length2) {
}
public Vertex getFirstVertex() {
return incidentPlaces[0];
}
public Vertex getSecondVertex() {
return incidentPlaces[1];
}
public int getLength() {
return length;
}
private int length;
private Vertex[] incidentPlaces;
public Vertex getEnd() {
return null;
}
}
//A class that represents a sparse matrix
public class RoadMap {
// Default constructor
public RoadMap() {
places = new ArrayList<Vertex>();
roads = new ArrayList<Edge>();
}
// Auxiliary function that prints out the command syntax
public static void printCommandError() {
System.err.println("ERROR: use one of the following commands");
System.err.println(" - Load a map and print information:");
System.err.println(" java RoadMap -i <MapFile>");
System.err.println(" - Load a map and determine if two places are connnected by a path with charging stations:");
System.err.println(" java RoadMap -c <MapFile> <StartVertexIndex> <EndVertexIndex>");
System.err.println(" - Load a map and determine the mininmum number of assistance cars required:");
System.err.println(" java RoadMap -a <MapFile>");
}
public static void main(String[] args) throws Exception {
if (args.length == 2 && args[0].equals("-i")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Error in reading map file");
System.exit(-1);
}
System.out.println();
System.out.println("Read road map from " + args[1] + ":");
map.printMap();
System.out.println();
}
else if (args.length == 2 && args[0].equals("-a")) {
RoadMap map = new RoadMap();
try {
map.loadMap(args[1]);
} catch (Exception e) {
System.err.println("Err.
Create a system to simulate vehicles at an intersection. Assume th.pdfarchanacomputers1
\"Create a system to simulate vehicles at an intersection. Assume that there is one lane going in
each of four directions, with stoplights facing each direction. Vary the arrival average of vehicles
in each direction and the frequency of the light changes to view the \"behavior\" of the
intersection.\"
You canNOT use the Java built-in Queue or Deque class. Use an Array or Linked List
implementation of a queue as explained in the text. This means a jsjf package containing
QueueADT.java file with CircularArrayQueue.java or LinkedQueue.java and LinearNode.java.
Include user-defined exceptions and javadoc comments.
Be sure to test thoroughly, and document your results.
Be sure to label your outputs so that when I run your code I can readily understand what you\'re
doing.
Determine what is the optimal light-change time to maximize car throughput.
WANT KNOW HOW CAN I MAKE IT RUN!
import java.lang.Math;
import java.io.*;
import jsjf.*;
import jsjf.exceptions.*;
import java.util.*;
import java.net.*;
import java.io.*;
/**
*This class is where all action resides. It contains all the queues that represent the lanes at the
intersection.
* It also contains all methods that pertain to populating the intersection and moving the vehicles
in their
* retrospective directions.
*/
public class Simulator {
/** This queue will hold only vehicle objects that enter in the left lane on Main Street headed
East. */
private LinkedQueue EMainL = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the right lane on Main Street headed
East. */
private LinkedQueue EMainR = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the left lane on Main Street headed
West. */
private LinkedQueue WMainL = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the right lane on Main Street headed
West. */
private LinkedQueue WMainR = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the left lane on Church Street
headed North. */
private LinkedQueue NChurchL = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the right lane on Church Street
headed North. */
private LinkedQueue NChurchR = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the left lane on Church Street
headed South. */
private LinkedQueue SChurchL = new LinkedQueue();
/** This queue will hold only vehicle objects that enter in the right lane on Church Street
headed South. */
private LinkedQueue SChurchR = new LinkedQueue();
/** This integer value will keep track of the current time during the simulation.*/
int time = 0;
/** This integer value will be used to make sure only two vehicles move during each light
change for each lane. */
int i = 0;
/** This integer value will keep track of the vehicle numbers of the cars that arrive at the
intersection. */
int vehicleNum = 1;
/** This creates a filewriter object that allows us for the ability to write streams o.
The document discusses Java serialization and the Externalizable interface. It provides examples of how to serialize and deserialize objects to allow their state to be written to a stream and restored later. The key points covered include:
- Using the Serializable interface to allow object serialization
- Implementing Externalizable for more control and better performance than Serializable
- Techniques for serializing singletons, enums, and collections for Externalizable
- Performance comparisons showing Externalizable can provide significant speed improvements over Serializable
// PersonData.h
#ifndef PersonData_h
#define PersonData_h
#include
#include
#include
using namespace std;
class PersonData {
protected:
//member variables
string lastName; //holds the users last name
string firstName; //holds the users first name
string address; //holds the users address
string city; //holds the users city
string state; //holds the users state
int zip; //holds the users zip code
int phone; //holds the users phone number
public:
//constructors and destructor
PersonData(); //default constructor
PersonData( string ln , string fn , string addr , string c , string s , int z , int p); // overloaded
constructor
~PersonData(){ /*cout << \"The object has been deleted.\" << endl ;*/ } //destructor
//member functions
//returns the users lastName
string getLastName();
//sets the users lastName
void setLastName( string lastN );
//returns the users firstName
string getFirstName();
//sets the users firstName
void setFirstName( string firstN );
//returns the users address
string getAddress();
//sets the users address
void setAddress( string addr );
//returns the users city
string getCity();
//sets the users city
void setCity( string city );
//returns the users state
string getState();
//sets the users state
void setState( string state );
//returns the users zip
int getZip();
//sets the users zip
void setZip( int zip );
//returns the users phone
int getPhone();
//sets the users phone
void setPhone( int phone );
};
#endif /* PersonData_h */
// PersonData.cpp
#include
#include \"PersonData.h\"
using namespace std;
//constructors and destructor
PersonData::PersonData(){
//defining arbitrary values for member variables
string lastName = \"\"; //holds the users last name
string firstName = \"\"; //holds the users first name
string address = \"\"; //holds the users address
string city = \"\"; //holds the users city
string state = \"\"; //holds the users state
int zip = 0; //holds the users zip code
int phone = 0; //holds the users phone number
}//default constructor
PersonData::PersonData( string strln , string name , string stradd , string liveingcity , string
livingstate , int code , int number){
// user defined values for member variables
string lastName = strln; //holds the users last name
string firstName = name; //holds the users first name
string address = stradd; //holds the users address
string city = liveingcity; //holds the users city
string state = livingstate; //holds the users state
int zip = code; //holds the users zip code
int phone = number; //holds the users phone number
}// overloaded constructor
//member functions
//returns the users lastName
string PersonData::getLastName(){
return lastName;
}
//sets the users lastName
void PersonData::setLastName( string lastN ){
lastName = lastN;
}
//returns the users firstName
string PersonData::getFirstName(){
return firstName;
}
//sets the users firstName
void PersonData::setFirstName( string firstN ){
firstName = firstN;
}
//returns the users address
string PersonData::getAddress(){
retur.
C#i need help creating the instance of stream reader to read from .pdfajantha11
C#
i need help creating the instance of stream reader to read from a file the using statement will also
close the StreamReader
the txt files are \"NumofAutos.txt\" which is 5
and the txt files for \"AutoData.txt\"
which is Corolla
2013
23000
6
FORD
F150
2012
31000
8
BMW
328XI
2009
42000
3
CHEVY
Volt
2013
39000
5
NISSAN
Cube
2012
17500
5
this is the code that i have
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutoInventory
{
//Class that holds the entire information related to Auto
class Auto
{
//Attributes
private string maker;
private string model;
private int year;
private double price;
private int inStock;
private double inventoryCost;
public static double totalInventoryCost = 0;
//Constructor
public Auto(string maker, string model, int year, double price, int inStock)
{
this.maker = maker;
this.model = model;
this.year = year;
this.price = price;
this.inStock = inStock;
}
//Setter methods
public void setMaker(string maker)
{
this.maker = maker;
}
public void setModel(string model)
{
this.model = model;
}
public void setYear(int year)
{
this.year = year;
}
public void setPrice(double price)
{
this.price = price;
}
public void setInStock(int stock)
{
this.inStock = stock;
}
//Getter Methods
public string getMaker()
{
return maker;
}
public string getModel()
{
return model;
}
public int getYear()
{
return year;
}
public double getPrice()
{
return price;
}
public int getInStock()
{
return inStock;
}
//Readonly Property
public double getInventoryCost()
{
return inventoryCost;
}
//Method that updates inventory
public void calcInventoryCost()
{
inventoryCost = price * inStock;
totalInventoryCost += inventoryCost;
}
}
//Main class
class Program
{
static void Main(string[] args)
{
//Getting number of autos
int count = getCount();
//Creating an array with size obtained
Auto[] autos = new Auto[count];
//Loading data
loadData(autos);
//Displaying and reading menu options
int option = menuOptions();
//Loop till user quits
while (true)
{
//Calling appropriate function
switch (option)
{
case 1: displayData(autos); break;
case 2: addAuto(autos); break;
case 3: sellAuto(autos); break;
case 4: saveExit(autos); Environment.Exit(0); break;
default: Console.WriteLine(\"\ \ Invalid Option.... \ \ \"); break;
}
option = menuOptions();
}
}
//Function that fetches the number of autos from file
public static int getCount()
{
int count = 0;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(\"c:/NumofAuto.txt\"))
{
string line;
//Reading count value
while ((line = sr.ReadLine()) != null)
{
count = Convert.ToInt32(line);
}
}
}
catch (Exception e)
{
//Handling exceptions
Console.WriteLine(\"The file could not be read:\");
Console.WriteLine(e.Message);
}
return count;
}
//Method that loads data from file to array
public static void loadData(Auto[] autos)
{
int i, length = autos.Length;
try
{
/.
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
Kotlin is a programming language developed by JetBrains that targets multiple platforms including the JVM, JavaScript, and native binaries. A year ago it has been adopted as an officially supported language for Android development. Kotlin offers clean and concise syntax, interoperability, both object-oriented and functional code constructs, and a lot of other cool features with little or no overhead. Let's find out together why developers love this language and how it helps them to be productive and have fun!
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdfaioils
Please do Part A, I'll be really grateful
The main.c is the skeleton code, the content of main.c is given below:
#include
#include
/* a rtpkt is the packet sent from one router to
another*/
struct rtpkt {
int sourceid; /* id of sending router sending this pkt */
int destid; /* id of router to which pkt being sent
(must be an directly connected neighbor) */
int *mincost; /* min cost to all the node */
};
struct distance_table
{
int **costs; // the distance table of curr_node, costs[i][j] is the cost from node i to node j
};
/*****************************************************************
***************** NETWORK EMULATION CODE STARTS BELOW ***********
The code below emulates the layer 2 and below network environment:
- emulates the transmission and delivery (with no loss and no
corruption) between two physically connected nodes
- calls the initializations routine rtinit once before
beginning emulation for each node.
You should read and understand the code below. For Part A, you should fill all parts with
annotation starting with "Todo". For Part B and Part C, you need to add additional routines for
their features.
******************************************************************/
struct event {
float evtime; /* event time */
int evtype; /* event type code */
int eventity; /* entity (node) where event occurs */
struct rtpkt *rtpktptr; /* ptr to packet (if any) assoc w/ this event */
struct event *prev;
struct event *next;
};
struct event *evlist = NULL; /* the event list */
struct distance_table *dts;
int **link_costs; /*This is a 2D matrix stroing the content defined in topo file*/
int num_nodes;
/* possible events: */
/*Note in this lab, we only have one event, namely FROM_LAYER2.It refer to that the packet
will pop out from layer3, you can add more event to emulate other activity for other layers. Like
FROM_LAYER3*/
#define FROM_LAYER2 1
float clocktime = 0.000;
/********************* EVENT HANDLINE ROUTINES *******/
/* The next set of routines handle the event list */
/*****************************************************/
void rtinit(struct distance_table *dt, int node, int *link_costs, int num_nodes)
{
/* Todo: Please write the code here*/
}
void rtupdate(struct distance_table *dt, struct rtpkt recv_pkt)
{
/* Todo: Please write the code here*/
}
void main(int argc, char *argv[])
{
struct event *eventptr;
/* Todo: Please write the code here to process the input.
Given different flag, you have different number of input for part A, B, C.
Please write your own code to parse the input for each part.
Specifically, in part A you need parse the input file and get num_nodes,
and fill in the content of dts and link_costs */
dts = (struct distance_table *) malloc(num_nodes * sizeof(struct distance_table));
link_costs = (int **) malloc(num_nodes * sizeof(int *));
for (int i = 0; i < num_nodes; i++)
{
link_costs[i] = (int *)malloc(num_nodes * sizeof(int));
}
for (int i = 0; i < num_nodes; i++)
{
rtinit(&dts[i], i, link_costs[i], num_nodes);
}
whil.
Complete skeletonimport java.util.ArrayList; public class My.pdfarhamnighty
**Complete skeleton**
import java.util.ArrayList;
public class MyGenerics{
//Declarations
//****************************************************************************
//No-argument constructor:
//****************************************************************************
public MyGenerics (){
}//end of constructor
//****************************************************************************
//max: Receives a generic one-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[] list){
return null;
}//end of max
//****************************************************************************
//max: Receives a generic two-dimensional array and returns the maximum
// value in the array.
//****************************************************************************
public > E max(E[][] list) {
return null;
}
//****************************************************************************
//largest: Receives a generic arrayList and returns the maximum
// value in the array.
//****************************************************************************
public > E largest(ArrayList list) {
return null;
}
//****************************************************************************
//binarySearch: Receives a generic one-dimensional array and a generic key
// and returns the location of the key (positive) or
// a negative location if not found.
//****************************************************************************
public > int binarySearch(E[] list, E key) {
int low = 0;
int high = list.length - 1;
return binarySearch (list, key, low, high);
}
public > int binarySearch(E[] list, E key, int low, int high) {
return -99; // update
}
//****************************************************************************
//sort: Receives a generic arrayList and returns nothing.
//****************************************************************************
public > void sort(ArrayList list) {
}
//****************************************************************************
//sort: Receives a generic one-dimensional array and returns nothing.
//****************************************************************************
public > void sort(E[] list) {
}
//****************************************************************************
//displayOneDList: Receives a generic one-dimensional array and displays its contents
//****************************************************************************
public void displayOneDList(E[] list, String listName){
}
//****************************************************************************
//displayTwoDList: Receives a generic two-dimensional array & a string name
// and displays its contents
//****************************************************************************
public void displayTwoDList(E[][] list, String listName){
}
//****************************************************************************
//displayArray.
Production.javapublic class Production { Declaring instance.pdfsooryasalini
The document defines classes for different types of productions - Production, Film, Play, and Musical. Production is the parent class that defines common properties like title, director, writer. Child classes like Film add properties specific to that type - box office gross for Film. The main method creates objects of each type and prints their details.
JavaScript for Unleashed a game about a robbery in London and its pretty long i do not know why you would want it but here have it :P also this is not pro its just for school because i am a loner like that and i have nothing better to do
-- Task 2- Debugging a program with stacks- queues- and doubly-linked.docxAdamq0DJonese
/* Task 2: Debugging a program with stacks, queues, and doubly-linked lists There are a number of errors in the following program. All errors are located in main() and structure definitions. Function declarations and definitions are correct! Locate all errors, fix them (as shown below), run the program and save its output as a comment at the end of the source file. Example: int num = 10; int *ptr; num = &ptr; // <== Error: Comment the line and write the correct line below // Write a short justification where appropriate // num = &ptr; // Error #1 ptr = # Name: */ #include #include #include #include #define DUMMY_TRAILER '\177' // octal ASCII code of the // last character in the ASCII table #define NUM_CITIES 10 typedef struct { char name[12]; int temperature[5]; } CITY; // Stack and Queue Node typedef struct node NODE; struct node { CITY city; node *next; }; // Doubly Linked List Node typedef struct d_node D_NODE; struct d_node { CITY city; NODE *forw; NODE *back; }; // Stack Functions NODE *push(NODE *stack, const CITY *pStu); NODE *pop(NODE **stack); // Queue Functions void enqueue(NODE **queue, NODE **rear, const CITY *pStu); NODE *dequeue(NODE **queue, NODE **rear); // Doubly Linked List Functions D_NODE *init_list(void); int insert(D_NODE *list, const CITY *pStu); void traverse_forw(D_NODE *list); void traverse_back(D_NODE *list); // Other Functions void printCity(const CITY *pCity); int main (void) { CITY cList[NUM_CITIES] = { {"Cupertino", {88, 89, 87, 85, 89}}, {"Flagstaff", {81, 80, 88, 89, 89}}, {"Los Angeles", {87, 88, 89, 89, 90}}, {"Philadelphia", {96, 99, 99, 90, 95}}, {"Phoenix", {106, 109, 109, 100, 105}}, {"Portland", {89, 90, 85, 89, 90}}, {"Reno", {108, 105, 109, 100, 108}}, {"Salem", {85, 90, 85, 89, 90}}, {"Tucson", {107, 100, 109, 100, 108}}, {"Yreka", {101, 109, 100, 108, 109}} }; NODE *stack = NULL; NODE *top = NULL; NODE *queue = NULL, *rear = NULL; NODE *front; D_NODE *list; list = init_list(); // build stack and queue with data from an array of CITY structures srand((unsigned int)time(NULL)); int count = rand() % 10; for ( int n = 0; n < count; n++) { int i = rand() % NUM_CITIES; int duplicate = insert(list, &cList[i]); if(duplicate) { // already in the list! push(stack, &cList[i]); enqueue(&queue, &rear, cList[i]); } } // display list printf("\nLIST contents (forwards):\n"); traverse_forw(list); printf("\nLIST contents (backwards):\n"); traverse_back(list); // display stack if (top) { printf("\nSTACK contents from top to bottom:\n"); while ((top = pop(stack))) { printCity(top->city); } } else printf ("Empty Stack!\n"); // display queue if (front) { printf("\nQUEUE contents from front to rear:\n"); while ((front = dequeue( queue, rear))) { printCity(front->city); } } else printf ("Empty Queue!\n"); return 0; } /*************************************************** Displays the fileds of a CIS_CLASS structure Pre pCls - a pointer to a CIS_CLASS structure Post */ void printCity(const CITY *pCity) { printf("%-20s %3d\n",.
infoShare 2014: Gino Marckx, Forget about Agile, let's write great code first!Infoshare
The document discusses values for software development such as individuals and interactions over processes and tools, working software over comprehensive documentation, and responding to change over following a plan. It emphasizes valuing craftsmanship over poor quality code and building the right system through testing, code ownership, and collaboration.
C346_PA3_W12/src/common/BaseThread.javaC346_PA3_W12/src/common/BaseThread.javapackage common;
import java.util.Random;
/**
* Class BaseThread
* Simply one customized base class for many of our own threads
*
* An attempt to maintain an automatic unique TID (thread ID)
* among all the derivatives and allow setting your own if needed.
* Plus some methods for the sync exercises.
*
* $Revision: 1.2 $
* $Last Revision Date: 2010/10/24 $
*
* @author Serguei A. Mokhov, mokhov@cs.concordia.ca
*/
publicclassBaseThreadextendsThread
{
/*
* ------------
* Data members
* ------------
*/
/**
* Preserves value across all instances
*/
publicstaticint siNextTID =1;
/**
* Our Thread ID
*/
protectedint iTID;
/**
* TID of a thread to proceed to the phase II
*/
privatestaticint siTurn =1;
/*
* ------------
* Constructors
* ------------
*/
/**
* Default
*/
publicBaseThread()
{
setTID();
}
/**
* Assigns name to the thread and places it to the specified group
*
* @param poGroup ThreadGroup to add this thread to
* @param pstrName A string indicating human-readable thread's name
*/
publicBaseThread(ThreadGroup poGroup,String pstrName)
{
super(poGroup, pstrName);
setTID();
}
/**
* Sets user-specified TID
*/
publicBaseThread(finalint piTID)
{
this.iTID = piTID;
}
/**
* Retrieves our TID
* @return TID, integer
*/
publicfinalint getTID()
{
returnthis.iTID;
}
/**
* Sets internal TID and updates next TID on contruction time, so it's private.
*/
privatefinalvoid setTID()
{
this.iTID = siNextTID++;
}
/**
* Just a make up for the PHASE I to make it somewhat tangeable.
* Must be atomic.
*/
protectedsynchronizedvoid phase1()
{
System.out.println(this.getClass().getName()+" thread [TID="+this.iTID +"] starts PHASE I.");
System.out.println
(
"Some stats info in the PHASE I:\n"+
" iTID = "+this.iTID +
", siNextTID = "+ siNextTID +
", siTurn = "+ siTurn +
".\n Their \"checksum\": "+(siNextTID *100+this.iTID *10+ siTurn)
);
System.out.println(this.getClass().getName()+" thread [TID="+this.iTID +"] finishes PHASE I.");
}
/**
* Just a make up for the PHASE II to make it somewhat tangeable.
* Must be atomic.
*/
protectedsynchronizedvoid phase2()
{
System.out.println(this.getClass().getName()+" thread [TID="+this.iTID +"] starts PHASE II.");
System.out.println
(
"Some stats info in the PHASE II:\n"+
" iTID = "+this.iTID +
", siNextTID = "+ siNextTID +
", siTurn = "+ siTurn +
".\n Their \"checksum\": "+(siNextTID *100+this.iTID *10+ siTurn)
);
System.out.println(this.getClass().getName()+" thread [TID="+this.iTID +"] finishes PHASE II.");
}
/**
* Test-and-Set for the iTurn variable.
*
* Use to proceed to the phase II in the correct order.
* Must be atomic.
*
* @param pcIncreasingOrder true if TIDs are in increasing order; false otherwis ...
assignmentTwo/Car.javaassignmentTwo/Car.javapackage assignmentTwo;
// incomplete starter code for assignment two programming 1, sem 2 2014
// author: Kathleen Keogh version 1, incomplete. September 2014
publicclassCarextendsVehicle{
// instance variables
privateint numSeats, numDoors;
privateboolean hatch, tintedWindows;
publicCar(){
}
publicCar(int _numSeats,int _numDoors,boolean _hatch,boolean _tintedWindows){
// insert appropriate initialisation code here based on the parameters provided
}
// get and set methods for each car instance variable
publicint getNumSeats(){
return numSeats;
}
publicboolean setNumSeats(int _numSeats){
returntrue;// change this based on validation
}
publicint getNumDoors(){
return1;// change this to return appropriate value
}
publicvoid setNumDoors(){
}
publicboolean getHatch(){
returntrue;// change this to return the appropriate value
}
publicvoid setHatch(boolean _hatch){
}
publicboolean getTintedWindows(){
returntrue;// update this to return the appropriate value
}
publicvoid setTintedWindows(boolean _tintedWindows){
}
// toString method
publicString toString(){
// insert code here to appropriately return a string of data for this car, use superclass methods where appropriate
return("Car. Make "+ getMake());// change this to return more than just the make
}
}
assignmentTwo/Garage.javaassignmentTwo/Garage.javapackage assignmentTwo;
// Author, Version 1. Starter Code: Kathleen Keogh September 2014
// Author, Version 2. :
// Garage class is for a garage that contains a number of vehicles
publicclassGarage{
//instance variables
Vehicle vehicleList[];
int maxVehicles=10;// default maximum number of vehicles is 10
int currsize;
publicGarage(){// constructor with no parameters
vehicleList =newVehicle[maxVehicles];
currsize=0;
}
publicGarage(int _numMaxVehicles){// constructor with one parameter - maximum number of vehicles for garage
maxVehicles = _numMaxVehicles;
vehicleList =newVehicle[maxVehicles];
currsize =0;
}
// TODO: add get and set methods
// TODO: add toString() method
// TODO: add other methods including addVehicle, sortVehicles
}
assignmentTwo/Rectangle.javaassignmentTwo/Rectangle.javapackage assignmentTwo;
publicclassRectangleextendsShapes{
double length, width;// extra instance variables associated with Rectangle particularly
publicRectangle(){// constructor to create an 'empty' triangle
super("","",0,0);
length =0.0;//initialise length and width to zero for new rectangle
width =0.0;
}
publicRectangle(double initLength,double initWidth,String initName,String initColour,double xCoord,double yCoord){
super(initName, initColour, xCoord, yCoord);// use constructor from super class: Shapes
setLength(initLength);// initialise length to provided value
setWidth(initWidth);
}
publicboolean setLength(double _length){// mutator method to set length to new value
if(_length >0.0){// validate length is positi ...
Modify the bouncing ball example demonstrated/tutorialoutletCleasbyz
FOR MORE CLASSES VISIT
tutorialoutletdotcom
COIS 2240 Assignment#3 Question#1
Modify the bouncing ball example demonstrated in class to include a rectangle as shown in the
figure here: The width of the rectangle should be equal to radius*4, while the height should be equal to the
radius.
A class that automates conversion from a C++ recursive function to an iterative function. It allow the recursive function to preserve its structure by reproducing the "call stack" on an std::stack. The examples use combinatorics to illustrate usage.
Similar to proj6Collision.javaproj6Collision.javapackage proj6;import.docx (20)
Melissa HinkhouseWeek 3-Original PostNURS 6050 Policy and A.docxwkyra78
Melissa Hinkhouse
Week 3-Original Post
NURS 6050: Policy and Advocacy for Improving Population Health
Walden University
In 2010 The Affordable Care Act (ACA) was enacted; the hope was to expand access to medical care, make coverage more affordable, and decrease the number of people without medical insurance. The Affordable Care Act (ACA) expanded and improved health insurance coverage in two primary ways. First, the number of individuals receiving insurance coverage grown by increasing access to coverage through Medicaid expansion and providing subsidies to purchase private insurance on the health care exchanges. Second, the ACA upgraded the quality and scope of coverage by improving benefit design, including implementing the essential health benefits (Willison & Singer, 2017). People who did not have coverage through their employer or Medicaid were required to purchase insurance through the Marketplace. The Marketplace was created as a one-stop-shop for people to view multiple plans and purchase insurance. Just because you have access to health care insurance does not mean you are going to receive quality health care (Teitelbaum, 2018).
Both parties have asked that the ACA be repealed or replaced for multiple reasons. Every Republican presidential candidate for 2016 has called for the repeal of the ACA. Some, but not all, Republican candidates have proposed health policies that they would like to put in place after repeal, but there is no broad agreement on a replacement for the ACA (Buettgens & Blumberg, 2016). The federal government would spend $90.9 billion less on health care for the nonelderly in 2021 if the ACA were repealed (Buettgens & Blumberg, 2016). State governments as a whole would spend $5.2 billion more on health care for the nonelderly in 2021 if the ACA were repealed (Buettgens & Blumberg, 2016). Healthcare is a priority to many Americans for obvious reasons; it was more costly for those with preexisting conditions before the ACA to obtain Medical Insurance. With the ACA the income guidelines for Medicaid where changed so additional people qualified that didn’t prior. As a Behavioral Health Nurse, I am a fan of anyone and everyone having access to Healthcare Services. I have seen to many times my patient not have the money for their medications because insurance was canceled so they go off their medications, they become unstable and ended up in the Emergency Department and admitted Inpatient, costing more money, hurting themselves and their loved ones.
Politicians are aware that election time is the best time to play the tug of war game with the heavy ticket items to capture someone votes. Republicans ran hard on promises to get rid of the law in every election since it passed in 2010. But when the GOP finally got control of the House, the Senate and the White House in 2017, Republicans found
they could not reach agreement
on how to "repeal and replace" the law (Kaiser Health News, 2018). And political strategists s.
Melissa Hinkhouse
Advanced Pharmacology NURS-6521N-43
Professor Dr. Vicki Gardin
Discussion Board Week 1-Original Post
11/30/2020
I have worked in an outpatient behavioral health clinic for the past seven years with many different providers. I live in a rural community, many patients wait six to twelve months to be seen. Patients being treated for Attention Deficit Disorder must be officially tested before being seen by a Psychologist. For this discussion board post, I have changed the name of my patient to Paul to ensure patient confidentially. The provider I worked with this particular patient will also be referred to as PMHNP to ensure provider confidentiality.
Paul was a ten-year-old Caucasian male referred to our clinic diagnosed per DSM criteria, confirmed via Psychologist testing with ADHD. When he saw the Psychologist, he was also diagnosed with mild depression and anxiety. He struggled with concentration, hyperactivity, impulse control, and disorganization. He presented to his appointment with his mother and father, clean, well-nourished, pleasant, interactive with staff, reported no medication allergies, current medication Zyrtec for seasonal allergies. Paul just had his well-child exam and is current on vaccinations and his primary care provider completed lab work to include CBC, CMP, TSH, Vit D, B12, and A1C, all have returned normal. Family history reported father has a history of ADHD (never medicated), brother has a history of depression and anxiety (never medicated treating with psychotherapy), no other significant family history to report. Paul’s current weight at his appointment was 30kg.
PMHNP spent one hour with Paul and his parents for the initial new patient appointment (Thursday). It was decided Paul would be prescribed Strattera (atomoxetine) 40mg once a day for one week then increase to 80mg once a day. I returned to work on Monday and received a call from Paul’s mom, she said he was acting strange. He was tearful, had been in his room with the door closed for most of the weekend, she stated on Sunday she went into his room and he was crying and said he was just thinking about dying and his parents dying. She stated he had already had his meds Sunday so she kept him with her that entire day and made Sunday night a campout night in the Livingroom so he would think it was fun and she could keep a close eye on him. I had a cancelation that morning for him to come to see PMHNP and he was in to see her within twenty minutes and removed from Strattera. His parents decided medications were no longer the route they wanted to try for treatment and a referral was made for psychotherapy.
The only medication Paul takes on occasion is Zyrtec which is in an antihistamine drug class, Strattera is a selective norepinephrine reuptake inhibitor; there is no known drug interaction between the two medications. Reflecting on his age and the medication, Strattera has a black box labeled for suicidal ideation with adolescents dia.
Meiner, S. E., & Yeager, J. J. (2019). Chapter 17Chap.docxwkyra78
Meiner, S. E., & Yeager, J. J. (2019).
Chapter 17
Chapter_017.pptx
Chapter 18
Chapter_018.pptx
Chapter 19
Chapter_019.pptx
Chapter 20
Chapter_020.pptx
Watch
None.
Supplemental Materials & Resources
Visit the
CINAHL Complete
under the
A-to-Z Databases
on the
University Library's
website and locate the article(s) below:
O’Keefe-McCarthy, S. (2009). Technologically-mediated nursing care: The impact on moral agency. Nursing Ethics, 16(6), 76-796.
Teutsch, S., & Rechel, B. (2012). Ethics of resource allocation and rationing medical care in a time of fiscal restraint: US and Europe. Public Health Reviews, 34(1), 1-10.
QUESTION
Define presbycusis, name signs and symptoms, etiology and differential diagnosis.
Create 3 interventions-education measures with a patient with Presbycusis.
List, define and elaborate on three different retinal and macular diseases age-related.
Submission Instructions:
Your initial post should be at least 500 words, formatted and cited in current APA style with support from at least 2 academic sources
Your assignment will be graded according to the grading rubric.
.
member is a security software architect in a cloud service provider .docxwkyra78
member is a security software architect in a cloud service provider company, assigned to a project to provide the client with data integrity and confidentiality protections for data in transit that will be using applications in the cloud. Your client is an HR company that is moving HR applications and HR data into a community cloud, sharing tenancy with other clients. Your company has set up a software as a service, SAS, offering for its client base.
The data that the HR company will be pushing to and from the cloud will contain sensitive employee information, such as personally identifiable information, PII. You will have to address sensitive data and transit issues of the client data using the HR applications stored in the cloud, and provide a life cycle management report that includes solutions to the cloud computing architect of your company.
Software Development Life Cycle
Technology development and implementation usually follow a software development life cycle (SDLC) methodology. This approach ensures accuracy of information for analysis and decision making, as well as appropriate resources for effective technology management.
You and your team members will use components of the SDLC methodology to develop a
life cycle management report
for the cloud computing architect of a company. This is a group exercise, representing the kind of collaboration often required in the cybersecurity technology community.
There are 11 steps to lead you through this project. Similar steps are typically used in organizational SDLC projects. Most steps should take no more than two hours to complete, and the entire project should take no more than three weeks to complete. Begin with the workplace scenario, and then continue with Step 1: “Initiating the Project.”
Life Cycle Management Report:
A 10- to 15-page double-spaced Word document on data protection techniques for a cloud-based service with citations in APA format. The page count does not include figures or tables. There is no penalty for using additional pages if you need them. Include a minimum of six references. Include a reference list with the report.
As the cloud security architect, you must understand the security development life cycle process. Review the following resources to learn about the security development life cycle process:
security development life cycle
software development methodologies
Click the following links to learn more about critical infrastructure sectors:
Critical Infrastructure Sectors
. Read their descriptions and consider which sector you support in your role.
Process Control Systems: Cybersecurity and Defense
To be completed by a designated team member:
You will begin your Life Cycle Management Report now.
Choose a fictional or actual organization. Describe the mission of the organization and the business need to move to a cloud environment.
Identify the scope of the security architecture and include a topology. To narrow your scope, focus on is.
Melissa ShortridgeWeek 6COLLAPSEMy own attitude has ch.docxwkyra78
Melissa Shortridge
Week 6
COLLAPSE
My own attitude has changed from lack of understanding to enlightenment over the years. In elementary school I never experienced students with disabilities in my classrooms, growing up. But as the years went on and legislation changed students with disabilities started trickling into general education classrooms. They were always ignored by other students and often times had an aide to assist them with assignments. As an adult my heart has opened up to accept all types of people. In the Pennhurst documentary, it was reiterated, they are just people (Baldini, 1968). Which is my outlook on how to treat everyone. Every single person is a human being, treat them the way you wish to be treated. Everyone no matter their race, disability or socio-economic status deserves to be treated humanely.
As an educator I have worked with several different types of students. Students from low socio-economic areas, behavioral issues, vision impairments, hearing impairments, with autism, hyper activity and down syndrome, and with all of these students I have given them my best effort to show them that they are students first. Slavin and Schunk (2017) said it best, “Each student has many characteristics, and the disability is only one of them. To define the child in terms of the disability does him or her an injustice” (p. 235). It is our role as an educator to incorporate different learning styles to give each student, regardless of disabilities, the education that they deserve.
Welcoming students with disabilities into my classroom will be an important aspect in my role as an educator. Allowing each student to feel love and acceptance by peers is important for any students success. Van Brummelen (2009) states, “ It is important to appreciate students with special needs for who they are. Always look beyond their disabilities and teach them as whole persons” (p. 208). Being an advocate for my students with learning disabilities will garner them respect and dignity that they need to be self sufficient. In the Pennhurst documentary, the children did not have complete proper advocacy from the people that worked with them. They were simply shuffled along and not given the proper education and care that they needed to be self-sufficient (Baldini, 1968). “Defend the weak and the fatherless; uphold the cause of the poor and oppressed. Rescue the weak and the needy; deliver them from the hand of the wicked” (Psalm 82:3-4, New International Version). It is our Godly duty to defend individuals who can not defend themselves. In His eyes we are all created equal and in that we all deserve equal treatment and opportunities.
References
Baldini, B. (1968). Suffer the Little Children: Pennhurst Pennsylvania State Home for Disabled Children [Video file]. Retrieved from
https://youtu.be/YG33HvIKOgQ
Slavin, R.E., & Schunk D.H. (2017). Learning Theories: EDUC 500 (1st ed.) Boston, MA: Pearson.
Van Brummelen, H. (2009). Walking wit.
Melissa is a 15-year-old high school student. Over the last week.docxwkyra78
Melissa is a 15-year-old high school student. Over the last week, she had been feeling tired and found it difficult to stay awake in class. By the time the weekend had arrived, she developed a sore throat that made it difficult to eat and even drink. Melissa was too tired to get out of bed, and she said her head ached. On Monday morning, her mother took her to her doctor. Upon completing the physical exam, he told Melissa the lymph nodes were enlarged in her neck and she had a fever. He ordered blood tests and told Melissa he thought she had mononucleosis, a viral infection requiring much bed rest.
Innate and adaptive immune defenses work collectively in destroying invasive microorganisms. What is the interaction between macrophages and T lymphocytes during the presentation of antigen?
Melissa’s illness is caused by a virus. Where are type I interferons produced, and why are they important in combating viral infections?
Humoral immunity involves the activation of B lymphocytes and production of antibodies. What are the general mechanisms of action that make antibodies a key component of an immune response?
.
1. The document describes measuring the angle θ between momentum vectors of particles π- and Σ- produced in a particle interaction using a bubble chamber photograph. The angle can be determined by drawing tangents to the particle tracks and measuring the angle between them.
2. An alternative method to measure the angle not requiring a protractor is described using ratios of distances along the tangents.
3. Instructions are given to estimate uncertainties in measurements taken from repeated readings using calculations of average and standard deviation.
Measurement of the angle θ For better understanding .docxwkyra78
Measurement of the angle θ
For better understanding I am showing you a different particle track diagram bellow. Where at
point C particle 𝜋 − 𝑎𝑛𝑑 Σ− are created and the Σ− decays into 𝜋 ∓ 𝑎𝑛𝑑 K− particles
The angle θ between the π− and Σ− momentum vectors can be determined by drawing tangents
to the π− and Σ− tracks at the point of the Σ− decay. We can then measure the angle between
the tangents using a protractor. Alternative method which does not require a protractor is also
possible. Let AC and BC be the tangents to the π− and Σ− tracks respectively. Drop a
perpendicular (AB) and measure the distances AB and BC. The ratio AB/BC gives the tangent of
the angle180◦−θ. It should be noted that only some of the time will the angle θ exceed 90◦ as
shown here.
Determining the uncertainty of Measurements
In part B, It is asked to estimate the uncertainty of your measurements of 𝜃 and r.
Uncertainty of measurement is the doubt that exists about the result of any measurement. You
might think that well-made rulers, clocks and thermometers should be trustworthy, and give
the right answers. But for every measurement - even the most careful - there is always a margin
of doubt.
It is important not to confuse the terms ‘error’ and ‘uncertainty’.
Error is the difference between the measured value and the ‘true value’ of the thing being
measured.
Uncertainty is a quantification of the doubt about the measurement result
Since there is always a margin of doubt about any measurement, we need to ask ‘How big is the
margin?’ and ‘How bad is the doubt?’ Thus, two numbers are really needed in order to quantify
an uncertainty. One is the width of the margin, or interval. The other is a confidence level, and
states how sure we are that the ‘true value’ is within that margin.
You can increase the amount of information you get from your measurements by taking a
number of readings and carrying out some basic statistical calculations. The two most
important statistical calculations are to find the average or arithmetic mean, and the standard
deviation for a set of numbers.
The ‘true’ value for the standard deviation can only be found from a very large (infinite) set of
readings. From a moderate number of values, only an estimate of the standard deviation can be
found. The symbol s is usually used for the estimated standard deviation.
Suppose you have a set of n readings. Start by finding the average:
For the set of readings x={16, 19, 18, 16, 17, 19, 20, 15, 17 and 13}, the average is �̅� =
∑ 𝑥𝑖
𝑛
=
17.
Next find (𝑥𝑖 − �̅�)
2
Then 𝑠 = √
(𝑥𝑖−�̅�)
2
𝑛−1
= 2.21
Lifetime calculation
In part C you are asked to determine the life time of the neutral particles from their
momentums.
The Σ− lifetime can be approximately determined using the measured values of the Σ− track
lengths. The average momentum of the Σ− particle can be found from its initial and fin
Meaning-Making Forum 2 (Week 5)Meaning-Making Forums 1-4 are thi.docxwkyra78
Meaning-Making Forum 2 (Week 5)
Meaning-Making Forums 1-4 are this course's unique final project.
Be fully engaged in Phase Two!
After reviewing the readings, presentations, lecture notes, articles, and web-engagements, and previous assignments, artificially move your predetermined careseeker (i.e., Crossroads’ Careseekers: Bruce, Joshua, Brody, Justin, or Melissa) through Phase Two.
NOTE: These research-based forums require that you draw upon ALL
of the course readings and learning activities to date, in order to substantively develop each phase in our
Solution
-based, Short-term, Pastoral Counseling (SbStPC) process. Noticeably support each core assertion.
Rapport and Relational Alignment.
Briefly discuss how you will continue to build rapport and shift your relational style in order to best align with the careseeker’s style (i.e., use DISC language) and current behavioral position (i.e., attending, blaming, or willing).
Phase Two Distinctive Features.
Narrate movement of careseeker through Phase Two’s distinctive features (i.e., purpose, goal, chief aim, role/responsibility, use of guiding assumptions) and apply pertinent insights and techniques from ALL the readings, previous assignments, and the Bible.
Supportive Feedback Break.
What portrait, definition(s), key thought(s), and/or assessment insight from the
Quick Reference Guide
might be utilized in the supportive feedback technique?
Phase Two Marker.
Describe a marker that indicates you have collaboratively ‘imagineered” a picture of life without the problem. In what way does this marker indicate the careseeker is in a willing position and ready for Phase Three?
Food for Thought:
When learning a new people skill or counseling technique, is it normal to “feel” awkward and fake? Use at least 1 example and thoughtfully explain how this “feeling” might be normalized.
TIPS:
Carefully Follow Meaning-Making Forum Guidelines & Tips!
Make sure to use headings (5) so that the most inattentive reader may easily follow your thoughts.
Use the annotated outline approach. Bullets should have concise, complete, well-developed sentences or paragraphs.
Foster a “noble-minded” climate for investigating claims through well-supported core assertions (i.e., consider the validation pattern of the Bereans; Acts 17:11).
Noticeably support assertions to facilitate further investigation and to avoid the appearance of plagiarism.
Since you have the required materials (e.g.,
Masterpiece)
, abridge any related citations (Nichols, p. 12) and do not list the required source in a References’ section.
Secondary sources must follow current APA guidelines for citations and References.
Make every effort to prove that you care about the subject matter by proofreading to eliminate grammar and spelling distractions.
A substantive thread (at least 450 words)
.
MBA6231 - 1.1 - project charter.docxProject Charter Pr.docxwkyra78
MBA6231 - 1.1 - project charter.docx
Project Charter
Project Charter
Student Name
Institution
Course Code
Project Title: Michael Joseph Place, The place to be
Project Start Date: 25/7/2018
Projected Finish Date: 25/12/2018
Budget Information: $ 4,500.00
Project Manager: Student name,[email protected], 210- 105 - 6676
Business Need
The project manager will be hosting an evening lounge event that will be targeting the clientele to an upscale lounge to be built in downtown. Through such an event the city will have a positive exposure.
There will be need for effective marketing, music, modern décor and most likely investors. The menu for food and drinks will need to be within budget. The venue needs to have amiable space and adequate seats for all guests.
The first step to this project involves coming up with a plan on a piece of paper. Once this is done the next step will involve selection of vendors to various goods and services. Once everything has been put to perspective the next stage will be to involve investors who will include local business owners. These investors will be encouraged to do so with the exchange for them to market and advertise their products at the event. We will have three packages for investors including Silver, Gold and Platinum packages.
Project Objectives
The proposal is to have a social entertainment evening lounge in Chicago. The project managers will be showcasing the new concept of entertainment by holding a series of events known as “The Place to be!”
· The events will be used to showcase the atmosphere that the new lounge will be offering
· The events will offer the professional audiences an opportunity to network while at the same time being entertained.
· The events will be targeting an audience of 150 attendants
· To have an environment where attendants can dance, dine and drink socially while discussing business.
Approach
This project will be managed in accordance with the PMI approach as modified.
Assumptions/Constraints/Dependencies
The assumption is that with the provision of an exquisite and upscale venue that is mature in Chicago, IL, will be successful due to the fact that there is no such a venue within a 100 mile radius.
One of the likely constraint is finding a venue that grabs attention of the targeted crowd.
The success of these events depends on attracting two sets of individuals. One of them is investors and the other is private professionals who will attend a social event at night.
Initial Risk Factors
· Obtaining a liquor license on time for the event is the major risk factor.
· Failure of attendees despite investing money and time is another risk.
· Failing to complete the organizational plans within 30 days before the event series begin.
· Not attracting any viable investors
Regulatory cost/impact
One of the needed licensing is from the city council where I will be required to get a special event license. This will enable us to have alcohol i.
Medication Errors Led to Disastrous Outcomes1. Search th.docxwkyra78
Medication Errors Led to Disastrous Outcomes
1. Search the internet and learn about the cases of nurses Julie Thao and Kimberly Hiatt.
2. List and discuss lessons that you and all healthcare professionals can learn from these two cases.
3. Describe how the principle of beneficence and the virtue of benevolence could be applied to these cases. Do you think the hospital administrators handled the situations legally and ethically?
4. In addition to benevolence, which other virtues exhibited by their colleagues might have helped Thao and Hiatt?
5. Discuss personal virtues that might be helpful to second victims themselves to navigate the grieving process.
.
Meet, call, Skype or Zoom with a retired athlete and interview himh.docxwkyra78
Meet, call, Skype or Zoom with a retired athlete and interview him/her about his or her transition experiences.
Please use this
interview guide
Actions
when conducting your interview.
Submit a minimum 400 word written reflection with the following:
Brief summary of the athlete's sport career transition
Main takeaways from the conversation
Advice you received and what you learned
Connection to course material
.
Medication Administration Make a list of the most common med.docxwkyra78
Medication Administration
Make a list of the most common medication administration errors and suggest steps that can be taken to prevent these errors.
APA format is required for this written assignment. This is a safe assign homework, no more that 20% of similarities permitted.
.
media portfolio”about chapter 1 to 15 from the book Ci.docxwkyra78
“media portfolio”
about chapter 1 to 15
from the book
Ciccarelli, S., & White, J. (2017).
Psychology
(5th Edition), Pearson.
which can include
newspaper,
magazine clippings
, and other media
that illustrate
psychological concepts covered in this course.
o
It is encouraged to be creative as possible and consider a wide variety of
sources which include: newspapers, magazines, editorials, advice and
medical columns, cartoons, etc. The sky is the l
imit!
o
A minimum of 15 clippings
should be included and should cover each
chapter
in the text book
(Chapters 1 through 15).
o
Each clipping should be explained by providing the source and how it is
related to a particular psychological concept, theory, or research finding
from the text or class lectures.
o
Sources should be in APA format!
Each “media clipping” should be on letter sized (8 ½ x 11) sized paper,
Paper can colored, etc...be creative!
.
Mediation
Name
AMU
Date
Mediation
Recently, I had a dispute with a friend based on sharing of roles and duties at work. If I were to use a mediation to solve the conflict I would have used facilitative mediation instead of evaluative mediation. Facilitative mediation refers to the types of solving conflicts where the mediator creates a process to assist the parties in reaching into a mutual agreement. Evaluative mediation on the other hand refers to the type of mediation where the judge helps the parties in reaching into a resolution through using the weakness of the case (Shrout & Bolger, 2017). The nature of the dispute plays a very huge role when choosing the type of mediation style to use. Since some cases can not fit well or makes it hard to find a solution when using a certain mediation style. For instance work related disputes and family related disputes require mediation that won’t seem to favor one party.
I would use transformative mediation, since it is mostly bases on improving the personal power of each party (Folberg & Taylor, 2016). Also transformative mediation mainly helps in creating a sense of understanding between the two parties through communication so as to solve the dispute. And lastly the reason why I would use the mediation is because; the process that is used does not favor one party. During the process, the mediator listens to both parties and from this he or she is able to help in making the two understand each other and be able to come into a mutual agreement.
References
Folberg, J., & Taylor, A. (2016). Mediation: A comprehensive guide to resolving conflicts without litigation.
Preacher, K. J., & Hayes, A. F. (2014). SPSS and SAS procedures for estimating indirect effects in simple mediation models. Behavior research methods, instruments, & computers, 36(4), 717-731.
Shrout, P. E., & Bolger, N. (2017). Mediation in experimental and nonexperimental studies: new procedures and recommendations. Psychological methods, 7(4), 422.
.
Media coverage influences the publics perception of the crimina.docxwkyra78
Media coverage influences the public's perception of the criminal justice system and the policy agendas of those within the system. This often results in changes within the operational structure of the police, courts, and corrections centers. These changes include the firing of employees, the initiation of internal investigations, and the privatization of services. Respond to the following questions, and support your positions using credible research:
Assignment Guidelines
Address the following in 1,250–1,750 words:
How is the criminal justice system portrayed in the media? Explain.
What impact do the media have on a viewer's perception as to the system's efficacy in dealing with crime? Explain.
Does coverage of sensationalistic and violent crime create fear among the general public? Explain.
Does this fear influence criminal justice policy attitudes? Explain in detail.
Is there a correlation between gender, education, income, age, and perceived neighborhood problems and police effectiveness in dealing with crime? Explain in detail.
In this assignment, external research is essential to successful submission. You must utilize at least 5–7 academic or scholarly external resources to support your arguments.
Be sure to reference all of your sources using APA style.
.
Media Content AnalysisPurpose Evaluate the quality and value of.docxwkyra78
Media Content Analysis
Purpose: Evaluate the quality and value of claims made and information presented by various authors.
Task: Write an essay in which you critically analyze at least 3 published commentaries/presentations related to an issue connected to social media. For each commentary/presentation, your analysis must include an evaluation of the evidence and reasoning presented as well as an examination of the value the commentary/presentation has for its intended audience and others. Compare and contrast various authors’ claims and perspectives.
Points: 200 (160 points from rubric-based assessment; 40 points for submitting a Reviewed Draft*).
Requirements:
Review a minimum of three substantive articles, videos, or presentations that have been published in major print or multimedia sources (e.g., a magazine article; a blog; a YouTube video),
Provide a brief, meaningful summary of each of the published presentations.
Analyze the quality of the claim, evidence, and reasoning in each presentation, with a focus on the validity and value of the presentations.
Use APA format – including in-text parenthetical citations along with a reference list at the end of the assignment.
Answer the following questions in your analysis:
What are the purpose, claims, evidence, and reasoning of each presentation?
What are the qualifications and authority of each author?
In what ways do the authors reflect bias? How do the authors account for their bias?
Are there any significant statements or omissions that might affect the reliability of the information or arguments presented?
Presentation Format:
1000 - 2,000 words
12 point, Times New Roman or Arial Font
Double-Spaced
APA format for body and References page
Follow the paragraph format below to be sure that you have covered all the requirements for the topic you have chosen:
Paragraph #1 1st article title, author and their qualifications along with a summary of it. 20 points
Paragraph #2 2nd article title/presentation, author and their qualifications along with a summary of it 20 points
Paragraph #3 3rd article title/presentation, author and their qualifications and of course a summary of it. 20 points
Paragraph #4 compare and contrast the purpose and the claims of each of the three authors 20 points
Paragraph #5 compare and contrast the evidence shown and the reasoning of each author/presentation 30 points
Paragraph #6 in what ways do the author's reflect bias/fallacies and how do they account for them? 20 points
Paragraph #7 Are there any significant statements or omissions that might affect the reliability of the
information or arguments presented? Which one drew your attention and why? 20 points
APA References alphabetized, double spaced and indented on t.
Mayan gods and goddesses are very much a part of this text. Their i.docxwkyra78
Mayan gods and goddesses are very much a part of this text. Their interactions with one another and later with humans form a major part of our reading. How are the gods and goddesses portrayed in this text? How are those portrayals similar to or different from other representations of gods we have encountered?
.
Media and SocietyIn 1,100 words, complete the followingAn.docxwkyra78
Media and Society
In 1,100 words, complete the following:
Analyze two ways that media affect culture and society. Identify at least one positive and one negative implication arising from technology’s effect on society.
Media has changed exponentially over the past 25 years with the introduction of the Internet and social media. How can people enhance their media literacy? Identify one to two challenges that media will introduce for society in the next 20-30 years and how people can use their media literacy to meet these challenges.
Prepare this assignment according to the guidelines found in the APA Style Guide, located in the Student Success Center. An abstract is not required.
This assignment uses a rubric. Please review the rubric prior to beginning the assignment to become familiar with the expectations for successful completion.
You are required to submit this assignment to LopesWrite. Refer to the
LopesWrite Technical Support articles
for assistance.
FOLLOW THE RUBRIC- CHECK YOUR FINAL PAPER WITH THE ATTACHED RUBRIC!
.
MBA 5110 – Business Organization and ManagementMidterm ExamAns.docxwkyra78
MBA 5110 – Business Organization and Management
Midterm Exam
Answer each of the following questions in this document, inserting your answers between each question. You may use your textbook and notes, but you may not consult with another individual. You may not use the Internet for assistance in answering these questions. Each question should be answered with a minimum of one paragraph, properly formatted according to APA 6th edition guidelines and referencing your textbook. Please list your textbook in a reference section at the end of this document. Submit this Word document with your answers to Moodle.
1. How have organizational structures and management styles changed over the past century?
2. Explain the concept of open and closed systems and how this relates to organization theory.
3. Define each of Porter’s Competitive Strategies and give an example of a company using each of these strategies.
4. Compare vertical and horizontal organizational structures in terms of effectiveness and adaptability in the rapidly changing business environment.
5. Choose one of the following theories and explain the theory. Give an example of a company that demonstrates the chosen theory and how the company uses the theory.
Theories: Chaos Theory, Resource-Dependence Theory, Population-Ecology Perspective, Contingency Theory, or Organizational Learning Theory
Response 1 PD
Question 1
A set of beliefs, norms and values that is shared by a group, culture is a systemic sense that can create a common commitment to an organization’s mission. With identifying markers that extend beyond the individual, it can be represented in a fabric of shared themes and feelings. Whether displayed in forms of dress, symbols, verbal phrases or typical behaviors, its permeance can be silent in its mode of action, yet quite visible to internal and external stakeholders (Daft, 2018).
Serving two fundamental and critical functions, the culture of an organization can be a catalyst in uniting members in how they relate to one another within the organization and how the members follow the same process in relation to the outside environment (Daft, 2018). However, although it is often associated with ethical decision making (Kara, Rojas-Mendez & Turan), the element of inequality can create fear and discourse if an unrealistic and bias culture themes are dictated, thus resulting in disagreement or conflict with management. Therefore, the perception of stakeholders or groups of interest regarding the cultural practices of the organization may not be entirely correct (Gonzalez-Rodriguez, Diaz-Fernández & Biagio, 2019).
Directly related to the perception of the value system of the organization and its management, the acceptable cultural differences that shape the internal behavior of members can have an impact in external relationships (Gonzalez-Rodriguez, Diaz-Fernández & Biagio, 2019). However, as Daft (2018) noted, a mechanistic or controlling system may block any organic input,.
Temple of Asclepius in Thrace. Excavation resultsKrassimira Luka
The temple and the sanctuary around were dedicated to Asklepios Zmidrenus. This name has been known since 1875 when an inscription dedicated to him was discovered in Rome. The inscription is dated in 227 AD and was left by soldiers originating from the city of Philippopolis (modern Plovdiv).
Gender and Mental Health - Counselling and Family Therapy Applications and In...PsychoTech Services
A proprietary approach developed by bringing together the best of learning theories from Psychology, design principles from the world of visualization, and pedagogical methods from over a decade of training experience, that enables you to: Learn better, faster!
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏)-𝐏𝐫𝐞𝐥𝐢𝐦𝐬
𝐃𝐢𝐬𝐜𝐮𝐬𝐬 𝐭𝐡𝐞 𝐄𝐏𝐏 𝐂𝐮𝐫𝐫𝐢𝐜𝐮𝐥𝐮𝐦 𝐢𝐧 𝐭𝐡𝐞 𝐏𝐡𝐢𝐥𝐢𝐩𝐩𝐢𝐧𝐞𝐬:
- Understand the goals and objectives of the Edukasyong Pantahanan at Pangkabuhayan (EPP) curriculum, recognizing its importance in fostering practical life skills and values among students. Students will also be able to identify the key components and subjects covered, such as agriculture, home economics, industrial arts, and information and communication technology.
𝐄𝐱𝐩𝐥𝐚𝐢𝐧 𝐭𝐡𝐞 𝐍𝐚𝐭𝐮𝐫𝐞 𝐚𝐧𝐝 𝐒𝐜𝐨𝐩𝐞 𝐨𝐟 𝐚𝐧 𝐄𝐧𝐭𝐫𝐞𝐩𝐫𝐞𝐧𝐞𝐮𝐫:
-Define entrepreneurship, distinguishing it from general business activities by emphasizing its focus on innovation, risk-taking, and value creation. Students will describe the characteristics and traits of successful entrepreneurs, including their roles and responsibilities, and discuss the broader economic and social impacts of entrepreneurial activities on both local and global scales.
1. proj6/Collision.javaproj6/Collision.javapackage proj6;
import java.util.ArrayList;
/**
* Collision objects represent individual collisions occuring on
NYC streets.
* Each object contains information regarding the time, location
, number
* of injuries and fatalities and types of involved vehicles.
* @author Joanna K.
*
*/
publicclassCollisionimplementsComparable<Collision>{
staticprivateSortOrder sortOrder =SortOrder.ZIP;
privateString date;
privateString time;
privateString borough;
privateString zip;
privateint personsInjured;
privateint personsKilled;
privateint pedestriansInjured;
privateint pedestriansKilled;
privateint cyclistsInjured;
privateint cyclistsKilled;
privateint motoristsInjured;
privateint motoristsKilled;
privateString vehicleCode1;
privateString vehicleCode2;
privateString uniqueKey;
2. /**
* Creates a Collision object given an array of entries.
* There should be 21 string entries in the following order:
* date
* time
* borough
* zip
* lattitude^
* longitude ^
* on street name^
* cross street name ^
* personsInjured
* personsKilled
* pedestriansInjured
* pedestriansKilled
* cyclistsInjured
* cyclistsKilled
* motoristsInjured
* motoristsKilled
* contributing factor vehicle 1^
* contributing factor vehicle 2^
* uniqueKey
* vehicleCode1
* vehicleCode2
* The entries indicated with ^ are not used.
*
* @param entries an array of entries containing information
about the
* collision
* @throws IllegalArgumentException when the Collision obj
ect cannot be created
* due to errors or incompleteness of the entries parameter
*/
3. publicCollision(ArrayList<String> entries )throwsIllegalArgum
entException{
date = entries.get(0);
time = entries.get(1);
borough = entries.get(2);
zip = entries.get(3);
if(!verifyZip(zip)){
thrownewIllegalArgumentException("invalid zip");
}
try{
personsInjured =Integer.parseInt(entries.get(8));
personsKilled =Integer.parseInt(entries.get(9));
pedestriansInjured =Integer.parseInt(entries.get(10));
pedestriansKilled =Integer.parseInt(entries.get(11));
cyclistsInjured =Integer.parseInt(entries.get(12));
cyclistsKilled =Integer.parseInt(entries.get(13));
motoristsInjured =Integer.parseInt(entries.get(14));
motoristsKilled =Integer.parseInt(entries.get(15));
}
catch(NumberFormatException ex ){
thrownewIllegalArgumentException( ex.getMessage());
}
uniqueKey = entries.get(18);
vehicleCode1 = entries.get(19);
vehicleCode2 = entries.get(20);
}
/*
* Verifies accuracy of the zip code.
* @param zip the zip code to be verified
* @return true if zip is a valid zip code, false otherwise
*/
privateboolean verifyZip (String zip ){
4. if( zip.length()!=5)returnfalse;
for(int i =0; i < zip.length(); i++){
if(!Character.isDigit( zip.charAt(i))){
returnfalse;
}
}
returntrue;
}
/**
* Computes and returns string representation of this Collisio
n object.
* @see java.lang.Object#toString()
*/
@Override
publicString toString(){
return"Collision [date="+ date +", time="+ time +", borough="+
borough +", zip="+ zip
+", personsInjured="+ personsInjured +", personsKilled="+ pers
onsKilled +", pedestriansInjured="
+ pedestriansInjured +", pedestriansKilled="+ pedestriansKilled
+", cyclistsInjured="
+ cyclistsInjured +", cyclistsKilled="+ cyclistsKilled +", motori
stsInjured="+ motoristsInjured
+", motoristsKilled="+ motoristsKilled +", vehicleCode1="+ ve
hicleCode1 +", vehicleCode2="
+ vehicleCode2 +", uniqueKey="+ uniqueKey +"]";
}
/**
* Set the sort order for Collision objects to be one of the all
owed values by the SortOrder enumerator.
* @param sortOrder the sortOrder to set
5. */
publicstaticvoid setSortOrder(SortOrder sortOrder){
Collision.sortOrder = sortOrder;
}
/**
* Compares two Collision objects based on their zip code, n
umber of cyclist-injuries or
* number of person-
injuries. The comparison is determined by the value of a flag set
by
* setSortOrder() method.
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
publicint compareTo(Collision other){
if( sortOrder ==SortOrder.ZIP ){
returnthis.zip.compareTo(other.zip);
}
elseif(sortOrder ==SortOrder.CYCLISTS){
return((this.cyclistsInjured +this.cyclistsKilled)
-(other.cyclistsInjured +this.cyclistsKilled ));
}
elseif(sortOrder ==SortOrder.PERSONS){
return((this.personsInjured +this.personsKilled)
-(other.personsInjured +this.personsKilled ));
}
return0;
}
/**
* Return the time of this Collision object.
* @return the time
*/
publicString getTime(){
return time;
6. }
/**
* Return the zip code of this Collision object.
* @return the zip
*/
publicString getZip(){
return zip;
}
/**
* Return the number of injured cyclists of this Collision obje
ct.
* @return the cyclistsInjured
*/
publicint getCyclistsInjured(){
return cyclistsInjured;
}
/**
* Return the number of killed cyclists of this Collision objec
t.
* @return the cyclistsKilled
*/
publicint getCyclistsKilled(){
return cyclistsKilled;
}
/**
* Return the number of injured persons of this Collision obje
ct.
* @return the personsInjured
*/
publicint getPersonsInjured(){
return personsInjured;
}
7. /**
* Return the number of killed persons of this Collision objec
t.
* @return the personsKilled
*/
publicint getPersonsKilled(){
return personsKilled;
}
/**
* Return the number of injured pedestrians of this Collision
object.
* @return the pedestriansInjured
*/
publicint getPedestriansInjured(){
return pedestriansInjured;
}
/**
* Return the number of killed pedestrians of this Collision o
bject.
* @return the pedestriansKilled
*/
publicint getPedestriansKilled(){
return pedestriansKilled;
}
/**
* Return the number of injured motorists of this Collision ob
ject.
* @return the motoristsInjured
*/
publicint getMotoristsInjured(){
8. return motoristsInjured;
}
/**
* Return the number of killed motorists of this Collision obj
ect.
* @return the motoristsKilled
*/
publicint getMotoristsKilled(){
return motoristsKilled;
}
/**
* Return the vehicle 1 of this Collision object.
* @return the vehicleCode1
*/
publicString getVehicleCode1(){
return vehicleCode1;
}
/**
* Return the vehicle 2 of this Collision object.
* @return the vehicleCode2
*/
publicString getVehicleCode2(){
return vehicleCode2;
}
}
proj6/CollisionInfo.javaproj6/CollisionInfo.java
9. package proj6;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This is a program that computes some information about the d
ata posted by
* OpenNYC regarding the collision records on the streets of N
YC.
*
* @author Joanna K.
*
*/
publicclassCollisionInfo{
/**
* The main method that starts the program. It is responsible
for opening and reading the
* input file, creating the CollisionList object and using it co
mpute the
* predetermined results.
* @param args the array should contain the name of the inpu
t file as the first element,
* all other elements are ignored
* @throws FileNotFoundException if the input file is corrup
ted or vanishes during the
* execution of this program
*/
publicstaticvoid main(String[] args)throwsFileNotFoundExcepti
on{
finalint NUM_OF_ENTRIES =21;
long startTimer, elapsedTime1, elapsedTime2;
10. startTimer =System.nanoTime();
if(args.length <1){
System.err.println("File name missing");
System.exit(0);
}
File fileName =newFile(args[0]);
if(!fileName.canRead()){
System.err.printf("Cannot read from file %sn.", fileName.getA
bsolutePath());
System.exit(0);
}
Scanner fin =newScanner(fileName);
CollisionList list =newCollisionList();
while( fin.hasNextLine()){
String textLine = fin.nextLine();
ArrayList<String> words = split (textLine );
if(words.size()!= NUM_OF_ENTRIES){
continue;//skip lines that are not complete
}
list.add(words);
}
elapsedTime1 =System.nanoTime()- startTimer;
startTimer =System.nanoTime();
//task 1
System.out.println("ZIP codes with the largest number of collisi
ons:");
11. System.out.println( list.getZipCodesWithMostCollisions(3));
//task2
System.out.println("ZIP codes with the fewest number of collisi
ons:");
System.out.println( list.getZipCodesWithLeastCollisions(3));
//task 3
System.out.println("ZIP codes with the most injuries and fataliti
es (combined):");
System.out.println( list.getZipCodesWithMostPersonIncidents(3
));
//task 4
System.out.println("ZIP codes with the most cyclist injuries and
fatalities:");
System.out.println( list.getZipCodesWithMostCyclistIncidents(3
));
//task5:
System.out.println("Percentage of collisions involving certain v
ehicle type:");
System.out.println(list.getVehicleTypeStats());
//task6:
System.out.println("Fraction of collisions by hour:");
System.out.println(list.getHourlyStats());
elapsedTime2 =System.nanoTime()- startTimer;
System.out.println("nn=============================
===============n");
System.out.printf("Reading and storing data: %,15d nanosecond
sn", elapsedTime1);
System.out.printf("Computation of results : %,15d nanoseconds
n", elapsedTime2);
12. fin.close();
}
/**
* Splits a given line according to commas (commas within e
ntries are ignored)
* @param textLine line of text to be parsed
* @return an ArrayList object containing all individual entri
es/tokens
* found on the line.
*/
publicstaticArrayList<String> split (String textLine ){
ArrayList<String> entries =newArrayList<String>();
int lineLength = textLine.length();
StringBuffer nextWord =newStringBuffer();
char nextChar;
boolean insideQuotes =false;
for(int i =0; i < lineLength; i++){
nextChar = textLine.charAt(i);
//add character to the current entry
if( nextChar !=','&& nextChar !='"'){
nextWord.append( nextChar );
}
//double quote found, decide if it is opening or closing one
elseif(nextChar =='"'){
if( insideQuotes ){
insideQuotes =false;
}
else{
insideQuotes =true;
}
}
13. //found comma inside double quotes, just add it to the string
elseif(nextChar ==','&& insideQuotes){
nextWord.append( nextChar );
}
//end of the current entry reached, add it to the list of entries
//and reset the nextWord to empty string
elseif(nextChar ==','&&!insideQuotes){
//trim the white space before adding to the list
entries.add( nextWord.toString().trim());
nextWord =newStringBuffer();
}
else{
System.err.println("This should never be printed.n");
}
}
//add the last word
//trim the white space before adding to the list
entries.add( nextWord.toString().trim());
return entries;
}
}
proj6/CollisionList.javaproj6/CollisionList.javapackage proj6;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* CollisionList class stores a list of collisions. The organizatio
14. n of this list is
* based on the zip code associated with a given collision. This
organization simplifies
* processing of collisions that occur within a particular zip cod
e.
* @author Joanna K.
*/
publicclassCollisionList{
privateArrayList<ZipCodeList> list;
/**
* Creates an empty CollisionList object.
*/
publicCollisionList(){
list =newArrayList<ZipCodeList>();
}
/**
* Adds a particular record to this CollisionList object.
* The record should consist of 21 string entries in the follow
ing order:
* date
* time
* borough
* zip
* lattitude^
* longitude ^
* on street name^
* cross street name ^
* personsInjured
* personsKilled
* pedestriansInjured
* pedestriansKilled
15. * cyclistsInjured
* cyclistsKilled
* motoristsInjured
* motoristsKilled
* contributing factor vehicle 1^
* contributing factor vehicle 2^
* uniqueKey
* vehicleCode1
* vehicleCode2
* The entries indicated with ^ are not used.
*
* @param record an list of string describing a particular coll
ision (see above
* for order of entries)
* @return true if the record was added to this CollisionList
object, false if any
* problem occurred and the record was not added
*/
publicboolean add (ArrayList<String> record ){
try{
Collision col =newCollision(record);
ZipCodeList tmp =newZipCodeList(col);
int index = list.indexOf(tmp);
if(index >=0){//add the collision object to the existing zip code
list
list.get(index).add(col);
}
else{//add the new zip code list
list.add(tmp);
}
}
catch(IllegalArgumentException ex ){
returnfalse;//return false if the Collision constructor failed
}
16. returntrue;//return true to indicate that the object was added
}
/**
* Determines k zip codes with most collisions in this Collisi
onList object.
* @param k number of zip codes with the highest number of
collisions
* @return a string formatted as
* zip numOfCollisions
* one per line, that contains k zip codes with the highest nu
mber of collisions
*/
publicString getZipCodesWithMostCollisions (int k){
@SuppressWarnings("unchecked")
ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>)
list.clone();
//sort the list
Collections.sort(sortedList,newCompareByNumOfCollisionsDes
cending());
StringBuffer result =newStringBuffer();
int count =0;
for(int i =0; i < k && i < sortedList.size()&& count<sortedList.
size(); i++){
do{
result.append(String.format(" %5s %5d collisions
n",sortedList.get(count).getZip(),
sortedList.get(count).getTotalNumOfCollisions()))
;
count++;
}while( count+1< sortedList.size()
17. && sortedList.get(count).getTotalNumOfCollisions()
== sortedList.get(count+1).getTotalNumOfCollisions());
}
return result.toString();
}
/**
* Determines k zip codes with least collisions in this Collisi
onList object.
* @param k number of zip codes with the lowest number of
collisions
* @return a string formatted as
* zip numOfCollisions
* one per line, that contains k zip codes with the lowest nu
mber of collisions
*/
publicString getZipCodesWithLeastCollisions (int k){
@SuppressWarnings("unchecked")
ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>)
list.clone();
//sort the list
Collections.sort(sortedList,newCompareByNumOfCollisionsAsc
ending());
StringBuffer result =newStringBuffer();
int count =0;
for(int i =0; i < k && i < sortedList.size()&& count<sortedList.
size(); i++){
do{
result.insert(0,String.format(" %5s %5d collisions
n",sortedList.get(count).getZip(),
sortedList.get(count).getTotalNumOfCollisions()))
18. ;
count++;
}while( count+1< sortedList.size()
&& sortedList.get(count).getTotalNumOfCollisions()
== sortedList.get(count+1).getTotalNumOfCollisions());
}
return result.toString();
}
/**
* Determines k zip codes with most number of collisions inv
olving
* cyclists in this CollisionList object.
* @param k number of zip codes with the highest number of
collisions that involved cyclists
* @return a string formatted as
* zip numOfCycliststHurt (numOfCyclists killed)
* one per line, that contains k zip codes with the highest nu
mber of injured cyclists
*/
publicString getZipCodesWithMostCyclistIncidents (int k ){
@SuppressWarnings("unchecked")
ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>)
list.clone();
//sort the list
CompareByNumOfCyclistsIncidentsDescending comp =newCom
pareByNumOfCyclistsIncidentsDescending();
Collections.sort(sortedList, comp );
StringBuffer result =newStringBuffer();
int inj =0, killed =0;
19. int count =0;
for(int i =0; i < k && i < sortedList.size()&& count< sortedList.
size(); i++){
do{
inj = sortedList.get(count).getTotalNumOfCyclistsInj
ured();
killed = sortedList.get(count).getTotalNumOfCyclist
sKilled();
result.append(String.format(" %5s %5d (%3d kille
d ) cyclists hurtn", sortedList.get(count).getZip(),
inj + killed, killed ));
count++;
}
while( count+1< sortedList.size()
&&0== comp.compare(sortedList.get(count), sortedList.get(cou
nt+1)));
}
return result.toString();
}
/**
* Determines k zip codes with most number of injured and ki
lled persons.
* @param k number of zip codes with the highest number of
injured and killed persons
* @return a string formatted as
* zip numOfPersonsHurt (numOfPersons killed)
* one per line, that contains k zip codes with the highest nu
mber of injured persons
*/
publicString getZipCodesWithMostPersonIncidents (int k ){
@SuppressWarnings("unchecked")
20. ArrayList<ZipCodeList> sortedList =(ArrayList<ZipCodeList>)
list.clone();
//sort the list
CompareByNumOfPersonsIncidentsDescending comp =newCom
pareByNumOfPersonsIncidentsDescending();
Collections.sort(sortedList, comp );
StringBuffer result =newStringBuffer();
int inj =0, killed =0;
int count =0;
for(int i =0; i < k && i < sortedList.size()&& count< sortedList.
size(); i++){
do{
inj = sortedList.get(count).getTotalNumOfPersonsInj
ured();
killed = sortedList.get(count).getTotalNumOfPerson
sKilled();
result.append(String.format(" %5s %5d (%3d kille
d ) persons hurtn", sortedList.get(count).getZip(),
inj + killed, killed ));
count++;
}
while( count+1< sortedList.size()
&&0== comp.compare(sortedList.get(count), sortedList.get(cou
nt+1)));
}
return result.toString();
}
/**
* Computes percentage of total collisions in this CollisionLi
st object that involved one
21. * of the following vehicle types: taxi, bus, bicycle, truck, fir
e truck and ambulance.
* @return a string containing the results of the computation
*/
publicString getVehicleTypeStats (){
String result =newString();
int taxi =0;
int bus =0;
int bicycle =0;
int fireTruck =0;
int ambulance =0;
int totalNumOfCollisions =0;
for(ZipCodeList l : list ){
totalNumOfCollisions += l.getTotalNumOfCollisions();
for(Collision c : l ){
if(c.getVehicleCode1().equalsIgnoreCase("taxi")||
c.getVehicleCode2().equalsIgnoreCase("taxi"))
taxi++;
if(c.getVehicleCode1().equalsIgnoreCase("bus")||
c.getVehicleCode2().equalsIgnoreCase("bus"))
bus++;
if(c.getVehicleCode1().equalsIgnoreCase("bicycle")||
c.getVehicleCode2().equalsIgnoreCase("bicycle
")) bicycle++;
if(c.getVehicleCode1().equalsIgnoreCase("fire truck")||
c.getVehicleCode2().equalsIgnoreCase("fire tru
ck")) fireTruck++;
if(c.getVehicleCode1().equalsIgnoreCase("ambulance")||
c.getVehicleCode2().equalsIgnoreCase("ambula
nce")) ambulance++;
}
}
22. //create a string object with results
result +=String.format(" %-
11s %5.2f%%n","taxi",(float)(taxi)/totalNumOfCollisions*100)
;
result +=String.format(" %-
11s %5.2f%%n","bus",(float)(bus)/totalNumOfCollisions*100);
result +=String.format(" %-
11s %5.2f%%n","bicycle",(float)(bicycle)/totalNumOfCollision
s*100);
result +=String.format(" %-
11s %5.2f%%n","fire truck",(float)(fireTruck)/totalNumOfColl
isions*100);
result +=String.format(" %-
11s %5.2f%%n","ambulance",(float)(ambulance)/totalNumOfC
ollisions*100);
return result;
}
/**
* Computes percentage of total collisions in this CollisionLi
st object that occured within
* a particular hour. The collisions are placed into bins of 1 h
our intervals.
* @return a string containing the results of the computation
*/
publicString getHourlyStats (){
StringBuffer result =newStringBuffer();
//counter for each hour
int[] hourlyCount =newint[24];
String hour ="", time ="";
StringBuffer bar;
int totalNumOfCollisions =0;
23. for(ZipCodeList l : list ){
totalNumOfCollisions += l.getTotalNumOfCollisions();
for(Collision c : l ){
try{
//extract the hour from the time entry
time = c.getTime();
hour = time.substring(0,time.indexOf(':')).trim();
//increment counter for that hour
hourlyCount[Integer.parseInt(hour)]++;
}catch(IndexOutOfBoundsException e){
//ignore incorrectly formed times
}catch(NumberFormatException e ){
//ignore incorrectly formed times
}
}
}
for(int i =0; i <24; i++){
//determine number of "bars" to be printed for visual representat
ion of
//the histogram
int numOfBars =(int)(((double)hourlyCount[i]/totalNumOfColli
sions)*240);
bar =newStringBuffer(numOfBars);
for(int j =0; j < numOfBars; j++)
bar.append("|");
result.append(String.format("%3d h %5.1f%% %s%n",
i,100.0*hourlyCount[i]/totalNumOfCollisions, bar.
toString()));
}
return result.toString();
}
}
24. /*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of collisions occurring in each. The resulting order is
ascending.
* @author Joanna K.
*
*/
classCompareByNumOfCollisionsAscendingimplementsCompar
ator<ZipCodeList>{
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java
.lang.Object)
*/
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
return arg0.getTotalNumOfCollisions()-
arg1.getTotalNumOfCollisions();
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of collisions occurring in each. The resulting order is
descending.
* @author Joanna K.
*
*/
classCompareByNumOfCollisionsDescendingimplementsCompa
rator<ZipCodeList>{
25. /* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java
.lang.Object)
*/
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
return arg1.getTotalNumOfCollisions()-
arg0.getTotalNumOfCollisions();
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of injured persons. The resulting order is descending.
Ties are resolved
* based on the number of killed persons.
* @author Joanna K.
*
*/
classCompareByNumOfPersonsIncidentsDescendingimplements
Comparator<ZipCodeList>{
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
int diff =( arg1.getTotalNumOfPersonsInjured()+ arg1.getTotal
NumOfPersonsKilled())
-
( arg0.getTotalNumOfPersonsInjured()+ arg0.getTotalNumOfPe
rsonsKilled());
if(diff !=0)
return diff;
elsereturn( arg1.getTotalNumOfPersonsKilled()-
arg0.getTotalNumOfPersonsKilled());
26. }
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of injured persons. The resulting order is ascending.
Ties are resolved
* based on the number of killed persons.
* @author Joanna K.
*
*/
classCompareByNumOfPersonsIncidentsAscendingimplementsC
omparator<ZipCodeList>{
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
int diff =-
( arg1.getTotalNumOfPersonsInjured()+ arg1.getTotalNumOfPe
rsonsKilled())
+( arg0.getTotalNumOfPersonsInjured()+ arg0.getTotalNumOfP
ersonsKilled());
if(diff !=0)
return diff;
elsereturn(-
arg1.getTotalNumOfPersonsKilled()+ arg0.getTotalNumOfPerso
nsKilled());
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
27. * number of injured cyclists. The resulting order is descending.
Ties are resolved
* based on the number of killed cyclists.
* @author Joanna K.
*
*/
classCompareByNumOfCyclistsIncidentsDescendingimplements
Comparator<ZipCodeList>{
@Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
int diff =( arg1.getTotalNumOfCyclistsInjured()+ arg1.getTotal
NumOfCyclistsKilled())
-
( arg0.getTotalNumOfCyclistsInjured()+ arg0.getTotalNumOfC
yclistsKilled());
if(diff !=0)
return diff;
elsereturn( arg1.getTotalNumOfCyclistsKilled()-
arg0.getTotalNumOfCyclistsKilled());
}
}
/*
* Comparator class for comparing two @see ZipCodeList objec
ts based on the
* number of injured cyclists. The resulting order is ascending.
Ties are resolved
* based on the number of killed cyclists.
* @author Joanna K.
*
*/
classCompareByNumOfCyclistsIncidentsAscendingimplementsC
omparator<ZipCodeList>{
28. @Override
publicint compare(ZipCodeList arg0,ZipCodeList arg1){
int diff =-
( arg1.getTotalNumOfCyclistsInjured()+ arg1.getTotalNumOfC
yclistsKilled())
+( arg0.getTotalNumOfCyclistsInjured()+ arg0.getTotalNumOf
CyclistsKilled());
if(diff !=0)
return diff;
elsereturn(-
arg1.getTotalNumOfCyclistsKilled()+ arg0.getTotalNumOfCycl
istsKilled());
}
}
proj6/SortOrder.javaproj6/SortOrder.javapackage proj6;
/**
* Enumerator used to decide on sort order of Collision objects.
* @author Joanna K.
*
*/
enum SortOrder{ ZIP, CYCLISTS, PERSONS}
proj6/ZipCodeList.javaproj6/ZipCodeList.javapackage proj6;
import java.util.ArrayList;
import java.util.Iterator;
/**
* ZipCodeList contains collision objects that all occured in the
29. same zip
* code. It keeps track of additional information like total numb
er of
* collisions, injuries and fatalities.
* @author Joanna K.
*
*/
publicclassZipCodeListimplementsIterable<Collision>,Compara
ble<ZipCodeList>{
privateArrayList<Collision> list;
privateString zip;
privateint totalNumOfCollisions;
privateint totalNumOfPersonsInjured;
privateint totalNumOfPersonsKilled;
privateint totalNumOfCyclistsInjured;
privateint totalNumOfCyclistsKilled;
privateint totalNumOfPedestriansInjured;
privateint totalNumOfPedestriansKilled;
privateint totalNumOfMotoristsInjured;
privateint totalNumOfMotoristsKilled;
/**
* Creates a ZipCodeList objects based on the first collision.
The
* zip code for this ZipCodeList is set to the zip code
* associated with the collision col.
* @param col the initial collisions for this ZipCodeList obje
ct
*/
publicZipCodeList(Collision col ){
list =newArrayList<Collision>();
zip = col.getZip();
add(col);
30. }
/**
* Adds another Collision object to this ZipCodeList object.
* @param col a Collision object to be added to this ZipCode
List object
* @throws IllegalArgumentException when the zip code of t
he new Collision
* object col is not the same as the zip code for this ZipCode
List object
*/
publicvoid add (Collision col)throwsIllegalArgumentException{
if(col ==null)return;
if(!col.getZip().equals(zip))
thrownewIllegalArgumentException("Error: zip codes are not m
atching. ");
list.add(col);
totalNumOfCollisions ++;
totalNumOfPersonsInjured += col.getPersonsInjured();
totalNumOfPersonsKilled += col.getPersonsKilled();
totalNumOfCyclistsInjured += col.getCyclistsInjured();
totalNumOfCyclistsKilled += col.getCyclistsKilled();
totalNumOfPedestriansInjured += col.getPedestriansInjure
d();
totalNumOfPedestriansKilled += col.getPedestriansKilled(
);
totalNumOfMotoristsInjured += col.getMotoristsInjured();
totalNumOfMotoristsKilled += col.getMotoristsKilled();
}
/**
* Returns an iterator for this ZipCodeList object.
* @see java.lang.Iterable#iterator()
31. */
@Override
publicIterator<Collision> iterator(){
return list.iterator();
}
/**
* Computes the hash code for this ZipCodeList object. The h
ashcode
* is based on the zip code associated with this object.
* @see java.lang.Object#hashCode()
*/
@Override
publicint hashCode(){
finalint prime =31;
int result =1;
result = prime * result +((zip ==null)?0: zip.hashCode());
return result;
}
/**
* Returns true if this ZipCodeList object and the parameter h
ave the
* same zip code associated with them. Returns false otherwis
e.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
publicboolean equals(Object obj){
if(this== obj)
returntrue;
if(obj ==null)
returnfalse;
if(getClass()!= obj.getClass())
32. returnfalse;
ZipCodeList other =(ZipCodeList) obj;
if(zip ==null){
if(other.zip !=null)
returnfalse;
}elseif(!zip.equals(other.zip))
returnfalse;
returntrue;
}
/**
* Compares two ZioCodeList objects based on the zip code v
alue stored in them.
* The results are based on string comparison of the two zip c
odes.
* @see java.lang.Comparable#compareTo(java.lang.Object)
* Compares two ZipCodeList objects based on the zip codes.
*/
@Override
publicint compareTo(ZipCodeList o){
return zip.compareTo(o.zip);
}
/**
* Returns the zip code of this ZipCodeList object
* @return the zip
*/
publicString getZip(){
return zip;
}
/**
33. * Returns the total number of collisions of this ZipCodeList
object
* @return the totalNumOfCollisions
*/
publicint getTotalNumOfCollisions(){
return totalNumOfCollisions;
}
/**
* Returns the total number of persons injured of this ZipCo
deList object
* @return the totalNumOfPersonsInjured
*/
publicint getTotalNumOfPersonsInjured(){
return totalNumOfPersonsInjured;
}
/**
* Returns the total number of persons killed of this ZipCode
List object
* @return the totalNumOfPersonsKilled
*/
publicint getTotalNumOfPersonsKilled(){
return totalNumOfPersonsKilled;
}
/**
* Returns the total number of cyclists injured of this ZipCo
deList object
* @return the totalNumOfCyclistsInjured
*/
publicint getTotalNumOfCyclistsInjured(){
return totalNumOfCyclistsInjured;
}
/**
34. * Returns the total number of cyclists killed of this ZipCode
List object
* @return the totalNumOfCyclistsKilled
*/
publicint getTotalNumOfCyclistsKilled(){
return totalNumOfCyclistsKilled;
}
/**
* Returns the total number of pedestrians injured of this Zip
CodeList object
* @return the totalNumOfPedestriansInjured
*/
publicint getTotalNumOfPedestriansInjured(){
return totalNumOfPedestriansInjured;
}
/**
* Returns the total number of pedestrians killed of this ZipC
odeList object
* @return the totalNumOfPedestriansKilled
*/
publicint getTotalNumOfPedestriansKilled(){
return totalNumOfPedestriansKilled;
}
/**
* Returns the total number of motorists injured of this ZipC
odeList object
* @return the totalNumOfMotoristsInjured
*/
publicint getTotalNumOfMotoristsInjured(){
return totalNumOfMotoristsInjured;
}
/**
35. * Returns the total number of motorists killed of this ZipCo
deList object
* @return the totalNumOfMotoristsKilled
*/
publicint getTotalNumOfMotoristsKilled(){
return totalNumOfMotoristsKilled;
}
/**
* Computes and returns a string representation of this ZipCo
deList object.
* @see java.lang.Object#toString()
*/
@Override
publicString toString(){
return"ZipCodeList for "+ zip +": "+ totalNumOfCollisions +",
"+ totalNumOfPersonsInjured +", "
+ totalNumOfPersonsKilled +", "+ totalNumOfCyclistsInjured +
", "+ totalNumOfCyclistsKilled +", "
+ totalNumOfPedestriansInjured +", "+ totalNumOfPedestrians
Killed +", "+ totalNumOfMotoristsInjured
+", "+ totalNumOfMotoristsKilled ;
}
}
CSCI-UA 102 sec 3,5, Fall 2015
Programming Project 6
Joanna Klukowska
[email protected]
Programming Project 6:
36. NYPD Motor Vehicle Collisions Analysis - Revisited
Due date: Dec. 11, 11:55 PM EST.
You may discuss any of the assignments with your classmates
and tutors (or anyone else) but all work for all assignments must
be entirely your own. Any sharing or copying of assignments
will be considered cheating. If you get significant help from
anyone,
you should acknowledge it in your submission (and your grade
will be proportional to the part that you completed on your
own).
You are responsible for every line in your program: you need to
know what it does and why. You should not use any data
structures or features of Java that have not been covered in class
(or the prerequisite class). If you have doubts whether or not
you are allowed to use certain structures, just ask your
instructor.
In this project you will revisit your project 1 implementation of
a program that used the NYPD motor vehicle collision data. A
version
of the solution to the original project is provided (it has been
slightly modified from the specification of the original project).
You should
use that implementation as the basis for your project 6 solution.
Please, see project 1 for the details of tasks and implementation
requirements.
Objectives
The goal of this programming project is for you to master (or at
least get practice on) the following tasks:
• using/modifying existing code
37. • selecting data structures appropriate for given tasks
• writing Java programs
The Program Input and Output
You should not change this part of the implementation.
There are three data sets posted on the course website that you
should be using for this project. The largest of them contains all
collision
data for the entire NYC from July 1, 2012 till June 30, 2015
(three years total). The medium size data set contains all
collision data for
the entire NYC from July 1, 2013 till June 30, 2015 (two years
total). Finally, the smallest data set contains all collision data
for the
entire NYC from July 1, 2014 till June 30, 2015 (one year
total).
For testing purposes, you may wish to use smaller data sets.
Computational Task
The posted program stores all the Collision objects in an
ArrayList of ZipCodeList objects. The ZipCodeList object, in
turn, stores all Collision objects from a particular zip code in an
ArrayList of collisions.
At this point in the semester, you should realize that this is not
an optimal way of organizing the data. Your task for this project
is to
modify how the Collision objects are stored in memory when
the program is running in order to improve the time
performance of the
38. program.
1
CSCI-UA 102 sec 3,5, Fall 2015
Programming Project 6
Joanna Klukowska
[email protected]
You do not need to provide implementation of any data
structures yourself. You should use the implementations
provided by Java API.
You should only use the data structures that we discussed in
class during this semester. Here is the list with links to Java
API interfaces
and classes:
• linked list
https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.ht
ml
• stack
https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
• queue
https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
(any of the implementing classes)
• (self-balancing) binary search tree
http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
• priority queue
https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueu
e.html
39. • hashtable
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
(any of the implementing classes)
You are not supposed to use all of the above data structures.
Your task is to decide which of them could improve the time
performance
of the program and use those.
You may wish to try several different changes. In your final
program you should leave only the changes that resulted in a
better time
performance of the program. All other changes should be
described in the written report (see below).
Written Report: Performance Analysis
You should write a 1-2 page report that summarizes the results
of this project. Your report should include justification for why
particular
data structures are appropriate and others are not. You may wish
to include time comparison results for different sizes of data
sets that
you obtain with the provided version of the code and with your
modified version of the code. If you tried some of the data
structures and
they did not turn out to be appropriate, mention that in your
report.
If you decide to include graphs and tables, those do not count
towards the 2-page limit.
Program Design
You should only change parts of the design of this program that
40. are related to change in data structures. Overall program design
should
remain the same.
Programming Rules
You should follow the rules outlined in the document Code
conventions posted on the course website at http://cs.nyu.edu/
˜joannakl/cs102_f15/notes/CodeConventions.pdf.
You must document all your code using Javadoc. Your class
documentation needs to provide a description of what it is used
for and
the name of its author. Your methods need to have description,
specification of parameters, return values, exceptions thrown
and any
assumptions that they are making.
A class’s data fields and methods should not be declared static
unless they are to be shared by all instances of the class or
provide
access to such data.
You must use the provided implementation of the program and
modify only the parts that change the storage of Collision
objects.
Grading
Make sure that you are following all the rules in the
Programming Rules section above.
If your program does not compile or crashes (almost) every time
it is ran, you will get a zero on the assignment.
2
42. How and What to Submit
Your should submit all your source code files (the ones with
.java extensions only) and your report (in PDF format) in a
single zip file to
NYU Classes. If you are unsure how to create a zip file or how
to get to your source code files, you should ask long before the
project is
due.
If you wish to use your (one and only) freebie for this project
(one week extension, no questions asked), then complete the
form at
http://goo.gl/forms/YFDVBlscEB before the due date for the
assignment. All freebies are due seven days after the original
due date and should be submitted to NYU Classes.
3
http://goo.gl/forms/YFDVBlscEB