Questions
Code in C Instructions For this programming assignment you are going to implement a simulation of...

Code in C

Instructions
For this programming assignment you are going to implement a simulation of Dijkstra’s
solution to the Dining Philosophers problem using threads, locks, and condition variables.


Dijkstra’s Solution
Edsgar Dijkstra’s original solution to the Dining Philosophers problem used semaphores,
but it can be adapted to use similar mechanisms:
• Each philosopher is in one of three states: THINKING, HUNGRY, or EATING.
• Every philosopher starts out in the THINKING state.
• When a philosopher is ready to eat, her state is changed to HUNGRY.
• Before she can eat, she must test to see if it is safe to do so. If either of her neighbors is
in the EATING state, it is not safe for her to eat and she must wait until the situation
changes, at which point her state is changed to EATING.
• When a philosopher is done eating, her state is changed to THINKING and she must test
to see if either of her neighbors is in the HUNGRY state and it is now safe for them to eat.
If it is, she must notify that philosopher that it is now safe to start eating.
Note that the same test is used to assure two different requirements of the problem:
1. Safety: a philosopher only eats if it is safe to do so.
2. Liveness: no philosopher should go hungry if it is safe to eat.


The Dining Room
I have implemented a structure called dining_room that can be used to create a monitorlike
object that manages a simulation of the Dining Philosophers problem.


It contains the following fields:
• num_phils - an integer representing the number of philosophers.
• num_cycles - an integer representing how many times each philosopher tries to eat.
• phil_state - an array of values indexed by philosopher ID of type p_state, one for
each philosopher, each of which has a value of THINKING, HUNGRY, or EATING depending
on the state of that philosopher.
• table_lock - a lock to control access to the shared data in phil_state.
• safe_to_eat - an array of condition variables indexed by philosopher ID, each of which corresponds to the event when it is safe for that philosopher to eat.
• phil_threads - an array of threads indexed by philosopher ID.
• phil_args - an array of structures of type p_args, indexed by philosopher ID, each of which contains three fields:
– phil_num - the ID of the philosopher.
– num_cycles - the number of times that philosopher should try to eat.
– room - a pointer to the dining_room structure to use as a monitor.


I have implemented the following utility functions in the diningRoom.c file:
• init_dining_room - takes a pointer to an existing dining_room structure, and parameters representing the number of philosophers and the number of cycles and initializes the fields of the structure.
• left_neighbor - returns the ID of the left neighbor of a philosopher.
• right_neighbor - returns the ID of the right neighbor of a philosopher.
• display_headings - displays column headings for a table of state changes.
• display_states - displays the current state of each philosopher for a table of state changes.
• think - simulates the philosopher thinking.
• eat - simulates the philosopher eating.
• start_philosopher - the function to be used to start a philosopher thread. It uses information passed in a p_args structure to repeatedly do the following:
1. think
2. grab the forks
3. eat
4. release the forks


You must implement the following functions in the dining_room.c file:
• void run_simulation(dining_room *room) - starts a simulation of the Dining Philosophers problem:
1. Display the headings and the philosophers’ initial states.
2. Start the thread for each philosopher.
3. Wait for each philosopher’s thread to complete.
• void grab_forks(dining_room *room, int phil) - simulates a philosopher picking up forks:
1. Acquire the table lock.
2. Set the state for phil to HUNGRY.
3. Display the current states of the philosophers.
4. Until it is safe to eat, wait on the condition variable for phil in the safe_to_eat array.
5. Set the state for phil to EATING.
6. Display the current states of the philosophers.
7. Release the table lock.
• void release_forks(dining_room *room, int phil) - simulates a philosopher putting down forks:
1. Acquire the table lock.
2. Set the state for phil to THINKING.
3. Display the current states of the philosophers.
4. Test to see if it is safe for each of phil’s neighbors to eat.
5. If it is, notify the philosopher using the appropriate condition variable in the safe_to_eat array.
6. Release the table lock.
• int test_phil(dining_room *room, int phil) - checks to see if it is safe for a philosopher to eat:
1. If the state for phil is HUNGRY and neither of her neighbors is in the EATING state return true (1).
2. Otherwise return false (0).
3. The table lock must be acquired before this function is called.
4. This function should not do anything with locks or condition variables.


Starting a Simulation
I have also provided the file dpsim.c, which contains a main function. This function takes two command line arguments, creates a dining_room structure using those values, and calls the run_simulation member function to start a simulation. See the Compiling and Running Your Code section below for more information.


Compiling and Running Your Code
To create an executable file called dpsim use the following command:
gcc -o dpsim dpsim.c dining_room.c -lpthread


To run your code with 5 philosophers that try to eat 10 times, type:
./dpsim 5 10


If it is working correctly it should display a table showing the current state of each philosopher each time any philosopher’s state changes.


$ ./dpsim 5 2

PHIL 0 PHIL 1 PHIL 2 PHIL 3 PHIL 4

THINKING THINKING THINKING THINKING THINKING

THINKING THINKING THINKING THINKING HUNGRY

THINKING THINKING THINKING THINKING EATING

THINKING THINKING THINKING HUNGRY EATING

HUNGRY THINKING THINKING HUNGRY EATING

HUNGRY THINKING THINKING HUNGRY THINKING

EATING THINKING THINKING HUNGRY THINKING

EATING THINKING THINKING EATING THINKING

EATING THINKING THINKING EATING HUNGRY

THINKING THINKING THINKING EATING HUNGRY

THINKING THINKING THINKING THINKING HUNGRY

THINKING THINKING THINKING THINKING EATING

THINKING THINKING HUNGRY THINKING EATING

THINKING THINKING EATING THINKING EATING

THINKING HUNGRY EATING THINKING EATING

THINKING HUNGRY EATING THINKING THINKING

HUNGRY HUNGRY EATING THINKING THINKING

EATING HUNGRY EATING THINKING THINKING

EATING HUNGRY EATING HUNGRY THINKING

EATING HUNGRY THINKING HUNGRY THINKING

EATING HUNGRY THINKING EATING THINKING

THINKING HUNGRY THINKING EATING THINKING

THINKING EATING THINKING EATING THINKING

THINKING EATING HUNGRY EATING THINKING

THINKING EATING HUNGRY THINKING THINKING

THINKING THINKING HUNGRY THINKING THINKING

THINKING THINKING EATING THINKING THINKING

THINKING HUNGRY EATING THINKING THINKING

THINKING HUNGRY THINKING THINKING THINKING

THINKING EATING THINKING THINKING THINKING

THINKING THINKING THINKING THINKING THINKING


A correct implementation should satisfy the safety and liveness conditions described above (remember the first and last philosophers are neighbors too.)


File Orginization
dining_room.c

In: Computer Science

Part I – Build a simple Servlet called MyServlet using NetBeans. Add this Servlet to you...

Part I Build a simple Servlet called MyServlet using NetBeans. Add this Servlet to you “ChattBank” Project. This MyServlet will display a message like “Go Braves” in a simple <h1> tag. Run this servlet from a Browser window by typing in the servlet name in the URL line.

(ie. http://localhost:8080/ChattBank/MyServlet). Make sure that your Server is up and running before you test this Servlet. The best way to do this is just Run your “ChattBank” Project once before you test the Servlet. Running the Project will start the Server.

Part IINext, build a simple Servlet called LoginServlet in your “ChattBank” Project. Now make it so that when the Customer logs in, the LoginServlet will get called and will validate the user id and password.

  1. At first, just make sure that the Servlet gets called correctly. So just print a simple message like “LoginServlet Running…”.
  2. Remember, to call the LoginServlet, you will need to modify the FORM tag in the “Login.html” file:

<form action=”http://localhost:8080/ChattBank/LoginServlet”      method=”post”>

  1. Test it out. When you click the Login Button on the LoginForm, you should see “LoginServlet Running….”

Part IIINow, modify the LoginServlet.

  1. Make it so that when the Servlet gets called, it reads the id and password from the Login Form.

Use :    request.getParameter() to get these items. At first just read in these 2 strings and display them to the Server Log.

2.) If the id = “admin” and the Password = “123”, return an HTML page     that says “Valid Login”.

3.) If not return an HTML page that says “InValid Login”. Use out.println() to send these HTML messages.

     4.) Test out your WebApp.            

Part IVLastly, modify the LoginServlet. This time we are going to go to the database to verify the user login. First look at the ChattBank database. There is a Customers table. In this table there is a UserID and a Passwd. Write the database code, in your LoginServlet to let anyone of these customers login, using their own ids and passwords.    

In: Computer Science

Give examples of a C++ program that allow users to manipulate (adding, removing, sort, etc.) a...

Give examples of a C++ program that allow users to manipulate (adding, removing, sort, etc.) a list of items. To start, you need to propose a problem that you would like to work on and you can't use TO-DO list.

In: Computer Science

For tablet and desktop devices, you’ll lay out the horizontal navigation list as a single row...

For tablet and desktop devices, you’ll lay out the horizontal navigation list as a single row of links. Within the media query, create a style rule that displays the ul element within the horizontal navigation list as a flexbox, oriented in the row direction with no wrapping. Set the height of the element to 40 pixels For each li element within the ul element of the horizontal navigation list set their growth, shrink, and basis size values to 1, 1, and auto respectively so that each list items grows and shrinks at the same rate.

In: Computer Science

The painter Mondrian is known for paintings that are made up of rectangles of different colors...

The painter Mondrian is known for paintings that are made up of rectangles of different colors arranged together in patterns like the one below. Write an application that displays a Mondrian-like picture in a window using JavaFX (you are not allowed to use panels or frames). There must be at least nine rectangles, and they must be aligned so that they fill the window without any gaps. There must be at least two different colors, one of them you have to create (using the Color class) and at least two different sizes of rectangles. Use Mondrian as the class name

In: Computer Science

please answer as text You are given a Node class and a List class: public class...

please answer as text

You are given a Node class and a List class:

public class Node {

       int           data;

       Node       next;

       Node(int d, Node n){

            data = d;

            next = n;

      }

}

public class List{

       Node header;

}

Write a java method insertNodeBefore( ) which takes two integers: int ref which is the data of the node that we need to insert a new node before, and int d which is the data of the new node we want to insert, for the Linked list mylist.

In: Computer Science

C++ Given Code: #include <iostream> #include <string> using namespace std; int main() { //declare variables to...

C++
Given Code:

#include <iostream>
#include <string>
using namespace std;


int main()
{
//declare variables to store user input

bool cont = true;

//implement a loop so that it will continue asking until the user provides a positive integer
// the following provides ONLY part of the loop body, which you should complete
{
cout <<"How many words are in your message? \n";
cout <<"Enter value: ";

// get user input integer here
  
cout <<"\nInvalid value. Please Re-enter a number of positive value\n";

}

//declare a dynamic array of string type with the specified number of elements

  
  
//
while(cont)
{
cout <<"\nSelect one of these options: (1) Get Message (2) Encrypt (3) Print (4) Quit";
cout <<"\nSelection: ";

// obtain user input option (an integer)

// based on the input the program will perform one of the following operations using switch statement
switch(selection)
{
case 1://Get Message

// Get the specified number of words from the user

break;

case 2: //Encrypt

// Based on the shifting encryption strategy described above, encrypt the individual words
// Be careful about the difference between the lower case letters and upper case letters
  
break;

case 3: //Print

// Print out the encrypted words

break;

case 4:
cont = false;
break;

default:
break;
}
}
  
// Remember to release the memory you allocate above!!
  
return 0;

}


Encryption using Pointers and Dynamic Arrays

Objective:

Agent James Vond, one of our secret agents, Agent 008, has recently been captured in the Caribbean. We have been able to establish contact with him, but need help sending him messages in secret to let him know help is on the way. We believe we can send him messages using a Caesar Cipher, but need your help encoding it. Agent Vond, we task you with encrypting the message and helping Agent 008 escape the Caribbean

Sincerely, M.

Assignment:

The Caesar Cipher technique is one of the earliest and simplest method of encryption. It’s a substitution cipher, i.e., each letter of a given text is replaced by a letter some fixed number of positions down the alphabet. For example with a shift of 1, A would be replaced by B, B would become C, and so on.

The encryption equation is E(x) = (x + n) % 26.

The x = the numeric letter value, n = number of shifts, and (% 26) is so that whatever value your result is, it will stay within the alphabet range (0-25).

However, since we will be looking at characters in strings, you need to implement ASCII code so that your equation will look more like:

letter = ( ( (letter - 'A') + shift ) % 26 + 'A')) if it is upper case

Or

letter = ( ( (letter - 'a') + shift ) % 26 + 'a' ) ) if it is lower case.

You subtract 'A' and 'a' in order to get the value of the letter. In ASCII code, letters are assigned values. For example, 'B' is 66. If I subtract the value of 'A' (65) then I get 1. This helps me encode because I can get the values 0-25 for each letter.

Your assignment is to implement a dynamic string array in order to store a message of variable length, and then a pointer to iterate through each letter of the string in order to encrypt it using the equations given above.

You will need to ask the user for the amount of words in the message and then create your dynamic array that way. If the amount of words is a negative number or equal to zero you should output to the screen "Invalid value. Please Re-enter a number of positive value" until they have the correct input.

Get Message

Use cin to get each word the user wishes to put into the message.

After they have input all the strings required, ask for the number of letter shifts they would like to do

Encrypt

Encrypt each letter in each string using the equations provided above if the getMessage pointer isn't null (aka if Get Message option has already been called)

Print Message

Print out the encrypted or unencrypted message

Quit

Simply quits out of the loop

Input:

You many assume that the input to be encrypted will only consist of capital and lower letters, and no other symbols such as white spaces, numbers, or special characters will have to be encrypted.

In order to choose the different options you will take an integer value as input. 1 is for Get Message, 2 is for Encrypt, 3 is for Print, 4 is for Quit

Requirements:

  • Use a dynamic array to store a message of variable length (not using dynamic array will receive 50% penalty)

  • Use a pointer to iterate through each string and encrypt it

  • Do not allow for number of letter shifts to be > 26 (Must be in the range of 0-25 aka the range of 26) [Ex: If I give you 27, your shift should end up being 1] [Hint: %]

  • Do not expect int to hold all possible values when I input the value of shift, test very large numbers

  • Print out your message using pointer arithmetic (ex: *p; p++;)

  • DO NOT iterate through your pointer like an array when printing!!

In: Computer Science

Write a program using a Scanner that asks the user for a number n between 1...

Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with 2n - 1 rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed. Starting at row n + 1, the squares between (n - 1) to 1 are printed, again right justified.  Row n + 2 prints the squares between (n -2) to 1.

Assuming the user enters 4, the program prints the following triangle of 7 rows to the console

              1
          4  1
      9  4  1
16  9  4  1
      9  4  1
          4  1
              1

If the user enters 7, the following 13-row triangle is printed

                              1
                          4  1
                      9  4  1 
                16  9  4  1
           25 16  9  4  1
      36 25 16  9  4  1
 49 36 25 16  9  4  1
      36 25 16  9  4  1
           25 16  9  4  1
                16  9  4  1 
                      9  4  1
                          4  1
                              1
 

Notes

  • Your solution should NOT use the conditionaloperator
  • Your solution should NOT use tabs
  • Your solutions SHOULD have at least one nested loop

Hint

Don't think of the output as a triangle. Think of it as two rectangular tables: one of the first n rows, the second of the last (n-1) rows.

Within each table, some cells are three spaces, some are one space and two digits, and some are two spaces and one digit.

Start by printing an entire table with each cell its appropriate square value. Then figure out how to replace the cells that should "empty" with three spaces instead of a number.

Finally, figure out how to print the one-digit numbers as two spaces and one digit, and the two-digit numbers as one space and two digits.

Grading Elements

  • Program asks the user for a number in the specified range
  • Program displays the correct number of rows
  • Program displays the correct number of columns
  • Each column entry contains the appropriate square number
  • Each row is right-justified, with 1 in the right-most column
  • Row spacing is consistent, with each column's entry directly below the preceding row
  • Program does not use the conditional operator or tabs
  • Program has a nested loop

In: Computer Science

IDS 201 Lab Exercise 5 Within a class named LX5, write methods as follows: 1. a...

IDS 201 Lab Exercise 5

Within a class named LX5, write methods as follows:

1. a method named valueCheck that accepts a parameter int named value and, using a switch statement, displays text output as follows:

  • if value is 4 or greater: "LOTS"
  • if value equals 3: "three"
  • if value equals 2: "two"
  • if value equals 1: "one"
  • if value equals 0: "zero"
  • if value is negative: "NEGATIVE"

2. a method named textMatch that accepts two parameter String objects named string1 and string2 and returns true if their text is identical and false otherwise

3. a method named sameObject that accepts two Objects as parameters and returns true if they are the same object and false otherwise (note that the Object class does not require any import statement)

4. a method named factorCheck that accepts a parameter int named value and returns values as follows:

  • if value is greater than 49 or less than 1, return -1
  • if value equals 1, return 0
  • if value is evenly divisible by 7, return 7
  • if value is evenly divisible by 5, return 5
  • if value is evenly divisible by 3, return 3
  • if value is evenly divisible by 2, return 2
  • if none of the above are true, return 1

5. Write an equivalent version of String's indexOf() method. The method will accept as parameters two Strings, big and small. If the same text of small is contained in big, the method will return the index of the first character of small from its first appearance in big.

6. Write an extended version of String's indexOf() method. The method will accept as parameters two Strings, big and small, and two ints, start and end. Like 3) above, this method will search big for matching text with the String small and return the index of the first character of small from its first appearance in big. However, in this case the search will cover not the entire String big but the match must begin at or after index start and end at or before index end.

In: Computer Science

For an example BNF grammar, be able to identify the tokens which a lexical analyzer would...

For an example BNF grammar, be able to identify the tokens which a lexical analyzer would be able to produce.

For an example BNF grammar, and a list of tokens, construct a state diagram of the language’s lexical analyzer.

In: Computer Science

Write pseudocode for a function that translates a telephone number with letters in it (such as...

Write pseudocode for a function that translates a telephone number with letters in it (such as 1-800-FLOWERS) into the actual phone number. Use the standard letters on a phone pad

In: Computer Science

Write a complete static method named addUp that accepts, in order, an integer number and an...

Write a complete static method named addUp that accepts, in order, an integer number and an integer thisMany as parameters and that prints a complete line of output reporting all the numbers that result from adding number to itself thisMany number of times (starting at 1 and ending at thisMany). For example, the following calls:

addUp(3, 5);

addUp(7, 3);

should produce this output:

Adding up 3 for 5 times gives: 3, 6, 9, 12, 15

Adding up 7 for 3 times gives: 7, 14, 21

Notice that the answers are separated by commas and a space. You must exactly reproduce this format. You may assume that the number of add ups you will be asked to do (thisMany) is greater than or equal to 1. Your method must work with any value of number including negative numbers and zero.

Write a main method that tests your addUp method.

In: Computer Science

This program must be done in JAVA. Write a program to monitor the flow of an...

This program must be done in JAVA.

Write a program to monitor the flow of an item into an out of a warehouse. The warehouse has numerous deliveries and shipments for this item (a widget) during the time period covered. A shipment out (an order) is billed at a profit of 50% over the cost of the widget. Unfortunately each incoming shipment may have a different cost associated with it. The accountants of the firm have instituted a last-in, first out system for filling orders. This means that the newest widget are the first ones sent out to satisfy an order. This method of inventory can be represented by a stack. The Push procedure will insert an incoming shipment while a Pop should be called for a shipment out. Each data record in the text file warehouse.txt will consist of one shipment per line with fields (separated by white space of) I or O (char) shipment coming IN or shipment going OUT # (integer) quantity of the shipment Cost (float) cost per widget of the shipment (Incoming only) Vendor (String) name of the company sending or receiving the shipment Write the necessary procedures to store the shipments received and to process the orders. The output for an order consists of the quantity and the total costs of the widget in the order. Each widget price is 50% higher than its cost. The widgets used to fill an order may come from multiple shipments with different costs. If there are not sufficient widgets in inventory, use all the remaining and bill accordingly. When the simulation terminates display the total amount owed to each of the suppliers (incoming), the number of widgets on hand and the total profit.

Sample Input:

I 20 34.00 Fred’s Supply Company

I 30 25.00 Jumbo Exports

O 40 Acme Industries

Output:

Orders: Shipment to Acme Industries 40 units for $1635.00

Summary: Suppliers Fred’s Supply Company $680.00

Jumbo Exports $750.00

There are 10 widgets in the warehouse.

Profit is $545.00

In: Computer Science

to be done in java Your task is to finish the StockItem class so that it...

to be done in java

Your task is to finish the StockItem class so that it meets the following criteria

• The StockItem class will have 4 attributes:

a stock number;

a name;

the price of the item;

the total number of items currently in stock

• The first three of the above characteristics will need to be set at the time a StockItem object is created, with the total number of items set to 0 at this time. The stock number and name will not need to be changed after an item is created.

• The following methods are also required:

o A method that allows the price to be re-set during the object's lifetime

o a method that takes an integer argument and adds this to the total number of items in stock

o a method that returns the total value of items of this stock type;

calculated by multiplying the price of the item by the number of items in stock (price * units)

Required Methods: StockItem(String, String, double) (class constructor) setPrice(double) increaseTotalStock(int) getStockNumber(): String getName(): String getTotalStock(): int getPrice(): double calculateTotalPrice(): double

Requested files StockItem.java

/** * A class representing an item in stock in some sort * of inventory system */

public class StockItem {

//TODO: add fields for a: name, stockNumber, price, units.

//TODO: create a constructor that takes name, stockNumber and price as arguments

// and sets units to 0.

//TODO: create accessor ("getter") methods for price, stock number and name.

//TODO: create a method increaseTotalStock that increases units by a given quantity.

//TODO:create a mutator ("setter") method setPrice that sets price to a given amount.

//TODO: create a method calculateTotalPrice that returns the total price of the current inventory

// (Calculated as current price * number of units) }

In: Computer Science

What might it mean to an organization to have an enterprise system that would be used...

What might it mean to an organization to have an enterprise system that would be used to manage both customers and suppliers rather than have those two types of relationships managed in different systems?

In: Computer Science