In Section 8.5.4, we described a situation in which we prevent deadlock by ensuring that all locks are acquired in a certain order. However, we also point out that deadlock is possible in this situation if two threads simultaneously invoke the transaction () function. Fix the transaction () function to prevent deadlocks.

Answers

Answer 1

Answer:

See Explaination

Explanation:

Separating this critical section into two sections:

void transaction(Account from, Account to, double amount)

{

Semaphore lock1, lock2;

lock1 = getLock(from);

lock2 = getLock(to);

wait(lock1);

withdraw(from, amount);

signal(lock1);

wait(lock2);

deposit(to, amount);

signal(lock2);

}

will be the best solution in the real world, because separating this critical section doesn't lead to any unwanted state between them (that is, there will never be a situation, where there is more money withdrawn, than it is possible).

The simple solution to leave the critical section in one piece, is to ensure that lock order is the same in all transactions. In this case you can sort the locks and choose the smaller one for locking first.


Related Questions

Suppose that the first number of a sequence is x, where x is an integer. Define ; ‍ if is even; ‍ ‍ ‍ if is odd. Then there exists an integer k such that ‍ . Write a program that prompts the user to input the value of x. The program outputs the integer k such that ‍ and the numbers . (For example, if ‍ , then ‍ , and the numbers , respectively, are 75, 226, 113, 340, 170, 85, 256, 128, 64, 32, 16, 8, 4, 2, 1.) Test your program for the following values of x: 75, 111, 678, 732, 873, 2048, and 65535.

Answers

Answer:

The program is written in c++ , go to the explanation part for it, the output can be found in the attached files.

Explanation:

C++ Code:

#include <iostream>

using namespace std;

int main() {

int x;

cout<<"Enter a number: ";

cin>>x;

int largest = x;

int position = 1, count = 0;

while(x != 1)

{

count++;

cout<<x<<" ";

if(x > largest)

{

largest = x;

position = count;

}

if(x%2 == 0)

x = x/2;

else

x = 3*x + 1;

}

cout<<x<<endl;

cout<<"The largest number of the sequence is "<<largest<<endl;

cout<<"The position of the largest number is "<<position<<endl;

return 0;

}

The program prompts the user for an integer ( x ). It calculates ( k ), the number of iterations until ( x ) becomes 1 in a sequence generated by specific rules: if ( x ) is even, it's divided by 2; if odd, it's multiplied by 3 and incremented by 1. .

Here's a Python program that implements the described sequence and finds the integer ( k ) for the given ( x ) value:

```python

def find_k(x):

   k = 0

   while x != 1:

       if x % 2 == 0:

           x = x // 2

       else:

           x = 3 * x + 1

       k += 1

   return k

def generate_sequence(x):

   sequence = [x]

   while x != 1:

       if x % 2 == 0:

           x = x // 2

       else:

           x = 3 * x + 1

       sequence.append(x)

   return sequence

def main():

   test_values = [75, 111, 678, 732, 873, 2048, 65535]

   

   for x in test_values:

       k = find_k(x)

       sequence = generate_sequence(x)

       print(f"For x = {x}, k = {k}, sequence: {sequence}")

if __name__ == "__main__":

   main()

```

This program calculates the integer \( k \) for each given value of \( x \) and generates the sequence according to the rules provided. Then it prints the \( k \) value and the sequence for each test value. You can run this program to verify the results for the provided test values.

You are working with a MySQL installation in Windows. You plan to use the mysql client utility in batch mode to run a query that has been saved to a file in the C:\mysql_files directory. The name of the file is users.sql, and it includes a command to use the mysql database, which the query targets. You want to save the results of the query to a file named users.txt, which should also be saved to the C:\mysql_files directory. What command should you use to execute the query

Answers

Answer:

mysql -t < c:\mysql_files\users.sql > c:\mysql_files\users.txt

Explanation:

MySQL is a system software that is written in programming language such as c++ and c, the software was initially released on the 23rd day of the month of May, in the year 1995 by Oracle corporation. It is a popular software in companies that are commerce related or orientated since it deals with things related to web database.

So, to answer the question we are given that the file that will results of the query is users.txt and the directory is C:\mysql_files, therefore, the command that should you use to execute the query is; mysql -t < c:\mysql_files\users.sql > c:\mysql_files\users.txt

Create an application that creates a report from quarterly sales. Console The Sales Report application Region Q1 Q2 Q3 Q4 1 $1,540.00 $2,010.00 $2,450.00 $1,845.00 2 $1,130.00 $1,168.00 $1,847.00 $1,491.00 3 $1,580.00 $2,305.00 $2,710.00 $1,284.00 4 $1,105.00 $4,102.00 $2,391.00 $1,576.00 Sales by region: Region 1: $7,845.00 Region 2: $5,636.00 Region 3: $7,879.00 Region 4: $9,174.00 Sales by quarter: Q1: $5,355.00 Q2: $9,585.00 Q3: $9,398.00 Q4: $6,196.00 Total sales: $30,534.00

Answers

Answer:

See explaination

Explanation:

package miscellaneous;

import java.text.NumberFormat;

import java.util.Currency;

import java.util.Locale;

public class sales {

public static void main(String[] args) {

double[][] sales= {

{1540.0,2010.0,2450.0,1845.0},//region1

{1130.0,1168.0,1847.0,1491.0},//region2

{1580.0,2305.0,2710.0,1284.0},//region3

{1105.0,4102.0,2391.0,1576.0}};//region4

//object for NumberFormat class

//needed in $

NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(java.util.Locale.US);

System.out.println("The sales report application: ");

//the j(th) element in i(th) row in sales matrix contains sales value for

//sales in j(th) quarter

System.out.println("Sales by quarter: ");

System.out.println("Region\tQ1\t\tQ2\t\tQ3\t\tQ4");

for(int i=0;i<sales.length;i++) {

System.out.print(i+1+"\t");

for(int j=0;j<sales[i].length;j++) {

System.out.print(defaultFormat.format(sales[i][j])+"\t");

}

System.out.println();

}

//i(th) row in the matrix has sales for i(th) region

System.out.println("Sales by region: \n");

for(int i=0;i<sales.length;i++) {

System.out.print("Region "+(i+1)+":");

double region_sale=0;

for(int j=0;j<sales[i].length;j++) {

region_sale+=sales[i][j];

}

System.out.println(defaultFormat.format(region_sale));

}

System.out.println("\nSales by Quarter: \n");

//we have quarters so for adding up their sales we need 4 variables

double q1=0;

double q2=0;

double q3=0;

double q4=0;

for(int i=0;i<sales.length;i++) {

for(int j=0;j<sales[i].length;j++) {

//j=0 implies the sales data for first quarter

if(j==0) {

q1+=sales[i][j];

}

//j=1 implies the sales data for second quarter

if(j==1) {

q2+=sales[i][j];

}

//j=2 implies the sales data for third quarter

if(j==2) {

q3+=sales[i][j];

}

//j=3 implies the sales data for fourth quarter

if(j==3) {

q4+=sales[i][j];

}

}

}

System.out.println("Q1: "+defaultFormat.format(q1));

System.out.println("Q2: "+defaultFormat.format(q2));

System.out.println("Q3: "+defaultFormat.format(q3));

System.out.println("Q4: "+defaultFormat.format(q4));

//with the help of 2 loops every sales data

//in the matrix can be accessed, which can be added

//to total_sales variable

double total_sales=0;

for(int i=0;i<sales.length;i++) {

for(int j=0;j<sales[i].length;j++) {

total_sales+=sales[i][j];

}

}

System.out.println("\nTotal Sales: "+defaultFormat.format(total_sales));

}

}

This program will read a word search and a word dictionary from the provided files. Develop four methods: (1) A method to read the word search. (2) A method to read a dictionary of words, and (3) two methods to test the first two methods. The Method stubs are provided for you. (1) The first method, readDictionary will take as input a string that contains the name of the provided dictionary text file. The name of the text file provided is dictionary.txt. This method will return a list of the words found in the dictionary.txt file.

Answers

Answer:

See explaination

Explanation:

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayList;

public class WordSearch {

public static void main(String[] args) {

testReadDictionary();

testReadWordSearch();

}

/**

* Opens and reads a dictionary file returning a list of words. Example: dog cat

* turtle elephant

*

* If there is an error reading the file, such as the file cannot be found, then

* the following message is shown: Error: Unable to read file with replaced with

* the parameter value.

*

* atparam dictionaryFilename The dictionary file to read.

* atreturn An ArrayList of words.

*/

public static ArrayList readDictionary(String dictionaryFilename) {

ArrayList<String> animals = new ArrayList<>();

FileInputStream filestream;

try {

filestream = new FileInputStream(dictionaryFilename);

BufferedReader br = new BufferedReader(new InputStreamReader(filestream));

String str = br.readLine();

while (str != null) {

animals.add(str);

str = br.readLine();

}

br.close();

} catch (FileNotFoundException e) {

System.out.println(" Unable to read file " + dictionaryFilename);

} catch (IOException e) {

e.printStackTrace();

}

return animals;

}

/**

* Opens and reads a wordSearchFileName file returning a block of characters.

* Example: jwufyhsinf agzucneqpo majeurnfyt

*

* If there is an error reading the file, such as the file cannot be found, then

* the following message is shown: Error: Unable to read file with replaced with

* the parameter value.

*

* atparam wordSearchFileName The dictionary file to read.

* atreturn A 2d-array of characters representing the block of letters.

*/

public static char[][] readWordSearch(String wordSearchFileName) {

ArrayList<String> words = new ArrayList<>();

FileInputStream filestream;

try {

filestream = new FileInputStream(wordSearchFileName);

BufferedReader br = new BufferedReader(new InputStreamReader(filestream));

String str = br.readLine();

while (str != null) {

words.add(str);

str = br.readLine();

}

br.close();

} catch (FileNotFoundException e) {

System.out.println(" Unable to read file " + wordSearchFileName);

} catch (IOException e) {

e.printStackTrace();

}

char[][] charWords = new char[words.size()][];

for (int i = 0; i < words.size(); i++) {

charWords[i] = words.get(i).toCharArray();

}

return charWords;

}

public static void testReadDictionary() {

// ADD TEST CASES

ArrayList dictionaryWords;

System.out.println("Positive Test Case for Dictionary Serach");

String dictionaryFilePath = "C:\\PERSONAL\\LIBRARY\\JAVA\\file\\dictionary.txt";

dictionaryWords = readDictionary(dictionaryFilePath);

System.out.println("Number of words found : "+dictionaryWords.size());

System.out.println("They are : "+dictionaryWords.toString());

System.out.println("\nNegative Test Case for Dictionary Serach");

dictionaryFilePath = "C:\\PERSONAL\\LIBRARY\\JAVA\\file\\dictionaryDummy.txt";

dictionaryWords = readDictionary(dictionaryFilePath);

}

public static void testReadWordSearch() {

// ADD TEST CASES

char[][] wordsList;

System.out.println("\n\nPositive Test Case for Word Serach");

String wordFilePath = "C:\\PERSONAL\\LIBRARY\\JAVA\\file\\wordsearch.txt";

wordsList = readWordSearch(wordFilePath);

System.out.println("Number of words found : "+wordsList.length);

System.out.println("\nNegative Test Case for Word Serach");

wordFilePath = "C:\\PERSONAL\\LIBRARY\\JAVA\\file\\wordsearchDummy.txt";

wordsList = readWordSearch(wordFilePath);

}

}

Note: replace at with the at symbol

Implement the A5/1 algorithm. Suppose that, after a particular step, the values of the register are: X = (x0, x1, …, x18) = (1010101010101010101) Y = (y0, y1, …, y21) = (1100110011001100110011) Z = (z0, z1, …, z22) = (11100001111000011110000) List the next 32 keystream bits and give the contents of X, Y, and Z after these 32 bits have been generated.

Answers

Answer:

Check the explanation

Explanation:

After a particular step the registers X, Y and Z values are as it is in the first attached image below.

Now calculate the key stream bit, s using the following formula:

key stream bit , s= x0 XOR y0 XOR z0

                       s= 1 XOR 1 XOR 1

           Hence, the 1st key bit stream ,s= 1

Now, for the next step we have to re calculate the contents of registers X, Y and Z as it is in the second attached image below.

For register X:

t= x5 XOR x2 XOR x1 XOR x0

= 0 XOR 1 XOR 0 XOR 1

t=0

For register Y:

t= y1 XOR y0

=1 XOR 1

t=0

For register Z:

t= z15 XOR z2 XOR z1 XOR z0

=1 XOR 1 XOR 1 XOR 1

t=0

Now, the contents of X, Y and X are as it is in the third attached image below.

Key stream bit, s= x0 XOR y0 XOR z0

                             S= 0 XOR 1 XOR 1

                             Hence the 2nd key stream bit, s= 0

The A5/1 algorithm generates keystream bits by shifting three LFSRs based on a majority bit mechanism and producing output bits through XOR operations. Following this process, the registers X, Y, and Z are updated, and the keystream is generated. The new register states and keystream give us the final output.

The A5/1 algorithm uses three Linear Feedback Shift Registers (LFSRs) named X, Y, and Z. Here are the initial states of the registers:

X = (1010101010101010101)Y = (1100110011001100110011)Z = (11100001111000011110000)

To generate the next 32 keystream bits and update the registers, the following steps are followed:

Identify the majority bit of X<11>, Y<11>, and Z<11>.Only the registers with bits equal to the majority bit are shifted.Shift each register, updating the bits according to their feedback taps (for X: positions 13, 16, 17, 18; for Y: positions 20, 21; for Z: position 7, 20, 21, 22).Compute the output bit as the XOR of bits X<18>, Y<21>, Z<22>.Repeat until 32 bits are produced.

After generating 32 keystream bits, the contents of the registers and the keystream are:

Keystream = (Provide the actual calculation here)X = (Updated state)Y = (Updated state)Z = (Updated state)

The Phonebook class must also have the following functions: Constructor with 1 integer parameter for size (numberOfContacts is initially set to 0; allocate memory for myContacts). Copy constructor. Assignment operator. Destructor. int getNumberOfContacts() // Getter int getSize() // Getter contact getContact(int i) //returns contact at index i (you can assume 0 < i < numberOfContacts) bool addContact(string name, string phonenumber, string email) // add a new contact at the end of the phonebook using the received parameters. Returns true if succesful, false if the contact couldn't be added because the phonebook is already full.

Answers

Answer:

See explaination

Explanation:

#include <iostream>

using namespace std;

struct contact

{

string name;

string phoneNumber;

string email;

bool available;

};

class Phonebook

{

private :

int numberOfContacts;

int size;

contact *myContacts;

public :

Phonebook(int size)

{

this->size=size;

this->numberOfContacts=0;

myContacts=new contact[size];

}

~Phonebook()

{

delete[] myContacts;

}

int getNumberOfContacts()

{

return numberOfContacts;

}

int getSize()

{

return size;

}

void addContact(string name,string phonenumber,string email)

{

contact c;

c.name=name;

c.phoneNumber=phonenumber;

c.email=email;

c.available=true;

myContacts[numberOfContacts]=c;

numberOfContacts++;

}

void removeContact(string name)

{

for(int i=0;i<numberOfContacts;i++)

{

if(myContacts[i].name.compare(name)==0)

{

this->myContacts[i].available=false;

contact temp=myContacts[numberOfContacts-1];

myContacts[numberOfContacts-1]=myContacts[i];

myContacts[i]=temp;

numberOfContacts--;

}

}

}

Phonebook(const Phonebook& pb)

{

this->myContacts=pb.myContacts;

this->size=pb.size;

this->numberOfContacts=numberOfContacts;

}

Phonebook& operator=(const Phonebook & pb)

{

myContacts=new contact[size];

this->size=pb.size;

this->numberOfContacts=pb.numberOfContacts;

for(int i=0;i<numberOfContacts;i++)

{

this->myContacts[i]=pb.myContacts[i];

}

return *this;

}

void print()

{

for(int i=0;i<numberOfContacts;i++)

{

if(myContacts[i].available==true)

{

cout<<"Name :"<<myContacts[i].name<<endl;

cout<<"Phone Number :"<<myContacts[i].phoneNumber<<endl;

cout<<"Email :"<<myContacts[i].email<<endl;

cout<<endl;

}

}

}

};

int main(){

Phonebook pb1(10);

pb1.addContact("Williams","9845566778","williamatmail.com");

pb1.addContact("James","9856655445","jamesatmail.com");

cout<<"_____ Displaying Phonebook#1 contacts _____"<<endl;

pb1.print();

pb1.removeContact("Williams");

cout<<"_____ After removing a contact Displaying Phonebook#1 _____"<<endl;

pb1.print();

Phonebook pb2(5);

pb2.addContact("Billy","9845554444","billyatmail.com");

pb2.addContact("Jimmy","9834444444","jimmyatmail.com");

cout<<"_____ Displaying Phonebook#2 contacts _____"<<endl;

pb2.print();

pb2=pb1;

cout<<"____ After Assignment Operator Displaying Phonebook#2 contacts____"<<endl;

pb2.print();

return 0;

}

Nb: Replace the at with at symbol.

.2. What approach to deviance do you find most persuasive: that

of functionalists, conflict theorists, feminists, interactionists,

or labeling theorists?

Answers

Answer:

The description for the given question is described in the explanation section below.

Explanation:

Since deviance constitutes a breach of a people's current standard. I believe Erickson's psychological concept that Deviance becomes a trait that is commonly considered to need social control agencies' intervention, i.e. 'Something must being done'.

There most probably resulted whenever the rules governing behavior appear inconsistent in just about any particular frame. Therefore the principle of this theory is that even in the analysis of deviance this same significant point seems to be the social community, instead of the participant.

Amanda indicates that she wants to do some advertising to make people in the local area aware of the development, but she admits that her advertising budget is limited, so she wants to spend her advertising dollars wisely by reaching her target audience -- adults age 55+.She asks you for your recommendations on the following advertising media. Which of the following advertising media would you recommend as being most useful in promoting Act Two Retirement Community to the target market?

Television
Radio
AARP Magazine
Direct mail

Answers

Answer:

Either Radio or AARP Magazine

Explanation:

Given the clue that Amanda's audience is aimed towards adults aged 55+, they were born before online mail and televisions were big on the market. Many seniors enjoy reading daily news papers while others enjoy getting their news from an audio channel like the radio.

To effectively promote Act Two Retirement Community to the target market of adults aged 55+, I would recommend focusing on advertising media that resonate with this demographic and offer cost-effective ways to reach them.

Among the options provided:

AARP Magazine: This publication is specifically tailored to the 50+ age group and offers a highly targeted platform to reach the desired audience. It provides an opportunity to showcase the retirement community's features and benefits in detail.

Direct Mail: Direct mail can be an effective way to reach the target audience directly in their homes. It allows for personalized, detailed information about the retirement community, making it suitable for a demographic that appreciates tangible information.

Read more about adverts here:

https://brainly.com/question/14227079

#SPJ3

Design and implement an application that reads a sequence of up to 25 pairs of names and postal (ZIP) codes for individuals. Store the data in an object designed to store a first name (string), last name (string), and postal code (integer). Assume each line of input will contain two strings followed by an integer value, each separated by a tab character. Then, after the input has been read in, print the list in an appropriate format to the screen.

Answers

Answer:

Kindly go to the explanation for the answer.

Explanation:

Person.java

public class Person{

private String firstName, lastName;

private int zip;

public Person(String firstName, String lastName, int zip) {

super();

this.firstName = firstName;

this.lastName = lastName;

this.zip = zip;

}

public String toString() {

String line = "\tFirst Name = " + this.firstName + "\n\tLast Name = " + this.lastName;

line += "\n\tZip Code = " + this.zip + "\n";

return line;

}

}

Test.java

import java.util.ArrayList;

import java.util.Scanner;

public class Test{

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

ArrayList<Person> al = new ArrayList<Person>();

for(int i = 0; i < 25; i++) {

System.out.print("Enter person details: ");

String line = in.nextLine();

String words[] = line.split("\t");

String fname = words[0];

String lname = words[1];

int numb = Integer.parseInt(words[2]);

Person p = new Person(fname, lname, numb);

al.add(p);

}

for(int i = 0; i < 25; i++) {

System.out.println("Person " + (i + 1) + ":");

System.out.println(al.get(i));

}

}

}

Pfizer increases production of Zithromax® after finding that the number of cases of blinding trachoma is increasing in parts of Africa.

Answers

Answer:

Take Corrective Action

Write an algorithm using pseudocode to input numbers . reject any numbers that are negative and count how many numbers are positive . when the number zero is input the process ends and the count of positive numbers is output .​

Answers

Answer:

Explanation:

Let's use Python for this. We will start prompting the user for input number, until it get 0, count only if it's positive:

input_number = Input("Please input an integer")

positive_count = 0

while input_number != 0:

    if input_number > 0:

         positive_count += 1

    input_number = Input("Please input an integer")

print(positive_count)

   

Suppose you design an algorithm to multiply two n-bit integers x and y. The general multiplication technique takes T(n) = O(n2) time. For a more efficient algorithm, you first split each of x and y into their left and right halves, which are n=2 bits long. For example, if x = 100011012, then xL = 10002 and xR = 11012, and x = 24 xL + xR. Then the product of x and y can be re-written as the following: x y = 2n (xL yL) + 2n=2 (xL yR + xR yL) + (xR yR)

Answers

Answer:

See Explaination

Explanation:

a) Assume there are n nits each in x and y.SO we divide them into n/2 and n/2 bits.

x = xL * 2^{n/2} + xR

y = yL * 2^{n/2} + yR

x.y = 2^{n}.(xL.yL) + 2^{n/2}.(xL.yR + xR.yL) +(xR.yR)

If you see there are 4 multiplications of size n/2 and we took all other additions and subtractions as O(n).

So T(n) = 4*T(n/2) + O(n)

Now lets find run time using master theorem.

T(n) = a* T(n/b) + O(n^{d})

a = 4

b = 2

d = 1

if a > b^{d}

T(n) = O(n^v) where v is log a base b

In our case T(n) = O(n^v) v = 2

=> T(n) = O(n^{2})

The splittinng method is not benefecial if we solve by this way as the run time is same even if go by the naive approach

b)

x.y = 2^{n}.(xL.yL) + 2^{n/2}.((xL+xR).(yL+yR)-(xL.yL) - (xR.yR)) +(xR.yR)

Here we are doing only three multipliactions as we changed the term.

So T(n) = 3*T(n/2) + O(n)

a = 3

b = 2

d = 1

if a > b^{d}

T(n) = O(n^v) where v is log a base b

In our case T(n) = O(n^v) v = log 3 base 2

v = 1.584

So T(n) = O(n^{1.584})

As we can see this is better than O(n^{2}).Therefore this algorithm is better than the naive approach.

what is the molarity of a solution prepared by dissolving 15.0g of sodium hydroxide in enough water to make a total of 225 ml of solution​

Answers

Answer:

1.6666 g/mol = 1 [tex]\frac{2}{3}[/tex] g/mol

Explanation:

Molar mass of NaOH= 23+16+1 =40g/mol

Mols in 15g = 15/40 mol

If this was dissolved in 225ml of water molarity of the solution is

[tex]\frac{15}{40}[/tex] ÷ 225 x 1000 = 1.6666 g/mol = 1 [tex]\frac{2}{3}[/tex] g/mol

Final answer:

The molarity of the sodium hydroxide solution is calculated by dividing the number of moles of NaOH (0.375 moles) by the volume of the solution in liters (0.225 L), resulting in 1.667 M.

Explanation:

The molarity of a solution is determined by the number of moles of solute per liter of solution. To find the molarity of the solution, we need to know the molar mass of sodium hydroxide (NaOH), which is approximately 40 g/mol. First, we convert the mass of NaOH to moles:

Mass of NaOH = 15.0 g

Molar mass of NaOH = 40 g/mol

Moles of NaOH = Mass / Molar mass = 15.0 g / 40 g/mol = 0.375 moles

Second, we convert the volume of the solution from milliliters to liters:

Volume of solution = 225 mL

1 liter = 1000 mL

Volume in liters = 225 mL / 1000 = 0.225 liters

Finally, we calculate the molarity of the solution using the formula:

Molarity (M) = Moles of solute / Volume of solution in liters

Molarity (M) = 0.375 moles / 0.225 liters

Molarity (M) = 1.667 M

Therefore, the molarity of the sodium hydroxide solution is 1.667 M.

Use semaphore(s) to solve the following problem. There are three processes: P1, P2, and P3. Each process Pi has a segment of codes Ci, i=1, 2, 3. These three processes are executed only once, i.e., no repeat or loop at all, and their executions can start at any time. Your goal is to ensure that the execution of C1, C2, and C3 must satisfy the following conditions:
a. If C1 is executed ahead of C2 and C3, C2 must be executed ahead of C3.
b. Otherwise, C1 must be executed after both C2 and C3 are executed. In this case, the order of C2 and C3's execution doesn't matter. One of the possible execution orders is demonstrated below. Obviously, two other possible sequences in time are C2, C3, C1 and C3, C2, C1.
Please write your algorithm level code for semaphore initialization and usage in each code segment. [Hint: no if statements should ever be used. All you need is some semaphore function calls surrounding C1, C2, and C3 and their initial values.]

Answers

Answer:

See explaination

Explanation:

Here we will use two semaphore variables to satisfy our goal

We will initialize s1=1 and s2=1 globally and they are accessed by all 3 processes and use up and down operations in following way

Code:-

s1,s2=1

P1 P2 P3

P(s1)

P(s2)

C1

V(s2) .

P(s2). .

. C2

V(s1) .

P(s1)

. . C3

V(s2)

Explanation:-

The P(s1) stands for down operation for semaphore s1 and V(s1) stands for Up operation for semaphore s1.

The Down operation on s1=1 will make it s1=0 and our process will execute ,and down on s1=0 will block the process

The Up operation on s1=0 will unblock the process and on s1=1 will be normal execution of process

Now in the above code:

1)If C1 is executed first then it means down on s1,s2 will make it zero and up on s2 will make it 1, so in that case C3 cannot execute because P3 has down operation on s1 before C3 ,so C2 will execute by performing down on s2 and after that Up on s1 will be done by P2 and then C3 can execute

So our first condition gets satisfied

2)If C1 is not executed earlier means:-

a)If C2 is executed by performing down on S2 then s2=0,so definitely C3 will be executed because down(s2) in case of C1 will block the process P1 and after C3 execute Up operation on s2 ,C1 can execute because P1 gets unblocked .

b)If C3 is executed by performing down on s1 then s1=0 ,so definitely C2 will be executed now ,because down on s1 will block the process P1 and after that P2 will perform up on s1 ,so P1 gets unblocked

So C1 will be executed after C2 and C3 ,hence our 2nd condition satisfied.

Write a program that reads students’ names followed by their test scores. The program should output each student’s name followed by the test scores and the relevant grade. It should also find and print the highest test score and the name of the students having the highest test score. Student data should be stored in a struct variable of type studentType, which has four components: studentFName and studentLName of type string, testScore of type int (testScore is between 0 and 100), and grade of type char. Suppose that the class has 20 students. Use an array of 20 components of type studentType. Your program must contain at least the following functions: A function to read the students’ data into the array. A function to assign the relevant grade to each student. A function to find the highest test score. A function to print the names of the students having the highest test score. Your program must output each student’s name in this form: last name followed by a comma, followed by a space, followed by the first name; the name must be left justified. Moreover, other than declaring the variables and opening the input and output files, the function main should only be a collection of function calls.

Answers

The program will manage students' test scores using a struct that records each student's name, score, and grade. It involves functions to input data, calculate grades, and identify the highest scorer. Output is formatted as 'LastName, FirstName: Grade'.

Explanation:

Program Structure for Student Grade Records

To create a program for managing student test scores and grades, we would define a struct named studentType with components studentFName, studentLName, testScore, and grade. We'd use an array of studentType of size 20 to store each student's details. The program would include functions to read student data, assign grades, find the highest test score, and print students with the highest score. Grades would be assigned based on the test scores in a typical A-F scale.

The main function should be clean and comprise primarily of function calls to handle various operations such as reading data and processing grades.

The output format for each student's name and grade should be "LastName, FirstName: Grade" with the last name and first name left justified, following the requirements specified for the assignment.

What are the programming concepts (within or outside the scope of IT210) that you would like to strengthen and delve into further after this course. Why? What is your plan to learn more about the concept(s) you identify? Identify the course concept(s) that you would like this course to provide more content about. Why? Is there any topic and / or concept for which you need more explanation? In addition to Java, what are the programming languages you are interested to learn? Why?

Answers

Answer:

The description for the given question is described in the explanation section below.

Explanation:

I would like to reinforce in advanced or complex concepts such as documents as well as channels, internet programming, multi-threading, after that last lesson.

I am interested in learning web development to develop applications or software. I would also like to explore those concepts by using open source tools.Course concepts will have to develop models for handling.No there is no subject matter or definition you provide further clarity for.I'm interested in studying java as well as web development in comparison to C++ so I can use it in my contract work.

(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character. (1 pt) (2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character. (2 pts) Example output for triangle_char = % and triangle_height = 5:

Answers

Answer:

Following are the code to this question can be described as follows:

c= input('Input triangle_char: ') #defining variable c that input character value  

length = int(input('Enter triangle_height: ')) # Enter total height of triangle

for i in range(length): # loop for column values

   for j in range(i+1): #loop to print row values

       print(c,end=' ') #print value  

   print()# for new line

Output:

please find the attachment.

Explanation:

In the above python code, two variable "c and length" variables are declared, in variable c is used to input char variable value, in the next line, length variable is defined, that accepts total height from the user.

In the next line, two for loop is declared, it uses as nested looping, in which the outer loop prints column values and inner the loop is used to prints rows. To prints all the value the print method is used, which prints the user input character triangle.
Final answer:

The question asks how to modify a program to print a right triangle using a character and height defined by the user. The solution is to use a nested loop, wherein an outer loop specifies the number of rows equal to the triangle's height and the inner loop iterates over each row to print the specified character. The range of the inner loop increases with each outer loop iteration.

Explanation:

To modify the given program to output a right triangle using the user-specified character and of a specified height, we would implement a nested loop in the program. An outer loop would control the number of rows, which equals the triangle's height, and an inner loop would handle the printing of the user-specified character per line. The inner loop's range would increase with each iteration of the outer loop. Here's an example in Python:

triangle_char = input('Enter a character: ') triangle_height = int(input('Enter triangle height: ')) for i in range(1, triangle_height + 1):for j in range(i): print(triangle_char, end=' ') print()

The triangle_char variable is the character used to generate the triangle. The triangle_height variable determines the number of rows. The range() function in the loops determines how many times the loop executes.

Learn more about Programming Nested Loops here:

https://brainly.com/question/35123300

#SPJ11

please code this in c++

5.19 Farmer's market - files

Get the file name from the user and open it using code. The file has the product name and price/lb in each line.

Until the EOF is reached:

Read the product name from the file

prompt the user for entering the weight of that product. (Points will be taken off if you hard-code the product name inside your code).

Once the user enters the weight(0 if user does not buy that item), calculate the cost of that item by reading the price of that item from the file and multiplying by the weight entered by the user.

Maintain a running total of the cost until all the items have been entered by user.

Once EOF is reached, display the total cost of the purchase

product.txt // contains the following

apple 1.59
orange 0.99
banana 0.69
grapes 2.99

Answers

Answer:

See explaination

Explanation:

#include<iostream>

#include<fstream>

using namespace std;

int main(){

double price, totalPrice = 0, weight;

string product, filename;

cout<<"Enter filename: ";

cin>>filename;

ifstream fin;

fin.open(filename.c_str());

while(fin>>product>>price){

cout<<"Enter weight for "<<product<<": ";

cin>>weight;

totalPrice+=price*weight;

}

cout<<"\nThe total cost of the purchase: $"<<totalPrice<<endl;

return 0;

}

Define a function drawCircle.

This function should expect a Turtle object, the coordinates of the circle's center point, and the circle's radius as arguments.The function should draw the specified circle. The pen color should be changed to yellow before drawing a circle and the width of the pen to 5 pixels. The algorithm should draw the circle's circumference by turning 3 degrees and moving a given distance 120 times. Calculate the distance moved with the formula 2.0*n*radius/120.0.

Fill in the circle with blue color. After drawing the circle, hide the turtle.

import turtle

import math

def drawCircle(centerpoint, radius):

degree = 3

count = 0

centerpoint = (2.0 * math.pi * radius / 120)

t.home()

t.setheading(degree)

while count <= 120:

t.down()

t.forward(2.0 * math.pi * radius / 120)

t.up()

degree += 3

t.setheading(degree)

count += 1

drawCircle(centerpoint, radius)

Answers

Final answer:

To draw a circle using a Turtle object in Python, you can define a function called drawCircle that takes in the Turtle object, the center point coordinates, and the radius as arguments. This code uses the turtle module in Python to draw a circle.

Explanation:

Draw a Circle using a Turtle in Python

To draw a circle using a Turtle object in Python, you can define a function called drawCircle that takes in the Turtle object, the center point coordinates, and the radius as arguments. Here's an example of how the function can be implemented:

import turtle
import math

def drawCircle(t, centerpoint, radius):
   t.pensize(5)
   t.color('yellow')
   circumference_distance = 2.0 * math.pi * radius / 120.0
   angle = 3
   t.penup()
   t.goto(centerpoint)
   t.pendown()
   for _ in range(120):
       t.forward(circumference_distance)
       t.right(angle)
   t.fillcolor('blue')
   t.begin_fill()
   t.circle(radius)
   t.end_fill()
   t.hideturtle()
t = turtle.Turtle()
drawCircle(t, (0, 0), 100)

This code uses the turtle module in Python to draw a circle. It sets the pen size to 5 pixels and the color to yellow. The circle is drawn by turning 3 degrees and moving a distance of 2.0 * math.pi * radius / 120.0. After drawing the circumference, the function fills the circle with a blue color and hides the turtle.

Final answer:

The drawCircle function is designed for the Python Turtle library to draw a colored circle based on specified parameters. The Turtle's pen is set to yellow and the pen width to 5 pixels before the circle is drawn and filled with blue. After drawing, the Turtle is hidden.

Explanation:

The function drawCircle is intended to work with the Python Turtle graphics library to draw a circle on the screen. The function will expect a Turtle object, the coordinates of the circle's center point, and the circle's radius as arguments. Below is a corrected version of the function that follows the stated requirements:

import turtle
import math

def drawCircle(t, x, y, radius):
   t.penup()
   t.goto(x, y-radius) # Move to the circle's starting point
   t.setheading(0) # Face east
   t.pendown()
   t.color('yellow')
   t.width(5)
   t.begin_fill()
   t.fillcolor('blue')

   for _ in range(120):
       t.forward(2.0 * math.pi * radius / 120.0)
       t.left(3)

   t.end_fill()
   t.hideturtle()

Make sure to create a Turtle object and pass it to the drawCircle function along with the center point's coordinates and the radius of the circle you wish to draw.

Which term describes measurable results expected in a given time frame?

Answers

Answer: I think a deadline?

The term that describes the results expected in a given time frame is the goal. The correct option is A.

What are goals?

The desired states that people want to achieve, maintain, or avoid are referred to as life goals. When we make goals, we commit to imagining, planning for, and obtaining these desired outcomes. The satisfaction with our careers is the satisfaction with our lives because we spend more than half of our waking hours at work.

The most significant professional goal we can set for ourselves is to identify our areas of love and make them into lifelong careers. An objective is something you hope to accomplish. It is the desired outcome that you or a group of people plan for and firmly resolve to attain. The phrase "goal" refers to the outcomes anticipated in a specific time range.

Therefore, the correct option is A, Goals.

To learn more about goals, refer to the link:

https://brainly.com/question/21032773

#SPJ2

The question is incomplete. Your most probably complete question is given below:

Goals

Mind maps

Purposes

Ideas

Write a function called find_max that takes in a single parameter called random_list, which should be a list. This function will find the maximum (max) value of the input list, and return it. This function will assume the list is composed of only positive numbers. To find the max, within the function, use a variable called list_max that you initialize to value 0. Then use a for loop to loop through random_list. Inside the list, use a conditional to check if the current value is larger than list_max, and if so, re-assign list_max to store this new value. After the loop, return list_max, which should now store the maximum value from within the input list.

Answers

Answer:

see explaination

Explanation:

python code

def find_max(random_list):

list_max=0

for num in random_list:

if num > list_max:

list_max=num

return list_max

print(find_max([1,45,12,11,23]))

Implement the logic function ( , , ) (0,4,5) f a b c m =∑ in 4 different ways. You have available 3to-8 decoders with active high (AH) or active low (AL) outputs and OR, AND, NOR and NAND gates with as many inputs as needed. In every case clearly indicate which is the Most Significant bit (MSb) and which is the Least Significant bit (LSb) of the decoder input.

Answers

Answer:

See explaination

Explanation:

Taking a look at the The Logic function, which states that an output action will become TRUE if either one “OR” more events are TRUE, but the order at which they occur is unimportant as it does not affect the final result. For example, A + B = B + A.

Alternatively the Most significant bit which is also known as the alt bit, high bit, meta bit, or senior bit, the most significant bit is the highest bit in binary.

See the attached file for those detailed logic functions designed with relation to the questions asked.

Create a Visual Logic flow chart with four methods. Main method will create an array of 5 elements, then it will call a read method, a sort method and a print method passing the array to each. The read method will prompt the user to enter 5 numbers that will be stored in the array. The sort method will sort the array in ascending order (smallest to largest). The print method will print out the array.

Answers

Answer:

See explaination

Explanation:

import java.util.Scanner;

public class SortArray {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

System.out.println("Enter Size Of Array");

int size = sc.nextInt();

int[] arr = new int[size]; // creating array of size

read(arr); // calling read method

sort(arr); // calling sort method

print(arr); // calling print method

}

// method for read array

private static void read(int[] arr) {

Scanner sc = new Scanner(System.in);

for (int i = 0; i < arr.length; i++) {

System.out.println("Enter " + i + "th Position Element");

// read one by one element from console and store in array

arr[i] = sc.nextInt();

}

}

// method for sort array

private static void sort(int[] arr) {

for (int i = 0; i < arr.length; i++) {

for (int j = 0; j < arr.length; j++) {

if (arr[i] < arr[j]) {

// Comparing one element with other if first element is greater than second then

// swap then each other place

int temp = arr[j];

arr[j] = arr[i];

arr[i] = temp;

}

}

}

}

// method for display array

private static void print(int[] arr) {

System.out.print("Your Array are: ");

// display element one by one

for (int i = 0; i < arr.length; i++) {

System.out.print(arr[i] + ",");

}

}

}

See attachment

Which of the following should you NOT do when using CSS3 properties to create text columns for an article element? a. make the columns wide enough to read easily b. include a heading in the article element c. set rules between the columns of the article element d. justify the text

Answers

Answer:

b. include a heading in the article element

Explanation:

If you put a heading element in an article element where you've applied the CSS column property or similar, the heading will be forced into one of the columns.

B I believe it is so

Programming Exercise 8.2 on page 327. Additional details: The size of an array cannot be changed based on user input (dynamic memory allocation), so the matrix should be dimensionsed to the max size ever expected (10 x 10 perhaps). Prompt user to enter N (the size of the N x N matrix). The program should work for any N >= 2. N should not be used anywhere for matrix dimensions. It is only used in for loops to control user input and printing. Note that a 3x3 matrix is really just using the upper corner of the 10x10 matrix. Prompt the user to enter the elements in the matrix row-by-row. Display the NxN matrix. Display the sum of the elements in the major diagonal. The sum should be displayed from the main function, not from the function sumMajorDiagonal. Include a printout of the main program and the function. Include printouts for the test case in the textbook as well as for a 2x2 matrix and a 3x3 matrix.

Answers

Answer:

#include<iostream>

using namespace std;

double sumMajorDiagonal(double n,double sum);

int main()

{

int N;

double a[10][10],n,sum=0; //declare and define matrix of size 10x10

cout<<"Enter the size of the matrix: ";

cin>>N; //input the size of the matrix

if(N<2) //check condition wheather size of the matrix is greater than or equal to 2

{

cout<<"Size of matrix must be 2 or more!"<<"\n";

return 0;

}

for(int i=0;i<N;i++) //loop for Row

{

for(int j=0;j<N;j++) //loop for column

{

cout<<"Enter element: ";

cin>>n; //input the element in matrix

a[i][j] = n;

if(i==j) //check for major diagonal condition

{

sum = sumMajorDiagonal(a[i][j],sum); //call sunMajorDiagonal funtion if condition statisfied

}

}

}

for(int i=0;i<N;i++) //loop for row

{

for(int j=0;j<N;j++) //loop for column

{

cout<<a[i][j]<<" "; //print elements of matrix

}

cout<<"\n"; //next line for new row

}

cout<<"Sum of the elements of major diagonal is: "<<sum<<"\n"; //print sum of the major row calculated

}

double sumMajorDiagonal(double n,double sum)

{

return sum+n; //add the major diagonal elements and return the value

}

Explanation:

See attached image for output

//Add you starting comment block public class BubbleBubbleStarter //Replace the word Starter with your initials { public static void main (String[] args) { //Task 1: create an input double array list named mylist with some values pSystem.out.println("My list before sorting is: "); //Task 2: print the original list //Use println() to start and then replace with your printList() method after Task 4a is completed. p//Task 3: call the bubblesort method for mylist p//Task 4b: print the sorted list p} //Task 4a: create a method header named printlist to accept a formal parameter of a double array //create a method body to step through each array element println each element p//printList method header p//for loop p//println statement static void bubbleSort(double[] list) { boolean changed = true; do { changed = false; for (int j = 0; j < list.length - 1; j++) if (list[j] > list[j+1]) { //swap list[j] with list[j+1] double temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; changed = true; } } while (changed); } }

Answers

Answer:

See explaination

Explanation:

import java.util.Scanner;

public class BubbleBubbleStarter {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

double arr[] = new double[10];

System.out.println("Enter 10 GPA values: ");

for (int i = 0; i < 10; i++)

arr[i] = sc.nextDouble();

sc.close();

System.out.println("My list before sorting is: ");

printlist(arr);

bubbleSort(arr);

System.out.println("My list after sorting is: ");

printlist(arr);

}

static void bubbleSort(double[] list) {

boolean changed = true;

do {

changed = false;

for (int j = 0; j < list.length - 1; j++) {

if (list[j] > list[j + 1]) {

double temp = list[j];

list[j] = list[j + 1];

list[j + 1] = temp;

changed = true;

}

}

} while (changed);

}

static void printlist(double list[]) {

for (int j = 0; j < list.length; j++) {

System.out.println(list[j]);

}

}

}

3.14 LAB: Simple statistics for Python
Given 4 floating-point numbers. Use a string formatting expression with conversion specifiers to output their product and their average as integers (rounded), then as floating-point numbers.

Output each rounded integer using the following:
print('{:.0f}'.format(your_value))

Output each floating-point value with three digits after the decimal point, which can be achieved as follows:
print('{:.3f}'.format(your_value))

Ex: If the input is:

8.3
10.4
5.0
4.8
the output is:

2072 7
2071.680 7.125


So far I came up with the following:
num1 = float(input())
num2 = float(input())
num3 = float(input())
num4 = float(input())

avg = (num1+num2+num3+num4)/4
prod = num1*num2*num3*num4
print('%d %d'%(avg,prod))
print('%0.3f %0.3f'%(avg,prod))

I keep getting this output and I don't know what I'm doing wrong:
7 2071
7.125 2071.680
Expected output should be:
2072 7
2071.680 7.125

Answers

Following are the correct python code to this question:

Program Explanation:

In the python program four variable "n1, n2, n3, and n4" is defined, in which we input method is used that input value from the user end. In this, we use the float method, which converts all the input values into a float value.In the next step, two variables "average and product" are defined, which calculate all input numbers product, average, and hold value in its variable.In the last step, a print method is used, that prints its round and format method value.

Program:

n1 = float(input('Input first number: '))#input first number

n2 = float(input('Input second number: '))#input second number

n3 = float(input('Input third number: '))#input third number

n4 = float(input('Input fourth number: '))#input fourth number

average = (n1+n2+n3+n4)/4 #calculate input number average

product = n1*n2*n3*n4 # calculate input number product

print('product: {:.0f} average: {:.0f}'.format(round(product),round(average))) #print product and average using round function

print('product: {:.3f} average: {:.3f}'.format(product,average)) #print product and average value

Output:

Please find the attachment.

Learn more:

brainly.com/question/14689516

The program calculates the product and average of four floating-point numbers, and outputs them as integers (rounded) and as floating-point numbers with three digits after the decimal point, using specified string formatting expressions.

Here's the Python code to achieve that:

# Input

num1 = float(input())

num2 = float(input())

num3 = float(input())

num4 = float(input())

# Calculate product and average

product = num1 * num2 * num3 * num4

average = (num1 + num2 + num3 + num4) / 4

# Output rounded integers

print('{:.0f} {:.0f}'.format(product, average))

# Output floating-point numbers with three digits after the decimal point

print('{:.3f} {:.3f}'.format(product, average))

User inputs four floating-point numbers.The product and average of the four numbers are calculated.Using string formatting with conversion specifiers, the product and average are output as integers (rounded) and as floating-point numbers with three digits after the decimal point.

This code snippet ensures the desired output format by using the specified string formatting expressions.

A Solutions Architect must review an application deployed on EC2 instances that currently stores multiple 5-GB files on attached instance store volumes. The company recently experienced a significant data loss after stopping and starting their instances and wants to prevent the data loss from happening again. The solution should minimize performance impact and the number of code changes required. What should the Solutions Architect recommend?

Answers

Answer:

Store the application data in an EBS volume

Explanation:

EC2 Instance types determines the hardware of the host computer used for the instance.

Each instance type offers different compute, memory, and storage capabilities and are grouped in instance families based on these capabilities

EC2 provides each instance with a consistent and predictable amount of CPU capacity, regardless of its underlying hardware.

EC2 dedicates some resources of the host computer, such as CPU, memory, and instance storage, to a particular instance.

EC2 shares other resources of the host computer, such as the network and the disk subsystem, among instances. If each instance on a host computer tries to use as much of one of these shared resources as possible, each receives an equal share of that resource. However, when a resource is under-utilized, an instance can consume a higher share of that resource while it’s available

Write a program that opens a text file (name the textfile "problem4.txt") and reads its contents into a queue of characters. The user must then enter a character they are looking for. The program should then dequeue each character and count the number of characters that are equal to what the user is looking for. Output the count of the character or lack thereof in a second file (name the textfile "resultsp4.txt").

Answers

Answer:

See explaination

Explanation:

/* reading a text file Character by Character

* Enter the character to Queue

* Search Specific character and Printingits occurrence

* otherwise Lack thereof

*/

// Include header file for File Reading

#include <iostream>

#include <fstream>

// Maximum no of character in a file

# define N 50

using namespace std;

// Queue Data Structure

typedef struct

{

char arr[N];

int front;

int rear;

int size;

}Queue;

// Function Prototypes

void initialize(Queue*);

void Enqueue(Queue*,char);

char Dequeue(Queue*);

int isEmpty(Queue*);

int isFull(Queue*);

int Qsize(Queue*);

int main () {

// Variable Declaration

char ch;

char searchchar;

// Allocating memeory for the Queue.

Queue *Q=(Queue *)malloc(sizeof(Queue));

// Reading from the file

fstream fin("problem4.txt", fstream::in);

//initialize Queue with front rear and size

initialize(Q);

//Looping through the file and Enqueue it in Queue

while (fin >> noskipws >> ch) {

Enqueue(Q,ch);

}

// close the opened file.

fin.close();

int i=0;

int n=Qsize(Q);

int count=0;

//Asking user for Input

cout << "Please character to found ";

cin >> searchchar;

while (i<n) {

if(Dequeue(Q)==searchchar)

count++; // if found increase the count

i++;

}

// Total Count od character searched

cout << "Total Count of Character " << count << endl;

// Output Total Count of Character to a file named resultsp4.txt

ofstream outfile;

outfile.open("resultsp4.txt");

cout << "Writing to the file" << endl;

if (count>0)

outfile << "The total occurence of the " << searchchar <<" is "<< count <<endl;

else

outfile << "lack thereof " << searchchar <<endl;

// close the opened file.

outfile.close();

return 0;

}

void initialize(Queue *Q)

{

Q->front=-1;

Q->rear=-1;

Q->size=0;

}

void Enqueue(Queue * Q,char ch)

{

(Q->rear)+=1;

(Q->arr[Q->rear])=ch;

(Q->size)++;

}

char Dequeue(Queue * Q)

{

char ch=Q->arr[Q->front];

(Q->front)++;

(Q->size)--;

return ch;

}

int isEmpty(Queue * Q)

{

if ((Q->size)==0)

return 1;

else

return 0;

}

int isFull(Queue * Q)

{

if ((Q->size)==N)

return 1;

else

return 0;

}

int Qsize(Queue * Q)

{

return Q->size;

}

2. Use inheritance to create a hierarchy of Exception classes -- EndOfSentenceException, PunctuationException, and CommaException. EndOfSentenceException is the parent class to PunctuationException, which is the parent class to CommaException. Test your classes in a Driver class with a main method that asks the user to input a sentence. If the sentence ends in anything except a period (.), exclamation point (!), or question mark (?), the program should throw a PunctuationException. If the sentence specifically ends in a comma, the program should throw a CommaException. Use a catch block to catch all EndOfSentenceExceptions, causing the program to print a message and terminate. If a general PunctuationException is caught, the program should print "The sentence does not end correctly." If a CommaException is caught, the program should print "You can't end a sentence in a comma." If there are no exceptions, the program should print "The sentence ends correctly." and terminate.

Answers

Answer:

See explaination

Explanation:

EndOfSentenceException.java

//Create a class EndOfSentenceException that

//extends the Exception class.

class EndOfSentenceException extends Exception

{

//Construtor.

EndOfSentenceException(String str)

{

System.out.println(str);

}

}

CommaException.java

//Create a class CommaException that extends the class

//EndOfSentenceException.

class CommaException extends EndOfSentenceException

{

//Define the constructor of CommaException.

public CommaException(String str)

{

super(str);

}

}

PunctuationException.java

//Create a class PunctuationException that extends the class

//EndOfSentenceException.

class PunctuationException extends EndOfSentenceException

{

//Constructor.

public PunctuationException(String str)

{

super(str);

}

}

Driver.java

//Include the header file.

import java.util.Scanner;

//Define the class Driver to check the sentence.

public class Driver {

//Define the function to check the sentence exceptions.

public String checkSentence(String str)

throws EndOfSentenceException

{

//Check the sentence ends with full stop,

//exclamation mark

//and question mark.

if(!(str.endsWith(".")) && !(str.endsWith("!"))

&& !(str.endsWith("?")))

{

//Check the sentence is ending with comma.

if(str.endsWith(","))

{

//Throw the CommaException.

throw new CommaException("You can't "

+ "end a sentence in a comma.");

}

//Otherwise.

else

{

//Throw PunctuationException.

throw new PunctuationException("The sentence "

+ "does not end correctly.");

}

}

//If the above conditions fails then

//return this message to the main function.

return "The sentence ends correctly.";

}

//Define the main function.

public static void main(String[] args)

{

//Create an object of Scanner

Scanner object = new Scanner(System.in);

//Prompt the user to enter the sentence.

System.out.println("Enter the sentence:");

String sentence=object.nextLine();

//Begin the try block.

try {

//Call the Driver's check function.

System.out.println(new

Driver().checkSentence(sentence));

}

//The catch block to catch the exception.

catch (EndOfSentenceException e)

{}

}

}

Other Questions
Conjugate the verb Rester in the passe compose with etre.Reminder: The past participle must agree with the subject. In this poem, crystal stair is used to symbolizeA. An easy life B. An obstacle C. True love D. A nice house B: Which detail from the poem best supports the answer to PART A?A. "Against injustice, fear deadens their pleas" (Line 14)B. "Nothing we are, chained by parentheses." (Line 16)C. "That foreign face, my countryman, is you" (Line 17)D. "Though seldom have you worn parentheses." (Line 20) Use the cost and revenue data to answer the questions. Quantity Price Total Revenue Total Cost 15 90 1350 900 30 80 2400 1500 45 70 3150 2250 60 60 3600 3150 75 50 3750 4200 90 40 3600 5400 What is marginal revenue when quantity is 30 ? 30? $ What is marginal cost when quantity is 60 ? 60? $ If this firm is a monopoly, at what quantity will profit be maximized? quantity: If this is a perfectly competitive market, which quantity will be produced? quantity: Comparing monopoly to perfect competition, which statement is true? The perfectly competitive market's ouput is lower. The consumer surplus is smaller with a monopoly. The monopoly's price is higher. which of the following is a rational number [tex] \sqrt{6} [/tex][tex]2\pi[/tex][tex] \sqrt{196} [/tex][tex] \sqrt{8} [/tex] Read the excerpt from The Boy Who Harnessed the Wind by William Kamkwamba. One Saturday, Gilbert met me in the library and we flipped through books we thought might be fun. I couldn't study all the time. One book that caught my attention was the Malawi Junior Integrated Science book, used by Form Four students. Hmm, I thought, and flipped it open. There were lots of pictures and diagrams, which I found easy to understand. I saw pictures of cancer and scabies and children stricken with kwashiorkor, like so many who'd wandered the country. One picture had a man in a shiny silver suit walking on the moon.What is the primary idea that the details in the excerpt tell a reader about Kamkwamba?He has varied interests in reading material.He is intelligent despite his lack of education.He and Gilbert are good friends who share interests.He is not really interested in studying. Please help me! Germans where u at????? ASAAAAP 20 points + best answer gets marked BRAINLIEST! 25 points!What does "domestic affair" and "foreign affair" mean in terms of politics and government? Please I need this soon! Completa. Complete the sentences with words shown above.1. Janet y Andy son losde Marisa2. Luis y Carmen son losde Marisa3. Tess y Rita son lasde Mack y Tim.4. Lade Luisito es Carmen.5. Marisa es lade Xochitl.6. Luisito es elde Xochitl.PLSSS HELLPPP ASAP Which situation can be modeled by the inequality 3+7 (15 pt., 5 pt. each) A player in the Powerball lottery picks five different integers between 1 and 69, inclusive, and a sixth integer between 1 and 26, inclusive, which may duplicate one of the earlier five integers. The player wins the jackpot (currently $43 million) if the first five numbers picked match the first five numbers drawn (in any order) and the sixth number picked matches the sixth number drawn. a. What is the probability that a player wins the jackpot El sacerdote les aconseja que ellos_________ amables con sus compaeros. (ser) son somos sean ser What is the atomic number of this atom? How do we write 1/5 as a decimal? A regulation basketball hoop has a rim with an 18-inch diameter. What is the approximate length around the rim of a regulation basketball hoop? Rewrite the following sentence using the correct verb. Me ( cepillo / maquillo ) la cara. The process of land becoming a desert because there are no plants to help hold and cycle water. a erosion b . weathering C. desertification d. soil conservation. In "To His Excellency George Washington," the speaker creates a sense of Columbia mainly by ___________.A. detailing the powerful storms that occcur inland B. recalling a memory of a favored hill she visited C. documenting the actions of the army during warD. describing the land with human characteristics The addition of 9.54 kJ of heat is required to raise the temperature of 225.0 g of a liquid hydrocarbon from 20.5 degree C to 45.0 degree C. What is the heat capacity of this hydrocarbon? What the answer to this Steam Workshop Downloader