Questions
Please use java language in an easy way and comment as much as you can! Thanks...

Please use java language in an easy way and comment as much as you can! Thanks

  1. (Write a code question) Write a generic method called "findMin" that takes an array of Comparable objects as a parameter. (Use proper syntax, so that no type checking warnings are generated by the compiler.) The method should search the array and return the index of the smallest value.

  2. (Analysis of Algorithms question) Determine the growth function and time complexity (in Big-Oh notation) of the findMin method from the previous problem. Please show your work by annotating the code.

In: Computer Science

ENCODE THE FOLLOWING STREAM OF BITS USING 4B/5B encoding :- 1101011011101111 what is the ratio of...

ENCODE THE FOLLOWING STREAM OF BITS USING 4B/5B encoding :-

1101011011101111

what is the ratio of redundant bits in 4B/5B?

In: Computer Science

1. Write a python program to create a list of integers using random function. Use map...

1. Write a python program to create a list of integers using random function. Use map function to process the list on the expression: 3x2+4x+5 and store the mapped elements in another list. Now use filter to do sum of all the elements in another list.

2. Write a function that takes n as input and creates a list of n lists such that ith list contains first 10 multiples of i.

3. Write a function that takes a number as input parameter and returns the corresponding text in word. For example, on input 458, the function should return ‘Four Five Eight’. Use dictionary for mapping digits to their string representation.

4. Write a program to create two sets of integer type using random function. Perform following operations on these two sets:

a) Union

b) Intersection

c) Difference

d) Symmetric difference

In: Computer Science

can someome investigate my program that utilizes semaphores that can result in deadlock due to programming...

can someome investigate my program that utilizes semaphores that can result in deadlock due to programming errors and help in finding out if the solution meet all criteria for the critical section
  • If yes, then comment code identifying the parts of code that do
  • If no, could you help in fixing the code wherever given solution fails criteria in the code below

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>

#define N 5
#define THINKING 2
#define HUNGRY 1
#define EATING 0
#define LEFT (phnum + 4) % N
#define RIGHT (phnum + 1) % N

int state[N];
int phil[N] = { 0, 1, 2, 3, 4 };

sem_t mutex;
sem_t S[N];

void test(int phnum)
{
if (state[phnum] == HUNGRY
&& state[LEFT] != EATING
&& state[RIGHT] != EATING) {
// state that eating
state[phnum] = EATING;

sleep(2);

printf("Philosopher %d takes fork %d and %d\n",
phnum + 1, LEFT + 1, phnum + 1);

printf("Philosopher %d is Eating\n", phnum + 1);

// sem_post(&S[phnum]) has no effect
// during takefork
// used to wake up hungry philosophers
// during putfork
sem_post(&S[phnum]);
}
}

// take up chopsticks
void take_fork(int phnum)
{

sem_wait(&mutex);

// state that hungry
state[phnum] = HUNGRY;

printf("Philosopher %d is Hungry\n", phnum + 1);

// eat if neighbours are not eating
test(phnum);

sem_post(&mutex);

// if unable to eat wait to be signalled
sem_wait(&S[phnum]);

sleep(1);
}

// put down chopsticks
void put_fork(int phnum)
{

sem_wait(&mutex);

// state that thinking
state[phnum] = THINKING;

printf("Philosopher %d putting fork %d and %d down\n",
phnum + 1, LEFT + 1, phnum + 1);
printf("Philosopher %d is thinking\n", phnum + 1);

test(LEFT);
test(RIGHT);

sem_post(&mutex);
}

void* philospher(void* num)
{

while (1) {

int* i = num;

sleep(1);

take_fork(*i);

sleep(0);

put_fork(*i);
}
}

int main()
{

int i;
pthread_t thread_id[N];

// initialize the semaphores
sem_init(&mutex, 0, 1);

for (i = 0; i < N; i++)

sem_init(&S[i], 0, 0);

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

// create philosopher processes
pthread_create(&thread_id[i], NULL,
philospher, &phil[i]);

printf("Philosopher %d is thinking\n", i + 1);
}

for (i = 0; i < N; i++)

pthread_join(thread_id[i], NULL);
}

In: Computer Science

There are at least five (probably more) places in the attached C# program code that could...

There are at least five (probably more) places in the attached C# program code that could be optimized. Find at least five things in the Program.cs file that can be changed to make the program as efficient as possible.

  1. List five problems you found with the code (Put your list either in comments within the code or in a separate Word or text document), and then optimize the code in the attached code below to make it as efficient as possible. The program output must not be affected by your changes. To the user it should still do everything it did before your changes provided the user enters valid data.

using System;

namespace COMS_340_L4A
{
class Program
{
static void Main(string[] args)
{
Console.Write("How many doughnuts do you need for the first convention? ");
int.TryParse(Console.ReadLine(), out int total1);

Console.Write("How many doughnuts do you need for the second convention? ");
int.TryParse(Console.ReadLine(), out int total2);

int totalDonuts = Calculator.CalculateSum(new int[] { total1, total2 });

Console.WriteLine($"{ totalDonuts } doughnuts is { Calculator.ConvertToDozen(totalDonuts)} dozen.");
Console.WriteLine("Press Enter to quit...");
Console.ReadLine();
}
}

static class Calculator
{
static int DOZEN = 12;

public static int CalculateSum(int[] args)
{
int return_value = 0;
foreach (int i in args)
{
return_value += i;
}
return return_value;
}

public static int ConvertToDozen(int total)
{
int dozen = DOZEN;
return total / dozen;
}
}
}

In: Computer Science

1.) Simplify the following expression to a minimum number of literals. This problem must be solved...

1.) Simplify the following expression to a minimum number of literals. 
This problem must be solved through Algebraic Manipulation.
All work must be shown on the submitted work. 
Things to remember. 
 If you can't see anything to work with from the beginning, expand.
 Formula Sheet has been provided. 

a.) Simplify (you MUST submit your work to get credit for this problem)
F(a, b, c) = bc + a’b + ab’ + ac’

2.) Express the given function in terms of its minterms and Maxterms. You may use a truth table or algebraic manipulation to determine your solution. F(a, b, c) = abc’ + a’c’ + ab’ + b’c

a.)F(a, b, c) =   ∑m( #, #, ... , #)

b.) Write out the full expression for the Product of Maxterms. DO NOT use the Pi notation, ∏M (#, #, ... #).

(i.e. (...) (...) .... (...) )

In: Computer Science

Which of the following two statements are correct? The prediction performance of a model increases monotonically...

Which of the following two statements are correct?

The prediction performance of a model increases monotonically with the number of features used in the model

Clustering in a high dimensional space is challenging because there tends to be limited variation in pairwise distance of data points

The amount of data needed to produce reliable results grows exponentially with the number of dimensions

Suppose we collect a dataset with a billion users and each user has 10 features, we may run into the issue of curse of dimensionality

In: Computer Science

I keep getting minor errors I can't figure out and I don't know how to convert...

I keep getting minor errors I can't figure out and I don't know how to convert decimal .10 to percentage 10% either.  
With these functions defined now expand the program for a company who gives discounts on items bought in bulk.
Create a main function and inside of it ask the user how many different items they are buying.
For each item have the user input a price and quantity, validating them with the functions that you wrote.
Use your discount function to find the discount for each item's quantity and calculate the discounted price.
Print the discounted price in $9,999.99 format

Sum the discounted totals for all items and display this grand total at the end.
Print the percentages in 99.9% format.

In addition to summing the discounted totals, also sum the un-discounted totals.
At the end display both of these values and then calculate and print the overall percentage saved in 99.9% format.

def discount ():
discount = 0.00
if quantity >= 0 and quantity <= 19 :
discount = 0.00
if quantity >= 20 and quantity >= 49 :
discount = 0.05
if quantity >= 50 and quantity <= 99 :
discount = 0.08
if quantity >= 100 :
discount = 0.10
return discount
# user input quantity
def quantity ():
quantity = 0
quantity = int (input ('What is the quantity? '))
while quantity < 1 or quantity > 2000 :
print ('Error, Please enter a quantity between 1 and 2000.')
quantity = int (input ('What is the quantity? '))
return quantity
# user input price
def price ():
price = 0.0
price = float (input ('What is the price? '))
while price < 0.0 :
print ('Error, the price must be greater than $0.00')
price = float (input ('What is the price? '))
return price
# main
def main ():
for i in range (items)   
items = int (input ('How many different items are you purchasing? '))
quantity ()
discount ()
price ()
Total_price = sum (price)
Total_discount = sum (discount)
Discounted_price = price - (price * discount)
Total_Discounted_price = Total_price - (Total_price * Total_discount)
print ('For item ',i +1,,' ' Discounted_price, ' with a ', discount, format (.2f, sep=''))
print ('Total order is ', Total_Discounted_price, ' with a ', Total_discount, format (.2f, sep=''))
#initiate
main ()

In: Computer Science

Part Two: Download VendingChange.java (above). Run it and become familiar with the output. Essentially, you need...

Part Two: Download VendingChange.java (above). Run it and become familiar with the output. Essentially, you need to create a user friendly GUI app using the code parameters of VendingChange. Turn VendingChange.java into a GUI app.

1) Your program must display the input dialog.
2) You must check that the data entered by the user follows the required input. If not, your program must display an error dialog and exit.

3) If the input is valid, then your program must display a message dialog similar to the one shown in listing 2.12, but the message must pertain to VendingChange and not ChangeMaker. Your message dialog must show the number of pennies, nickels, dimes and quarters.
4) Your program must exit when the user closes the output message dialog.
5) Comment and document your program.

Complete the programming problems such that they produce output that looks similar to that shown in the text or upcoming class presentations (in-class and Announcements). Tips and formulas (if any) will be discussed in class. Additional details will be provided in class and Announcements.

add comments to code please.

import java.util.Scanner;

public class VendingChange
{
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter price of item");
        System.out.println
                ("(from 25 cents to a dollar, in 5-cent increments)");
        int originalAmount = keyboard.nextInt();
        int change = 100 - originalAmount;

        int quarters = change/25;
        change = change%25;// remaining change after deducting quarters
        int dimes = change/10;
        change = change%10;// remaining change after deducting dimes, too
        int nickels = change/5;
        change = change%5;
        int pennies = change;

        //The grammar will be incorrect if any of the values are 1
        //because the required program statements to handle that
        //situation have not been covered, yet.   
        System.out.println
                ("You bought an item for " + originalAmount
                + " and gave me a dollar,");
        System.out.println("so your change is");
        System.out.println(quarters + " quarters,");
        System.out.println(dimes + " dimes, and");
        System.out.println(nickels + " nickel.");
    }
}

In: Computer Science

*Note: someone else answered the question but queried for the average. I need the median NOT...

*Note: someone else answered the question but queried for the average. I need the median NOT the average. Thanks.

Hi, please help me create the following SQL query:

Create Table A with 1 column and 10 rows. The rows are filled with numbers : 1,2,3,4,5,6,7,8,9,10.

Create Table B with 1 column and 9 rows. The rows are filled with numbers: 1,2,3,4,5,6,7,8,9.

Write a single query that returns the median value of the 10 rows of TableA.

The same query should also work for Table B and return the median value of the 9 rows in Table B.

Expected Answers:

Median for Table A: 5.5

Median for Table B: 5

It would be really helpful if you could include screenshots. Thanks!

In: Computer Science

Using Python The script is to open a given file. The user is to be asked...

Using Python

  • The script is to open a given file. The user is to be asked what the name of the file is. The script will then open the file for processing and when done, close that file.
  • The script will produce an output file based on the name of the input file. The output file will have the same name as the input file except that it will begin with "Analysis-". This file will be opened and closed by the script.
  • The script is to process the file and calculate the following information and output the information to the file in the order presented here.
  • The script it to count the number of lines, the number of words, and the number of characters in the file and put this information out into the output file with appropriate labels for the reader to know what the numbers are. This information is to be echoed on the screen to the user.
    • You may find it easier to determine the number of words if you remove the punctuation, digits, and other non letter characters other than spaces before trying to count the words. Those items are not considered to be part of a word. Keep that in mind when referencing words in following instructions.
    • Count spaces, digits, punctuation and other non letter characters as characters though
  • The script is produce a list of all unique words in the file and the of times each word appears in the file. This list with frequency counts is to be put in the output file in alphabetical order and one word/frequency pair to a line. The format should be word (frequency count). Be sure there is a space between the word and the beginning parentheses. You will count words that appear only once. Due to the possible length of this list, you are not to echo this list to the screen, only place it in the output file.
  • The script is to produce a list of 2 word pairs found in the file that appear more than once. If a 2 word pair appears only once, it is not to be put into the output file. The format of the line in the output file should be the two word pair followed by the frequency count in parentheses as seen in the previous item involving unique words. This list is put out after the single word list. There is to be a heading to the list to let the user know that the information is changing and a blank line put in before the heading. This information is to be echoed on the screen to the user.
  • The last bit of information the script it to place into the output file is the total number of words, the average length of a word, the number of unique words, the average number of letters in the unique words, and the number of word pairs that have frequencies of 2 or more.   Properly label each item of information output in this section as well as placing a blank line before the section and giving the section a heading. This information is to be echoed on the screen to the user.
    • It is fully conceivable that the average number of letters in a word (length of a word) for the over all document is different than the average number of letters in a word for the unique word list. This is because a word such as "the" might appear multiple times in the file. In the first calculation, each instance of the is counted. In the second calculation, the word "the" is only counted 1 time on the list.
  • The script is to use solid programming practices like comments, self documenting variable names (also known as meaningful variable names) and easy to read and neat code.
  • You are to place a comment block at the very top of the script containing your name, the semester, the due date of the exam, and the instructor's name each on separate lines.

The logic is built to examine the process incoming data for specific items of information. This may need to be done in specific order with multiple processing steps.

You are to run your script of this test data file. Screen shot your interactions with the user for your submission document. Then place your analysis file, your python code file, and your submission document into a single zip file.

Some advice would be since you have the test data file, you can do these calculations by hand and check them against your analysis file to see if your program is working correctly.

In: Computer Science

C++ Make this class generic so that the sides of the shape may be integer or...

C++

Make this class generic so that the sides of the shape may be integer or float.

---------------shape.h------------

class Shape
{
public:
Shape();
virtual int getSide();
virtual bool setSide(int x);
virtual int getArea();
virtual int getPerimeter();
void display();
~Shape();


protected:

private:
int side;

// T_sides[numSides];

};

----------------shape.cpp----------

#include "Shape.h"
#include <iostream>

using namespace std;

Shape::Shape()
{
}

void Shape::display()
{
cout<<"side: "<<getSide()<<endl;
cout<<" area: "<<getArea()<<endl;
cout<<"perimeter: "<<getPerimeter()<<endl;
}

bool Shape::setSide(int x)
{
if(x>0){
side = x;
return true;
}else
return false;
}


int Shape::getSide()
{
return side;
}

int Shape::getArea()
{
return side*side;

}

int Shape::getPerimeter()
{
return side*4;

}


Shape::~Shape()
{
//dtor
}

int main()
{
int num;
Shape s1;

cout<<"Enter side of shape: ";
cin>>num;

if (!s1.setSide(num))
{
cout<<"Please enter a valid side."<<endl;
}

s1.display();
return 0;
}

In: Computer Science

Modify programming problem 4 from Assignment 2. You will create a number of threads—for example, 100—and...

Modify programming problem 4 from Assignment 2. You will create a number of threads—for example, 100—and each thread will request a pid, sleep for a random period of time, and then release the pid. (Sleeping for a random period of time approximates the typical pid usage in which a pid is assigned to a new process, the process executes and then terminates, and the pid is released on the process's termination.) On UNIX and Linux systems, sleeping is accomplished through the sleep() COMP2004 Assignment 3 & Assignment 4 Fall 2020 function, which is passed an integer value representing the number of seconds to sleep.

HERE IS MY CODE:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MIN_PID 300
#define MAX_PID 5000

typedef struct node {
int pid;
struct node* next;
}Node;

int allocate_map(void);
int allocate_pid(void);
void release_pid(int pid);
int i;
Node *head;
/*
main function tests all three functions
*/
int main(){
allocate_map();
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
release_pid(301);
printf("allocated pid: %d\n",allocate_pid());
allocate_map();
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
printf("allocated pid: %d\n",allocate_pid());
release_pid(305);
release_pid(30);

}

int allocate_map(void){
if(i>0){
return -1;
}
head = malloc(sizeof(Node));
Node *curr = head;
for(i=0;i<MAX_PID-MIN_PID;i++){
curr->pid = 0;
curr->next = (i<(MAX_PID-MIN_PID)) ? malloc(sizeof(Node)):NULL;
curr = curr->next;
}

return 1;
}
int allocate_pid(void){
if(head->next == NULL){
return -1;
}

int i = MIN_PID +1 ;

Node *iter = head;
if(head->pid == 0){
head->pid = MIN_PID;
return head->pid;
}
while(iter ->next->pid !=0 && i<MAX_PID){
iter = iter->next;
i++;
}
if(i<MAX_PID ){

iter->next->pid = i;
return iter->next->pid;
}
else{return -1;}
}

void release_pid(int pid){
if(head->next == NULL && head->pid==0){
printf("Nothing to release\n");
return;
}
else if(pid<MIN_PID || pid>MAX_PID){
printf("invalid release\n");
return;
}
if(head->pid==pid){
head->pid=0;
}
Node *iter = head;
while(iter->next !=NULL){
if(iter->next->pid==pid){
iter->next->pid=0;
return;
}
iter = iter->next;
}
printf("Nothing to release\n");
}

In: Computer Science

Program Behavior This program will analyze real estate sales data stored in an input file. Each...

Program Behavior

This program will analyze real estate sales data stored in an input file. Each run of the program should analyze one file of data. The name of the input file should be read from the user.

Here is a sample run of the program as seen in the console window. User input is shown in blue:

Let's analyze those sales!

Enter the name of the file to process? sales.txt

Number of sales: 6

Total: 2176970

Average: 362828

Largest sale: Joseph Miller 610300

Smallest sale: Franklin Smith 199200

Now go sell some more houses!

Your program should conform to the prompts and behavior displayed above. Include blank lines in the output as shown.

Each line of the data file analyzed will contain the buyer's last name, the buyer's first name, and the sale price, in that order and separated by spaces. You can assume that the data file requested will exist and be in the proper format.

The data file analyzed in that example contains this data:

Cochran Daniel 274000
Smith Franklin 199200
Espinoza Miguel 252000
Miller Joseph 610300
Green Cynthia 482370
Nguyen Eric 359100

You can download that sample data file here https://drive.google.com/file/d/1bkW8HAvPtU5lmFAbLAJQfOLS5bFEBwf6/view?usp=sharing to test your program, but your program should process any data file with a similar structure. The input file may be of any length and have any filename. You should test your program with at least one other data file that you make.

Note that the average is printed as an integer, truncating any fractional part.

Your program should include the following functions:

read_data - This function should accept a string parameter representing the input file name to process and return a list containing the data from the file. Each element in the list should itself be a list representing one sale. Each element should contain the first name, last name, and purchase price in that order (note that the first and last names are switched compared to the input file). For the example given above, the list returned by the read_data function would be:

[['Daniel', 'Cochran', 274000], ['Franklin', 'Smith', 199200], ['Miguel', 'Espinoza', 252000], ['Joseph', 'Miller', 610300], ['Cynthia', 'Green', 482370], ['Eric', 'Nguyen', 359100]]

Use a with statement and for statement to process the input file as described in the textbook.

compute_sum - This function should accept the list of sales (produced by the read_data function) as a parameter, and return a sum of all sales represented in the list.

compute_avg - This function should accept the list of sales as a parameter and return the average of all sales represented in the list. Call the compute_sum function to help with this process.

get_largest_sale - This function should accept the list of sales as a parameter and return the entry in the list with the largest sale price. For the example above, the return value would be ['Joseph', 'Miller', 610300].

get_smallest_sale - Like get_largest_sale, but returns the entry with the smallest sale price. For the example above, the return value would be ['Franklin', 'Smith', 199200].

Do NOT attempt to use the built-in functions sum, min, or max in your program. Given the structure of the data, they are not helpful in this situation.

main - This function represents the main program, which reads the file name to process from the user and, with the assistance of the other functions, produces all output. For this project, do not print output in any function other than main.

Other than the definitions of the functions described above, the only code in the module should be the following, at the end of the file:

if __name__ == '__main__':
main()

That if statement keeps your program from being run when it is initially imported into the Web-CAT test environment. But your program will run as normal in Thonny. Note that there are two underscore characters before and after name and main.

Include an appropriate docstring comment below each function header describing the function.

Do NOT use techniques or code libraries that have not been covered in this course.

Include additional hashtag comments to your program as needed to explain specific processing.

A Word about List Access

A list that contains lists as elements operates the same way that any other lists do. Just remember that each element is itself a list. Here's a list containing three elements. Each element is a list containing integers as elements:

my_list = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

So my_list[0] is the list [1, 2, 3, 4] and my_list[2] is [9, 10, 11, 12].

Since my_list[2] is a list, you could use an index to get to a particular value. For instance, my_list[2][1] is the integer value 10 (the second value in the third list in my_list).

In this project, the sales list is a list of lists. When needed, you can access a particular value (first name, last name, or sales price) from a particular element in the sales list.

In: Computer Science

Course: Computer Architecture (Theme: Input-Output) A computer consists of a processor and an I/O device D...

Course: Computer Architecture (Theme: Input-Output)

  1. A computer consists of a processor and an I/O device D connected to main memory M via a shared bus with a data bus width of one word. The processor can execute a max of 2 MIPS. An average instruction requires 5 machine cycles, 3 of which use the memory bus. A memory read/write operation uses 1 m/c cycle. Suppose that the processor is continuously executing “background” programs that require 96% of the instruction rate but not any I/O instructions. Assume that one processor cycle equals one bus cycle. Now suppose the I/O device is used to transfer very large amounts of data between M and D.
    1. If programmed I/O is used and each one word transfer requires the processor to execute 3 instructions, estimate the max I/O data transfer rate in words/sec possible through D?
    2. Estimate the same rate if DMA is used?

In: Computer Science