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.
Please fill in the code to run the program based on the following in.pdfamarnathmahajansport
Please fill in the code to run the program based on the following instructions(Please make sure it
compiles and runs and gives output in the given format):
(Please note that I don't need an explanation for the code, but the code itself. Thanks in advance)
Input: Take a filed named topo.txt as an input, the contents of the file is below
0 10 5 2
10 0 1 1
5 1 0 3
2 1 3 0
Your simulator should read a topology file (say, topo.txt) with a matrix {Di,j }, i, j {0.., N 1}. N
is the number of nodes (routers) and Di,j is the link cost from node i to node j. If nodes i and j are
the same, Di,j = 0; If nodes i and j are directly connected (adjacent), Di,j = e, where e 0.
Otherwise, nodes i and j are not directly connected and you should assign link cost Di,j = 1.
Implementation:
You need to first implement DV initialization per node via rtinit(struct distance table *dt, int
node id, int *link costs, int num nodes)
For every node, rtinit() will be called only ONCE at the beginning of the simulation (k=0). For
example, to initialize node 0, you need to use rtinit(&dt, 0, link cost, 4) (Please check the sample
code for more information). Node 0 should firstly initialize its distance table by setting all
distances to 1. After that, node 0s distance vector in the distance table is changed to (0,10,5,2),
representing the minimum distance from node 0 to all nodes in the topology. Lastly, node 0
needs to send its distance vector in a routing packet to its connected neighbors using
send2neighbor(rtpkt packet) (you can find this function in the sample code) based on the input
topology.
You then need to implement DV update for each received routing packets. Please assume that
every DV update happens in a synchronous manner while it is not true for DV in reality.
Please use this method to update DV for each node- rtupdate(struct distance table *dt, struct rtpkt
recv pkt)
This method will be called for each received routing packet at each simulation time slot k 1. It
parses the input, which is a routing packet recv pkt to update the distance table based on the DV
algorithm. If its own minimum distance to any of the other nodes is updated, the node informs its
directly connected neighbors of this change in minimum cost by sending them a routing packet
(send2neighbor(rtpkt packet)). Therefore, in the given example, nodes 0 and 1 will communicate
with each other, but nodes 1 and 3 will not.
Convergence: Please make sure that your code can run successfully and produce correct and
converged output under any topology with any N 10.
Test cases and the expected outputs:
Assume the simulation starts at slot k = 0 for initialization and k 1 when updating DVs at each
simulation slot. You need to print out the current slot k followed by DVs of all the nodes in the
ascending order at the end of the simulation slots. Please print them out in the first five slots (k =
0, 1, 2, 3, 4) and then every 10 slots (k = 10, 20, 30, ) until they converge. In this test case, the
expected out.
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack\'s top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack\'s top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with \',\'
return \"\";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(\"\ \"+
\"*******************************************************\ \"+
\"Sample Expected output:\ \"+
\"\ \"+
\"OK: stack is empty\ \"+
\"Push 3 data: 10, 30, 50\ \"+
\"Print stack [50,30,10,]\ \"+
\"OK: sta.
In this lab, we will write an application to store a deck of cards i.pdfcontact41
In this lab, we will write an application to store a deck of cards in a linked list, and then write
methods to sort and shuffle the deck.
Copy your completed LinkedList class from Lab 4 into the LinkedList.java file below.
Complete all methods of the Card class as described by the Javadoc comments. The class
contains both a suit and a rank. A suit is one of the categories into which the cards of a deck are
divided. The rank is the relative importance of the card within its suit.
Note that the Card constructor must convert any rank and suit letters to uppercase.
For the equals() method, be sure to follow the steps outlined in Lesson 4. How to implement the
compareTo() method is also covered in Lesson 4.
Note that you are not allowed to add any additional methods or member variables to this class or
you will not receive credit for this assignment.
Complete all methods of the CardApp class in the CardApp.java file as described by the Javadoc
comments.
You may add as many methods as you would like to this file, but are not allowed to add any
additional member variables.
The CardApp program must prompt for and allow the user to enter the name of any input file as
shown in the Example output below.
Implement the shuffle() method as specified in the comments for shuffle(). After you have
shuffled the deck of cards, write the result into a file named shuffled.txt.
Implement the sort() method using bubble sort from Lesson 4. First sort by suit in alphabetical
order and then by rank from 2 to A. The pseudocode for bubble sort is as follows:
After you have sorted the deck of cards, write the result to a file named sorted.txt.
The CardApp.java file also contains the main() method of the application. Use Develop mode to
test your CardApp code along with your Card and LinkedList code.
All input and output files must contain a list of cards, with each card stored on its own line. See
the example files cards1.txt and cards2.txt for example file formats.
[[[cards1.txt]]]
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
[[[cards2.txt]]]
AS
2S
3S
4S
5S
6S
7S
8S
9S
10S
JS
QS
KS
AC
2C
3C
4C
5C
6C
7C
8C
9C
10C
JC
QC
KC
AH
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
QH
KH
AD
2D
3D
4D
5D
6D
7D
8D
9D
10D
JD
QD
KD
[[[CardApp.java]]]
/**
* CardApp.java
* @author Your name
* @author Partner's name
* CIS 22C, Applied Lab 1
*/
public class CardApp {
private LinkedList list;
/**
* User interface prompts user, reads and writes files.
*/
public static void main(String[] args) {
}
/**
* Default constructor to initialize the deck
*/
public CardApp() {
}
/**
* Inserts a new Card into the deck
* @param card a playing Card
*/
public void addCard(Card card) {
}
/**
* Shuffles cards following this algorithm:
* First swaps first and last card
* Next, swaps every even card with the card 3
* nodes away from that card. Stops when it
* reaches the 3rd to last node
* Then, swaps ALL cards with the card that is
* 2 nodes away from it, starting at the 2nd card
* and stopping stopping at the 3rd to last node
*/
public vo.
can someone fix the errors in this code- the name needs to be Fraction.pdfvinaythemodel
can someone fix the errors in this code? the name needs to be FractionDemo.java
//author: Jazmine Tapia
//date: 20 February 2023
//file: FractionDemo.java
/*
Lab 13 will also be using demonstation the
the multiplication of two factors.
*/
//import statements for Scanner class
import java.util.Scanner;
// Define a public class called Fraction
public class FractionDemo
{
// Define private instance variables for the numerator and denominator
private int numerator;
private int denominator;
// Define a constructor for the Fraction class that takes a numerator and denominator as
arguments
public FractionDemo(int numerator, int denominator)
{
// Set the denominator using the setDenominator() method defined below
setDenominator(denominator);
// Set the numerator
this.numerator = numerator;
// Reduce the fraction
reduce();
// Adjust the signs of the numerator and denominator if necessary
adjustSigns();
}
// Define a getter method for the numerator
public int getNumerator()
{
return numerator;
}
// Define a setter method for the numerator
public void setNumerator(int numerator)
{
this.numerator = numerator;
}
// Define a getter method for the denominator
public int getDenominator()
{
return denominator;
}
// Define a setter method for the denominator
public void setDenominator(int denominator)
{
// Set the denominator using the setDenominator() method defined below
setDenominator(denominator);
// Reduce the fraction
reduce();
// Adjust the signs of the numerator and denominator if necessary
adjustSigns();
}
// Define a private method to set the denominator
private void setDenominator(int denominator)
{
// If the denominator is zero, throw an exception
if (denominator == 0)
{
throw new IllegalArgumentException("Denominator cannot be zero");
}
// Set the denominator
this.denominator = denominator;
}
// Define a private method to calculate the greatest common divisor of two integers
private int gcd(int a, int b)
{
if (b == 0)
{
return a;
} else {
return gcd(b, a % b);
}
}
// Define a public method to reduce the fraction
public void reduce()
{
// Calculate the greatest common divisor of the numerator and denominator
int gcd = gcd(numerator, denominator);
// Divide both the numerator and denominator by the greatest common divisor to reduce the
fraction
numerator /= gcd;
denominator /= gcd;
}
// Define a private method to adjust the signs of the numerator and denominator if necessary
private void adjustSigns()
{
// If the denominator is negative, multiply both the numerator and denominator by -1 to adjust
the signs
if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
}
// Define a public method to add two fractions
public FractionDemo add(FractionDemo other)
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Get the numerator and denominator for the first fraction
System.out.print("Enter the numerator of the first fraction: ");
int num1 = input.nextInt();
System.out.print("Enter the denominator of the first fraction.
I need help completing this C++ code with these requirements.instr.pdfeyeonsecuritysystems
I need help completing this C++ code with these requirements.
instructions: IN C++ LANGUAGE PLEASE
Update the comments for each prototype by filling in the pre and post conditions.
Remember that pre conditions indicate what conditions must be met BEFORE the user calls the
function. The function will not work properly unless the pre conditions are met.
Post conditions indicate what will be the result of the function call. In other words, what
conditions will exist after the function is called.
See class notes from Thursday on pre and post conditions for some examples and further
explanation.
Code begins here:
#include //for NULL
class List
{
private:
struct Node
{
int data;
Node* next;
Node(int data): data(data), next(NULL){}
};
typedef struct Node* Nodeptr;
Nodeptr first;
Nodeptr last;
int size;
public:
/**Constructors and Destructors*/
List();
//Default constructor; initializes and empty list
//Postcondition:
~List();
//Destructor. Frees memory allocated to the list
//Postcondition:
/**Accessors*/
int getFirst();
//Returns the first element in the list
//Precondition:
int getLast();
//Returns the last element in the list
//Precondition:
bool isEmpty();
//Determines whether a list is empty.
int getSize();
//Returns the size of the list
/**Manipulation Procedures*/
void removeLast();
//Removes the value of the last element in the list
//Precondition:
//Postcondition:
void removeFirst();
//Removes the value of the first element in the list
//Precondition:
//Postcondition:
void insertLast(int data);
//Inserts a new element at the end of the list
//If the list is empty, the new element becomes both first and last
//Postcondition:
void insertFirst(int data);
//Inserts a new element at the start of the list
//If the list is empty, the new element becomes both first and last
//Postcondition:
/**Additional List Operations*/
void printList();
//Prints to the console the value of each element in the list sequentially
//and separated by a blank space
//Prints nothing if the list is empty
};
Solution
PROGRAM CODE:
#include
#include //for NULL
using namespace std;
class List
{
private:
struct Node
{
int data;
Node* next;
Node(int data): data(data), next(NULL){}
};
typedef struct Node* Nodeptr;
Nodeptr first;
Nodeptr last;
int size;
public:
/**Constructors and Destructors*/
List()
{
first = (Node*) malloc(sizeof(Node));
last = (Node*) malloc(sizeof(Node));
size = 0;
}
//Default constructor; initializes and empty list
//Postcondition:
~List()
{
delete first;
delete last;
}
//Destructor. Frees memory allocated to the list
//Postcondition:
/**Accessors*/
int getFirst()
{
return first->data;
}
//Returns the first element in the list
//Precondition:
int getLast()
{
return last->data;
}
//Returns the last element in the list
//Precondition:
bool isEmpty()
{
if(first == NULL)
return true;
else return false;
}
//Determines whether a list is empty.
int getSize()
{
return size;
}
//Returns the size of the list
/**Manipulation Procedures*/
void removeLast()
{
last = .
please help me with this and explain in details also in the first qu.pdfnewfaransportsfitnes
please help me with this and explain in details also in the first question modify them both please
trap1 and trap2:
Q1 Consider the below omp_trap1.c implantation, modify the code so that: i. The time used by
the parallel block is timed using the OpenMP function omp_get_wtime(). The syntax is double
omp_get_wtime ( void ) It returns the number of seconds that have elapsed since some time in
the past. ii. Now on a system with at least two cores, time the program with a. one thread and a
large value of n, and b. two threads and the same value of n. Explain what happens? Then Do the
same measurements for the omp_trap2.c code.
1. How does its performance compare with the performance of the omp_trap1.c ?
2. Explain your answers.
3. provide with your answers the code and detailed screenshots showing how did you compile
and run the code and times for each run:
/* File: omp_trap1.c * Purpose: Estimate definite integral (or area under curve) using trapezoidal
rule. * Input: a, b, n * Output: estimate of integral from a to b of f(x) * using n trapezoids. * *
Compile: gcc -g -Wall -fopenmp -o omp_trap1 omp_trap1.c * Usage: ./omp_trap1 * * Notes: *
1. The function f(x) is hardwired. * 2. In this version, each thread explicitly computes the
integral over its assigned subinterval, a critical directive is used for the global sum. * 3. This
version assumes that n is evenly divisible by the number of threads #include #include #include
#include void Usage(char* prog_name); double f(double x); /* Function we're integrating */
double Local_trap ( double a , double b , i n t n ) ; int main(int argc, char* argv[]) { double
global_result = 0.0; /* Store result in global_result */ double a, b; /* Left and right endpoints */
int n; /* Total number of trapezoids */ int thread_count; if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10); printf("Enter a, b, and n\n"); scanf("%lf %lf %d", &a,
&b, &n); if (n % thread_count != 0) Usage(argv[0]); double global_result = 0.0; # pragma omp p
a r a l l e l num_threads ( t h r e a d _ c o u n t ) { # pragma omp c r i t i c a l global_result +=
Local_trap ( double a , double b , i n t n ) ; } printf("With n = %d trapezoids, our estimate\n", n);
printf("of the integral from %f to %f = %.14e\n", a, b, global_result); return 0; } /* main */ /*----
---------------------------------------------------------------- * Function: Usage * Purpose: Print
command line for function and terminate * In arg: prog_name */ void Usage(char* prog_name) {
fprintf(stderr, "usage: %s \n", prog_name); fprintf(stderr, " number of trapezoids must be evenly
divisible by\n"); fprintf(stderr, " number of threads\n"); exit(0); } /* Usage */ /*---------------------
--------------------------------------------- * Function: f * Purpose: Compute value of function to be
integrated * Input arg: x * Return val: f(x) */ double f(double x) { double return_val; return_val
= x*x; return return_val; } /* f */ /*------------------------------------------.
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
How do you stop infinite loop? Because I believe that it is making an infinite circular list.
c++ code:
Here is the list class:
#ifndef LIN_J_LIST
#define LIN_J_LIST
typedef unsigned int uint;
#include
#include
using namespace std;
/**
* a simplified generic singly linked list class to illustrate C++ concepts
* @author Jerry Lin
* @version 2/17/17
*/
template< typename Object >
class List
{
private:
/**
* A class to store data and provide a link to the next node in the list
*/
class Node
{
public:
/**
* The constructor
* @param data the data to be stored in this node
*/
explicit Node( const Object & data )
: data{ data }, next{ nullptr } {}
Object data;
Node * next;
};
public:
/**
* The constructor for an empty list
*/
List()
: size{ 0 }, first{ nullptr }, last{ nullptr } {}
/**
* the copy constructor-creates and copy the list
*/
List( List && rhs ) = delete;
List( const List & rhs )
{
count = 0;
size = 0;
if(rhs.size != 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first;
size++;
while(current->next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op.
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode->next;
size++;
}
}
// you document and implement this method
}
/**
* the operator= method-copies the list
*/
List & operator=( List && rhs) = delete;
List & operator=( const List & rhs )
{
count = 0;
size = 0;
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
if(rhs.size!= 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first; //create a temporary to store
size++;
while(current -> next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode -> next;
size++;
}
}
return *this;
// you document and implement this method
}
/**
* accessor
* @return count
*/
int get_count() const
{
return count;
}
/**
* The destructor that gets rid of everything that\'s in the list and
* resets it to empty. If the list is already empty, do nothing.
*/
~List()
{
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
}
/**
* Put a new element onto the beginning of the list
* @param item the data the new element will contain
*/
void push_front( const Object& item )
{
Node * new_node = new Node( item );//basic op.
if(is_empty())
{
last = new_node;
}
else
{
new_node->next = first;
}
first = new_node;
size++;
/* you complete the rest */
}
/**
* Remove the element that\'s at the front of the list. Causes an
* assertion error if the list is empty.
*/
void pop_front()
{
assert( !is_empty() );
Node * temp = first;
if( first == last )
{
first = last = nullptr;
}
else
{
first = first->next;
}
delete temp;
size--;
}
/**
* Accessor to return the da.
Please fill in the code to run the program based on the following in.pdfamarnathmahajansport
Please fill in the code to run the program based on the following instructions(Please make sure it
compiles and runs and gives output in the given format):
(Please note that I don't need an explanation for the code, but the code itself. Thanks in advance)
Input: Take a filed named topo.txt as an input, the contents of the file is below
0 10 5 2
10 0 1 1
5 1 0 3
2 1 3 0
Your simulator should read a topology file (say, topo.txt) with a matrix {Di,j }, i, j {0.., N 1}. N
is the number of nodes (routers) and Di,j is the link cost from node i to node j. If nodes i and j are
the same, Di,j = 0; If nodes i and j are directly connected (adjacent), Di,j = e, where e 0.
Otherwise, nodes i and j are not directly connected and you should assign link cost Di,j = 1.
Implementation:
You need to first implement DV initialization per node via rtinit(struct distance table *dt, int
node id, int *link costs, int num nodes)
For every node, rtinit() will be called only ONCE at the beginning of the simulation (k=0). For
example, to initialize node 0, you need to use rtinit(&dt, 0, link cost, 4) (Please check the sample
code for more information). Node 0 should firstly initialize its distance table by setting all
distances to 1. After that, node 0s distance vector in the distance table is changed to (0,10,5,2),
representing the minimum distance from node 0 to all nodes in the topology. Lastly, node 0
needs to send its distance vector in a routing packet to its connected neighbors using
send2neighbor(rtpkt packet) (you can find this function in the sample code) based on the input
topology.
You then need to implement DV update for each received routing packets. Please assume that
every DV update happens in a synchronous manner while it is not true for DV in reality.
Please use this method to update DV for each node- rtupdate(struct distance table *dt, struct rtpkt
recv pkt)
This method will be called for each received routing packet at each simulation time slot k 1. It
parses the input, which is a routing packet recv pkt to update the distance table based on the DV
algorithm. If its own minimum distance to any of the other nodes is updated, the node informs its
directly connected neighbors of this change in minimum cost by sending them a routing packet
(send2neighbor(rtpkt packet)). Therefore, in the given example, nodes 0 and 1 will communicate
with each other, but nodes 1 and 3 will not.
Convergence: Please make sure that your code can run successfully and produce correct and
converged output under any topology with any N 10.
Test cases and the expected outputs:
Assume the simulation starts at slot k = 0 for initialization and k 1 when updating DVs at each
simulation slot. You need to print out the current slot k followed by DVs of all the nodes in the
ascending order at the end of the simulation slots. Please print them out in the first five slots (k =
0, 1, 2, 3, 4) and then every 10 slots (k = 10, 20, 30, ) until they converge. In this test case, the
expected out.
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack\'s top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack\'s top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with \',\'
return \"\";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(\"\ \"+
\"*******************************************************\ \"+
\"Sample Expected output:\ \"+
\"\ \"+
\"OK: stack is empty\ \"+
\"Push 3 data: 10, 30, 50\ \"+
\"Print stack [50,30,10,]\ \"+
\"OK: sta.
In this lab, we will write an application to store a deck of cards i.pdfcontact41
In this lab, we will write an application to store a deck of cards in a linked list, and then write
methods to sort and shuffle the deck.
Copy your completed LinkedList class from Lab 4 into the LinkedList.java file below.
Complete all methods of the Card class as described by the Javadoc comments. The class
contains both a suit and a rank. A suit is one of the categories into which the cards of a deck are
divided. The rank is the relative importance of the card within its suit.
Note that the Card constructor must convert any rank and suit letters to uppercase.
For the equals() method, be sure to follow the steps outlined in Lesson 4. How to implement the
compareTo() method is also covered in Lesson 4.
Note that you are not allowed to add any additional methods or member variables to this class or
you will not receive credit for this assignment.
Complete all methods of the CardApp class in the CardApp.java file as described by the Javadoc
comments.
You may add as many methods as you would like to this file, but are not allowed to add any
additional member variables.
The CardApp program must prompt for and allow the user to enter the name of any input file as
shown in the Example output below.
Implement the shuffle() method as specified in the comments for shuffle(). After you have
shuffled the deck of cards, write the result into a file named shuffled.txt.
Implement the sort() method using bubble sort from Lesson 4. First sort by suit in alphabetical
order and then by rank from 2 to A. The pseudocode for bubble sort is as follows:
After you have sorted the deck of cards, write the result to a file named sorted.txt.
The CardApp.java file also contains the main() method of the application. Use Develop mode to
test your CardApp code along with your Card and LinkedList code.
All input and output files must contain a list of cards, with each card stored on its own line. See
the example files cards1.txt and cards2.txt for example file formats.
[[[cards1.txt]]]
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
[[[cards2.txt]]]
AS
2S
3S
4S
5S
6S
7S
8S
9S
10S
JS
QS
KS
AC
2C
3C
4C
5C
6C
7C
8C
9C
10C
JC
QC
KC
AH
2H
3H
4H
5H
6H
7H
8H
9H
10H
JH
QH
KH
AD
2D
3D
4D
5D
6D
7D
8D
9D
10D
JD
QD
KD
[[[CardApp.java]]]
/**
* CardApp.java
* @author Your name
* @author Partner's name
* CIS 22C, Applied Lab 1
*/
public class CardApp {
private LinkedList list;
/**
* User interface prompts user, reads and writes files.
*/
public static void main(String[] args) {
}
/**
* Default constructor to initialize the deck
*/
public CardApp() {
}
/**
* Inserts a new Card into the deck
* @param card a playing Card
*/
public void addCard(Card card) {
}
/**
* Shuffles cards following this algorithm:
* First swaps first and last card
* Next, swaps every even card with the card 3
* nodes away from that card. Stops when it
* reaches the 3rd to last node
* Then, swaps ALL cards with the card that is
* 2 nodes away from it, starting at the 2nd card
* and stopping stopping at the 3rd to last node
*/
public vo.
can someone fix the errors in this code- the name needs to be Fraction.pdfvinaythemodel
can someone fix the errors in this code? the name needs to be FractionDemo.java
//author: Jazmine Tapia
//date: 20 February 2023
//file: FractionDemo.java
/*
Lab 13 will also be using demonstation the
the multiplication of two factors.
*/
//import statements for Scanner class
import java.util.Scanner;
// Define a public class called Fraction
public class FractionDemo
{
// Define private instance variables for the numerator and denominator
private int numerator;
private int denominator;
// Define a constructor for the Fraction class that takes a numerator and denominator as
arguments
public FractionDemo(int numerator, int denominator)
{
// Set the denominator using the setDenominator() method defined below
setDenominator(denominator);
// Set the numerator
this.numerator = numerator;
// Reduce the fraction
reduce();
// Adjust the signs of the numerator and denominator if necessary
adjustSigns();
}
// Define a getter method for the numerator
public int getNumerator()
{
return numerator;
}
// Define a setter method for the numerator
public void setNumerator(int numerator)
{
this.numerator = numerator;
}
// Define a getter method for the denominator
public int getDenominator()
{
return denominator;
}
// Define a setter method for the denominator
public void setDenominator(int denominator)
{
// Set the denominator using the setDenominator() method defined below
setDenominator(denominator);
// Reduce the fraction
reduce();
// Adjust the signs of the numerator and denominator if necessary
adjustSigns();
}
// Define a private method to set the denominator
private void setDenominator(int denominator)
{
// If the denominator is zero, throw an exception
if (denominator == 0)
{
throw new IllegalArgumentException("Denominator cannot be zero");
}
// Set the denominator
this.denominator = denominator;
}
// Define a private method to calculate the greatest common divisor of two integers
private int gcd(int a, int b)
{
if (b == 0)
{
return a;
} else {
return gcd(b, a % b);
}
}
// Define a public method to reduce the fraction
public void reduce()
{
// Calculate the greatest common divisor of the numerator and denominator
int gcd = gcd(numerator, denominator);
// Divide both the numerator and denominator by the greatest common divisor to reduce the
fraction
numerator /= gcd;
denominator /= gcd;
}
// Define a private method to adjust the signs of the numerator and denominator if necessary
private void adjustSigns()
{
// If the denominator is negative, multiply both the numerator and denominator by -1 to adjust
the signs
if (denominator < 0)
{
numerator *= -1;
denominator *= -1;
}
}
// Define a public method to add two fractions
public FractionDemo add(FractionDemo other)
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Get the numerator and denominator for the first fraction
System.out.print("Enter the numerator of the first fraction: ");
int num1 = input.nextInt();
System.out.print("Enter the denominator of the first fraction.
I need help completing this C++ code with these requirements.instr.pdfeyeonsecuritysystems
I need help completing this C++ code with these requirements.
instructions: IN C++ LANGUAGE PLEASE
Update the comments for each prototype by filling in the pre and post conditions.
Remember that pre conditions indicate what conditions must be met BEFORE the user calls the
function. The function will not work properly unless the pre conditions are met.
Post conditions indicate what will be the result of the function call. In other words, what
conditions will exist after the function is called.
See class notes from Thursday on pre and post conditions for some examples and further
explanation.
Code begins here:
#include //for NULL
class List
{
private:
struct Node
{
int data;
Node* next;
Node(int data): data(data), next(NULL){}
};
typedef struct Node* Nodeptr;
Nodeptr first;
Nodeptr last;
int size;
public:
/**Constructors and Destructors*/
List();
//Default constructor; initializes and empty list
//Postcondition:
~List();
//Destructor. Frees memory allocated to the list
//Postcondition:
/**Accessors*/
int getFirst();
//Returns the first element in the list
//Precondition:
int getLast();
//Returns the last element in the list
//Precondition:
bool isEmpty();
//Determines whether a list is empty.
int getSize();
//Returns the size of the list
/**Manipulation Procedures*/
void removeLast();
//Removes the value of the last element in the list
//Precondition:
//Postcondition:
void removeFirst();
//Removes the value of the first element in the list
//Precondition:
//Postcondition:
void insertLast(int data);
//Inserts a new element at the end of the list
//If the list is empty, the new element becomes both first and last
//Postcondition:
void insertFirst(int data);
//Inserts a new element at the start of the list
//If the list is empty, the new element becomes both first and last
//Postcondition:
/**Additional List Operations*/
void printList();
//Prints to the console the value of each element in the list sequentially
//and separated by a blank space
//Prints nothing if the list is empty
};
Solution
PROGRAM CODE:
#include
#include //for NULL
using namespace std;
class List
{
private:
struct Node
{
int data;
Node* next;
Node(int data): data(data), next(NULL){}
};
typedef struct Node* Nodeptr;
Nodeptr first;
Nodeptr last;
int size;
public:
/**Constructors and Destructors*/
List()
{
first = (Node*) malloc(sizeof(Node));
last = (Node*) malloc(sizeof(Node));
size = 0;
}
//Default constructor; initializes and empty list
//Postcondition:
~List()
{
delete first;
delete last;
}
//Destructor. Frees memory allocated to the list
//Postcondition:
/**Accessors*/
int getFirst()
{
return first->data;
}
//Returns the first element in the list
//Precondition:
int getLast()
{
return last->data;
}
//Returns the last element in the list
//Precondition:
bool isEmpty()
{
if(first == NULL)
return true;
else return false;
}
//Determines whether a list is empty.
int getSize()
{
return size;
}
//Returns the size of the list
/**Manipulation Procedures*/
void removeLast()
{
last = .
please help me with this and explain in details also in the first qu.pdfnewfaransportsfitnes
please help me with this and explain in details also in the first question modify them both please
trap1 and trap2:
Q1 Consider the below omp_trap1.c implantation, modify the code so that: i. The time used by
the parallel block is timed using the OpenMP function omp_get_wtime(). The syntax is double
omp_get_wtime ( void ) It returns the number of seconds that have elapsed since some time in
the past. ii. Now on a system with at least two cores, time the program with a. one thread and a
large value of n, and b. two threads and the same value of n. Explain what happens? Then Do the
same measurements for the omp_trap2.c code.
1. How does its performance compare with the performance of the omp_trap1.c ?
2. Explain your answers.
3. provide with your answers the code and detailed screenshots showing how did you compile
and run the code and times for each run:
/* File: omp_trap1.c * Purpose: Estimate definite integral (or area under curve) using trapezoidal
rule. * Input: a, b, n * Output: estimate of integral from a to b of f(x) * using n trapezoids. * *
Compile: gcc -g -Wall -fopenmp -o omp_trap1 omp_trap1.c * Usage: ./omp_trap1 * * Notes: *
1. The function f(x) is hardwired. * 2. In this version, each thread explicitly computes the
integral over its assigned subinterval, a critical directive is used for the global sum. * 3. This
version assumes that n is evenly divisible by the number of threads #include #include #include
#include void Usage(char* prog_name); double f(double x); /* Function we're integrating */
double Local_trap ( double a , double b , i n t n ) ; int main(int argc, char* argv[]) { double
global_result = 0.0; /* Store result in global_result */ double a, b; /* Left and right endpoints */
int n; /* Total number of trapezoids */ int thread_count; if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10); printf("Enter a, b, and n\n"); scanf("%lf %lf %d", &a,
&b, &n); if (n % thread_count != 0) Usage(argv[0]); double global_result = 0.0; # pragma omp p
a r a l l e l num_threads ( t h r e a d _ c o u n t ) { # pragma omp c r i t i c a l global_result +=
Local_trap ( double a , double b , i n t n ) ; } printf("With n = %d trapezoids, our estimate\n", n);
printf("of the integral from %f to %f = %.14e\n", a, b, global_result); return 0; } /* main */ /*----
---------------------------------------------------------------- * Function: Usage * Purpose: Print
command line for function and terminate * In arg: prog_name */ void Usage(char* prog_name) {
fprintf(stderr, "usage: %s \n", prog_name); fprintf(stderr, " number of trapezoids must be evenly
divisible by\n"); fprintf(stderr, " number of threads\n"); exit(0); } /* Usage */ /*---------------------
--------------------------------------------- * Function: f * Purpose: Compute value of function to be
integrated * Input arg: x * Return val: f(x) */ double f(double x) { double return_val; return_val
= x*x; return return_val; } /* f */ /*------------------------------------------.
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
How do you stop infinite loop? Because I believe that it is making an infinite circular list.
c++ code:
Here is the list class:
#ifndef LIN_J_LIST
#define LIN_J_LIST
typedef unsigned int uint;
#include
#include
using namespace std;
/**
* a simplified generic singly linked list class to illustrate C++ concepts
* @author Jerry Lin
* @version 2/17/17
*/
template< typename Object >
class List
{
private:
/**
* A class to store data and provide a link to the next node in the list
*/
class Node
{
public:
/**
* The constructor
* @param data the data to be stored in this node
*/
explicit Node( const Object & data )
: data{ data }, next{ nullptr } {}
Object data;
Node * next;
};
public:
/**
* The constructor for an empty list
*/
List()
: size{ 0 }, first{ nullptr }, last{ nullptr } {}
/**
* the copy constructor-creates and copy the list
*/
List( List && rhs ) = delete;
List( const List & rhs )
{
count = 0;
size = 0;
if(rhs.size != 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first;
size++;
while(current->next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op.
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode->next;
size++;
}
}
// you document and implement this method
}
/**
* the operator= method-copies the list
*/
List & operator=( List && rhs) = delete;
List & operator=( const List & rhs )
{
count = 0;
size = 0;
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
if(rhs.size!= 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first; //create a temporary to store
size++;
while(current -> next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode -> next;
size++;
}
}
return *this;
// you document and implement this method
}
/**
* accessor
* @return count
*/
int get_count() const
{
return count;
}
/**
* The destructor that gets rid of everything that\'s in the list and
* resets it to empty. If the list is already empty, do nothing.
*/
~List()
{
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
}
/**
* Put a new element onto the beginning of the list
* @param item the data the new element will contain
*/
void push_front( const Object& item )
{
Node * new_node = new Node( item );//basic op.
if(is_empty())
{
last = new_node;
}
else
{
new_node->next = first;
}
first = new_node;
size++;
/* you complete the rest */
}
/**
* Remove the element that\'s at the front of the list. Causes an
* assertion error if the list is empty.
*/
void pop_front()
{
assert( !is_empty() );
Node * temp = first;
if( first == last )
{
first = last = nullptr;
}
else
{
first = first->next;
}
delete temp;
size--;
}
/**
* Accessor to return the da.
-- 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",.
Q1 Consider the below omp_trap1.c implantation, modify the code so t.pdfabdulrahamanbags
Q1 Consider the below omp_trap1.c implantation, modify the code so that: i. The time used by
the parallel block is timed using the OpenMP function omp_get_wtime(). The syntax is double
omp_get_wtime ( void ) It returns the number of seconds that have elapsed since some time in
the past. ii. Now on a system with at least two cores, time the program with a. one thread and a
large value of n, and b. two threads and the same value of n. Explain what happens? Then Do the
same measurements for the omp_trap2.c code.
1. How does its performance compare with the performance of the omp_trap1.c ?
2. Explain your answers.
3. provide with your answers the code and detailed screenshots showing how did you compile
and run the code and times for each run:
/* File: omp_trap1.c * Purpose: Estimate definite integral (or area under curve) using trapezoidal
rule. * Input: a, b, n * Output: estimate of integral from a to b of f(x) * using n trapezoids. * *
Compile: gcc -g -Wall -fopenmp -o omp_trap1 omp_trap1.c * Usage: ./omp_trap1 * * Notes: *
1. The function f(x) is hardwired. * 2. In this version, each thread explicitly computes the
integral over its assigned subinterval, a critical directive is used for the global sum. * 3. This
version assumes that n is evenly divisible by the number of threads #include #include #include
#include void Usage(char* prog_name); double f(double x); /* Function we're integrating */
double Local_trap ( double a , double b , i n t n ) ; int main(int argc, char* argv[]) { double
global_result = 0.0; /* Store result in global_result */ double a, b; /* Left and right endpoints */
int n; /* Total number of trapezoids */ int thread_count; if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10); printf("Enter a, b, and n\n"); scanf("%lf %lf %d", &a,
&b, &n); if (n % thread_count != 0) Usage(argv[0]); double global_result = 0.0; # pragma omp p
a r a l l e l num_threads ( t h r e a d _ c o u n t ) { # pragma omp c r i t i c a l global_result +=
Local_trap ( double a , double b , i n t n ) ; } printf("With n = %d trapezoids, our estimate\n", n);
printf("of the integral from %f to %f = %.14e\n", a, b, global_result); return 0; } /* main */ /*----
---------------------------------------------------------------- * Function: Usage * Purpose: Print
command line for function and terminate * In arg: prog_name */ void Usage(char* prog_name) {
fprintf(stderr, "usage: %s \n", prog_name); fprintf(stderr, " number of trapezoids must be evenly
divisible by\n"); fprintf(stderr, " number of threads\n"); exit(0); } /* Usage */ /*---------------------
--------------------------------------------- * Function: f * Purpose: Compute value of function to be
integrated * Input arg: x * Return val: f(x) */ double f(double x) { double return_val; return_val
= x*x; return return_val; } /* f */ /*------------------------------------------------------------------ *
Function: Trap * Purpose: Use trapezoidal rule to estimate definite integral * Input args.
complete the following functions in c++ singleRotation putNo.pdfabbecindia
complete the following functions in c++
singleRotation
putNode: Insert or update the entry in the extended AVL tree map (TreeMapStats) using
the inputted key and value. In addition, efficiently update the statistics information of only
the nodes affected by the insertion of the new entry into the map
eraseNode: Remove the entry in the extended AVL tree map (TreeMapStats) with the
inputted key, if the key is in the map, if necessary. In addition, efficiently update the statistics
information of only the nodes affected by the removal of the new entry from the map
also right a function updateStats
class TreeMapStats : public AVLTreeMap {
public:
// embedded node class extension of an AVL-Tree node
class Node : public AVLTreeMap::Node {
private:
// stats class to account for basic statistics/information of subtree rooted at each node
class Stats {
private:
// data members: number of nodes/map entries stored in the subtree; sum of all the map values of
map entries stored in the subtree; the minimum map value of all the map entries stored in the
subtree; the maximum map value of the map entries stored in the subtree
int num;
int sum;
int min;
int max;
public:
// stats constructors
Stats() { };
Stats(int v, Node *l, Node* r) : num(1), sum(v), min(v), max(v) {
};
// stats destructor
~Stats() { };
// overloading output stream for a representation of stats s
friend ostream& operator<<(ostream& os, const Stats& s) {
os << "{" << s.num << "," << s.sum << "," << s.min << "," << s.max << "}";
return os;
};
};
// data member: node info/stats
Stats *info;
public:
// tree node constructors
Node() : AVLTreeMap::Node() { };
Node(int k, int v, Node* l, Node* r, Node* p) : AVLTreeMap::Node(k,v,l,r,p) {
info = new Stats(v, l, r);
};
// tree node destructor
virtual ~Node() { if (this->info) delete this->info; };
// overloading output stream for a representation of TreeMapStats node w
friend ostream& operator<<(ostream& os, const Node& w) {
os << ((AVLTreeMap::Node) w) << *(w.info) ;
return os;
};
// (overloading) print utility for a node, including map entry and additional info and stats
void printStats() { cout << *this << endl; }
/*
# PRECONDITION: the info values for the left and right nodes for the children of the node have
been properly set, consistent with the subtree that they root
# POSTCONDITION: the info values for the node have been properly set, consistent with the
subtree that it roots
*/
};
// print utilities
void printTreeMapStats();
void printTreeMapStats(Node* w);
void printTreeMap();
// tree constructor
TreeMapStats() { };
// tree desctructor
virtual ~TreeMapStats() { };
protected:
// (overloadable) auxiliary node creation utility
virtual Node* createNode(int k, int v, BSTMap::Node* l, BSTMap::Node* r, BSTMap::Node* p) {
return new Node(k,v,(Node*) l, (Node*) r, (Node*) p); };
// prints a representation of AVL node w
// (overloadable)
// INPUT: node w
virtual void printNode(const BSTMap::Node* w) const { if (w) cout << *((Node*) w); };
// (overloa.
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docxMARRY7
/* Lab Assignment 4 CSE330 Spring 2014 */
/* Skeleton Code for ex0 of lab4 */
/* No code will be provided for ex1 of lab4 */
#include <stdio.h> /* for NULL */
#include <ctype.h> /* for atoi() */
#include <errno.h> /* for perror() */
#include <signal.h> /* for sigvec() etc. */
#include <sys/types.h> /* for <arpa/inet.h> */
#include <sys/socket.h> /* for PF_INET, etc. */
#include <netinet/in.h> /* for struct sockaddr_in */
#include <arpa/inet.h> /* for inet_addr() */
#include <sys/time.h>
#include "lab4.h"
/* this is in netinet/in.h; included here for reference only.
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
*/
/***************************************************************************/
#define LINESIZE 80
#define TYPE0TIMEOUT 3
#define TYPE1TIMEOUT 30
/* You should give a long timeout, like 30sec, otherwise */
/* duplicated responses from the server may cause some problem */
#define MAXRETRY 3
/***************************************************************************/
static char *RCSId="$Id: client2.c,v 4 2014/04/20 03:15:07 cse3300 Exp $";
/***************************************************************************/
/* some functions you may find useful if you implement them */
extern int stringToAddress(char *s, struct sockaddr_in *a);
extern int msgok(LABMSG *);
extern u_short msgchecksum(u_short *);
extern void alarmCatcher(void);
extern int tries; /* for retransmission routines */
int numtries;
/***** this will die ****/
FILE *logFile;
void die(char *s)
{
perror(s);
exit(2);
}
void startTimer(int secs)
{
alarm(secs);
}
void stopTimer(void)
{
alarm(0);
}
/* should change it by yourself if needed!!! */
void printResponse(LABMSG *mp, int ck)
{
int type;
mp->courseEtc = ntohs(mp->courseEtc);
type = ( (mp->courseEtc & MESSAGETYPE) !=0)?1:0;
printf("course=%d, Type=%d\n", mp->courseEtc&0x3fff,type);
if (ntohl(mp->cookie) != ck)
printf("Cookies don't match: sent %x received %x\n",mp->cookie,ck);
if (mp->courseEtc & REQRESP)
printf("response ");
else {
printf("request??\n");
return;
}
mp->result = ntohs(mp->result);
/*printf(" result = %x: ",mp->result);*/
if (mp->result&TRANSOUTCOME) { /* Check outcome */
printf("error: ");
switch (mp->result & 0x7fff) {
case ERROR_CHECKSUM:
printf("checksum failure\n");
break;
case ERROR_SYNTAX:
printf("syntax error\n");
break;
case ERROR_UNKSSN:
printf("unknown SSN %d\n", ntohl(mp->reqSSN) );
break;
case ERROR_SERVER:
printf("Unspecified Server Error\n");
default:
printf("Unknown Error.\n");
} /* case switch */
} else { /* successful transaction */
if(type)printf("Test succeeded.");
if (!type) /* Type 0 -- print SSN and Response */
printf(": %d -> %d\n", ntohl(mp->reqSSN), mp->result&0x7fff);
else
printf("\n"); /* XXX print number of responses */
}
}
/*-----------------------------------*/
/* added by ZXC:
this fun ...
Complete in JavaCardApp.javapublic class CardApp { private.pdfMAYANKBANSAL1981
Complete in Java
CardApp.java
public class CardApp {
private LinkedList list;
/**
* User interface prompts user, reads and writes files.
*/
public static void main(String[] args) {
}
/**
* Default constructor to initialize the deck
*/
public CardApp() {
}
/**
* Inserts a new Card into the deck
* @param card a playing Card
*/
public void addCard(Card card) {
}
/**
* Shuffles cards following this algorithm:
* First swaps first and last card
* Next, swaps every even card with the card 3
* nodes away from that card. Stops when it
* reaches the 3rd to last node
* Then, swaps ALL cards with the card that is
* 2 nodes away from it, starting at the 2nd card
* and stopping stopping at the 3rd to last node
*/
public void shuffle() {
}
/**
* Implements the bubble sort algorithm
* to sort cardList into sorted order, first by suit
* (alphabetical order)
* then by rank from 2 to A
*/
public void sort() {
}
/**
* Returns the deck of cards with each card separated
* by a blank space and a new line character at the end.
* @return The deck of cards as a string.
*/
@Override public String toString() {
return "";
}
}
Card.java
public class Card implements Comparable{
private String rank;
private String suit;
/**
* Constructor for the Card class
* @param rank the rank of card from 2 to A
* @param suit the suit of card C, D, H, or S
*/
public Card(String rank, String suit) {
}
/**
* Returns the card's rank
* @return rank a rank from 2 (low) to A (high)
*/
public String getRank() {
return "";
}
/**
* Returns the card's suit
* @return C, D, H, or S
*/
public String getSuit() {
return "";
}
/**
* Updates the card's rank
* @param rank a new rank
*/
public void setRank(String rank) {
}
/**
* Updates the card's suit
* @param suit the new suit
*/
public void setSuit(String suit) {
}
/**
* Concatenates rank and suit
* @return card rank and suit
*/
@Override public String toString() {
return "";
}
/**
* Overrides the equals method for Card
* Compares rank and suit and
* follows the equals formula given in
* Lesson 4 and also in Joshua Block's text
* @param obj another Object to compare for
* equality
* @return whether obj is a Card and, if so,
* of equal rank and suit
*/
@Override public boolean equals(Object obj) {
return false;
}
/**
* Orders two cards first by suit (alphabetically)
* Next by rank. "A" is considered the high card
* Order goes 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A
* @param card another Card to compare to this Card
* @return a negative number if this comes before c
* and a positive number if c comes before this
* and 0 if this and c are equal according to the above
* equals method
*/
@Override public int compareTo(Card card) {
return -1;
}
}
}
LinkedList.Java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterato.
The following is the (incomplete) header file for the class Fracti.pdf4babies2010
The following comparative income statement (in thousands of dollars) for the two recent fiscal
years was adapted from the annual report of Speedway Motorsports, Inc., owner and operator of
several major motor speedways, such as the Atlanta, Texas, and Las Vegas Motor Speedways.
Current Year Previous Year 2 Revenues: 3 Admissions 4Event-related revenue $104,312.00
$116,644.00 131,164.00 170,368.00 65,824.00 $472,000.00 $484,000.00 42,544.00 180,304.00
44,840.00 NASCAR broadcasting revenue Other operating revenue 7 Total revenue 8 Expenses
and other: 9 Direct expense of events 10 NASCAR purse and sanction fees 91,568.00
$101,640.00 117,612.00 20,328.00 220,220.00 424800.00 $459,800.00 $24,200.00 118,000.00
19,352.00 195,880.00 11 Other direct expenses 2 General and administrative 13 Total expenses
and other Income from continuing operations $47,200.00 14 Required A. Prepare a comparative
income statement for these two years in vertical form, stating each item as a percent of revenues.
Enter all amounts as positive numbers. Rounding instructions
Solution
VERTICAL ANALYSIS OF INCOME STATEMENT Particulars Current Year
Amount Current Year Percentage Previous Year Amount Previous Year Percentage
Admissions $ 1,04,312.00 22.10% $ 1,16,644.00 24.10% Event Related revenue $ 1,42,544.00
30.20% $ 1,31,164.00 27.10% NASCAR Broadcasting Revenue $ 1,80,304.00 38.20% $
1,70,368.00 35.20% Other Operating Income $ 44,840.00 9.50% $ 65,824.00 13.60%
Total Revenue $ 4,72,000.00 100.00% $ 4,84,000.00 100.00% Expenses and others
Direct expenses of events $ 91,568.00 19.40% $ 1,01,640.00 21.00% NASCAR purse and
sanction fees $ 1,18,000.00 25.00% $ 1,17,612.00 24.30% Other direct expenses $ 19,352.00
4.10% $ 20,328.00 4.20% General and adminstrative $ 1,95,880.00 41.50% $ 2,20,220.00
45.50% Total Expenses and others $ 4,24,800.00 90.00% $ 4,59,800.00 95.00% Income
from continuing operation $ 47,200.00 10.00% $ 24,200.00 5.00%.
CC++ echo serverThis assignment is designed to introduce network .pdfsecunderbadtirumalgi
C/C++ echo server
This assignment is designed to introduce network programing and the socket API. You will build
a simple ECHO server, that is a program that accepts incoming connection requests and then
echoes back any string that is sent.
Required Behavior
1. Your submission must be written in C or C++ and must compile and run on the schools Linux
server.
2. Your code should be clean and easy to read with reasonable comments and variable names.
3. You must provide a makefile that compiles your program. It should compile without errors or
warnings to a binary named echo_s.
4. Your program should take one optional command line argument, -v, that invokes verbose
mode causing the program to print diagnostic messages as it operates.
5. When run the program should:
* Create a socket and prepare it to listen for incoming TCP connections on the port of your
choice.
* Print Using port: X to tell the user what port your program is listening on.
* Begin waiting for a new connection
* When a new connection is established:
- Read a block of data from the connection note the length of the data received (blocks can
be up to 1024 bytes long)
- Check the block to see if it starts with the letters CLOSE or QUIT.
+If CLOSE, close the connection and start waiting for another connection (return to
waiting for a connection).
+If QUIT, close the connection and the listening socket and exit your program.
- Send the block back with a write() call.
- Return to waiting for the next block of data from the client.
6. If run with the v flag you should print a diagnostic message at least
* When the socket is opened
* When the socket is bound.
* Before it blocks waiting for a new connection.
* When a new connection is accepted.
* Before it blocks waiting for new data.
* When you get a block of data.
* If the data included the CLOSE command,
* If the data included the QUIT command.
* Any other time you think it would be useful.
Suggested Approach
There is some skeleton code at the end
The skeleton includes a makefile and everything you need to get started.
Once you have the skeleton setup and running you should start filling in the code. You may of
course do this however you like, but I would recommend the following:
* Fill in the sections of main() required to process command line arguments, create, bind,
establish a listening queue and then close a stream type socket.
- If you run the program without the v flag it should print what port was selected, then exit.
- If you run the program with the v you should see each step of the socket creation process.
* Add code to accept new connection requests and as requests are received call the
processConnection() At this point you can test by connect to the program with telnet.
* At this point you should have the functioning skeleton of a TCP server application. Up to this
point the structure of all server applications are almost identical, regardless of the application
protocol they are going to implement.
* Modify the processCon.
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
write the To Do\'s to get the exact output:
NOte: A valid Fraction number has a non-negative numerator and a positive denominator.
Default constructor initializes the object to safe empty state (an object with denom equals -1).
The two-argument constructor also validates the parameters and sets the object to the safe empty
state if the parameters are not valid.
Write the definitions and prototypes of following functions in Fraction.cpp and Fraction.h
respectively (They are indicated in the files by //TODO tag):
Define isEmpty function as a member function, which returns true if the object is in safe empty
state (an object is in the safe empty state if denominator (denom) equals -1).
Define display function, which sends a Fraction number to the output stream (with the
“Numerator/denominator” format). This function just prints \"Invalid Fraction Object!\" in the
screen if the object is in the safe empty state. In case that object denominator equals 1, it just
print the numerator.
Define the operator functions for the following operators:
“+=”, “+”, “*”
The overload of the above operators should make the following code possible:
The member operator+ : Adds two Fraction numbers and returns a Fraction number as the result.
This function returns an object with the safe empty state if either of Fraction numbers (operands)
is in safe empty state. It makes following code possible:
A+B ( where A and B are Fraction objects)
The member operator+= : Adds two Fraction numbers and assigns the result to the left operand,
then returns a reference to the left operand. If either of Fraction numbers (operands) is in safe
empty state, it initializes the left operand to the safe empty state, then returns a reference to the
left operand. It makes following code possible:
A+=B ( where A and B are Fraction objects)
The member operator* : Multiplies two Fraction numbers and returns a Fraction number as the
result. This function returns an object with the safe empty state if either of Fraction numbers
(operands) is in safe empty state. It makes following code possible:
A*B ( where A and B are Fraction objects)
fraction.cpp
#include \"Fraction.h\"
using namespace std;
namespace sict{
Fraction::Fraction(){
denom =-1; // safe empty state
}
Fraction::Fraction(int n, int d) // n: numerator, d: denominator
{
if(n >= 0 && d > 0){
num = n;
denom = d;
reduce();
}
else
denom =-1; // set to safe empty state
}
int Fraction::gcd() // returns the greatest common divisor of num and
denom
{
int mn = min(); // min of num and denom
int mx = max(); // mX of num and denom
for (int x=mn ; x > 0 ; x--) // find the greatest common divisor
if( mx % x == 0 && mn % x == 0)
return x;
return 1;
}
void Fraction::reduce() // simplify the Fraction number
{
int tmp = gcd();
num /= tmp;
denom /= tmp;
}
int Fraction::max ()
{
return (num >= denom) ? num : denom;
}
int Fraction::min()
{
return (num >= denom) ? denom : num;
}
// in_lab
// TODO: write the implementation of display function HERE
// TODO: w.
operating system ubuntu,linux,MacProgram will work only if you g.pdfaptcomputerzone
//operating system ubuntu,linux,Mac
Program will work only if you give command like
sum 2 3 or
sum 4 (sub 4 3)
#include
#include
#include
#include
/*Sum function implementation*/
int sum(int number1,int number2){
return number1+number2;
}
/*sub function implementation*/
int sub(int number1,int number2){
return number1-number2;
}
/*mul function implementation*/
int mul(int number1,int number2){
return number1*number2;
}
/*divide function implementation*/
float divide(int number1,int number2){
if(number2==0){
printf(\"We can not divide by 0 \ \");
return 0.0f;
}
return (float)(number1/number2);
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = malloc(length+1);
if (pointer == NULL)
{
printf(\"Unable to allocate memory.\ \");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = \'\\0\';
return pointer;
}
/*Main Function start*/
int main(int argc, char *argv[]){
/*Variable declarations*/
int number1,number2;
char *operator,*str1,*str2;
char line[50];
char s[2] = \" \";
int errorFlag=0;// checking if user entered more then one operands
while(1){
/*User input*/
printf(\"Please Enter the command \");
gets(line);
int len=0;
for(int i=0; line[i]!=\'\\0\'; ++i){len++;}
if(len==0){
return 1;
}
/*Spliting into Tokens*/
operator = strtok(line, \" \");
if(strcmp(operator,\"bye\")==0){
break;
}
/*String to integer --- token1*/
number1=atoi(strtok(NULL, s));
/*Removing ( and ) from String*/
str2=strtok(NULL, s);
char *content;int length=0;
for(int i=0; str2[i]!=\'\\0\'; ++i){length++;}
if(str2[0]==\'(\'){
content=substring(str2,2,length-1);
char *opr=content;
int n1=atoi(strtok(NULL, s));
int n2=atoi(strtok(NULL, s));
/*If user entered more then two operands then it will return some token otherwise it will
return NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}else{
if(strcmp(opr,\"sum\")==0){
number2=sum(n1,n2);
}else if(strcmp(opr,\"sub\")==0){
number2=sub(n1,n2);
}else if(strcmp(opr,\"mul\")==0){
number2=mul(n1,n2);
} else if(strcmp(opr,\"div\")==0){
number2=divide(n1,n2);
}
}
}else{
number2=atoi(str2);
/*If user entered more then two operands then it will return some token otherwise it will return
NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}
}
if(errorFlag!=1){
/*Checking operator by strcmp function*/
if(strcmp(operator,\"sum\")==0){
printf(\"Result %d \ \",sum(number1,number2));
}else if(strcmp(operator,\"sub\")==0){
printf(\"Result %d \ \",sub(number1,number2));
}else if(strcmp(operator,\"mul\")==0){
printf(\"Result %d \ \",mul(number1,number2));
} else if(strcmp(operator,\"div\")==0){
printf(\"Result %.2f \ \",divide(number1,number2));
}
}
}
return 0;
}
/*******************Output***********************/
gopal@gopal:~/Desktop/chegg$ gcc Calculator.c
Calculator.c: In function ‘main’:
Calculator.c:67:3: warning: implici.
prog 5~$AD FOR WHAT TO DO.docxprog 5alerts.txt2009-09-13.docxwkyra78
prog 5/~$AD FOR WHAT TO DO.docx
prog 5/alerts.txt
2009-09-13T20:16,2009-09-13T21:15,26-145,SEVERE THUNDERSTORM WARNING
2009-10-02T10:10,2009-10-13T11:20,39-125,TORNADO WARNING
2009-02-03T06:40,2009-02-03T08:00,15-009,TSUNAMI WARNING
2009-11-15T12:00,2009-11-17T00:00,02-068,WINTER STORM WARNING
2009-09-13T20:10,2009-09-20T12:00,26-111,CHEMICAL EMERGENCY
1776-07-04T00:00,2009-12-31T00:00,11-001,EXCESSIVE GOVT SPENDING
2009-09-29T10:15,2009-10-01T09:00,27-077,FLOOD WARNING
2009-11-01T05:10,2009-11-04T17:00,12-011,HURRICANE WARNING
2009-03-13T10:10,2009-03-24T23:00,49-035,NUCLEAR MATERIAL RELEASE
2009-05-05T02:15,2009-05-07T09:00,02-150,VOLCANIC ASH WARNING
prog 5/READ FOR WHAT TO DO.docx
Purpose
This program will provide an opportunity to practice using multiple C++ classes and class composition.
Specifications
Write a program that will interpret weather and national emergency messages disseminated by the U.S. Government.
The government has created a dataset of "FIPS codes." Each county in the U.S. is assigned a unique five-digit code. This code is used to identify the county when warnings are generated. It is most used for weather warnings, but also could be used for industrial or national emergencies. For example, for Saginaw County, MI, the code is 26145.
You are provided with a data file containing all FIPS codes for each county in the nation (filename usfips.txt). An example line of data in the file would be:
MI,26,145,Saginaw
You are also provided with a file that contains a list of active warnings nationwide (filename alerts.txt). A typical warning message in this file would look like the following example:
2009-09-13T20:16,2009-09-13T21:15,26-145,SEVERE THUNDERSTORM WARNING
Output for this warning message should be something like:
SEVERE THUNDERSTORM WARNING for Saginaw County, MI
Effective: 13 SEP 09 at 8:16 p.m. until 13 SEP 09 at 9:15 p.m
Write your program such that it processes through all active warnings, decodes the data, and writes a warning message similar to the provided example for each alert.
Design your solution using an object-oriented approach. Create a class that will store and manage information for one county. This should include data members for FIPS code, county name, and state code. Include get/set functions for all data members as well as at least one constructor. Next, design a "manager" class that will include and manage a list of FIP code objects. This manager class will act as a "database" of FIP codes. Be sure it includes a function to return the county and state name given a valid FIP code.
Your program should be driven by a list of warning messages(found in file alerts.txt). Each line of data in this file represents a distinct warning message that is disseminated by an agency of the U.S. Government. So finally, create a class that will store one alert message. This will store relevant information about the alert including the FIPS code. Note that objects of the class must have access to a FIPS ...
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfmdameer02
Merge Sort implementation in C++ The implementation for Mergesort given in Section 7.4 takes
an array as input and soils that array. At the beginning of Section 7.4 there is a simple
pseudocode implementation for sorting a linked list using Mergesort. Implement both a linked
list-based version of Mergesort and the array-based version of Mergesort. and compare and
analyze their running times.
Solution
/* Merger sort array-based version */
/* C program for Merge Sort */
#include
#include
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf(\"%d \", A[i]);
printf(\"\ \");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf(\"Given array is \ \");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf(\"\ Sorted array is \ \");
printArray(arr, arr_size);
return 0;
}
--------------------------------------------------------------------------------------------------------------------
/* merge sort link-list version
#include
#include
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* function prototypes */
struct node* SortedMerge(struct node* a, struct node* b);
void FrontBackSplit(struct node* source,
struct node** frontRef, struct node** backRef);
/* sorts the linked list by changing next pointers (not data) */
void MergeSort(struct node** headRef)
{
struct node* head = *headRef;
struct node* a;
struct node* b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
{
return;
}
/* Split head into \'a\' and \'b\' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
MergeSort(&a);
MergeSort(&b);
/* answer = merge the two sorted lists together */
*.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
BUMP implementation in Java.docxThe project is to implemen.docxhartrobert670
BUMP implementation in Java.docx
The project is to implement the BUMP client in java, with window size 1. Here is an overview of the three WUMP protocols (BUMP, HUMP, and CHUMP). Here are the files wumppkt.java, containing the packet format classes, and wclient.java, which contains an outline of the actual program. Only the latter file should be modified; you should not have to make changes to wumppkt.java.
What you are to do is the following, by modifying and extending the wclient.java outline file:
· Implement the basic transfer
· Add all appropriate packet sanity checks: timeouts, host/port, size, opcode, and block number
· Generate output. The transferred file is to be written to System.out. A status message about every packet (listing size and block number) is to be written to System.err. Do not confuse these!
· Terminate after a packet of size less than 512 is received
· Implement an appropriate "dallying" strategy
· send an ERROR packet if it receives a packet from the wrong port. The appropriate ERRCODE in this case is EBADPORT.
An outline of the program main loop is attached
recommended that you implement this in phases, as follows.
1. Latch on to the new port: save the port number from Data[1], and make sure all ACKs get sent to this port. This will mean that the transfer completes. You should also make sure the client stops when a packet with less than 512 bytes of data is received. Unless you properly record the source port for Data[1], you have no place to which to send ACK[1]!
2. For each data packet received, write the data to System.out. All status messages should go to System.err, so the two data streams are separate if stdout is redirected. To write to System.out, use System.out.write:
System.out.write(byte[] buf, int offset, int length);
For your program, offset will be 0, buf will typically be dpacket.data(), where dpacket is of type DATA (wumppkt.DATA). The length will be dpacket.size() - wumppkt.DHEADERSIZE (or, equivalently, dg.getLength() - wumppkt.DHEADERSIZE, where dg is a DatagramPacket object).
3. Add sanity checks, for (in order) host/port, packet size, opcode, and block number.
4. Handle timeouts, by retransmitting the most recently sent packet when the elapsed time exceeds a certain amount (4 seconds?). One way to do this is to keep a DatagramPacket variable LastSent, which can either be reqDG or ackDG, and just resend LastSent. Note that the response to an InterruptedIOException, a "true" timeout, will simply be to continue the loop again.
5. Add support for an dallying and error packets. After the client has received the file, dallying means to wait 2.0 - 3.0 timeout intervals (or more) to see if the final data packet is retransmitted. If it is, it means that the final ACK was lost. The dally period gives the client an opportunity to resend the final ACK. Error packets are to be sent to any sender of an apparent data packet that comes from the wrong port.
vanilla Normal transfer
lose Lose ever ...
Interfacepackage PJ1; public interface SimpleFractionInterface.pdfsutharbharat59
Interface
package PJ1;
public interface SimpleFractionInterface
{
/** Task: Sets a fraction to a given value.
* @param num is the integer numerator
* @param den is the integer denominator
* @throw ArithmeticException if denominator is 0 */
public void setSimpleFraction(int num, int den);
/** Task: convert a fraction to double value
* @return the double floating point value of a fraction */
public double toDouble();
/** Task: Adds two fractions.
* @param secondFraction is a fraction that is the second operand of the addition
* @return a fraction which is the sum of the invoking fraction and the secondFraction */
public SimpleFractionInterface add(SimpleFractionInterface secondFraction);
/** Task: Subtracts two fractions.
* @param secondFraction a fraction that is the second operand of the subtraction
* @return a fraction which is the difference of the invoking fraction and the second operand */
public SimpleFractionInterface subtract(SimpleFractionInterface secondFraction);
/** Task: Multiplies two fractions.
* @param secondFraction a fraction that is the second operand of the multiplication
* @return a fraction which is the product of the invoking fraction and the secondFraction*/
public SimpleFractionInterface multiply(SimpleFractionInterface secondFraction);
/** Task: Divides two fractions.
* @param secondFraction a fraction that is the second operand of the division
* @return a fraction which the quotient of the invoking fraction and the secondFraction
* @throw FractionException if secondFraction is 0 */
public SimpleFractionInterface divide(SimpleFractionInterface secondFraction);
/** Task: Get\'s the fraction\'s reciprocal
* @return the reciprocal of the invoking fraction
* @throw FractionException if the new number with denominator is 0*/
public SimpleFractionInterface getReciprocal();
}
exception class
package PJ1;
public class SimpleFractionException extends RuntimeException
{
public SimpleFractionException()
{
this(\"\");
}
public SimpleFractionException(String errorMsg)
{
super(errorMsg);
}
}
class with main method
package PJ1;
public class SimpleFraction implements SimpleFractionInterface, Comparable
{
// integer numerator and denominator
private int num;
private int den;
public SimpleFraction()
{
setSimpleFraction(0,1);// default numbers
} // end of the default constructor
public SimpleFraction(int num, int den)
{
setSimpleFraction(num, den);//
} // end constructor
public void setSimpleFraction(int num, int den)
{
if (den == 0)
throw new SimpleFractionException(\"denominator cannot be 0\");
else{
this.num= num;
this.den= den;
}
reduceSimpleFractionToLowestTerms();
} // end setSimpleFraction
public double toDouble()
{
// return double floating point value
return (double) num/den;
} // end toDouble
public SimpleFractionInterface add(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b + c/d is (ad + cb)/(bd)
int newNum = num*secondFraction2.getDen() + sec.
Please help solve! Suppose that X is an exponential random variable .pdfaioils
Please help solve! Suppose that X is an exponential random variable with a mean equal to 1.8 .
Another random variable Y is equal to Y=X+aX where a=5.6. Determine the covariance for X
and Y. Round your answer to 2 digits to the right of the decimal. -17.07 margin of error +/0.01.
-- 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",.
Q1 Consider the below omp_trap1.c implantation, modify the code so t.pdfabdulrahamanbags
Q1 Consider the below omp_trap1.c implantation, modify the code so that: i. The time used by
the parallel block is timed using the OpenMP function omp_get_wtime(). The syntax is double
omp_get_wtime ( void ) It returns the number of seconds that have elapsed since some time in
the past. ii. Now on a system with at least two cores, time the program with a. one thread and a
large value of n, and b. two threads and the same value of n. Explain what happens? Then Do the
same measurements for the omp_trap2.c code.
1. How does its performance compare with the performance of the omp_trap1.c ?
2. Explain your answers.
3. provide with your answers the code and detailed screenshots showing how did you compile
and run the code and times for each run:
/* File: omp_trap1.c * Purpose: Estimate definite integral (or area under curve) using trapezoidal
rule. * Input: a, b, n * Output: estimate of integral from a to b of f(x) * using n trapezoids. * *
Compile: gcc -g -Wall -fopenmp -o omp_trap1 omp_trap1.c * Usage: ./omp_trap1 * * Notes: *
1. The function f(x) is hardwired. * 2. In this version, each thread explicitly computes the
integral over its assigned subinterval, a critical directive is used for the global sum. * 3. This
version assumes that n is evenly divisible by the number of threads #include #include #include
#include void Usage(char* prog_name); double f(double x); /* Function we're integrating */
double Local_trap ( double a , double b , i n t n ) ; int main(int argc, char* argv[]) { double
global_result = 0.0; /* Store result in global_result */ double a, b; /* Left and right endpoints */
int n; /* Total number of trapezoids */ int thread_count; if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], NULL, 10); printf("Enter a, b, and n\n"); scanf("%lf %lf %d", &a,
&b, &n); if (n % thread_count != 0) Usage(argv[0]); double global_result = 0.0; # pragma omp p
a r a l l e l num_threads ( t h r e a d _ c o u n t ) { # pragma omp c r i t i c a l global_result +=
Local_trap ( double a , double b , i n t n ) ; } printf("With n = %d trapezoids, our estimate\n", n);
printf("of the integral from %f to %f = %.14e\n", a, b, global_result); return 0; } /* main */ /*----
---------------------------------------------------------------- * Function: Usage * Purpose: Print
command line for function and terminate * In arg: prog_name */ void Usage(char* prog_name) {
fprintf(stderr, "usage: %s \n", prog_name); fprintf(stderr, " number of trapezoids must be evenly
divisible by\n"); fprintf(stderr, " number of threads\n"); exit(0); } /* Usage */ /*---------------------
--------------------------------------------- * Function: f * Purpose: Compute value of function to be
integrated * Input arg: x * Return val: f(x) */ double f(double x) { double return_val; return_val
= x*x; return return_val; } /* f */ /*------------------------------------------------------------------ *
Function: Trap * Purpose: Use trapezoidal rule to estimate definite integral * Input args.
complete the following functions in c++ singleRotation putNo.pdfabbecindia
complete the following functions in c++
singleRotation
putNode: Insert or update the entry in the extended AVL tree map (TreeMapStats) using
the inputted key and value. In addition, efficiently update the statistics information of only
the nodes affected by the insertion of the new entry into the map
eraseNode: Remove the entry in the extended AVL tree map (TreeMapStats) with the
inputted key, if the key is in the map, if necessary. In addition, efficiently update the statistics
information of only the nodes affected by the removal of the new entry from the map
also right a function updateStats
class TreeMapStats : public AVLTreeMap {
public:
// embedded node class extension of an AVL-Tree node
class Node : public AVLTreeMap::Node {
private:
// stats class to account for basic statistics/information of subtree rooted at each node
class Stats {
private:
// data members: number of nodes/map entries stored in the subtree; sum of all the map values of
map entries stored in the subtree; the minimum map value of all the map entries stored in the
subtree; the maximum map value of the map entries stored in the subtree
int num;
int sum;
int min;
int max;
public:
// stats constructors
Stats() { };
Stats(int v, Node *l, Node* r) : num(1), sum(v), min(v), max(v) {
};
// stats destructor
~Stats() { };
// overloading output stream for a representation of stats s
friend ostream& operator<<(ostream& os, const Stats& s) {
os << "{" << s.num << "," << s.sum << "," << s.min << "," << s.max << "}";
return os;
};
};
// data member: node info/stats
Stats *info;
public:
// tree node constructors
Node() : AVLTreeMap::Node() { };
Node(int k, int v, Node* l, Node* r, Node* p) : AVLTreeMap::Node(k,v,l,r,p) {
info = new Stats(v, l, r);
};
// tree node destructor
virtual ~Node() { if (this->info) delete this->info; };
// overloading output stream for a representation of TreeMapStats node w
friend ostream& operator<<(ostream& os, const Node& w) {
os << ((AVLTreeMap::Node) w) << *(w.info) ;
return os;
};
// (overloading) print utility for a node, including map entry and additional info and stats
void printStats() { cout << *this << endl; }
/*
# PRECONDITION: the info values for the left and right nodes for the children of the node have
been properly set, consistent with the subtree that they root
# POSTCONDITION: the info values for the node have been properly set, consistent with the
subtree that it roots
*/
};
// print utilities
void printTreeMapStats();
void printTreeMapStats(Node* w);
void printTreeMap();
// tree constructor
TreeMapStats() { };
// tree desctructor
virtual ~TreeMapStats() { };
protected:
// (overloadable) auxiliary node creation utility
virtual Node* createNode(int k, int v, BSTMap::Node* l, BSTMap::Node* r, BSTMap::Node* p) {
return new Node(k,v,(Node*) l, (Node*) r, (Node*) p); };
// prints a representation of AVL node w
// (overloadable)
// INPUT: node w
virtual void printNode(const BSTMap::Node* w) const { if (w) cout << *((Node*) w); };
// (overloa.
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docxMARRY7
/* Lab Assignment 4 CSE330 Spring 2014 */
/* Skeleton Code for ex0 of lab4 */
/* No code will be provided for ex1 of lab4 */
#include <stdio.h> /* for NULL */
#include <ctype.h> /* for atoi() */
#include <errno.h> /* for perror() */
#include <signal.h> /* for sigvec() etc. */
#include <sys/types.h> /* for <arpa/inet.h> */
#include <sys/socket.h> /* for PF_INET, etc. */
#include <netinet/in.h> /* for struct sockaddr_in */
#include <arpa/inet.h> /* for inet_addr() */
#include <sys/time.h>
#include "lab4.h"
/* this is in netinet/in.h; included here for reference only.
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
*/
/***************************************************************************/
#define LINESIZE 80
#define TYPE0TIMEOUT 3
#define TYPE1TIMEOUT 30
/* You should give a long timeout, like 30sec, otherwise */
/* duplicated responses from the server may cause some problem */
#define MAXRETRY 3
/***************************************************************************/
static char *RCSId="$Id: client2.c,v 4 2014/04/20 03:15:07 cse3300 Exp $";
/***************************************************************************/
/* some functions you may find useful if you implement them */
extern int stringToAddress(char *s, struct sockaddr_in *a);
extern int msgok(LABMSG *);
extern u_short msgchecksum(u_short *);
extern void alarmCatcher(void);
extern int tries; /* for retransmission routines */
int numtries;
/***** this will die ****/
FILE *logFile;
void die(char *s)
{
perror(s);
exit(2);
}
void startTimer(int secs)
{
alarm(secs);
}
void stopTimer(void)
{
alarm(0);
}
/* should change it by yourself if needed!!! */
void printResponse(LABMSG *mp, int ck)
{
int type;
mp->courseEtc = ntohs(mp->courseEtc);
type = ( (mp->courseEtc & MESSAGETYPE) !=0)?1:0;
printf("course=%d, Type=%d\n", mp->courseEtc&0x3fff,type);
if (ntohl(mp->cookie) != ck)
printf("Cookies don't match: sent %x received %x\n",mp->cookie,ck);
if (mp->courseEtc & REQRESP)
printf("response ");
else {
printf("request??\n");
return;
}
mp->result = ntohs(mp->result);
/*printf(" result = %x: ",mp->result);*/
if (mp->result&TRANSOUTCOME) { /* Check outcome */
printf("error: ");
switch (mp->result & 0x7fff) {
case ERROR_CHECKSUM:
printf("checksum failure\n");
break;
case ERROR_SYNTAX:
printf("syntax error\n");
break;
case ERROR_UNKSSN:
printf("unknown SSN %d\n", ntohl(mp->reqSSN) );
break;
case ERROR_SERVER:
printf("Unspecified Server Error\n");
default:
printf("Unknown Error.\n");
} /* case switch */
} else { /* successful transaction */
if(type)printf("Test succeeded.");
if (!type) /* Type 0 -- print SSN and Response */
printf(": %d -> %d\n", ntohl(mp->reqSSN), mp->result&0x7fff);
else
printf("\n"); /* XXX print number of responses */
}
}
/*-----------------------------------*/
/* added by ZXC:
this fun ...
Complete in JavaCardApp.javapublic class CardApp { private.pdfMAYANKBANSAL1981
Complete in Java
CardApp.java
public class CardApp {
private LinkedList list;
/**
* User interface prompts user, reads and writes files.
*/
public static void main(String[] args) {
}
/**
* Default constructor to initialize the deck
*/
public CardApp() {
}
/**
* Inserts a new Card into the deck
* @param card a playing Card
*/
public void addCard(Card card) {
}
/**
* Shuffles cards following this algorithm:
* First swaps first and last card
* Next, swaps every even card with the card 3
* nodes away from that card. Stops when it
* reaches the 3rd to last node
* Then, swaps ALL cards with the card that is
* 2 nodes away from it, starting at the 2nd card
* and stopping stopping at the 3rd to last node
*/
public void shuffle() {
}
/**
* Implements the bubble sort algorithm
* to sort cardList into sorted order, first by suit
* (alphabetical order)
* then by rank from 2 to A
*/
public void sort() {
}
/**
* Returns the deck of cards with each card separated
* by a blank space and a new line character at the end.
* @return The deck of cards as a string.
*/
@Override public String toString() {
return "";
}
}
Card.java
public class Card implements Comparable{
private String rank;
private String suit;
/**
* Constructor for the Card class
* @param rank the rank of card from 2 to A
* @param suit the suit of card C, D, H, or S
*/
public Card(String rank, String suit) {
}
/**
* Returns the card's rank
* @return rank a rank from 2 (low) to A (high)
*/
public String getRank() {
return "";
}
/**
* Returns the card's suit
* @return C, D, H, or S
*/
public String getSuit() {
return "";
}
/**
* Updates the card's rank
* @param rank a new rank
*/
public void setRank(String rank) {
}
/**
* Updates the card's suit
* @param suit the new suit
*/
public void setSuit(String suit) {
}
/**
* Concatenates rank and suit
* @return card rank and suit
*/
@Override public String toString() {
return "";
}
/**
* Overrides the equals method for Card
* Compares rank and suit and
* follows the equals formula given in
* Lesson 4 and also in Joshua Block's text
* @param obj another Object to compare for
* equality
* @return whether obj is a Card and, if so,
* of equal rank and suit
*/
@Override public boolean equals(Object obj) {
return false;
}
/**
* Orders two cards first by suit (alphabetically)
* Next by rank. "A" is considered the high card
* Order goes 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K, A
* @param card another Card to compare to this Card
* @return a negative number if this comes before c
* and a positive number if c comes before this
* and 0 if this and c are equal according to the above
* equals method
*/
@Override public int compareTo(Card card) {
return -1;
}
}
}
LinkedList.Java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterato.
The following is the (incomplete) header file for the class Fracti.pdf4babies2010
The following comparative income statement (in thousands of dollars) for the two recent fiscal
years was adapted from the annual report of Speedway Motorsports, Inc., owner and operator of
several major motor speedways, such as the Atlanta, Texas, and Las Vegas Motor Speedways.
Current Year Previous Year 2 Revenues: 3 Admissions 4Event-related revenue $104,312.00
$116,644.00 131,164.00 170,368.00 65,824.00 $472,000.00 $484,000.00 42,544.00 180,304.00
44,840.00 NASCAR broadcasting revenue Other operating revenue 7 Total revenue 8 Expenses
and other: 9 Direct expense of events 10 NASCAR purse and sanction fees 91,568.00
$101,640.00 117,612.00 20,328.00 220,220.00 424800.00 $459,800.00 $24,200.00 118,000.00
19,352.00 195,880.00 11 Other direct expenses 2 General and administrative 13 Total expenses
and other Income from continuing operations $47,200.00 14 Required A. Prepare a comparative
income statement for these two years in vertical form, stating each item as a percent of revenues.
Enter all amounts as positive numbers. Rounding instructions
Solution
VERTICAL ANALYSIS OF INCOME STATEMENT Particulars Current Year
Amount Current Year Percentage Previous Year Amount Previous Year Percentage
Admissions $ 1,04,312.00 22.10% $ 1,16,644.00 24.10% Event Related revenue $ 1,42,544.00
30.20% $ 1,31,164.00 27.10% NASCAR Broadcasting Revenue $ 1,80,304.00 38.20% $
1,70,368.00 35.20% Other Operating Income $ 44,840.00 9.50% $ 65,824.00 13.60%
Total Revenue $ 4,72,000.00 100.00% $ 4,84,000.00 100.00% Expenses and others
Direct expenses of events $ 91,568.00 19.40% $ 1,01,640.00 21.00% NASCAR purse and
sanction fees $ 1,18,000.00 25.00% $ 1,17,612.00 24.30% Other direct expenses $ 19,352.00
4.10% $ 20,328.00 4.20% General and adminstrative $ 1,95,880.00 41.50% $ 2,20,220.00
45.50% Total Expenses and others $ 4,24,800.00 90.00% $ 4,59,800.00 95.00% Income
from continuing operation $ 47,200.00 10.00% $ 24,200.00 5.00%.
CC++ echo serverThis assignment is designed to introduce network .pdfsecunderbadtirumalgi
C/C++ echo server
This assignment is designed to introduce network programing and the socket API. You will build
a simple ECHO server, that is a program that accepts incoming connection requests and then
echoes back any string that is sent.
Required Behavior
1. Your submission must be written in C or C++ and must compile and run on the schools Linux
server.
2. Your code should be clean and easy to read with reasonable comments and variable names.
3. You must provide a makefile that compiles your program. It should compile without errors or
warnings to a binary named echo_s.
4. Your program should take one optional command line argument, -v, that invokes verbose
mode causing the program to print diagnostic messages as it operates.
5. When run the program should:
* Create a socket and prepare it to listen for incoming TCP connections on the port of your
choice.
* Print Using port: X to tell the user what port your program is listening on.
* Begin waiting for a new connection
* When a new connection is established:
- Read a block of data from the connection note the length of the data received (blocks can
be up to 1024 bytes long)
- Check the block to see if it starts with the letters CLOSE or QUIT.
+If CLOSE, close the connection and start waiting for another connection (return to
waiting for a connection).
+If QUIT, close the connection and the listening socket and exit your program.
- Send the block back with a write() call.
- Return to waiting for the next block of data from the client.
6. If run with the v flag you should print a diagnostic message at least
* When the socket is opened
* When the socket is bound.
* Before it blocks waiting for a new connection.
* When a new connection is accepted.
* Before it blocks waiting for new data.
* When you get a block of data.
* If the data included the CLOSE command,
* If the data included the QUIT command.
* Any other time you think it would be useful.
Suggested Approach
There is some skeleton code at the end
The skeleton includes a makefile and everything you need to get started.
Once you have the skeleton setup and running you should start filling in the code. You may of
course do this however you like, but I would recommend the following:
* Fill in the sections of main() required to process command line arguments, create, bind,
establish a listening queue and then close a stream type socket.
- If you run the program without the v flag it should print what port was selected, then exit.
- If you run the program with the v you should see each step of the socket creation process.
* Add code to accept new connection requests and as requests are received call the
processConnection() At this point you can test by connect to the program with telnet.
* At this point you should have the functioning skeleton of a TCP server application. Up to this
point the structure of all server applications are almost identical, regardless of the application
protocol they are going to implement.
* Modify the processCon.
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
write the To Do\'s to get the exact output:
NOte: A valid Fraction number has a non-negative numerator and a positive denominator.
Default constructor initializes the object to safe empty state (an object with denom equals -1).
The two-argument constructor also validates the parameters and sets the object to the safe empty
state if the parameters are not valid.
Write the definitions and prototypes of following functions in Fraction.cpp and Fraction.h
respectively (They are indicated in the files by //TODO tag):
Define isEmpty function as a member function, which returns true if the object is in safe empty
state (an object is in the safe empty state if denominator (denom) equals -1).
Define display function, which sends a Fraction number to the output stream (with the
“Numerator/denominator” format). This function just prints \"Invalid Fraction Object!\" in the
screen if the object is in the safe empty state. In case that object denominator equals 1, it just
print the numerator.
Define the operator functions for the following operators:
“+=”, “+”, “*”
The overload of the above operators should make the following code possible:
The member operator+ : Adds two Fraction numbers and returns a Fraction number as the result.
This function returns an object with the safe empty state if either of Fraction numbers (operands)
is in safe empty state. It makes following code possible:
A+B ( where A and B are Fraction objects)
The member operator+= : Adds two Fraction numbers and assigns the result to the left operand,
then returns a reference to the left operand. If either of Fraction numbers (operands) is in safe
empty state, it initializes the left operand to the safe empty state, then returns a reference to the
left operand. It makes following code possible:
A+=B ( where A and B are Fraction objects)
The member operator* : Multiplies two Fraction numbers and returns a Fraction number as the
result. This function returns an object with the safe empty state if either of Fraction numbers
(operands) is in safe empty state. It makes following code possible:
A*B ( where A and B are Fraction objects)
fraction.cpp
#include \"Fraction.h\"
using namespace std;
namespace sict{
Fraction::Fraction(){
denom =-1; // safe empty state
}
Fraction::Fraction(int n, int d) // n: numerator, d: denominator
{
if(n >= 0 && d > 0){
num = n;
denom = d;
reduce();
}
else
denom =-1; // set to safe empty state
}
int Fraction::gcd() // returns the greatest common divisor of num and
denom
{
int mn = min(); // min of num and denom
int mx = max(); // mX of num and denom
for (int x=mn ; x > 0 ; x--) // find the greatest common divisor
if( mx % x == 0 && mn % x == 0)
return x;
return 1;
}
void Fraction::reduce() // simplify the Fraction number
{
int tmp = gcd();
num /= tmp;
denom /= tmp;
}
int Fraction::max ()
{
return (num >= denom) ? num : denom;
}
int Fraction::min()
{
return (num >= denom) ? denom : num;
}
// in_lab
// TODO: write the implementation of display function HERE
// TODO: w.
operating system ubuntu,linux,MacProgram will work only if you g.pdfaptcomputerzone
//operating system ubuntu,linux,Mac
Program will work only if you give command like
sum 2 3 or
sum 4 (sub 4 3)
#include
#include
#include
#include
/*Sum function implementation*/
int sum(int number1,int number2){
return number1+number2;
}
/*sub function implementation*/
int sub(int number1,int number2){
return number1-number2;
}
/*mul function implementation*/
int mul(int number1,int number2){
return number1*number2;
}
/*divide function implementation*/
float divide(int number1,int number2){
if(number2==0){
printf(\"We can not divide by 0 \ \");
return 0.0f;
}
return (float)(number1/number2);
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = malloc(length+1);
if (pointer == NULL)
{
printf(\"Unable to allocate memory.\ \");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = \'\\0\';
return pointer;
}
/*Main Function start*/
int main(int argc, char *argv[]){
/*Variable declarations*/
int number1,number2;
char *operator,*str1,*str2;
char line[50];
char s[2] = \" \";
int errorFlag=0;// checking if user entered more then one operands
while(1){
/*User input*/
printf(\"Please Enter the command \");
gets(line);
int len=0;
for(int i=0; line[i]!=\'\\0\'; ++i){len++;}
if(len==0){
return 1;
}
/*Spliting into Tokens*/
operator = strtok(line, \" \");
if(strcmp(operator,\"bye\")==0){
break;
}
/*String to integer --- token1*/
number1=atoi(strtok(NULL, s));
/*Removing ( and ) from String*/
str2=strtok(NULL, s);
char *content;int length=0;
for(int i=0; str2[i]!=\'\\0\'; ++i){length++;}
if(str2[0]==\'(\'){
content=substring(str2,2,length-1);
char *opr=content;
int n1=atoi(strtok(NULL, s));
int n2=atoi(strtok(NULL, s));
/*If user entered more then two operands then it will return some token otherwise it will
return NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}else{
if(strcmp(opr,\"sum\")==0){
number2=sum(n1,n2);
}else if(strcmp(opr,\"sub\")==0){
number2=sub(n1,n2);
}else if(strcmp(opr,\"mul\")==0){
number2=mul(n1,n2);
} else if(strcmp(opr,\"div\")==0){
number2=divide(n1,n2);
}
}
}else{
number2=atoi(str2);
/*If user entered more then two operands then it will return some token otherwise it will return
NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}
}
if(errorFlag!=1){
/*Checking operator by strcmp function*/
if(strcmp(operator,\"sum\")==0){
printf(\"Result %d \ \",sum(number1,number2));
}else if(strcmp(operator,\"sub\")==0){
printf(\"Result %d \ \",sub(number1,number2));
}else if(strcmp(operator,\"mul\")==0){
printf(\"Result %d \ \",mul(number1,number2));
} else if(strcmp(operator,\"div\")==0){
printf(\"Result %.2f \ \",divide(number1,number2));
}
}
}
return 0;
}
/*******************Output***********************/
gopal@gopal:~/Desktop/chegg$ gcc Calculator.c
Calculator.c: In function ‘main’:
Calculator.c:67:3: warning: implici.
prog 5~$AD FOR WHAT TO DO.docxprog 5alerts.txt2009-09-13.docxwkyra78
prog 5/~$AD FOR WHAT TO DO.docx
prog 5/alerts.txt
2009-09-13T20:16,2009-09-13T21:15,26-145,SEVERE THUNDERSTORM WARNING
2009-10-02T10:10,2009-10-13T11:20,39-125,TORNADO WARNING
2009-02-03T06:40,2009-02-03T08:00,15-009,TSUNAMI WARNING
2009-11-15T12:00,2009-11-17T00:00,02-068,WINTER STORM WARNING
2009-09-13T20:10,2009-09-20T12:00,26-111,CHEMICAL EMERGENCY
1776-07-04T00:00,2009-12-31T00:00,11-001,EXCESSIVE GOVT SPENDING
2009-09-29T10:15,2009-10-01T09:00,27-077,FLOOD WARNING
2009-11-01T05:10,2009-11-04T17:00,12-011,HURRICANE WARNING
2009-03-13T10:10,2009-03-24T23:00,49-035,NUCLEAR MATERIAL RELEASE
2009-05-05T02:15,2009-05-07T09:00,02-150,VOLCANIC ASH WARNING
prog 5/READ FOR WHAT TO DO.docx
Purpose
This program will provide an opportunity to practice using multiple C++ classes and class composition.
Specifications
Write a program that will interpret weather and national emergency messages disseminated by the U.S. Government.
The government has created a dataset of "FIPS codes." Each county in the U.S. is assigned a unique five-digit code. This code is used to identify the county when warnings are generated. It is most used for weather warnings, but also could be used for industrial or national emergencies. For example, for Saginaw County, MI, the code is 26145.
You are provided with a data file containing all FIPS codes for each county in the nation (filename usfips.txt). An example line of data in the file would be:
MI,26,145,Saginaw
You are also provided with a file that contains a list of active warnings nationwide (filename alerts.txt). A typical warning message in this file would look like the following example:
2009-09-13T20:16,2009-09-13T21:15,26-145,SEVERE THUNDERSTORM WARNING
Output for this warning message should be something like:
SEVERE THUNDERSTORM WARNING for Saginaw County, MI
Effective: 13 SEP 09 at 8:16 p.m. until 13 SEP 09 at 9:15 p.m
Write your program such that it processes through all active warnings, decodes the data, and writes a warning message similar to the provided example for each alert.
Design your solution using an object-oriented approach. Create a class that will store and manage information for one county. This should include data members for FIPS code, county name, and state code. Include get/set functions for all data members as well as at least one constructor. Next, design a "manager" class that will include and manage a list of FIP code objects. This manager class will act as a "database" of FIP codes. Be sure it includes a function to return the county and state name given a valid FIP code.
Your program should be driven by a list of warning messages(found in file alerts.txt). Each line of data in this file represents a distinct warning message that is disseminated by an agency of the U.S. Government. So finally, create a class that will store one alert message. This will store relevant information about the alert including the FIPS code. Note that objects of the class must have access to a FIPS ...
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfmdameer02
Merge Sort implementation in C++ The implementation for Mergesort given in Section 7.4 takes
an array as input and soils that array. At the beginning of Section 7.4 there is a simple
pseudocode implementation for sorting a linked list using Mergesort. Implement both a linked
list-based version of Mergesort and the array-based version of Mergesort. and compare and
analyze their running times.
Solution
/* Merger sort array-based version */
/* C program for Merge Sort */
#include
#include
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf(\"%d \", A[i]);
printf(\"\ \");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf(\"Given array is \ \");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf(\"\ Sorted array is \ \");
printArray(arr, arr_size);
return 0;
}
--------------------------------------------------------------------------------------------------------------------
/* merge sort link-list version
#include
#include
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* function prototypes */
struct node* SortedMerge(struct node* a, struct node* b);
void FrontBackSplit(struct node* source,
struct node** frontRef, struct node** backRef);
/* sorts the linked list by changing next pointers (not data) */
void MergeSort(struct node** headRef)
{
struct node* head = *headRef;
struct node* a;
struct node* b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
{
return;
}
/* Split head into \'a\' and \'b\' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
MergeSort(&a);
MergeSort(&b);
/* answer = merge the two sorted lists together */
*.
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
Please read the comment ins code
ExpressionTree.java
----------------------------------
/**
* This is the class for Expression Tree.
* Used to create Expression Tree and Evaluate it
*/
/**
* Following logic is used to construct a Tree
* Here we use stack for Preparing Tree
* Loop through given Expression String
* If Character is Operand , Create node and push to stack
* If Character is Operator then
* 1)Create Node for Operator
* 2)Pop 2 nodes from Stack and Made
* OpretorNode--> left == first node pop
* OpretorNode--> right == second node pop
* At the end of creation of Expression Tree, Stack have only one node , which is root of
Expression tree
*/
/** Class ExpressionTree **/
class ExpressionTree
{
/** class TreeNode
* Stored Character ==> Digit(0..9) or a Operator +,-,*,/
* Left Node and Right Node
*
* **/
class TreeNode
{
char data;
TreeNode left, right;
/** constructor **/
public TreeNode(char data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
/** class StackNode **/
class StackNode
{
TreeNode treeNode;
StackNode next;
/** constructor **/
public StackNode(TreeNode treeNode)
{
this.treeNode = treeNode;
next = null;
}
}
private static StackNode top;
/** constructor
* Constructor takes input string like \"+-+7*935*82*625\"
* Input should be in Prefix notation
* **/
public ExpressionTree(String expression)
{
top = null;
//Call Method for prepare expression tree
buildTree(expression);
}
/** function to clear tree **/
public void clear()
{
top = null;
}
/** function to push a node **/
private void push(TreeNode ptr)
{
if (top == null)
top = new StackNode(ptr);
else
{
StackNode nptr = new StackNode(ptr);
nptr.next = top;
top = nptr;
}
}
/** function to pop a node
* When it find operator pop 2 elements from Stack
*
* **/
private TreeNode pop()
{
if (top == null)
throw new RuntimeException(\"Underflow\");
else
{
TreeNode ptr = top.treeNode;
top = top.next;
return ptr;
}
}
/** function to get top node **/
private TreeNode peek()
{
return top.treeNode;
}
/** function to insert character **/
private void insert(char val)
{
try
{
//If Operand , Create node and push to Stack
if (isDigit(val))
{
TreeNode nptr = new TreeNode(val);
push(nptr);
}
//If Operator , Create node and popup 2 elements and make them its right and left
else if (isOperator(val))
{
TreeNode nptr = new TreeNode(val);
nptr.left = pop();
nptr.right = pop();
push(nptr);
}
}
catch (Exception e)
{
System.out.println(\"Invalid Expression\");
}
}
/** function to check if digit **/
private boolean isDigit(char ch)
{
return ch >= \'0\' && ch <= \'9\';
}
/** function to check if operator **/
private boolean isOperator(char ch)
{
return ch == \'+\' || ch == \'-\' || ch == \'*\' || ch == \'/\';
}
/** function to convert character to digit **/
private int toDigit(char ch)
{
return ch - \'0\';
}
/** function to build tree from input */
public void buildTree(String eqn)
{
for (int i = eqn.length() - 1; i >= 0; i--)
insert(eqn.charAt(i));
}
/** function to evaluate tree */
public dou.
BUMP implementation in Java.docxThe project is to implemen.docxhartrobert670
BUMP implementation in Java.docx
The project is to implement the BUMP client in java, with window size 1. Here is an overview of the three WUMP protocols (BUMP, HUMP, and CHUMP). Here are the files wumppkt.java, containing the packet format classes, and wclient.java, which contains an outline of the actual program. Only the latter file should be modified; you should not have to make changes to wumppkt.java.
What you are to do is the following, by modifying and extending the wclient.java outline file:
· Implement the basic transfer
· Add all appropriate packet sanity checks: timeouts, host/port, size, opcode, and block number
· Generate output. The transferred file is to be written to System.out. A status message about every packet (listing size and block number) is to be written to System.err. Do not confuse these!
· Terminate after a packet of size less than 512 is received
· Implement an appropriate "dallying" strategy
· send an ERROR packet if it receives a packet from the wrong port. The appropriate ERRCODE in this case is EBADPORT.
An outline of the program main loop is attached
recommended that you implement this in phases, as follows.
1. Latch on to the new port: save the port number from Data[1], and make sure all ACKs get sent to this port. This will mean that the transfer completes. You should also make sure the client stops when a packet with less than 512 bytes of data is received. Unless you properly record the source port for Data[1], you have no place to which to send ACK[1]!
2. For each data packet received, write the data to System.out. All status messages should go to System.err, so the two data streams are separate if stdout is redirected. To write to System.out, use System.out.write:
System.out.write(byte[] buf, int offset, int length);
For your program, offset will be 0, buf will typically be dpacket.data(), where dpacket is of type DATA (wumppkt.DATA). The length will be dpacket.size() - wumppkt.DHEADERSIZE (or, equivalently, dg.getLength() - wumppkt.DHEADERSIZE, where dg is a DatagramPacket object).
3. Add sanity checks, for (in order) host/port, packet size, opcode, and block number.
4. Handle timeouts, by retransmitting the most recently sent packet when the elapsed time exceeds a certain amount (4 seconds?). One way to do this is to keep a DatagramPacket variable LastSent, which can either be reqDG or ackDG, and just resend LastSent. Note that the response to an InterruptedIOException, a "true" timeout, will simply be to continue the loop again.
5. Add support for an dallying and error packets. After the client has received the file, dallying means to wait 2.0 - 3.0 timeout intervals (or more) to see if the final data packet is retransmitted. If it is, it means that the final ACK was lost. The dally period gives the client an opportunity to resend the final ACK. Error packets are to be sent to any sender of an apparent data packet that comes from the wrong port.
vanilla Normal transfer
lose Lose ever ...
Interfacepackage PJ1; public interface SimpleFractionInterface.pdfsutharbharat59
Interface
package PJ1;
public interface SimpleFractionInterface
{
/** Task: Sets a fraction to a given value.
* @param num is the integer numerator
* @param den is the integer denominator
* @throw ArithmeticException if denominator is 0 */
public void setSimpleFraction(int num, int den);
/** Task: convert a fraction to double value
* @return the double floating point value of a fraction */
public double toDouble();
/** Task: Adds two fractions.
* @param secondFraction is a fraction that is the second operand of the addition
* @return a fraction which is the sum of the invoking fraction and the secondFraction */
public SimpleFractionInterface add(SimpleFractionInterface secondFraction);
/** Task: Subtracts two fractions.
* @param secondFraction a fraction that is the second operand of the subtraction
* @return a fraction which is the difference of the invoking fraction and the second operand */
public SimpleFractionInterface subtract(SimpleFractionInterface secondFraction);
/** Task: Multiplies two fractions.
* @param secondFraction a fraction that is the second operand of the multiplication
* @return a fraction which is the product of the invoking fraction and the secondFraction*/
public SimpleFractionInterface multiply(SimpleFractionInterface secondFraction);
/** Task: Divides two fractions.
* @param secondFraction a fraction that is the second operand of the division
* @return a fraction which the quotient of the invoking fraction and the secondFraction
* @throw FractionException if secondFraction is 0 */
public SimpleFractionInterface divide(SimpleFractionInterface secondFraction);
/** Task: Get\'s the fraction\'s reciprocal
* @return the reciprocal of the invoking fraction
* @throw FractionException if the new number with denominator is 0*/
public SimpleFractionInterface getReciprocal();
}
exception class
package PJ1;
public class SimpleFractionException extends RuntimeException
{
public SimpleFractionException()
{
this(\"\");
}
public SimpleFractionException(String errorMsg)
{
super(errorMsg);
}
}
class with main method
package PJ1;
public class SimpleFraction implements SimpleFractionInterface, Comparable
{
// integer numerator and denominator
private int num;
private int den;
public SimpleFraction()
{
setSimpleFraction(0,1);// default numbers
} // end of the default constructor
public SimpleFraction(int num, int den)
{
setSimpleFraction(num, den);//
} // end constructor
public void setSimpleFraction(int num, int den)
{
if (den == 0)
throw new SimpleFractionException(\"denominator cannot be 0\");
else{
this.num= num;
this.den= den;
}
reduceSimpleFractionToLowestTerms();
} // end setSimpleFraction
public double toDouble()
{
// return double floating point value
return (double) num/den;
} // end toDouble
public SimpleFractionInterface add(SimpleFractionInterface secondFraction)
{
SimpleFraction secondFraction2;
secondFraction2 = (SimpleFraction) secondFraction;
// a/b + c/d is (ad + cb)/(bd)
int newNum = num*secondFraction2.getDen() + sec.
Please help solve! Suppose that X is an exponential random variable .pdfaioils
Please help solve! Suppose that X is an exponential random variable with a mean equal to 1.8 .
Another random variable Y is equal to Y=X+aX where a=5.6. Determine the covariance for X
and Y. Round your answer to 2 digits to the right of the decimal. -17.07 margin of error +/0.01.
Please help me i will give good rating a) A wheel has 37 numbers 0.pdfaioils
Please help me i will give good rating a) A wheel has 37 numbers: 0,1,2,,35,36. The number
zero represents green, half of the other numbers represent red and the rest are black. A small ball
is thrown onto a spinning wheel and comes to rest on one of the numbers. What is the probability
that the number is i. 24 ? ii. Red? iii. Not 24? iv. Not Green?.
Please help me answer this question.Explain how oxygen content acc.pdfaioils
Please help me answer this question.
Explain how oxygen content accurately describes oxygen delivery to the tissues and explain why
PaO2, SaO2, and hemoglobin (Hb) are often unreliable measures of total oxygen delivery to the
tissues..
PLEASE HELP IN C++For this test, you will need to create the follo.pdfaioils
PLEASE HELP IN C++
For this test, you will need to create the following function. First add the function prototype to
person.h, then put the function implementation in person.cpp and finally invoke/test the function
in main.cpp. Please label your output clearly. E.g. After adding a person, the list is:
Create a function to read a persons information and insert into the list at a given position. The
function returns true if the insertion is successful and it returns false if the array is out of
capacity.
bool addPerson(PersonType list[], int &count);
Sample code in person.cpp
PersonType aPerson;
//read in person name, person citizenship, and age and populate aPerson
//e.g strcpy(aPerson.name, tempName)
//read position to insert inside the function - see sample //run
//position could be read from the user or you could set a //number that is not more than count. If
you read from the //user, check to make sure position is not > than count.
//shift and insert aPerson in the right position
Sample test code in main.cpp
if(addPerson(list, count) == true)
{output list}
You must be able to read cstrings with spaces.
You must not replace any existing values in the list. You must shift and insert in the right
position. See zybooks Lab 11.9 for reference.
You must be able to add at the beginning of the list and at the end - if your list has 4 elements,
users must be able to insert at position 0 through 4.
See Sample Runs below and test your code multiple times adding users at the beginning and at
the end.
You must make sure the position is within count.
You must check for unreasonable age (for example: age < 1 and age > 100 can be unreasonable).
Include a welcome and goodbye message. (See sample run below).
Must use all the given function prototypes under Task exactly as is. Function Prototypes and
implementations must be written in the appropriate files.
Do not add header comments for this exam, but you must have function comments for the
function you are writing.
Do not use containers of any sort or any vectors for this program. Use only the concepts we have
learned so far.
Criteria for Success
Test your program using the following sample runs, making sure you get the same output when
using the given inputs (in blue):
Welcome to my Citizens Database.
Here is your list so far:
Gayathri;USA;22
Stephanie;USA;27
Priya;India;34
Ahmed;Nigeria;52
Enter your name:
Navid
Enter your citizenship:
Ecuador
Enter your age:
34
Enter position number:
2
After adding a person, the list is:
Gayathri;USA;22
Stephanie;USA;27
Navid;Ecuador;34
Priya;India;34
Ahmed;Nigeria;52
Thank you for using my Citizen Database!!
Welcome to my Citizens Database.
Here is your list so far:
Gayathri;USA;22
Stephanie;USA;27
Priya;India;34
Ahmed;Nigeria;52
Enter your name:
Navid
Enter your citizenship:
Ecuador
Enter your age:
34
Enter position number:
9
Error! Invalid position.
Thank you for using my Citizen Database!!
Welcome to my Citizens Database.
Here is your list so far:
Gayathri;USA;22
S.
please help and thank you ! Experiments by Murphy et al. (2014) on t.pdfaioils
please help and thank you ! Experiments by Murphy et al. (2014) on the niches of parasitoid
wasps \& flies that parasitize slug caterpillars showed: [Select all that apply.] Wasps
preferentially parasitized smaller caterpillars. Wasps preferentially parasitized larger caterpillars.
Flies preferentially parasitized larger caterpillars. Wasps \& flies reduced competition through
niche partitioning. Wasps \& flies reduced competition by being active during different seasons
of the moth-caterpillar life cycles. Flies preferentially parasitized smaller caterpillars..
PLEASE HELP (also please dont answer with path because there is no .pdfaioils
PLEASE HELP (also please don't answer with path because there is no path provided from the
directions in this lab nor in the description)
What is the MD5 hash for the file 022m2001.gif? 5 How many files in the hashes file are
unknown when compared against NSRL? What does RDS stand for?.
please explain these topics if possible How companies account for.pdfaioils
please explain these topics if possible
How companies account for debt and equity investments (intent and valuation) Accounting for
debt securities (held to maturity, trading, and available for sale) Equity investment valuation
methods based on percentage ownership Accounting for equity securities (holdings less than
20%, holdings between 20% and 50%, and holdings more than 50% ) Financial Reporting - Fair
Value Option.
Pls introduced to various themes and theoretical issues pertaining t.pdfaioils
Pls introduced to various themes and theoretical issues pertaining to Global Entrepreneurship and
Innovation of Global Marketing; brands and social media.
You need to formally introduced to various themes and theoretical issues and challenges of
Global Entrepreneurship, Innovation, and Sustainability. An important aspect of this is exploring
the impact and disruption caused by the Covid 19 pandemic, climate change, and other key
themes and issues being prioritized by stakeholders in offering local and global solutions.
Pls be your own words (1200 -1500 words)
Thanks you..
please! 1. Match and pair the following basic genetic conce.pdfaioils
please!
1. Match and pair the following basic genetic concepts with their respective
descriptions/definitions: 1. Gene a. Two different alleles 2. Allele b. Observable heritable feature
that may vary among organisms. 3. Phenotype c. Two identical alleles 4. Genotype d. Describes
the specific alleles present in the offspring. 5. Homozygous e. Segments of DNA responsible for
producing a particular trait. 6. Heterozygous f. Variants of a gene present for a particular
character. 2. From the figure presented here, determine the following: a. Which letter(s) show a
phenotype? b. Which letter(s) show a genotype? c. In letter (c), are we looking at a homozygous
recessive, a homozygous dominant, or a heterozygous individual? d. In letter (e), are we looking
at a homozygous recessive, a homozygous dominant, or a heterozygous individual?
3. A and a are dominant and recessive alleles, respectively, of the same gene. Which genotype(s)
would result in an individual with the dominant trait? A) AA and aa B) AA and aa C) only AA
D) AA and Aa E) only Aa 4. For Labrador retrievers, black fur color (B) is dominant to yellow
fur color (b). If a heterozygous black male mated with a homozygous yellow female, what would
the puppies look like? Determine the phenotypic ratios. - Step 1: Determine the genotype of the
female and male Labradors. Heterozygous black male: Homozygous yellow female: - Step 2:
Write/Type the cross between the two Labradors. X -Step 3: Do a Punnett Square to determine
the probable genotypes for the offspring and to determine the phenotypic ratio.
-Step 4: Determine the Phenotype ratios of the progeny: s. There are many humans traits that are
fairly simple and that follow the Mendelian pattern of inheritance. However, most of our traits
are much more complex, involving many genes or interactions between genes. For example, hair
color is determined by at least four genes, each one coding for the productions of melanin, a
brown pigment. Because the effect of these genes is cumulative, hair color can range from
blonde (little melanin) to very dark brown (much melanin). 2 Human traits are of great interest to
us and there are few traits that seem to exhibit Mendelian inheritance, such as the ones shown
below (this can be found in your lab manual). Figure 134 some madiy absenutle human
Menoulae tak. Mid-digital hair b. Tongue rolling c. Widow's peak d. Earlobe attachment e.
Hitchhiker's thumb f. Relative finger length With the information provided in your lab manual,
Section 13-3 (pages 172-174), choose one out the six traits presented here and complete the
following table..
Please write out steps )You have genotyped an entire population o.pdfaioils
Please write out steps :)
You have genotyped an entire population of lab mice for a single locus (let's label it F) that you
have noticed have some interesting differences in size at a certain age. Based on your genotyping
work, you calculate the average of the FF genotype to be 68 grams, the Ff genotype to be 42
grams and the ff genotype to be 25 grams. The frequency of the F allele is 0.70. What is the
allele effect of the f allele in grams for this population (rounded to the nearest 0.01)?.
Please write out the steps )_You have genotyped an entire populat.pdfaioils
Please write out the steps :)_
You have genotyped an entire population of lab mice for a single locus (let's label it F) that you
have noticed have some interesting differences in size at a certain age. Based on your genotyping
work, you calculate the average of the FF genotype to be 82 grams, the Ff genotype to be 42
grams and the ff genotype to be 25 grams. The frequency of the F allele is 0.75. What is the
breeding value of the ff genotype in grams for this population (rounded to the nearest 0.01)?.
Please Use The Code Provided below. Thanks Study the Python code .pdfaioils
Please Use The Code Provided below. Thanks
Study the Python code and add add/pop code functions so that to add to the end of the queue and
pop will remove from head node but updates the head node to point to first node. Submit Python
code. Python 3.6 1 l = cur = ["Head", None] \#dummy N 2 for i in range (1,5): 3 cur [1]= [None,
None] 4 cur = cur [1] 5 cur [0]=i.
Please Use the Code Provided below. Thanks Visit LL Queue ; add.pdfaioils
Please Use the Code Provided below. Thanks
Visit LL Queue ; add function pop to remove from the queue head, add function add to add to
queue tail and add function display to print the queue. Submit code.
LLListasQueueA Python 3.6.
Please this is very important Im on a deadline The joint probabilit.pdfaioils
Please this is very important I'm on a deadline The joint probability distribution of two random
variables X,Y is given in the table below. From the information in the table, calculate each of the
following three probabilities. (a) P(X<4)= (b) P(X1,Y1)= (c) P(Y=1)=.
Please solve. In the Assembly Department of Martinez Company, budget.pdfaioils
Please solve. In the Assembly Department of Martinez Company, budgeted and actual
manufacturing overhead costs for the month of April 2022 were as follows. All costs are
controllable by the department manager. Prepare a responsibility report for April for the cost
center.
MARTINEZ COMPANY Assembly Department Manufacturing Overhead Cost Responsibility
Report Difference Favorable Unfavorable Neither Favorable Controllable Cost Budget Actual
nor Unfavorable $$$4 . $.
Please do parts labeled TODO LinkedList.java Replace.pdfaioils
Please do parts labeled TODO
/**
* LinkedList.java
*
* Replace all //TODO tags with your code
*
* Note that below the "//TODO" tag there may be
* something like "return null;", "return 0;", etc.
* That line is just "stubbed in" so the class
* will compile. When you add your code (one or many
* statements), you will want to delete the "stubbed" line.
* By "stubbed in" we mean "mocked" or "faked in" temporarily.
*
* When testing, construct using the static factory methods:
LinkedList.newEmpty()
LinkedList.from(arrayElements)
*/
package model.list;
import java.lang.reflect.Array;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import model.linearpub.DynamicList;
import model.linearpub.StructureIterator;
//This class is NOT java.util.LinkedList
public class LinkedList implements DynamicList {
//---------------------------------
// Instance Variables
//TODO - declare instance variable(s)
//---------------------------------
// Private Constructor
/** Constructs and returns new LinkedList (no args constructor) */
private LinkedList() {
}
//-------------------- List Statistics ---------------------
/**
* Return number of elements in this list.
*/
@Override
public int size() {
//TODO
return 0;
}
/**
* Return true is this list contains no elements.
*/
@Override
public boolean isEmpty() {
//TODO
return false;
}
//------------------ Accessing Elements --------------------
/**
* Return element at given index.
* Throws IndexOutOfBoundsException if passed index is invalid.
*/
@Override
public E get(int index) {
//TODO
return null;
}
/**
* Return first element
* Throws RuntimeException if list is empty
*/
@Override
public E first() {
//TODO
return null;
}
/**
* Return last element
* Throws RuntimeException if list is empty
*/
@Override
public E last() {
//TODO
return null;
}
/**
* Return a new list containing the elements of this list
* between the given index "start" (inclusive) and
* the given index "stop" (exclusive).
* Throws IndexOutOfBoundsException if either passed index is invalid.
*/
@Override
public DynamicList subList(int start, int stop) {
//TODO
return null;
}
/**
* Return index of first matching element (where searchFct outputs true)
* Return -1 if no match
* Example usage (first list of integers, then employees):
* index = list.find(eaInteger -> eaInteger == 10);
* index = employeeList.find(employee -> employee .getFirstName().equals("Kofi"));
*/
@Override
public int findFirst(Function searchFct) {
//TODO
return 0;
}
/**
* Return index of last matching element (where searchFct outputs true)
* E.g., if searching for employee with name "Kofi" and there is a match
* at index=3 and index=8, findLast will return 8 (the last matching index).
* Hint: start search at end of list and work backwards through list.
* Return -1 if no match
*/
@Override
public int findLast(Function searchFct) {
//TODO
return 0;
}
//------------------- Setting Elem.
Please do number 1 as its my choice for this project but, if there.pdfaioils
Please do number 1 as it's my choice for this project but, if there's an easier option go for it.
I appreciate your help with this since I have a lot of projects to finish in a short time. - Choose
your own project idea, or select one of the following examples: 1. Window Hider Tool - Develop
Window Hider tool 2. The Process of Reporting and Fixing Vulnerabilities in Windows and
Linux Distribution Development: Security vulnerabilities are revealed on a daily basis and each
vulnerability goes through a series of steps from its first discovery to being patched on an end
user's system. 3. Steganography: Implementation of steganography tools for hiding information
includes any type of information file and image files and the path where the user wants to save
Image and extruded file. 4. Develop network monitoring system: The purpose of our tool is to
create a simple and affordable network monitoring system that will allow small and medium
sized enterprises to keep their network secure. It will allow those businesses to still get a proper
network security system even if they don't have the money to purchase a more expensive tool or
the expertise of an IT department.
PROJECT Report Title page Table of contents Abstract Related work Proposed Design OR
Methodology Implementation OR Methodology Testing (Designed system Functionality)
Evaluation or Analysis Summary and recommendations References.
Please show workstepsYou have genotyped an entire population of l.pdfaioils
Please show work/steps
You have genotyped an entire population of lab mice for a single locus (let's label it F) that you
have noticed have some interesting differences in size at a certain age. Based on your genotyping
work, you calculate the average of the FF genotype to be 78 grams, the Ff genotype to be 34
grams and the ff genotype to be 24 grams. The frequency of the F allele is 0.76. What is the
average allele effect of the F locus in grams for this population (rounded to the nearest 0.01)?.
Please show all steps of algebra. I have the answer shown below but .pdfaioils
Please show all steps of algebra. I have the answer shown below but I need to know the steps to
solve.
Suppose that tastes for leisure (l) and consumption (c) are represented by CES utility function:
U(l,c)=(l+(1)c)1/ Find the labor supply assuming a leisure endowment of L. (5 points) ider the
more general constamt ciastancion probl (c+(1))1/. Solving the maximization tility function, and
doing some tedious algebra, we get =(w)1/(+1)+(1)1/(+1)L(1)1/(+1) ng labor supply function
l(w,L)=L(w)1/(+1)+(1)1/(+1)L(1)1/(+1).
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Please do Part A, Ill be really gratefulThe main.c is the skeleto.pdf
1. 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.
2. ******************************************************************/
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*/
}
3. 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);
}
while (1)
{
/* Todo: Please write the code here to handle the update of time slot k (We assume that in one
slot k, the traffic can go through all the routers to reach the destination router)*/
4. eventptr = evlist; /* get next event to simulate */
if (eventptr==NULL)
goto terminate;
evlist = evlist->next; /* remove this event from event list */
if (evlist!=NULL)
evlist->prev=NULL;
clocktime = eventptr->evtime; /* update time to next event time */
if (eventptr->evtype == FROM_LAYER2 )
{
/* Todo: You need to modify the rtupdate method and add more codes here for Part B and Part
C, since the link costs in these parts are dynamic.*/
rtupdate(&dts[eventptr->eventity], *(eventptr->rtpktptr));
}
else
{
printf("Panic: unknown event typen"); exit(0);
}
if (eventptr->evtype == FROM_LAYER2 )
free(eventptr->rtpktptr); /* free memory for packet, if any */
free(eventptr); /* free memory for event struct */
}
terminate:
printf("nSimulator terminated at t=%f, no packets in mediumn", clocktime);
}
/* jimsrand(): return a float in range [0,1]. The routine below is used to */
/* isolate all random number generation in one location. We assume that the*/
/* system-supplied rand() function return an int in therange [0,mmm] */
float jimsrand()
{
double mmm = 2147483647;
float x;
5. x = rand()/mmm;
return(x);
}
void insertevent(struct event *p)
{
struct event *q,*qold;
q = evlist; /* q points to header of list in which p struct inserted */
if (q==NULL) { /* list is empty */
evlist=p;
p->next=NULL;
p->prev=NULL;
}
else {
for (qold = q; q !=NULL && p->evtime > q->evtime; q=q->next)
qold=q;
if (q==NULL) { /* end of list */
qold->next = p;
p->prev = qold;
p->next = NULL;
}
else if (q==evlist) { /* front of list */
p->next=evlist;
p->prev=NULL;
p->next->prev=p;
evlist = p;
}
else { /* middle of list */
p->next=q;
p->prev=q->prev;
q->prev->next=p;
q->prev=p;
}
6. }
}
void printevlist()
{
struct event *q;
printf("--------------nEvent List Follows:n");
for(q = evlist; q!=NULL; q=q->next) {
printf("Event time: %f, type: %d entity: %dn",q->evtime,q->evtype,q->eventity);
}
printf("--------------n");
}
/************************** send update to neighbor (packet.destid)***************/
void send2neighbor(struct rtpkt packet)
{
struct event *evptr, *q;
float jimsrand(),lastime;
int i;
/* be nice: check if source and destination id's are reasonable */
if (packet.sourceid<0 || packet.sourceid >num_nodes) {
printf("WARNING: illegal source id in your packet, ignoring packet!n");
return;
}
if (packet.destid<0 || packet.destid > num_nodes) {
printf("WARNING: illegal dest id in your packet, ignoring packet!n");
return;
}
if (packet.sourceid == packet.destid) {
printf("WARNING: source and destination id's the same, ignoring packet!n");
return;
}
/* create future event for arrival of packet at the other side */
7. evptr = (struct event *)malloc(sizeof(struct event));
evptr->evtype = FROM_LAYER2; /* packet will pop out from layer3 */
evptr->eventity = packet.destid; /* event occurs at other entity */
evptr->rtpktptr = &packet; /* save ptr to my copy of packet */
/* finally, compute the arrival time of packet at the other end.
medium can not reorder, so make sure packet arrives between 1 and 10
time units after the latest arrival time of packets
currently in the medium on their way to the destination */
lastime = clocktime;
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==FROM_LAYER2 && q->eventity==evptr->eventity) )
lastime = q->evtime;
evptr->evtime = lastime + 2.*jimsrand();
insertevent(evptr);
}
2.1 Part A: Build A Network Simulator that Supports DV (25 points) In this part, you need to
build an Autonomous System (AS) with N routers (nodes) (assuming N10 ) with a static
topology. Please start with your code from main.c provided in lab2.zip, which gives a network
simulator framework. You need to implement DV routing protocol with a given static topology
in the following steps. 1. Input: Your simulator should read a topology file (say, topo.txt) with a
matrix {Di,j},i,j{0..,N1}. N is the number of nodes (routers) and Di,j is the link cost from node i
to node j. If nodes i and j are same, Di,j=0; If nodes i and j are directly connected (adjacent),
Di,j=e, where e0. Otherwise, nodes i and j are not directly connected and you should assign link
costDi,j=1. You can test your code with the topology shown in Figure 1 (Note that your code
should work with any static topology with N10 ). Evidently, its corresponding topology file is
given as follows (where N=4 ): 010521001151032130 create another network topology with any
number of nodes for testing. (Note that the test cases used for the grading are different). Assume
the simulation starts at slot k=0 for initialization and k1 when updating DVs at each simulation
slot. You need to prit slot. You need to print out the current slot k followed by DVs of all the
nodes in the ascending order at the end of the simulation slots. Please print them out in the first
five slots (k=0,1,2,3,4) and then every 10 slots (k=10,20,30,) until they converge. In this test
case, the expected output should be: k=0i Figure 1: an example of topology and corresponding
link costs. node-0: 01052