In this assignment, you will write a complete C program that will act as a simplecommand-line interpreter (i.e., a shell) for the Linux kernel. In writing your shell, you areexpected to use the fork-exec-wait model discussed in class. In particular, you are toimplement the following:• Loop continuously until the user enters quit, which exits your shell.• Inside the loop, you will print your "minor5" prompt and read in the user’scommand, which may consist of a Linux command with 0 or more options andarguments supported by the command. You are expected to read in and processonly 1 command at a time with no pipelining or redirection.• In a child process, you are to execute the command as given, including alloptions and arguments given. If the command is not valid, rather than display an"exec failed" message as shown in class examples, you will simply print outthe command itself with "command not found" as shown in the SAMPLEOUTPUT and then exit the child process. The parent process should wait for thechild process to finish.If you have any questions about this, please contact your instructor, TAs, or IAsassigned to this course to ensure you understand these directions.SAMPLE OUTPUT (user input shown in bold):$ ./a.outminor5> lsa.out grades.txt rec01.txt testdir phone.txt route.txt who.txtdu.txt rec01.c file1 rec01sol.c minor5.cminor5> ls -a -l -ttotal 144-rwx------ 1 cat0299 cat0299 7835 Oct 14 17:39 a.outdrwx------ 4 cat0299 cat0299 4096 Oct 14 17:39 .-rw------- 1 cat0299 cat0299 2665 Oct 14 17:39 minor5.c-rw------- 1 cat0299 cat0299 33 Oct 5 03:30 du.txt-rw------- 1 cat0299 cat0299 33 Oct 5 01:28 file1-rw------- 1 cat0299 cat0299 333 Oct 5 01:02 route.txt

Answers

Answer 1

Answer:

/ to access the input scanf()

// and output printf()

#include <stdio.h>  

// to access the functions like

// pipe(), fork(), execvp(), dup2()

#include <unistd.h>  

// to access the string functions like

// strtok()

#include <string.h>

// to access function wait()

#include <sys/wait.h>

#include <stdlib.h>

int main()

{

  // declare a variable to hold the process id

  pid_t p_id;

  // declare a variable to hold the index value

  int array_index;

  // declare the string to hold the user input

  // as command

  char userIn_Command[128];

  // use a continuous loop

  while (1)

  {

      // display the prompt for the user

      printf("minor5> ");

      // read the input from the user

      scanf("%[^\n]", userIn_Command);

      // check the condition that whether the user

      // inputs a command called "quit"

      // If the user inputs quit command then exit from

      // the script

      if (strcmp(userIn_Command, "quit") == 0)

      {

          printf("\n");

          break;

      }

      // if there are any usage of pipelining or redirection

      // display the error message and exit from the script

      if (strchr(userIn_Command, '|') != NULL || strchr(userIn_Command, '>') != NULL ||

          strchr(userIn_Command, '<') != NULL)

      {

          printf("Error: Cannot perform the multiple command operations or directions\n");

          break;

      }

      // declare the variables to hold the process

      int p_pids[2];

      // create the system call to pipe() from kernal

      // and display the error message

      if (pipe(p_pids) < 0)

      {

          printf("Error: Pipe creation failed!\n");

      }

      // create the child process

      p_id = fork();

      // condition to check whether the fork() is

      // created. If so, display an error message

      if (p_pids < 0)

      {

          printf("Error: fork() failed!\n");

          break;

      }

      // if the child process is created

      if (p_id == 0)

      {

          // close pipe in child process

          close(p_pids[0]);

          // create duplicate of the standard output

          dup2(p_pids[1], STDOUT_FILENO);

          // close the pipe in child process

          close(p_pids[1]);

          // declare a variable to store path

          // to execute the command

          char *command_path;

          // declare an array of string to hold the options

          char * args[32];

          // tokenize the command by using the delimiter at " "(single space)

          char *cmd_token = strtok(userIn_Command, " ");

          // store the token value

          command_path = cmd_token;

          args[0] = cmd_token;

          array_index = 1;

          // loop until all the options in the command are

          // tokenized

          while (1)

          {

              // get the next token

              cmd_token = strtok(NULL, " ");

              // condition to check whether the token is null

              // or not

              if (cmd_token == NULL)

              {

                  break;

              }

              // store the token if it is not null

              args[array_index] = cmd_token;

              // increment the index

              array_index++;

          }

          // last parameter to the command should be NULL */

          args[array_index] = NULL;

                     

          /* calling exec function with command path and parameters */

          if (strcmp(args[0], "cd") == 0 || strcmp(args[0], "history") == 0 ||

              strcmp(args[0], "exit") == 0)

          {

              printf("%s: Command not found\n", args[0]);

              break;

          }

          if (execvp(command_path, args) < 0 )

          {

              printf("%s: Command not found\n", args[0]);

              break;

          }

      }

      else

      {          

          /* closing writing end of pipe in parent process */

          close(p_pids[1]);

          /* reading ouput written to pipe in child process and

          * writing to console */

          while (1)

          {

              char output[1024];

              int n = read(p_pids[0], output, 1024);

              if (n <= 0)

              {

                  break;

              }

              output[n] = '\0';

              printf("%s", output);

          }

          /* closing read end of pipe1 */

          close(p_pids[0]);

          /* waiting until child process complete its execution */

          wait(NULL);

      }

      /* skipping newline character read while scanf() */

      getchar();

  }

  exit(0);

}

Explanation:

In This Assignment, You Will Write A Complete C Program That Will Act As A Simplecommand-line Interpreter
In This Assignment, You Will Write A Complete C Program That Will Act As A Simplecommand-line Interpreter
In This Assignment, You Will Write A Complete C Program That Will Act As A Simplecommand-line Interpreter

Related Questions

A company ABC asked you to design a simple payroll program that calculates and employee's weekly gross pay, including any overtime wages. If employees work over 40 hours in a week, they will get 1.5 times of their regular hourly rate for all hours over 40. Your program asks the user to input hours worked for a week, regular hourly rate, and then display the weekly gross pay. Draw the Raptor flowchart to represent the logic of the problem. Name the Raptor flowchart file as lab5.rap. Output sample Enter weekly hours worked: 35 Enter hourly rate: 30 Weekly gross pay: $ 1050 Output sample Enter weekly hours worked: 50 Enter hourly rate: 30 Weekly gross pay: $ 1650

Answers

Answer:

C++.

#include <iostream>

using namespace std;

////////////////////////////////////////////////////////////////

int main() {

   int weekly_hours = 0;

   int hourly_rate;

   float gross_pay = 0;

   cout<<"Enter weekly hours worked: ";

   cin>>weekly_hours;

   

   cout<<"Enter hourly rate: ";

   cin>>hourly_rate;

   

   cout<<endl;

   ////////////////////////////////////////////////

   if (weekly_hours > 40) {

       gross_pay = (weekly_hours*hourly_rate) + ((weekly_hours*hourly_rate)*0.5);

   }

   else

       gross_pay = weekly_hours*hourly_rate;

       

   cout<<"Weekly gross pay: $"<<gross_pay;

   ////////////////////////////////////////////////

   return 0;

}

Chapter 4 is called Claimed Spaces: ""Preparatory Privilege"" and High School Computer Science. Explain two concepts from chapter 4 that create ‘claimed spaces’ (2-3 sentences). Describe an example from your own experience of a claimed space (2-3 sentences)

Answers

Answer: isolation, predominant gender.

Explanation:

Isolation some students felt they were not as smart as their peers and as such were afraid to make contributions because they didn't want to be rediculed by Their peers or tutors.

Predominant gender most calsses are dominated by a certain gender which makes the other gender harbour fears and insecurity

I had difficulty in maths in high school, was always afraid when in class to make contributions because i was insecure, if i had spoken up or met my tutors maybe i would have being better at it

When it comes to social media technologies and formal learning in the corporate environment, the only social media platform that can be used effectively for teaching and learning purposes is Twitter (Steer, 2015).

Answers

Ootions: TRUE OR FALSE

Answer: FALSE

Explanation: According to (Steer,2015) there are many platforms for learning and teaching purposes in corporate Organisations, they include PINTEREST,WIKI,GOOGLE+, LINKEDIN,TWITTER etc, The social media platforms are available for effective and efficient Communication and has been the main driving force for Businesses the world over.

These social media platforms have aided the growth and expansion of product marketing strategies and enhanced the over all business efficiency.

We have seen in class that the sets of both regular and context-free languages are closed under the union, concatenation, and star operations. We have also seen in A2 that the regular languages are closed under intersection and complement. In this question, you will investigate whether the latter also holds for context-free languages.
(a) Use the languages A = {a^mb^nc^n \ m, n greaterthanorequalto 0} and B = {a^nb^nc^m \ m, n greaterthanorequalto 0} to show that the class of context-free languages is not closed under intersection. You may use the fact that the language C = {a^nb^nc^n | n greaterthanorequalto 0} is not context-free.
(b) Using part (a) above, show now that the set of context-free languages is not closed under complement.

Answers

Answer:

Attached is the solution. Hope it helps:

a) The class of context-free languages is not closed under intersection, as shown by the example of[tex]A = [ a^m b^n c^n | m, n \geq 0 ][/tex] and [tex]B = [a^n b^n c^m | m, n \geq 0 ][/tex]

Given that;

We have seen in class that the sets of both regular and context-free languages are closed under the union, concatenation, and star operations.

(a) We're given two languages A and B:

[tex]A = [ a^m b^n c^n | m, n \geq 0 ][/tex]

[tex]B = [a^n b^n c^m | m, n \geq 0 ][/tex]

We want to show that the intersection of A and B is not context-free.

To do this, we can use the fact that the language [tex]C = [a^n b^n c^n | n \geq 0 ][/tex] is not context-free.

Assume for contradiction that the intersection of A and B, which we'll call D, is context-free.

Since context-free languages are closed under intersection, we'd have D = A ∩ B is also a context-free language.

Now, notice that D is a subset of C (if a string belongs to D, it must belong to C as well).

However, C is not context-free, as given.

This contradicts our assumption that D is context-free.

Therefore, we can conclude that the class of context-free languages is not closed under intersection, as shown by the example of[tex]A = [ a^m b^n c^n | m, n \geq 0 ][/tex] and [tex]B = [a^n b^n c^m | m, n \geq 0 ][/tex]

(b) Using the result from part (a), we can now show that the set of context-free languages is not closed under complementation.

Let's consider the complement of a context-free language.

If the complement of a context-free language were always context-free, we could take the complement of C and obtain a context-free language.

However, as established earlier, C is not context-free.

Hence, we can conclude that the set of context-free languages is not closed under complementation.

Learn more about Programs here:

brainly.com/question/14368396

#SPJ3

You need to write a program that reads in the mass of an object (in kg) and output the weight (in N) on the Earth, on the Moon, and on Venus. An object's mass can be measured in kilograms. The weight is measured in newtons. So an object of a specific mass (in kilograms) would have one weight (in newtons) on the earth and a different weight on the moon. Your program will read in the mass (in kilograms) and convert it to newtons for the Earth, the Moon, and Venus. So, on the Earth we can convert kilograms to newtons with the following expression: weight = mass * 9.81 where 9.81 is the acceleration due to gravity on earth (in meters per second squared or m/s^2). On the Moon this formula would be: weight = mass * 1.62 where 1.62 is the acceleration due to gravity on the moon (m/s^2) Finally, for Venus it would be: weight = mass * 8.87

Answers

Answer:

#include <iostream>

#include<iomanip>

using namespace std;

int main()

{

double mass,e,m,v;

cout<<"Enter the mass : ";

cin>>mass;

cout<<"The mass is "<<mass<<" kg\n";

if(mass<=0){

cout<<" mass must be greater than zero";

return 0;

}

e= mass * 9.81;

m= mass * 1.62;

v = mass * 8.87;

cout.setf(ios::fixed);

cout<<"Location"<<right<<setw(10)<<"Weight\n";

cout<<"Earth"<<right<<setw(15)<<setprecision(4)<<e<<endl;

cout<<"Moon"<<right<<setw(15)<<setprecision(4)<<m<<endl;

cout<<"Venus"<<right<<setw(15)<<setprecision(4)<<v<<endl;

cout<<endl<<endl;

if(m>=1500)

cout<<"Object is light weight";

else

cout<<"Object is heavy weight";

}

Explanation:

Final answer:

An object's weight is calculated by multiplying its mass by the acceleration due to gravity, which varies by celestial body. On Earth, the weight is the mass times 9.81 m/s², while on the Moon it is mass times 1.62 m/s², and on Venus, the weight is calculated with an acceleration due to gravity of 8.87 m/s².

Explanation:

The mass of an object is a measure of the amount of matter in that object and does not change regardless of the object's location. On the other hand, weight is the force exerted by gravity on an object and is calculated by multiplying the mass (in kilograms) by the acceleration due to gravity (in meters per second squared, m/s²). This acceleration due to gravity varies depending on the celestial body.

On Earth, the acceleration due to gravity is approximately 9.81 m/s², which means that an object's weight can be calculated as its mass multiplied by 9.81. For example, a mass of 100 kg on Earth would have a weight of 981 Newtons (N).

The Moon's gravitational acceleration is much lower, around 1.62 m/s². Thus, the same 100 kg object would weigh 162 N on the Moon. It's clear that, although mass remains consistent, weight varies significantly depending on the acceleration due to gravity at the location.

Similarly, on Venus, the acceleration due to gravity is 8.87 m/s². To find the weight of an object on Venus, you multiply its mass by this acceleration. So, a 100 kg object would weigh approximately 887 N on Venus.

The distinction between mass and weight is important as it highlights that weight can change locationally due to variations in gravitational pull, while mass is an intrinsic property of an object that does not change with location.

Your friend is an intern at the local Department of Health and needs to prepare a report about the recent activity of the influenza virus. She has recorded the number of cases of each type of flu (A, B, and C) over the last several weeks. Write a C program that will calculate the total cases for each week, determine the level of activity for the week (low, moderate, or widespread) and print a report to a file, including a small bar chart for the weekly cases.

Answers

Answer:

#include<bits/stdc++.h>

using namespace std;

int main(){

  // Defining Variables

  int no_of_weeks;

  int total_cases = 0;

  //Declaring Vector of Pair of Integer and string

  std::vector<pair<int,string>> data;

  // Taking Input for the Number of Weeks

  cout<<"Enter No. of Weeks\n";

  cin >> no_of_weeks;

  // Running the Loop for no_of_weeks times

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

      int A,B,C;

      // Taking Input for different types of flus

      cout<<"Enter No. of Cases of Flu A, B, C for week" << i + 1 << " seperated by space : \n";

      cin >> A >> B >>C;

      // Adding all the cases in a week

      int cases_in_a_week = A + B + C;

      // Updating total cases

      total_cases += cases_in_a_week;

      // Declaring the level variable

      string level;

      // Updating the level of the week corresponding to each case

      if(cases_in_a_week < 500) level = "Low";

      else if(cases_in_a_week >= 500 && cases_in_a_week < 2000) level = "Moderate";

      else level = "Widespread";

      // Storing the Week's information by using a vector of pairs

      // in which pair's first is the number of cases which is of type int

      // while the second is the level of the flu which is of the type string

      data.push_back(make_pair(cases_in_a_week,level));

  }

  // Linking the stdoutput to the flu_report.txt file

  // this also creates the file with the same name if it doesn't exists

  freopen("flu_report.txt", "w", stdout);

  // Printing the respective output data with Bar Chart of stars for each level

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

      //printing the week no. and number of cases

      cout<<i+1<<" "<<data[i].first<<" "<<data[i].second<<" |";

      //calculating the number of stars

      int stars = data[i].first/250;

      //printing the stars of the bar chart

      for(int j = 0; j < stars ; j++) cout<<"*";

      cout<<endl;

  }

  //printing the total number of cases

  cout<<total_cases;

}

Explanation:

Answer:

C code explained below

Explanation:

I have provided the proper commented code below.

I hope that you find the answer helpful.

CODE:

-------------------------------------------------------------------------------------------------------------

#include<bits/stdc++.h>

using namespace std;

int main(){

  // Defining Variables

  int no_of_weeks;

  int total_cases = 0;

  //Declaring Vector of Pair of Integer and string

  std::vector<pair<int,string>> data;

  // Taking Input for the Number of Weeks

  cout<<"Enter No. of Weeks\n";

  cin >> no_of_weeks;

  // Running the Loop for no_of_weeks times

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

      int A,B,C;

      // Taking Input for different types of flus

      cout<<"Enter No. of Cases of Flu A, B, C for week" << i + 1 << " seperated by space : \n";

      cin >> A >> B >>C;

      // Adding all the cases in a week

      int cases_in_a_week = A + B + C;

      // Updating total cases

      total_cases += cases_in_a_week;

      // Declaring the level variable

      string level;

      // Updating the level of the week corresponding to each case

      if(cases_in_a_week < 500) level = "Low";

      else if(cases_in_a_week >= 500 && cases_in_a_week < 2000) level = "Moderate";

      else level = "Widespread";

      // Storing the Week's information by using a vector of pairs

      // in which pair's first is the number of cases which is of type int

      // while the second is the level of the flu which is of the type string

      data.push_back(make_pair(cases_in_a_week,level));

  }

  // Linking the stdoutput to the flu_report.txt file

  // this also creates the file with the same name if it doesn't exists

  freopen("flu_report.txt", "w", stdout);

  // Printing the respective output data with Bar Chart of stars for each level

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

      //printing the week no. and number of cases

      cout<<i+1<<" "<<data[i].first<<" "<<data[i].second<<" |";

      //calculating the number of stars

      int stars = data[i].first/250;

      //printing the stars of the bar chart

      for(int j = 0; j < stars ; j++) cout<<"*";

      cout<<endl;

  }

  //printing the total number of cases

  cout<<total_cases;

}

The ______ network became functional in 1969, linking scientific and academic researchers across the United States. Group of answer choices ARPANET NETAMERICA INTRANET AMERINET

Answers

Answer:

The ARPANET network became functional in 1969, linking scientific and academic researchers across the United States.

Explanation:

ARPA Net is the network that has become functional in 1969 in united States. The basic purpose of this network is to link all the researchers and scientists across united states. The full form of ARPANet is Advanced Research Project Agency Network.

The importance of this network is increase because small chunks of data that are called packets has been proposed for data transmission in the network. The data is divided into small packets and send it over the network, at destination point these packets are combined together and become orignal information.

Consider a point to point link 50 km in length. At what speed would propagation delay (at a speed 2 x 108 meters/second) equal transmit delay for 100 byte packets.

Answers

Answer:

The bandwidth is 3200 Kbps

Explanation:

Given:

The length of the point to point link = 50 km = 50×10³ = 50000 m

Speed of transmission = 2 × 10⁸ m/s

Therefore the propagation delay is the ratio of the length of the link to speed of transmission

Therefore,  [tex]t_{prop} = \frac{distance}{speed}[/tex]

[tex]t_{prop} = \frac{50000}{2*10^{8} }=2.5*10^{-4}[/tex]

Therefore the propagation delay in 25 ms

100 byte = (100 × 8) bits

Transmission delay = [tex]\frac{(100*8)bits }{(x)bits/sec}[/tex]

If propagation delay is equal to transmission delay;

[tex]\frac{(100*8)bits }{(x)bits/sec}= \frac{50000}{2*10^{8} }[/tex]

[tex]x=\frac{100*8*2*10^{8} }{50000}[/tex]

[tex]x=\frac{100*8}{2.5*10 ^-4}=3200000[/tex]

x = 3200 Kbps

Answer:

The complete question is here:

Consider a point-to-point link 2 km in length. At what bandwidth would propagation delay (at a speed of 2 x 108 m/s) equal transmission delay for

(a) 100-byte packets?

(b) 512-byte packets?

Explanation:

Given:

Length of the link = 50 km

Propagation delay = distance/speed = d/s

To find:

At what speed would propagation delay (at a speed 2 x 10^8 meters/second) equal transmit delay for 100 byte packets?

Solution:

Propagation Delay = t prop

                                 = 50 * 10^3 / 2 * 10^8

                                 = 50000 / 200000000

                                 = 0.00025

                                 = 25 ms

(a) When propagation delay is equal to transmission delay for 100 packets:

Transmission Delay = packet length / data rate = L / R

So when,

Transmission Delay = Propagation Delay

100 * 8  / bits/sec = 50 * 10^3  / 2 * 10^8

Let y denotes the data rate in bit / sec

speed = bandwidth = y bits/sec

         100 * 8  / y bits/sec = 50 * 10^3  / 2 * 10^8

                        y bit/sec   =  100 * 8  / 25 * 10^ -5

                                         = 800 / 0.00025

                                     y  = 3200000 bit/sec

                                      y = 3200 Kbps

(b) 512-byte packets

512 * 8  / y bits/sec = 50 * 10^3  / 2 * 10^8

                        y bit/sec   =  512 * 8  / 25 * 10^ -5

                                         = 4096 / 0.00025

                                     y  = 16384000 bit/sec

                                      y = 16384 Kbps

Define the body of the function read_data(filename). If filename is None, return the sentence (already defined for your), otherwise return the contents of the file (whose name is in the parameter filename). If there is any error during the opening or reading of the file, print out a warning and return sentence. If you haven't completed the lesson on Python local I/O, do so now.

Answers

Answer:

Answer explained

Explanation:

The main difference between parse_text_into_words( v1 and v2) is I have used splitlines also in v1 so the escape sequence '\n' will not be present in the list of words. while in v2 only split function is used so it will have '\n' present in words list.

Code:

def read_file(fileName = None):

  try:

      File = open(fileName,"r") # opening file in read mode

      for row in File:          # for each line in File

          print(row,end="")

  except IOError:      # handling exception of file opening

      print("Could not read file:",fileName)

def parse_text_into_words_v1(text):

  list_words = []

  list_lines = text.splitlines()

  for i in list_lines:

      list_words.extend(i.split(' '))

  return list_words

def parse_text_into_words_v2(text):

  list_words = []

  list_words.extend(text.split(' '))

  return list_words

def determine_difference(a_list,b_list):

  print("first list:",a_list)

  print("second list:",b_list)

  a_set = set(a_list)

  b_set = set(b_list)

  diff = a_set - b_set

  diff = list(diff)

  print("\nDifference between 2 sets: ",diff)

if __name__ == '__main__':

  print("Reading file using function read_file() to read \"data.txt\" :")

  read_file("data.txt")

  print("\n\n")

  t = '''vhfhyh ghgggj ghchvjhvj'''

  print("\nDemonstrating implementation of parse_text_into_words_v1:")

  l = parse_text_into_words_v1(t) # calling function with text parameter

  print("list of words:")

  print(l)

  print("\nDemonstrating implementation of parse_text_into_words_v2:")

  b = parse_text_into_words_v2(t) # calling function with text parameter

  print("list of words:")

  print(b)

  print("\nDemonstrating difference between two lists")

  a_list = [1,2,3,4,5,6,7,8,9,10]

  b_list = [2,4,6,8,10]

  determine_difference(a_list,b_list) # passing two list to take difference

Write a program that generates a random integer number in the range of 1 through 100 inclusively, and then asks the user to guess what the number is (User should be informed at the beginning that the number is between 1 to 100). If the user’s guess (input) is higher than the random number, the program should display "Too high, try again." If the user’s guess is lower than the random number, the program should display "Too low, try again." If the user guesses the number, the program should congratulate the user with a message as well as to display the number of guesses to get the right number. Next asking the user if he/she wants to play one more time. If yes, then generate a new random number so the game can start over

Answers

Answer:

Here is the Python program:

import random  #to generate random numbers

low = 1  #lowest range of a guess

high = 100  #highest range of a guess

attempts=0   # no of attempts

def guess_number(low, high, attempts):  #function for guessing a number

   print("Guess a number between 1 and 100")      

#prompts user to enter an integer between 1 to 100 as a guess

   number = random.randint(low, high)  

#return randoms digits from low to high

   for _ in range(attempts):  #loop to make guesses

       guess = input("Enter a number: ")   #prompts user to enter a guess

       num = int(guess)  #reads the input guess

       if num == number:  # if num is equal to the guess number

           print('Congratulations! You guessed the right number!')    

           command= input("Do you want to play another game? ")

#asks user if he wants to play another game

           if command=='Y':  #if user enters Y  

               guess_number(low,high,attempts)  #starts game again

           elif command=='N':  #if user types N

               exit() #exits the program

       elif num < number:   #if user entered a no less than random no

           print('Too low, Try Higher')  # program prompts user to enter higher no

       elif num > number: #if user entered a no greater than random no

           print('Too high, Try Lower') # program prompts user to enter lower no

       else:  #if user enters anything else

           print("You must enter a valid integer.")  

#if user guessed wrong number till the given attempts

   print("You failed to guess the number correctly in {attempts} attempts.".format(attempts=attempts))  

   exit() # program exits

Explanation:

The program has a function guess_number which takes three parameters, high and low are the range set for the user to enter the number in this range and attempts is the number of tries given to the user to guess the number.

random.randint() generates integers in a given range, here the range is specified i.e from 1 to 100. So it generates random number from this range.

For loop keeps asking the user to make attempts in guessing a number and the number of tries the user is given is specified in the attempts variable.

If the number entered by the user is equal to the random number then this message is displayed: Congratulations! You guessed the right number! Then the user is asked if he wants to play one more time and if he types Y the game starts again but if he types N then the exit() function exits the game.

If the number entered as guess is higher than the random number then this message is displayed Too high, Try Lower and if the number entered as guess is lower than the random number then this message is displayed Too low, Try Higher.

If the user fails to guess the number in given attempts then the following message is displayed and program ends. You failed to guess the number correctly in {attempts} attempts.

You can call this function in main by passing value to this function to see the output on the screen.

guess_number(1, 100, 5)

The output is shown in screenshot attached.

Write a for loop to print all elements in courseGrades, following each element with a space (including the last). Print forwards, then backwards. End each loop with a newline. Ex: If courseGrades = {7, 9, 11, 10}, print:

7 9 11 10
10 11 9 7

Hint: Use two for loops. Second loop starts with i = NUM_VALS - 1.


Note: These activities may test code with different test values. This activity will perform two tests, the first with a 4-element array (int courseGrades[4]), the second with a 2-element array (int courseGrades[2]). See How to Use zyBooks.

Also note: If the submitted code tries to access an invalid array element, such as courseGrades[9] for a 4-element array, the test may generate strange results. Or the test may crash and report "Program end never reached", in which case the system doesn't print the test case that caused the reported message.

code:

import java.util.Scanner;

public class CourseGradePrinter {
public static void main (String [] args) {
final int NUM_VALS = 4;
int[] courseGrades = new int[NUM_VALS];
int i = 0;

courseGrades[0] = 7;
courseGrades[1] = 9;
courseGrades[2] = 11;
courseGrades[3] = 10;


return;
}
}

Answers

Answer:

Java code explained below

Explanation:

CourseGradePrinter.java

import java.util.Scanner;

public class CourseGradePrinter {

public static void main (String [] args) {

final int NUM_VALS = 4;

int[] courseGrades = new int[NUM_VALS];

int i = 0;

courseGrades[0] = 7;

courseGrades[1] = 9;

courseGrades[2] = 11;

courseGrades[3] = 10;

for(i=0; i<NUM_VALS; i++){

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

}

System.out.println();

for(i=NUM_VALS-1; i>=0; i--){

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

}

return;

}

}

Output:

7 9 11 10

10 11 9 7

Create a C# GUI Windows Form application named JobDemo that declares and uses Job objects. The Job class holds job information for a home repair service. The class has five properties that include a job number, customer name, job description, estimated hours, and price for the job. Create a constructor that requires parameters for all the data except price. Include auto-implemented properties for the job number, customer name, and job description, but not for hours or price; the price field value is calculated as estimated hours times $45.00 whenever the hours value is set.

Also create the following for the class:

An Equals() method that determines two Jobs are equal if they have the same job number A ToString() method that returns a string containing all job information

The JobDemo Windows Form declares a few Job objects, sets their values, and demonstrates that all the methods work as expected.

Using the Job class you created in (a), write a new application named JobDemo2 that creates an array of five Job objects. Prompt the user for values for each Job. Do not allow duplicate job numbers; force the user to reenter the job when a duplicate job number is entered. When five valid objects have been entered (use List), display them all, plus a total of all prices.

Create a RushJob class that derives from Job. A RushJob has a $150.00 premium that is added to the normal price of the job. Override any methods in the parent class as necessary. Create a new Windows Form named JobDemo3 that creates an a List of five RushJobs. Prompt the user for values for each, and do not allow duplicates

Create a RushJob class that derives from Job. A RushJob has a $150.00 premium that is added to the normal price of the job. Override any methods in the parent class as necessary. Write a new Windows Form named JobDemo3 that creates a List of five RushJobs. Prompt the user for values for each, and do not allow duplicate job numbers. When five valid RushJob objects have been entered, display them all, plus a total of all prices. Make any necessary modifications to the RushJob class so that it can be sorted by job number.

Answers

Here's the implementation for the requested tasks:

### Job Class

```csharp

using System;

public class Job

{

   private static int nextJobNumber = 1;

   public int JobNumber { get; }

   public string CustomerName { get; set; }

   public string JobDescription { get; set; }

   public double EstimatedHours { get; set; }

   public double Price => EstimatedHours * 45.00;

   public Job(string customerName, string jobDescription, double estimatedHours)

   {

       JobNumber = nextJobNumber++;

       CustomerName = customerName;

       JobDescription = jobDescription;

       EstimatedHours = estimatedHours;

   }

   public override bool Equals(object obj)

   {

       if (obj == null || GetType() != obj.GetType())

       {

           return false;

       }

       Job otherJob = (Job)obj;

       return JobNumber == otherJob.JobNumber;

   }

   public override int GetHashCode()

   {

       return JobNumber.GetHashCode();

   }

   public override string ToString()

   {

       return $"Job Number: {JobNumber}, Customer Name: {CustomerName}, Job Description: {JobDescription}, Estimated Hours: {EstimatedHours}, Price: {Price:C}";

   }

}

```

### JobDemo Form

```csharp

using System;

using System.Collections.Generic;

using System.Windows.Forms;

namespace JobDemo

{

   public partial class JobDemoForm : Form

   {

       private List<Job> jobs = new List<Job>();

       public JobDemoForm()

       {

           InitializeComponent();

       }

       private void addButton_Click(object sender, EventArgs e)

       {

           string customerName = customerNameTextBox.Text;

           string jobDescription = jobDescriptionTextBox.Text;

           double estimatedHours;

           if (double.TryParse(estimatedHoursTextBox.Text, out estimatedHours))

           {

               Job job = new Job(customerName, jobDescription, estimatedHours);

               if (!jobs.Contains(job))

               {

                   jobs.Add(job);

                   outputListBox.Items.Add(job.ToString());

                   totalLabel.Text = $"Total: {CalculateTotal():C}";

               }

               else

               {

                   MessageBox.Show("Duplicate job number. Please enter a unique job number.");

               }

           }

           else

           {

               MessageBox.Show("Invalid estimated hours. Please enter a valid number.");

           }

       }

       private double CalculateTotal()

       {

           double total = 0;

           foreach (var job in jobs)

           {

               total += job.Price;

           }

           return total;

       }

   }

}

```

### RushJob Class

```csharp

public class RushJob : Job, IComparable<RushJob>

{

   private const double RushJobPremium = 150.00;

   public RushJob(string customerName, string jobDescription, double estimatedHours)

       : base(customerName, jobDescription, estimatedHours)

   {

   }

   public override double Price => base.Price + RushJobPremium;

   public int CompareTo(RushJob other)

   {

       return JobNumber.CompareTo(other.JobNumber);

   }

}

```

### JobDemo3 Form

```csharp

using System;

using System.Collections.Generic;

using System.Linq;

using System.Windows.Forms;

namespace JobDemo

{

   public partial class JobDemo3Form : Form

   {

       private List<RushJob> rushJobs = new List<RushJob>();

       public JobDemo3Form()

       {

           InitializeComponent();

       }

       private void addButton_Click(object sender, EventArgs e)

       {

           string customerName = customerNameTextBox.Text;

           string jobDescription = jobDescriptionTextBox.Text;

           double estimatedHours;

           if (double.TryParse(estimatedHoursTextBox.Text, out estimatedHours))

           {

               RushJob rushJob = new RushJob(customerName, jobDescription, estimatedHours);

               if (!rushJobs.Any(rj => rj.JobNumber == rushJob.JobNumber))

               {

                   rushJobs.Add(rushJob);

                   outputListBox.Items.Add(rushJob.ToString());

                   totalLabel.Text = $"Total: {CalculateTotal():C}";

               }

               else

               {

                   MessageBox.Show("Duplicate job number. Please enter a unique job number.");

               }

           }

           else

           {

               MessageBox.Show("Invalid estimated hours. Please enter a valid number.");

           }

       }

       private double CalculateTotal()

       {

           double total = 0;

           foreach (var rushJob in rushJobs)

           {

               total += rushJob.Price;

           }

           return total;

       }

   }

}

This code should fulfill the requirements you've specified. Let me know if you need further assistance!

Write a program that declares constants to represent the number of inches, feet, and yards in a mile. Name the constants INCHES_IN_MILE, FEET_IN_MILE, and YARDS_IN_MILE respectively. Also declare a variable named miles to represent a number of miles. Compute and display, with explanatory text, the value in inches, feet, and yards—for example: 4.0 miles is 253440.0 inches, or 21120.0 feet, or 7040.0 yards

Answers

Answer:

The cpp program for conversion is given below.

#include <iostream>

using namespace std;

 

int main() {

 

// declaring and initializing constant variables with standard values

   const  double INCHES_IN_MILE=63360;

   const  double FEET_IN_MILE=5280;

   const  double YARDS_IN_MILE=1760;

   

   // declaring and initializing miles with a random value

   double miles=4.0;

   

// declaring and computing inches in miles

double inch = INCHES_IN_MILE*miles;

 

// declaring and computing feet in miles

double feet = FEET_IN_MILE*miles;

 

// declaring and computing yards in miles

double yard = YARDS_IN_MILE*miles;

 

// displaying all the calculated values

std::cout<<miles<<" miles is "<<inch<<" inches"<<std::endl;

std::cout<<miles<<" miles is "<<feet<<" feet"<<std::endl;

       std::cout<<miles<<" miles is "<<yard<<" yards"<<std::endl;

   

       return 0;      

}

OUTPUT

4 miles is 253440 inches

4 miles is 21120 feet

4 miles is 7040 yards

Explanation:

The steps in the program are as described.

1. All the three constant variables, mentioned in the question, are declared as double and initialized. These variables hold the fixed conversion values for inches, feet and yards in one mile.

2. The variables are declared constant using the keyword, const.

3. The variable to hold value for mile, miles, is declared as double and initialized with a random value.

4. Next, three more variables are declared as double. These variables will hold the calculated values for inches, feet and yards in the given value of mile.

5. The values are calculated for inches, feet and yards for the given value of variable, miles and stored in the variables mentioned in step 3.

6. These values are displayed to the console along with explanations.

7. The program ends with the return statement.

8. The value of variable, miles, is hard coded in the program and not taken from the user.

9. There is no interaction with the user in this program as this is not mentioned in the question.

10. The program works for all numeric value of the variable, miles, since double accepts integers also.

11. The program can be tested by changing the value of variable, miles.

Consider the following code: // Linked Lists: TRAVERSE

struct ListNode { int data; struct ListNode *next; };

Assume that a linked list has been created and head points to a sentinel node. A sentinel node is an empty data node in the beginning of the list. It sometimes holds a sentinel value. The use of sentinel nodes is a popular trick to simplify the insert and delete operations.

You may also assume that the list is not empty. Each node in the list contains an integer representing a digit in a number. The data in the sentinel node is -1.

For instance, n = 234 will be stored as {-1, 4, 3, 2} in the linked list.

Write a function based on the list traversal named computeNumFromList that is passed the pointer to the first node in the list, it prints the digits in the list one per line, and it returns a long integer, the number calculated from its digits in the list (234 see the above example). You may assume that long int will hold the converted number (no need to check for numeric overflow).

Answers

Answer:

See attached file for detailed code.

Explanation:

See attached file.

Write a setInterval() function that increases the count by 1 and displays the new count in counterElement every 100 milliseconds. Call clearInterval() to cancel the interval when the count displays 4.

Answers

Answer:

var count = 0;

var counterElement = document.getElementById("counter");

counterElement.innerHTML = count;

var interval = setInterval(function () {

   count++;

   counterElement.innerHTML = count;

   if (count === 4) {

       clearTimeout(interval);

   }

}, 100);

Explanation:

Write two functions called permutation() and combination(), where permutation() computes and returns n!/(n-r)!whereas combination() returns. n!/(n-r)!r!A third function called par_input() gets the input values for n and r. An example of correct program behavior follows: Input: 3 2 Output: The permutation is 6, and the combination is 3.

Answers

Answer:

Here is the program in C.

#include<stdio.h>   // header file used to input output operations

int permutation(int n, int r);  // function to computer permutation

int combination(int n, int r);  //function to compute combination

int factorial(int number);  // function to computer factorial

void par_input(int n, int r);    // function take take input value of n and r

int main()  //start of main() function body

{    

   int n,r;  // declare n and r variables

   par_input(n,r);  //calls par_input() function to get values of n and r

}

 

int permutation(int n, int r)   // method to calculate permutation

{

   return factorial(n) / factorial(n-r);  //formula for permutation

}

 

int combination(int n, int r)  // method to calculate combination

{

   return permutation(n, r) / factorial(r); //formula for combination

}

 

int factorial(int number)  // to find factorial of a number

{

   int fact = 1;      

   while(number > 0)  //loop continues until value of number gets <=0

   {

       fact = fact *number;  

       number--;

   }      

   return fact;

}

void par_input(int n, int r)  //function to take input values

{

   printf("Enter n: ");  //prompts user to enter the value of n

   scanf("%d", &n);      //reads the value of n from user

   printf("Enter r: "); ////prompts user to enter the value of r

   scanf("%d", &r); //reads the value of r from user

  //calls the combination and permutation methods to display results

   printf("The permutation is = %d\n", permutation(n, r));    

   printf("The Combination is = %d", combination(n, r));      

}

Explanation:

The main() function calls par_input() function. This function asks user to enter values of n and r and then calls permutation() and combination() methods to compute the combination and permutation using these input values. Lets say user enters n=3 and r=2The permutation() function computes and returns permutation using the following formula: n! / (n-r)! factorial(n) / factorial(n-r); This function calls factorial method which calculates the factorial of n and n-r.This function then returns the permutation.3! / (3-2)! = 3*2*1 / 1! = 6Next the combination() function computes and returns combination using the following formula: n! / r! * (n - r)!permutation(n, r) / factorial(r)This function calls permutation() and factorial() methods which calculate the combination of n and n-rThis function then returns the combination.3! / 2! * (3-2)! = 3*2*1 / 2*1 * 1 = 6 / 2 = 3 Factorial function computes and returns the factorial of n, r and n-r.Lets take n! When n=3 So this function computes factorial as follows:while loops checks if number>0 It is true as number is 3It multiplies 3 by fact. fact is initialized to 1 So1*3 = 3Then it decreases number=3 by 1 so number=2Now while loops checks if number>0 It is true as number is 2It multiplies 2 by fact. Value of fact is now 3 So3*2 = 6Then it decreases number=2 by 1 so number=1Now while loops checks if number>0 It is true as number is 1It multiplies 1 by fact. Value of fact is now 6 So6*1 = 6Then it decreases number=1 by 1 so number=0Now while loops checks if number>0 It is false as number is 0So the loop breaks and the value of fact is returned.As fact= 6 So factorial of n is 6.

The output of the program is attached in the screen shot.

Search online for a Request for Proposal relating to IT. Critically evaluate the proposal. If you were a vendor receiving this proposal, do you have enough information to reply with a quote. What is good? What is missing? What would you change?

Answers

Answer and Explanation:

The company of that same Pasadena area thereafter named as "Center" allows RFP to apply regarding contracts for Contractor, but should not be restricted to providing the information infrastructure facilities to complement the Centre's in-house development solutions at either the optimum level of benefits.The contractor or provider shall offer the best facilities on just the basis of the services listed in the preceding documentation by sending two formal submissions no earlier than noon 14 December 2016 to certain stakeholders are encouraged to react towards this RFP.Sure I would also have bought that if I were a dealer since it is worth the investment.

So, it's the right answer.

Craig likes to work on his computer at his local coffee shop, but people around him may be able to see what he is doing, including entering passwords for his accounts. This method of gaining confidential information is referred to as ________.

(A) phishing
(B) shoulder surfing
(C) man-in-the-middle attacks
(D) spear phishing

Answers

Answer:

B

Explanation:

Craig could of left the coffee shop but instead he could just shoulder surfing so no one could see all the other options are just plain Wrong shoulder surfing can do no harm

Write a SELECT statement that returns two columns based on the Vendors table. The first column, Contact, is the vendor contact name in this format: first name followed by last initial (for example, "John S.") The second column, Phone, is the VendorPhone column without the area code. Only return rows for those vendors in the 559 area code. Sort the result set by first name, then last name.

Answers

The answer & explanation for this question is given in the attachment below.

The SQL query selects vendor contacts' first names followed by last initials and phone numbers without area codes from the Vendors table. It filters vendors with the 559 area code and sorts results alphabetically by first name and last name.

Below is the SQL SELECT statement that fulfills your requirements:

```sql

SELECT

   CONCAT(SUBSTRING_INDEX(ContactName, ' ', 1), ' ', LEFT(SUBSTRING_INDEX(ContactName, ' ', -1), 1), '.') AS Contact,

   SUBSTRING(VendorPhone, 5) AS Phone

FROM

   Vendors

WHERE

   VendorPhone LIKE '559%'

ORDER BY

   SUBSTRING_INDEX(ContactName, ' ', 1),

   SUBSTRING_INDEX(ContactName, ' ', -1);

```

This query selects the ContactName column from the Vendors table, concatenates the first name and the first letter of the last name, followed by a period, to create the Contact column.

It then extracts the phone number without the area code from the VendorPhone column and stores it in the Phone column.

Finally, it filters the results to include only vendors with the 559 area code and sorts the result set by first name and last name.

You are designing a write buffer between a write-through L1 cache and a write-back L2 cache. The L2 cache write data bus is 16 B wide and can perform a write to an independent cache address every 4 processor cycles.
a. How many bytes wide should each write buffer entry be?
b. What speedup could be expected in the steady state by using a merging write buffer instead of a non-merging buffer when zeroing memory by the execution of 64-bit stores if all other instructions could be issued in parallel with the stores and the blocks are present in the L2 cache?
c. What would be the effect of possible L1 misses on the number of required write buffer entries for systems with blocking and non-blocking caches?

Answers

Answer:

Clock 2.5GHz

L1 I cache 32KB, 8way, 64B line size, 4 cycle access latency

L1 Dcache write-back, write-allocate; MSHR with 0 (lockup

cache), 1, 2, and 64 (unconstrained non-blocking

cache) entries, write-back buffer with 16 entries

L2 cache 256KB, 8way, 64B line size, 10 cycle access latency

L3 cache 2MB per core, 64B line size, 36 cycle access latency

Memory DDR3-1600, 90 cycle access latency

Issue width 4

Instruction window size 36

ROB Size 128

Load Buffer Size 48

Store Buffer Size 32

b)

parallelism took this a step further by providing more parallelism and hence more

latency-hiding opportunities. It is likely that the use of instruction- and threadlevel

parallelism will be the primary tool to combat whatever memory delays are

encountered in modern multilevel cache systems.

that of the lockup cache setup (hit-under-0-miss). For the integer programs: the average performance

(measured as CPI) improvement is 7.08% for hit-under-1-miss, 8.36% for hit-under-2-misses, and 9.02%

for hit-under-64-misses (essentially the unconstraint non-blocking cache), compared to lockup cache. For

the floating point programs, the three numbers are 12.69%, 16.22%, and 17.76%, respectively

c)

Non-blocking caches are an effective technique for tolerating cache-miss latency. They can reduce

miss-induced processor stalls by buffering the misses and continuing to serve other independent access

requests. Previous research on the complexity and performance of non-blocking caches supporting

non-blocking loads showed they could achieve significant performance gains in comparison to blocking

caches. However, those experiments were performed with benchmarks that are now over a decade old.

Furthermore the processor that was simulated was a single-issue processor with unlimited run-ahead

capability, a perfect branch predictor, fixed 16-cycle memory latency, single-cycle latency for floating

point operations, and write-through and write-no-allocate caches. These assumptions are very different

from today's high performance out-of-order processors such as the Intel Nehalem. Thus, it is time to

re-evaluate the performance impact of non-blocking caches on practical out-of-order processors using

up-to-date benchmarks. In this study, we evaluate the impacts of non-blocking data caches using the latest

SPECCPU2006 benchmark suite on practical high performance out-of-order (OOO) processors.

Simulations show that a data cache that supports hit-under-2-misses can provide a 17.76% performance

gain for a typical high performance OOO processor running the SPECCPU 2006 benchmarks in

comparison to a similar machine with a blocking cache.

Explanation:

Design the logic and write the Java code that will use assignment statements to: Calculate the profit (profit) as the retail price minus the wholesale price Calculate the sale price (salePrice) as 25 percent deducted from the retail price Calculate the sale profit (saleProfit) as the sale price minus the wholesale price.

Answers

Answer:

Logic:

profit = retailPrice - wholeSalePrice

salePrice = retailPrice - (0.25 * retailPrice)

saleProfit = salePrice - wholeSalePrice

Java code:

double retailPrice, wholeSalePrice;

double profit = retailPrice - wholeSalePrice;

double salePrice = retailPrice - (0.25 * retailPrice);

double saleProfit = salePrice - wholeSalePrice;

Explanation:

The logic just represented the words in equation format. That is, profit is retailPrice minus wholesaleprice.

SalePrice is 25% deducted from retail price.

SaleProfit is saleprice minus wholesaleprice.

The whole logic is then represented in Java assignment statement using type double.

The factorial of an integer N is the product of the integers between 1 and N, inclusive. Write a while loop that computes the factorial of a given integer N.

Answers

the function and loop will be

def factorial(x):

   total = 1

   if x != 1 and x != 0:

       for i in range(x,1,-1):

           total *= i

   return total

The program is an illustration of loops

Loops are program statements that are used to perform repeated operations

The program in python, where comments are used to explain each line is as follows:

#This gets input for N

N = int(input())

#This initializes factorial to 1

factorial = 1

#This opens the while loop

while N >1:

   #This calculates the factorial

   factorial*=N

   N-=1

#This prints the factorial

print(factorial)

Read more about loops at:

https://brainly.com/question/14284157

Write a function called name_facts that will take a firstname (string) as an input parameter, and print out various facts about the name, including:
1) its length, 2) whether it starts with the letter A, and 3) whether it contains a Z or X.
To gain full credit for this exercise, you must use string formatting to print out the result. Hints: You will probably want to convert the string to lowercase when checking conditions 2 and 3. You can get by without it, but you'll have to make sure you check both lower and uppercase versions of the letters. You will have to use the in operator for condition 3. You will also probably want to make a separate message for conditions 2 and 3 (depending on the answer) and use string formatting to join them into the final message.

Answers

Answer:

def name_facts(firstname):

   print("Your name is",len(firstname),"letters long",end=", ")

   if(firstname[0] == 'A'):

       print("does start with the letter A",end=", ")

   else:

       print("does not start with the letter A", end=", ")

   if(firstname.count('Z')>0 or firstname.count('X')>0):

       print("and does not contain a Z or X")

   else:

       print("and does not contain a Z or X")

#Testing

name_facts("Allegra")

name_facts("Xander")

Explanation:

Answer:

// Comments are used for explanatory purpose

// Program starts here

#include<iostream>

using namespace std;

int main()

{

// Declare firstname

string firstname;

//Prompt to enter firstname

cout<<"What's your first name: ";

// Accept input

cin>>firstname;

// A. Get string's length

int length = firstname.length();

// Print length

cout<<"Length = "<<length<<endl;

// Copy string to chat array

char char_array[length + 1];

// copying the contents of the string to char array

strcpy(char_array, firstname.c_str());

// B. Check if it starts with letter A

if(char_array[0] == 'A')

{

cout<<"Your Firstname begins with letter A"<<endl;

}

else

{

cout<<"Your Firstname doesn't begin with letter A"<<endl;

}

// Check if it contains X or Z

int k = 0;

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

if(char_array[i] == 'Z' || char_array[i] == 'X')

{

k++;

}

if(k == 0)

{cout<<"Your Firstname doesn't contain Z or X";}

else

{cout<<"Your Firstname contains Z or X";}

}

return 0;

}

Which of the following statement is true?

a. the MAC address cannot be spoofed
b. the IP address can be spoofed, so if you want to read response from the deceived party, you can use
c. IP spoofing to hide yourself IP spoofing can be used for denial of service attack
d. IP spoofing can be prevented or detected by switches

Answers

Answer:

b. the IP address can be spoofed, so if you want to read response from the deceived party, you can use IP spoofing to hide yourself.

Explanation:

Choose two prime numbers p and q (these are your inputs). Suppose that you need to send a message to your friend, and you implement the RSA algorithm for secure key generation. You need public and private keys (these are your outputs). You are free to choose other parameters or inputs if you need any. Write a program for the RSA algorithm using any programing language you know (such as C++) to generate your public and private key.

Answers

Answer:

#include <iostream>

#include<math.h>

using namespace std;

int findGcd(int x, int y) {

int t;

while(1) {

t= x%y;

if(t==0)

return y;

x = y;

y= t;

}

}

int main() {

int v1,v2,p,q,flag = 0;

cout<<"Please enter 1st prime number: ";

cin>>p;

v1 = p/2;

cout<<"Please enter 2nd prime number: ";

cin>>q;

v2 = q/2;

for(int i = 2; i <= v1; i++)

{

if(p%i == 0)

{

cout<<"The number is not prime";

flag = 1;

return 0 ;

}

}

for(int i = 2; i <= v1; i++)

{

if(q%i == 0)

{

cout<<"You entered a number which is not prime";

flag = 1;

return 0;

}

}

double n=p*q;

double tr;

double phi= (p-1)*(q-1);

double e=7;

if( flag == 0)

{

while(e<phi) {

tr = findGcd(e,phi);

if(tr==1)

break;

else

e++;

}

cout<<"public key: "<<e<<endl;

double d1=1/e;

double d=fmod(d1,phi);

cout<<"private key: "<<d<<endl;

double message;

cout<<"please enter a message: ";

cin>>message;

double cipher = pow(message,e);

double m = pow(cipher,d);

cipher = fmod(cipher,n);

m = fmod(m,n);

cout<<"Encrypted message: "<<cipher;

}

}

Explanation:

Find n = p*q and calculate phi = (p-1) * (q-1). Select a number e such that 1 < e < phi(n) and findGcd(e, phi(n)) = 1. Find d which is private key  as d = e−1 (mod phi(n)).As m is original message so encrypt using, cipher = m*e mod n.

What term is defined as a private data placed in a packet with a header containing routing information that allows the data to travel across a network, such as the Internet?

Answers

Answer:

Data encapsulation

Explanation:

When we send data to someone else across another network, this data travels down a stack of layers of the TCP/IP model. Each layer of the TCP/IP layer encapsulates data or hides the data by adding headers and sometimes trailers. This packaging is what is known as data encapsulation. The data starts at the application layer and trickles down beneath. As it moves down the layers, it is encoded or compressed to a standard format and sometimes encrypted for security purposes.

Once sales are​ forecasted, ________ must be generated to estimate required raw materials. A. a pro forma statement B. a production plan C. a cash budget

Answers

Answer:

Option B i.e., a production plan.

Explanation:

While sales are estimated, the manufacturing schedule for estimating the necessary raw materials should be produced.

So when the revenue is already estimated then at that time the manufacturing schedule should be produced approximately that raw material which is needed, so the following option is correct according to the scenario.

Option a is incorrect because it is not related to the following scenario.Option B is incorrect because in the above statement, it is not mentioned or related to the budget plan.

Using the following code, answer the following questions

1. #pragma omp parallel
2.{
3. id-omp-get thread num();
4. numThreads- omp_get num threads0
5, printf("Hello from thread %d of %din", id, numThreads);
6.}

a. What is the output of the above program in PI 3 B+? .
b. What does the statement at line 1 mean?
c. How to compile the following code (executable should not be /a out)?
d. What does the statement at line 4 (after the equal sign) mean?

Answers

Answer:

Answer explained

Explanation:

as PI 3 B+ is quadcore processor(i.e. 4 cores)

omp_get_thread_num() is used for getting thread number.(i.e. 0,1,2,3)

omp_get_num_threads() is used for getting number of threads.(i.e. 4)

1. Output should be,

Hello from thread 0 of 4

Hello from thread 1 of 4

Hello from thread 2 of 4

Hello from thread 3 of 4

2. #pragma omp parallel is used to fork(create child) additional threads to carry out the work enclosed in the construct in parallel.

3. We can Compile this code using,

  gcc -o omp_helloc -fopenmp hello.c

4. We can Run this code using,

   ./hello

5.omp_get_num_threads() is used for getting number of threads.(i.e. 4)

Write a test program that creates two Rectangle objects—one with width 4 and height 40 and the other with width 3.5 and height 35.7. Display the width, height, area, and perimeter of each rectangle in this order.

Answers

Answer:

public class Rectangle {

   private double width;

   private double heigth;

   public Rectangle(double width, double heigth) {

       this.width = width;

       this.heigth = heigth;

   }

   public double getWidth() {

       return width;

   }

   public void setWidth(double width) {

       this.width = width;

   }

   public double getHeigth() {

       return heigth;

   }

   public void setHeigth(double heigth) {

       this.heigth = heigth;

   }

   public double perimeter(double width, double heigth){

       double peri = 2*(width+heigth);

       return peri;

   }

   public double area(double width, double heigth){

       double area = width*heigth;

       return  area;

   }

}

class RectangleTest{

   public static void main(String[] args) {

       //Creating two Rectangle objects

       Rectangle rectangle1 = new Rectangle(4,40);

       Rectangle rectangle2 = new Rectangle(3.5, 35.7);

       //Calling methods on the first Rectangel objects

       System.out.println("The Height of Rectangle 1 is: "+rectangle1.getHeigth());

       System.out.println("The Width of Rectangle 1 is: "+rectangle1.getWidth());

       System.out.println("The Perimeter of Rectangle 1 is: "+rectangle1.perimeter(4,40));

       System.out.println("The Area of Rectangle 1 is: "+rectangle1.area(4,40));

       // Second Rectangle object

       System.out.println("The Height of Rectangle 2 is: "+rectangle2.getHeigth());

       System.out.println("The Width of Rectangle 2 is: "+rectangle2.getWidth());

       System.out.println("The Perimeter of Rectangle 2 is: "+rectangle2.perimeter(4,40));

       System.out.println("The Area of Rectangle 2 is: "+rectangle2.area(4,40));

   }

}

Explanation:

Firstly A Rectangle class is created with two fields for width and heigth, a constructor and getters and setters the class also has methods for finding area and perimetersThen a RectangleTest class containing a main method is created and two Rectangle objects are created (Follow teh comments in the code)Methods to get height, width, area and perimeter are called on each rectangle object to print the appropriate value

Write a Python program to: ask the user to enter the price of an item. Note: use a while loop to check the validity of the price and, if the user enters a price less than or equal to zero, to prompt for a valid price. Prompt the user for the quantity being purchased. If the quantity is ten or greater, apply a discount of 5 percent. (.95*price*quantity).

Answers

Answer:

Hi there Tonyhh! Please find the implementation below.

Explanation:

You can save the below code in a file called "price_discount.py". The code is implemented in python 2.0+. To make it work in Python 3.0+, simply update the code to use "input" rather than "raw_input".

price_discount.py

def calculate_discount(price, quantity):

 total = 0.95 * price * quantity;

 return total;

price = raw_input("Enter a price: ");

try:

 price = int(price);

 while price <= 0:

   print("Input a valid number: ")

   price = raw_input("Enter a price: ");

 quantity = raw_input("Enter a quantity: ");

 try:

   quantity = int(quantity);

   if quantity >= 10:

     print(calculate_discount(price, quantity));

 except ValueError:

   print("Invalid quantity!")

except ValueError:

 print("Invalid input!");

 price = -1;

Other Questions
Read this paragraph from The Dark Game.It may seem surprising that no Confederate sympathizers took action against Van Lew, given her strong and public views on secession and slavery. Surely there were suspicions, especially among her upper-crust neighbors, but the matter never went beyond those suspicions. Historians have suggested that the secessionists were victims of their own cultural bias, believing that no aristocratic person, and certainly not a lady, would ever consider taking part in anything as impolite as spying. A true lady managed her servants, prepared parties and gatherings, and blindly supported her husband. Such attitudes worked in Van Lew's favor, diverting suspicion from her.What central idea is implied in this paragraph?1. Elizabeth Van Lew did not follow the rules society set forth for ladies of her time and social class.2. Elizabeth Van Lew was a successful spy because society did not expect a lady to serve in that role.3. Elizabeth Van Lew was able to disguise her spying activities because she kept her views about the war to herself.4. Elizabeth Van Lew created for herself an untrue but believable cover story: she was a wealthy lady living in a fancy neighborhood. Mr. Daniels is building a clubhouse for his children. He has decided that the floor will be square with an area of 64 square feet. Write this number using a power greater than 1 and a lesser base. Imagine that Reva has joined Enviropro, her neighborhood environmental-cleanup group. Enviropros objective is to maintain a clean neighborhood and provide better garbage collection facilities. Reva encourages her friend Marcel to join the group as well. Marcel refuses as he does not want to pay to join this group. He argues that he already gets collective benefits even without having paid an enrollment fee to join the group. In this scenario, Marcel's argument best exemplifies _______. Can you help me please? Lesson CheckPractice Vocabulary1. What key role did capitalists play in theIndustrial Revolution? The distribution of SAT scores of all college-bound seniors taking the SAT in 2014 was approximately normal with a mean of 149714971497 and standard deviation of 322322322. Let XXX represent the score of a randomly selected tester from this group. Find P(X>1800)P(X>1800)P, (, X, is greater than, 1800, ). When 6.0 mol H2O reacts with 5.0 mol Al in the reaction below, 4.0 mol of Al are used up in the reaction. How many moles of Al are left over unreacted? Reaction: 2Al + 3H2O Al2O3 + 3H2 The fluid mosaic model of the membrane proposed that membranes ____________ Yash is an artist. He does not like when people talk about the separate parts of his pictures because he believes that looking at the complete picture is most important. Yashs opinion is similar to the ________ approach. Group of answer choices The process of inflammation _____. a. is an ongoing response to long-term infectionb. produces chemotaxisc. is a fast process that destroys infected or damaged tissued. produces prostaglandinse. is never helpful to healing Suppose that the economy is at long-run equilibrium. If there is a sharp decline in the stock market combined with a significant increase in immigration of skilled workers, then in the short runa. real GDP will rise and the price level might rise, fall, or stay the same.b. real GDP will fall and the price level might rise, fall, or stay the same.c. the price level will rise, and real GDP might rise, fall, or stay the same.d. the price level will fall, and real GDP might rise, fall, or stay the same. Emersons view of nature 1.04 Graded Assignment: Reflections 1. El profesor tiene tiza.2. T tienes mochilas. 3. Los turistas tienen mapa.4. Usted tiene cuadernos. 5. Nosotros tenemos papelera. Using the social-conflict approach, what could be a problem withsuburbanization?OA. The roads in the cities lead to areas in the suburbs.OB. The schools in the cities are better equipped than those in thesuburbs.OC. Mass transportation can become confusing when there are toomany routes in and out of cities.OD. There is less money available to provide services for peopleremaining in cities. QUESTION 1 (0.5 POINTS) In a large restaurant an average of 3 out of every 5 customers ask for water with their meal. A random sample of 10 customers is selected. What is the probability that less than 3 customers ask for water with their meal? a). 0.012 b). 0.055 c). 0.042 d). 0.011 0.125 to the nearest thousandth state the aufbau principle. Systematic or Random Error? -This type of error affects overall accuracy but does not necessarily affect precision. This type of error affects precision but does not necessarily affect overall accuracy. This type of error occurs if you use a buret that was calibrated incorrectly when it was made. You can minimize this type of error by taking repeated measurements. Which biome has leaves that change colors and fall off as winter approaches?