Lab12
.pdf
keyboard_arrow_up
School
Texas Tech University *
*We aren’t endorsed by this school
Course
1330
Subject
Computer Science
Date
Dec 6, 2023
Type
Pages
1
Uploaded by juanchozulu31
Laboratory 12: Numpy for Bread!
Juans-MacBook-Pro.local
juanandreszuluqga
/Users/juanandreszuluqga/anaconda3/bin/python
3.11.4 (main, Jul
5 2023, 09:00:44) [Clang 14.0.6 ]
sys.version_info(major=3, minor=11, micro=4, releaselevel='final', serial=0)
Full name: Juan Zuluaga
R#: 11830028
Title of the notebook: Lab 12
Date: 10/04/23
Numpy
Numpy is the core library for scientific computing in Python. It provides a high-performance multidimensional array object, and tools for working with these arrays. The library’s name is short for “Numeric
Python” or “Numerical Python”. If you are curious about NumPy, this cheat sheet is recommended:
https://s3.amazonaws.com/assets.datacamp.com/blog_assets/Numpy_Python_Cheat_Sheet.pdf
Arrays
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving
the size of the array along each dimension. In other words, an array contains information about the raw data, how to locate an element and how to interpret an element.To make a numpy array, you can just use
the np.array() function. All you need to do is pass a list to it. Don’t forget that, in order to work with the np.array() function, you need to make sure that the numpy library is present in your environment. If you
want to read more about the differences between a Python list and NumPy array, this link is recommended:
https://webcourses.ucf.edu/courses/1249560/pages/python-lists-vs-numpy-arrays-what-is-the-
difference
Example- 1D Arrays
Let's create a 1D array from the 2000s (2000-2009):
[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009]
array([2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009])
Example- n-Dimensional Arrays
Let's create a 5x2 array from the 2000s (2000-2009):
[[2000, 2001], [2002, 2003], [2004, 2005], [2006, 2007], [2008, 2009]]
array([[2000, 2001],
[2002, 2003],
[2004, 2005],
[2006, 2007],
[2008, 2009]])
Arrays Arithmetic
Once you have created the arrays, you can do basic Numpy operations. Numpy offers a variety of operations applicable on arrays. From basic operations such as summation, subtraction, multiplication and
division to more advanced and essential operations such as matrix multiplication and other elementwise operations. In the examples below, we will go over some of these:
Example- 1D Array Arithmetic
Define a 1D array with [0,12,24,36,48,60,72,84,96]
Multiple all elements by 2
Take all elements to the power of 2
Find the maximum value of the array and its position
Find the minimum value of the array and its position
Define another 1D array with [-12,0,12,24,36,48,60,72,84]
Find the summation and subtraction of these two arrays
Find the multiplication of these two arrays
[ 0 12 24 36 48 60 72 84 96]
[
0
24
48
72
96 120 144 168 192]
[
0
144
576 1296 2304 3600 5184 7056 9216]
[
0
144
576 1296 2304 3600 5184 7056 9216]
96
8
0
0
[-12
0
12
24
36
48
60
72
84]
[-12
12
36
60
84 108 132 156 180]
Example- n-Dimensional Array Arithmetic
Define a 2x2 array with [5,10,15,20]
Define another 2x2 array with [3,6,9,12]
Find the summation and subtraction of these two arrays
Find the minimum number in the multiplication of these two arrays
Find the position of the maximum in the multiplication of these two arrays
Find the mean of the multiplication of these two arrays
Find the mean of the first row of the multiplication of these two arrays
[[ 5 10]
[15 20]]
[[ 3
6]
[ 9 12]]
[[ 8 16]
[24 32]]
[[105 150]
[225 330]]
[[105 150]
[225 330]]
202.5
127.5
Arrays Comparison
Comparing two NumPy arrays determines whether they are equivalent by checking if every element at each corresponding index are the same.
Example- 1D Array Comparison
Define a 1D array with [1.0,2.5,3.4,7,7]
Define another 1D array with [5.0/5.0,5.0/2,6.8/2,21/3,14/2]
Compare and see if the two arrays are equal
Define another 1D array with [6,1.4,2.2,7.5,7]
Compare and see if the first array is greater than or equal to the third array
[1.
2.5 3.4 7.
7. ]
[1.
2.5 3.4 7.
7. ]
[ True
True
True
True
True]
[6.
1.4 2.2 7.5 7. ]
[False
True
True False
True]
Arrays Manipulation
numpy.copy() allows us to create a copy of an array. This is particularly useful when we need to manipulate an array while keeping an original copy in memory. The numpy.delete() function returns a new array
with sub-arrays along an axis deleted. Let's have a look at the examples.
Example- Copying and Deleting Arrays and Elements
Define a 1D array, named "x" with [1,2,3]
Define "y" so that "y=x"
Define "z" as a copy of "x"
Discuss the difference between y and z
Delete the second element of x
[1 2 3]
[1 2 3]
[1 2 3]
[1 8 3]
[1 8 3]
[1 2 3]
[1 3]
Sorting Arrays
Sorting means putting elements in an ordered sequence. Ordered sequence is any sequence that has an order corresponding to elements, like numeric or alphabetical, ascending or descending. If you use the
sort() method on a 2-D array, both arrays will be sorted.
10
30
40
20
Original array
10
30
20
40
np
.
sort(a, axis=0)
Sort the array along the first axis
10
20
40
30
np
.
sort(a)
Sort the array along the last axis
10
20
30
40
Sort the flattened array
np.sort(a, axis=None)
Example- Sorting 1D Arrays
Define a 1D array as ['FIFA 2020','Red Dead Redemption','Fallout','GTA','NBA 2018','Need For Speed'] and print it out. Then, sort the array alphabetically.
['FIFA 2020' 'Red Dead Redemption' 'Fallout' 'GTA' 'NBA 2018'
'Need For Speed']
['FIFA 2020' 'Fallout' 'GTA' 'NBA 2018' 'Need For Speed'
'Red Dead Redemption']
Example- Sorting n-Dimensional Arrays
Define a 3x3 array with 17,-6,2,86,-12,0,0,23,12 and print it out. Then, sort the array.
[[ 17
-6
2]
[ 86 -12
0]
[
0
23
12]]
Along columns :
[[
0 -12
0]
[ 17
-6
2]
[ 86
23
12]]
Along rows :
[[ -6
2
17]
[-12
0
86]
[
0
12
23]]
Sorting by default :
[[ -6
2
17]
[-12
0
86]
[
0
12
23]]
Along None Axis :
[-12
-6
0
0
2
12
17
23
86]
Partitioning (Slice) Arrays
Slicing in python means taking elements from one given index to another given index.
We can do slicing like this: [start:end].
We can also define the step, like this: [start:end:step].
If we don't pass start its considered 0
If we don't pass end its considered length of array in that dimension
If we don't pass step its considered 1
Example- Slicing 1D Arrays
Define a 1D array as [1,3,5,7,9], slice out the [3,5,7] and print it out.
[1 3 5 7 9]
[3 5 7]
Example- Slicing n-Dimensional Arrays
Define a 5x5 array with "Superman, Batman, Jim Hammond, Captain America, Green Arrow, Aquaman, Wonder Woman, Martian Manhunter, Barry Allen, Hal Jordan, Hawkman, Ray Palmer, Spider
Man, Thor, Hank Pym, Solar, Iron Man, Dr. Strange, Daredevil, Ted Kord, Captian Marvel, Black Panther, Wolverine, Booster Gold, Spawn " and print it out. Then:
Slice the first column and print it out
Slice the third row and print it out
Slice 'Wolverine' and print it out
Slice a 3x3 array with 'Wonder Woman, Ray Palmer, Iron Man, Martian Manhunter, Spider Man, Dr. Strange, Barry Allen, Thor, Daredevil'
[['Superman' 'Batman' 'Jim Hammond' 'Captain America' 'Green Arrow']
['Aquaman' 'Wonder Woman' 'Martian Manhunter' 'Barry Allen' 'Hal Jordan']
['Hawkman' 'Ray Palmer' 'Spider Man' 'Thor' 'Hank Pym']
['Solar' 'Iron Man' 'Dr. Strange' 'Daredevil' 'Ted Kord']
['Captian Marvel' 'Black Panther' 'Wolverine' 'Booster Gold' 'Spawn']]
['Superman' 'Aquaman' 'Hawkman' 'Solar' 'Captian Marvel']
['Hawkman' 'Ray Palmer' 'Spider Man' 'Thor' 'Hank Pym']
Wolverine
[['Wonder Woman' 'Martian Manhunter' 'Barry Allen']
['Ray Palmer' 'Spider Man' 'Thor']
['Iron Man' 'Dr. Strange' 'Daredevil']]
This is a Numpy Cheat Sheet- similar to the one you had on top of this notebook!
Check out this link for more:
https://blog.finxter.com/collection-10-best-numpy-cheat-sheets-every-python-coder-must-own/
Here are some of the resources used for creating this notebook:
Johnson, J. (2020). Python Numpy Tutorial (with Jupyter and Colab). Retrieved September 15, 2020, from
https://cs231n.github.io/python-numpy-tutorial/
Willems, K. (2019). (Tutorial) Python NUMPY Array TUTORIAL. Retrieved September 15, 2020, from
https://www.datacamp.com/community/tutorials/python-numpy-tutorial?utm_source=adwords_ppc
Willems, K. (2017). NumPy Cheat Sheet: Data Analysis in Python. Retrieved September 15, 2020, from
https://www.datacamp.com/community/blog/python-numpy-cheat-sheet
W3resource. (2020). NumPy: Compare two given arrays. Retrieved September 15, 2020, from
https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-28.php
Here are some great reads on this topic:
"Python NumPy Tutorial"
available at *
https://www.geeksforgeeks.org/python-numpy-tutorial/
"What Is NumPy?"
a collection of blogs, available at *
https://realpython.com/tutorials/numpy/
"Look Ma, No For-Loops: Array Programming With NumPy"
by
Brad Solomon
available at *
https://realpython.com/numpy-array-programming/
"The Ultimate Beginner’s Guide to NumPy"
by
Anne Bonner
available at *
https://towardsdatascience.com/the-ultimate-beginners-guide-to-numpy-f5a2f99aef54
Here are some great videos on these topics:
"Learn NUMPY in 5 minutes - BEST Python Library!"
by
Python Programmer
available at *
https://www.youtube.com/watch?v=xECXZ3tyONo
"Python NumPy Tutorial for Beginners"
by
freeCodeCamp.org
available at *
https://www.youtube.com/watch?v=QUT1VHiLmmI
"Complete Python NumPy Tutorial (Creating Arrays, Indexing, Math, Statistics, Reshaping)"
by
Keith Galli
available at *
https://www.youtube.com/watch?v=GB9ByFAIAH4
"Python NumPy Tutorial | NumPy Array | Python Tutorial For Beginners | Python Training | Edureka"
by
edureka!
available at *
https://www.youtube.com/watch?v=8JfDAm9y_7s
Exercise: Python List vs. Numpy Arrays?
What are some differences between Python lists and Numpy arrays?
* Make sure to cite any resources that you may use.
Cell
In[13], line 29
*Windari, Leonie M. “Difference between Python List and NumPy Array.
^
SyntaxError:
invalid character '“' (U+201C)
In [1]:
# Preamble script block to identify host, user, and kernel
import
sys
!
hostname
!
whoami
print
(
sys
.
executable
)
print
(
sys
.
version
)
print
(
sys
.
version_info
)
In [2]:
import
numpy
as
np
#First, we need to impoty "numpy"
mylist
=
[
2000
,
2001
,
2002
,
2003
,
2004
,
2005
,
2006
,
2007
,
2008
,
2009
]
#Create a list of the years
print
(
mylist
)
#Check how it looks
np
.
array
(
mylist
)
#Define it as a numpy array
Out[2]:
In [3]:
myotherlist
=
[[
2000
,
2001
],[
2002
,
2003
],[
2004
,
2005
],[
2006
,
2007
],[
2008
,
2009
]]
#Since I want a 5x2 array, I should group the years two by two
print
(
myotherlist
)
#See how it looks as a list
np
.
array
(
myotherlist
)
#See how it looks as a numpy array
Out[3]:
In [4]:
import
numpy
as
np
#import numpy
Array1
=
np
.
array
([
0
,
12
,
24
,
36
,
48
,
60
,
72
,
84
,
96
])
#Step1: Define Array1
print
(
Array1
)
print
(
Array1
*
2
)
#Step2: Multiple all elements by 2
print
(
Array1
**
2
)
#Step3: Take all elements to the power of 2
print
(
np
.
power
(
Array1
,
2
))
#Another way to do the same thing, by using a function in numpy
print
(
np
.
max
(
Array1
))
#Step4: Find the maximum value of the array
print
(
np
.
argmax
(
Array1
))
##Step4: Find the postition of the maximum value
print
(
np
.
min
(
Array1
))
#Step5: Find the minimum value of the array
print
(
np
.
argmin
(
Array1
))
##Step5: Find the postition of the minimum value
Array2
=
np
.
array
([
-
12
,
0
,
12
,
24
,
36
,
48
,
60
,
72
,
84
])
#Step6: Define Array2
print
(
Array2
)
print
(
Array1
+
Array2
)
#Step7: Find the summation of these two arrays
In [5]:
import
numpy
as
np
#import numpy
Array1
=
np
.
array
([[
5
,
10
],[
15
,
20
]])
#Step1: Define Array1
print
(
Array1
)
Array2
=
np
.
array
([[
3
,
6
],[
9
,
12
]])
#Step2: Define Array2
print
(
Array2
)
print
(
Array1
+
Array2
)
#Step3: Find the summation
MultArray
=
Array1@Array2
#Step4: To perform a typical matrix multiplication (or matrix product)
MultArray1
=
Array1
.
dot
(
Array2
)
#Step4: Another way To perform a
matrix multiplication
print
(
MultArray
)
print
(
MultArray1
)
print
(
np
.
mean
(
MultArray
))
##Step6: Find the mean of the multiplication of these two arrays
print
(
np
.
mean
(
MultArray
[
0
,:]))
##Step7: Find the mean of the first row of the multiplication of these two arrays
In [6]:
import
numpy
as
np
#import numpy
Array1
=
np
.
array
([
1.0
,
2.5
,
3.4
,
7
,
7
])
#Step1: Define Array1
print
(
Array1
)
Array2
=
np
.
array
([
5.0
/
5.0
,
5.0
/
2
,
6.8
/
2
,
21
/
3
,
14
/
2
])
#Step2: Define Array1
print
(
Array2
)
print
(
np
.
equal
(
Array1
,
Array2
))
#Step3: Compare and see if the two arrays are equal
Array3
=
np
.
array
([
6
,
1.4
,
2.2
,
7.5
,
7
])
#Step4: Define Array3
print
(
Array3
)
print
(
np
.
greater_equal
(
Array1
,
Array3
))
#Step3: Compare and see if the two arrays are equal
In [7]:
import
numpy
as
np
#import numpy
x
=
np
.
array
([
1
,
2
,
3
])
#Step1: Define x
print
(
x
)
y
=
x
#Step2: Define y as y=x
print
(
y
)
z
=
np
.
copy
(
x
)
#Step3: Define z as a copy of x
print
(
z
)
# For Step4: They look similar but check this out:
x
[
1
]
=
8
# If we change x ...
print
(
x
)
print
(
y
)
print
(
z
)
# By modifying x, y changes but z remains as a copy of the initial version of x.
x
=
np
.
delete
(
x
,
1
)
#Step5: Delete the second element of x
print
(
x
)
In [8]:
import
numpy
as
np
#import numpy
games
=
np
.
array
([
'FIFA 2020'
,
'Red Dead Redemption'
,
'Fallout'
,
'GTA'
,
'NBA 2018'
,
'Need For Speed'
])
print
(
games
)
print
(
np
.
sort
(
games
))
In [9]:
import
numpy
as
np
#import numpy
a
=
np
.
array
([[
17
,
-
6
,
2
],[
86
,
-
12
,
0
],[
0
,
23
,
12
]])
print
(
a
)
print
(
"Along columns : \n"
,
np
.
sort
(
a
,
axis
=
0
) )
#This will be sorting in each column
print
(
"Along rows : \n"
,
np
.
sort
(
a
,
axis
=
1
) )
#This will be sorting in each row
print
(
"Sorting by default : \n"
,
np
.
sort
(
a
) )
#Same as above
print
(
"Along None Axis : \n"
,
np
.
sort
(
a
,
axis
=
None
) )
#This will be sorted like a 1D array
In [10]:
import
numpy
as
np
#import numpy
a
=
np
.
array
([
1
,
3
,
5
,
7
,
9
])
#Define the array
print
(
a
)
aslice
=
a
[
1
:
4
]
#slice the [3,5,7]
print
(
aslice
)
#print it out
In [11]:
import
numpy
as
np
#import numpy
Superheroes
=
np
.
array
([[
'Superman'
,
'Batman'
,
'Jim Hammond'
,
'Captain America'
,
'Green Arrow'
],
[
'Aquaman'
,
'Wonder Woman'
,
'Martian Manhunter'
,
'Barry Allen'
,
'Hal Jordan'
],
[
'Hawkman'
,
'Ray Palmer'
,
'Spider Man'
,
'Thor'
,
'Hank Pym'
],
[
'Solar'
,
'Iron Man'
,
'Dr. Strange'
,
'Daredevil'
,
'Ted Kord'
],
[
'Captian Marvel'
,
'Black Panther'
,
'Wolverine'
,
'Booster Gold'
,
'Spawn'
]])
print
(
Superheroes
)
#Step1
print
(
Superheroes
[:,
0
])
print
(
Superheroes
[
2
,:])
print
(
Superheroes
[
4
,
2
])
print
(
Superheroes
[
1
:
4
,
1
:
4
])
In [13]:
Type of Data Consistency
:
Lists can group various data types
(
including text
and
numbers
)
together
.
NumPy arrays are more tailored
for
numbers because they demand that every element be of the same type
.
Performance
:
For mathematical
and
numerical tasks
,
NumPy arrays are faster
.
For these tasks
,
lists are slower
.
Memory Performance
:
For large datasets
in
particular
,
NumPy arrays use memory more effectively
.
In terms of memory usage
,
lists can sometimes be less effective
.
Simple math
:
Math operations on entire arrays are simple
with
NumPy
.
Explicit loops are required
for
similar operations on lists
.
Changes
in
size
and
shape
:
For changing the size
or
shape of data
,
NumPy arrays are preferable
.
There are no built
-in
methods
for
these changes
in
lists
.
integration
:
Other scholarly libraries can easily be integrated
with
NumPy
.
Lists are simpler
and
more stand
-
alone
.
So choose NumPy
if
you need to work quickly
and
effectively
with
a lot of numbers
.
Python lists may be superior
if
you want more flexibility
and
mixed data types
.
Citations
*
Windari
,
Leonie M
.
“
Difference between Python List
and
NumPy Array
.
”
Plainenglish
.
io
/
Blog
/
Python
-
List
-
Vs
-
Numpy
-
Array
-
Whats
-
The
-
Difference
-
7308
cd4b52f6
,
11
July
2021
,
plainenglish
.
io
/
blog
/
python
-
list
-
vs
-
numpy
-
array
-
whats
-
the
-
difference
-
7308
cd4b52f6
.
Accessed
5
Oct
.
2023.
Discover more documents: Sign up today!
Unlock a world of knowledge! Explore tailored content for a richer learning experience. Here's what you'll get:
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
The code is in C++
arrow_forward
What is the result of the following operation in Python: 17/2 ?
Given the following code in Python:
>>> mydna = 'acgt'
>>> mydna = mydna + mydna
What will be the result of typing the following at the Python interpreter prompt: >>> myDna?
3. The following commands are entered at the prompt of Python interpreter.
>>> dna="atgctggggact"
>>> dna[:3]
>>> dna
What will be the output of the last command?
arrow_forward
Please write in C++ and run in linux.
This assignment is about fork(), exec(), and wait() system calls, and commandline arguments.
Write two C++ programs, to be named parent.cc and child.cc and compiled into executable parent and child, respectively that, when run, will work as follows:
parent
takes in a list of gender-name pairs from the commandline arguments
creates as many child processes as there are in the gender-name pairs and passes to each child process a child number and a gender-name pair
waits for all child processes to terminate
outputs “All child processes terminated. Parent exits.” And terminates.
child
receives a child number and one gender-name pair arguments from parent
outputs “Child # x, a boy (or girl), name xxxxxx.”
Note: content of output depends on data received from parent
Sample run
To invoke the execution:
>parent girl Nancy boy Mark boy Joseph
parent process does the following:
outputs “I have 3 children.” -- Note: the number 3…
arrow_forward
TASK: Build a simple shell.DESCRIPTION:Write a shell program in C similar to "csh" that takes commands from thekeyboard. In particular, your shell prompt must be the current time(instead of, say, % as is common in UNIX).Make it simple; that is, do not allow it to handle background processes,it can ignore the control-C key, and especially, do not design it tointerpret shell scripts.You will need the following system calls:forkwaitpidone of execv, execve, execvp (read the manual pages).You must NOT use the C library function "system".
arrow_forward
Code (C++) that will print the message
arrow_forward
Create a new C++ project in Visual Studio (or an IDE of your choice). Add the files listed below to your project:
BinaryTree.h Download BinaryTree.h
BinarySearchTree.h Download BinarySearchTree.h
main.cpp Download main.cpp
Build and run your project. The program should compile without any errors. Note that function main() creates a new BST of int and inserts the nodes 12, 38, 25, 5, 15, 8, 55 (in that order) and displays them using pre-order traversal. Verify that the insertions are done correctly. You may verify it manually or use the visualization tool at https://www.cs.usfca.edu/~galles/visualization/BST.html. (Links to an external site.)
Do the following:
1. add code to test the deleteNode and search member functions. Save screenshot of your test program run.
2. add code to implement the nodeCount member function of class BinaryTree. Test it and save screenshot of your test program run.
3. add code to implement the leafCount member function of class BinaryTree. Test it and…
arrow_forward
Need Help with C++ coding, and please explain
the first step in detail.
Write a program in C++ that performs three
functions using threads on the attached text file
called long_text.txt
1. Write your code in a such way that you can
show in terms of time that using threads does
not keep you blocked i.e., the main thread gets
free once all threads start.
a.This means that your program will run the
three functions without threading and then with
threading.
2. Functions to implement are:
a. word_count() → will count the number of
words in the text file
b. sentence_count() → will count the number of
sentences in the text file
c. find_frequent_word() → finds the most
frequently occurring word and number of times
it occurred in the text
arrow_forward
Need help to implement networking in python
Server.py
Load data from file This option will ask the user for a fully qualified path and will load a JSON file containing the information for users and pending messages. The format of the JSON file will be defined based on your implementation and it will the same used to save the data into file (menu option #4).
Functionalities the server must provide: 1)
User Sign Up: adds a user identified by a phone number to the system.
a) Protocol: USR|username|password|display_name
b) Response: 0|OK for success. 1| for an error.
c) The server should validate that the username does not exist
2) User Sign In: verify user credentials
a) Protocol: LOG|username|password
b) Response: i) 0|OK → the credentials are correct.
ii) 1|Invalid Credentials iii) 2|Already Logged In → in case that the user is logged in from another client.
c) This will help the server knowing which user is connected.
d) The server should keep a list of connected clients, which should…
arrow_forward
need help on Linux for c program. This question might be really hard or easy as there is not enough documentation. man page might be helpful though.
how can I check if a file is an AREGTYPE or REGTYPE using lstat() or fstat() in C program in Linux.
arrow_forward
Language: Java
Rewrite the ADA source code in Java.Within the Java version of the code, change the second half of the first loop so that all assignments to the counting array 'Freq()' are updated in the EXCEPTION portion of the code. There should be no valid updates to 'Freq()' anywhere else in the loop.ADA source code:with Ada.Text_IO , Ada.Integer_Text_IO ;use Ada.Text_IO, Ada.Integer_Text_IO;procedure Grade_Distribution isFreq: array (1..10) of Integer := (others => 0);New_Grade : Natural;Index,Limit_1,Limit_2 : Integer;beginGrade_Loop:loopbeginGet(New_Grade);exceptionwhen Constraint_Error =>exit Grade_Loop;end;Index := New_Grade/10 + 1;beginFreq(Index) := Freq(Index) +1 ;exceptionwhen Constraint_Error =>if New_Grade = 100 thenFreq(10) := Freq(10) + 1;elsePut("Error -- new grade: ");Put(New_Grade);Put(" is out of range");New_Line;end if;end;end loop Grade_Loop;Put("Limits Frequency");New_Line; New_Line;for Index in 0..8 loopLimit_1 := 10 * Index;Limit_2 := Limit_1 + 9;if…
arrow_forward
Fill in the blank question- Only answer needed without explanation
Q. To disbale execution of binaries use ____________ configuration in /etc/fstab.
arrow_forward
Please explain in C++
arrow_forward
DO IT IN JAVA PLEASE, IN 25 MINUTES
arrow_forward
Appendix A. BTB entries with PC and Target PC. Please include only entries with content.Entry PC Target0 423000 425E407 42E01C 42E0288 423020 4230A811 42E02C 42B30C14 423038 425E40: : :: : :1018 422FE8 4230A8
arrow_forward
How to create this given UML in intellij using java?
can you provide me the codes?
arrow_forward
Could anyone tell me what am I doing wrong with my code ? It's C Programming by the way.
arrow_forward
Please give me correct solution and fast.
arrow_forward
Compliant/Noncompliant Solutions
The following code segment was provided in Secure Coding Guidelines for Java SE:
void readData() throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream("file"))); // Read from the file String data = br.readLine();}
The code is presented as a noncompliant coding example. For this assignment, identify two compliant solutions that can be utilized to ensure the protection of sensitive data. Provide a detailed explanation of factors, which influence noncompliant code and specifically how your solutions are now compliant. Your explanation should be 2-3 pages in length.
Submit the following components:
Word document with appropriate program analysis for your compliant solutions and source code in the Word file.
Submit your .java source code file(s). If more than 1 file, submit a zip file.
arrow_forward
Exception in thread "main" java.util.NoSuchElementException: No line found at java.base/java.util.Scanner.nextLine(Scanner.java:1651) at LabProgram.main(LabProgram.java:7)
arrow_forward
Develop a program that will do the following using Java and Javaclasses of Filewriter and Arraylist:
The program has the interface[A] Add[D] Delete[U] Update[S] Search[X] Exit
Select Operation: A
You are about to add a user.
Enter the First name:Enter the Last name:Enter the username:Enter password:
The user has been successfully added.
Do you wish to do another operation? [Y/N]: Y
----------------------------------------------------------------------------------------------
[A] Add[U] Update[S] Search[D] Delete[X] Exit
Select Operation: U
You are about to update user information.
Search ID: 3
User information:First name: GeraldLast name: MorenoUsername: igeraldPassword: egerald
Enter new username: asxsEnter new password: erdasdfr
Username and Password have been updated successfully.
Do you wish to do another operation? [Y/N]: Y
----------------------------------------------------------------------------------------------------------
[A] Add[U] Update[S] Search[D] Delete[X] Exit
Select…
arrow_forward
Discuss the importance of error handling and exception handling when working with InputStreams.
arrow_forward
In C++, not C please!
Assume that your computer has 4 CPUs. Write a multithreaded program that runs 4 different threads concurrently. The entire process will add the first 1,000,000 numbers (from 1 to 1,000,000) to a shared variable sum. You need to use a pthread_mutex_t to provide mutual exclusion so that the final result of sum is 500,000,500,000 Note: you can download and modify the file summation_thread_shared_sum.cpp. This file does not use a mutex lock, so the result is incorrect. You must add a mutex lock correctly in the file so that the program generates the right outcome.
arrow_forward
I am having error E0020 and E0140 in C++. How can I fix it?
/*Christopher JimenezCIS247CATM application24 November */
// bring in our libraries //Step #1#include <iostream>#include <conio.h>#include <string>#include <fstream> // read/write to files#include <ctime> // time(0)#include <iomanip> //setprecision()using namespace std;
// prototypesvoid deposit(double* ptrBalance);void withdrawal(double* ptrBalance, float dailyLimit); // overloaded method - this version does not take withdrawal amountvoid withdrawal(double* ptrBalance, float dailyLimit, float amount); //overloaded method that takes withdrawal amount
///Entry point to the applicationint main(){
// create constant values -- cannot be changedconst int EXIT_VALUE = 5;const float DAILY_LIMIT = 400.0F;const string FILENAME = "Account.txt";
//create balance variabledouble balance = 0.0;
// look for the starting balance; otherwise generate a ramdom starting balanceifstream iFile(FILENAME.c_str());…
arrow_forward
Write a Java program that implements parallel programming using the Fork/Join framework. And must make use of the subclasses in the Fork/Join Framework.
Step1- The program should initially generate 15 million random numbers.
Step2-The generated numbers should be read into an array of doubles.
Step 2- Then use a method that uses this array to calculate the sum of these doubles.
Step 3-It must then display the sum and it must also output the number of processors available.
Lastly, Have a clear screenshoot of code in the IDE and a screenshot of the code running.
arrow_forward
Write a C++ program using Windows API to RemoveDirectory – For Removing the Directory
BOOL RemoveDirectory(LPCSTR lpPathName);
Return Type – Boolean (TRUE or FALSE).
LPCSTR – Long Pointer to constant String.
lpPathName – Directory Path Which one you want to delete.
If this function Fails then its return FALSE or ZERO. Also We can print the Error Information with the help of GetLastError() function.
RemoveDirectory Function Link.
arrow_forward
Language: Python
Goal: implement decryption in the attached code block
import argparse
import os
import time
import sys
import string
# Handle command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--decrypt", help='Decrypt a file', required=False)
parser.add_argument("-e", "--encrypt", help='Encrypt a file', required=False)
parser.add_argument("-o", "--outfile", help='Output file', required=False)
args = parser.parse_args()
encrypting = True
try:
ciphertext = open(args.decrypt, "rb").read()
try:
plaintext = open(args.encrypt, "rb").read()
print("You can't specify both -e and -d")
exit(1)
except Exception:
encrypting = False
except Exception:
try:
plaintext = open(args.encrypt, "rb").read()
except Exception:
print("Input file error (did you specify -e or -d?)")
exit(1)
def lrot(n, d):
return ((n << d) & 0xff) | (n >> (8 - d))
if encrypting:
#…
arrow_forward
Write in C for STM32F446RE microcontroller on the Nucleo-64 dev board uncluding proper header files
Write a source library that contains the with the following public functions:
void keypadInit(void); /Initiallized the GPIO to read the keypad.
uint16_t readKeypad(void); //Returns the state of all of the keypad buttons in the return value at the moment the function is called.
void decodeKeypad(uint16_t, char *); //Takes the state of the keypad and returns (by reference) an array of the key's pressed.
The library should work with the following main:
int main (void) { uint16_t key; char carray[17]; keypadInit(); while(1) { while(!(key = readKeypad())); /*Get which keys pressed*/ decodeKeypad(key, carray); /*What are those keys*/ printf("%s\n",carray); /*Print those keys to screen*/ while(readKeypad() == key); /*Wait for the keypad to change*/ }}
Problem 1: Write a library that works with the following…
arrow_forward
Write a Shell program in C that can handle pushd, popd , and dirs commands supported by many shell programs including bash, tcsh and zsh. examples/how it works: The user enters pushd + [directory] The user enters popd The user enters dirs
arrow_forward
C++ coding assigment 5
I am having trouble to get my coding working because I addressBook.cpp and addressbook.h is not working well with my Person so I need help figure out the problem because I have don't know how to fix my coding so that both person and addressbook work for the main.
remainder: due not type in java. Make sure to type c++ in different files like Main.cpp, Person.cpp, Person.j, AddressBook.cpp, and AddressBook.h
This small project is geared to test your understanding of File IO.
AddressBook Exception
Create an AddressBookException class that you can use to throw exceptions in your address book. Your class should have a constructor that will allow you to set the particular message that corresponds to the error.
You should use your custom exception class to throw an error in the findPerson method if the person being searched for cannot be found, in the getPerson method if the AddressBook is empty. You should also throw an error any time that the addressbook file that…
arrow_forward
python:
def typehelper(poke_name): """ Question 5 - API
Now that you've acquired a new helper, you want to take care of them! Use the provided API to find the type(s) of the Pokemon whose name is given. Then, for each type of the Pokemon, map the name of the type to a list of all types that do double damage to that type. Note: Each type should be considered individually.
Base URL: https://pokeapi.co/
Endpoint: api/v2/pokemon/{poke_name}
You will also need to use a link provided in the API response.
Args: Pokemon name (str)
Returns: Dictionary of types
Hint: You will have to run requests.get() multiple times!
>>> typehelper("bulbasaur") {'grass': ['flying', 'poison', 'bug', 'fire', 'ice'], 'poison': ['ground', 'psychic']}
>>> typehelper("corviknight") {'flying': ['rock', 'electric', 'ice'], 'steel': ['fighting', 'ground', 'fire']}
"""
# pprint(typehelper("bulbasaur"))#…
arrow_forward
IN JAVA, DO THESE INTERFACES IN POINT AND LINE CLASSES
arrow_forward
Write a Makefile line that will cause a library called libnetwork.so to be linked to every executable file produced by implicit linking rules.
(Do not use any spaces in your answer)
Write a cmake instruction for CMakeLists.txt that instructs cmake to build an executeable file called analyze from the modules analyze.c and io.c.
Write a cmake instruction for CMakeLists.txt that instructs cmake to link the library libperformance.so to the executable target profile.
arrow_forward
Exception in thread "main" java.lang.NumberFormatException: For input string: "x" for Java code
public class Finder {
//Write two recursive functions, both of which will parse any length string that consists of digits and numbers. Both functions
//should be in the same class and have the following signatures.
//use the if/else statement , Find the base case and -1 till you get to base case
//recursive function that adds up the digits in the String
publicstaticint sumIt(String s)
{
//if String length is less or equal to 1 retrun 1.
if (s.length()<= 1){
return Integer.parseInt(s);
}else{
//use Integer.praseInt(s) to convert string to Integer
//returns the interger values
//else if the CharAt(value in index at 0 = 1) is not equal to the last vaule in the string else {//return the numeric values of a char value + call the SumIt method with a substring = 1
return Character.getNumericValue(s.charAt(0) ) + sumIt(s.substring(1));
}
}
//write a recursion function that will find…
arrow_forward
Python please
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education
Related Questions
- The code is in C++arrow_forwardWhat is the result of the following operation in Python: 17/2 ? Given the following code in Python: >>> mydna = 'acgt' >>> mydna = mydna + mydna What will be the result of typing the following at the Python interpreter prompt: >>> myDna? 3. The following commands are entered at the prompt of Python interpreter. >>> dna="atgctggggact" >>> dna[:3] >>> dna What will be the output of the last command?arrow_forwardPlease write in C++ and run in linux. This assignment is about fork(), exec(), and wait() system calls, and commandline arguments. Write two C++ programs, to be named parent.cc and child.cc and compiled into executable parent and child, respectively that, when run, will work as follows: parent takes in a list of gender-name pairs from the commandline arguments creates as many child processes as there are in the gender-name pairs and passes to each child process a child number and a gender-name pair waits for all child processes to terminate outputs “All child processes terminated. Parent exits.” And terminates. child receives a child number and one gender-name pair arguments from parent outputs “Child # x, a boy (or girl), name xxxxxx.” Note: content of output depends on data received from parent Sample run To invoke the execution: >parent girl Nancy boy Mark boy Joseph parent process does the following: outputs “I have 3 children.” -- Note: the number 3…arrow_forward
- TASK: Build a simple shell.DESCRIPTION:Write a shell program in C similar to "csh" that takes commands from thekeyboard. In particular, your shell prompt must be the current time(instead of, say, % as is common in UNIX).Make it simple; that is, do not allow it to handle background processes,it can ignore the control-C key, and especially, do not design it tointerpret shell scripts.You will need the following system calls:forkwaitpidone of execv, execve, execvp (read the manual pages).You must NOT use the C library function "system".arrow_forwardCode (C++) that will print the messagearrow_forwardCreate a new C++ project in Visual Studio (or an IDE of your choice). Add the files listed below to your project: BinaryTree.h Download BinaryTree.h BinarySearchTree.h Download BinarySearchTree.h main.cpp Download main.cpp Build and run your project. The program should compile without any errors. Note that function main() creates a new BST of int and inserts the nodes 12, 38, 25, 5, 15, 8, 55 (in that order) and displays them using pre-order traversal. Verify that the insertions are done correctly. You may verify it manually or use the visualization tool at https://www.cs.usfca.edu/~galles/visualization/BST.html. (Links to an external site.) Do the following: 1. add code to test the deleteNode and search member functions. Save screenshot of your test program run. 2. add code to implement the nodeCount member function of class BinaryTree. Test it and save screenshot of your test program run. 3. add code to implement the leafCount member function of class BinaryTree. Test it and…arrow_forward
- Need Help with C++ coding, and please explain the first step in detail. Write a program in C++ that performs three functions using threads on the attached text file called long_text.txt 1. Write your code in a such way that you can show in terms of time that using threads does not keep you blocked i.e., the main thread gets free once all threads start. a.This means that your program will run the three functions without threading and then with threading. 2. Functions to implement are: a. word_count() → will count the number of words in the text file b. sentence_count() → will count the number of sentences in the text file c. find_frequent_word() → finds the most frequently occurring word and number of times it occurred in the textarrow_forwardNeed help to implement networking in python Server.py Load data from file This option will ask the user for a fully qualified path and will load a JSON file containing the information for users and pending messages. The format of the JSON file will be defined based on your implementation and it will the same used to save the data into file (menu option #4). Functionalities the server must provide: 1) User Sign Up: adds a user identified by a phone number to the system. a) Protocol: USR|username|password|display_name b) Response: 0|OK for success. 1| for an error. c) The server should validate that the username does not exist 2) User Sign In: verify user credentials a) Protocol: LOG|username|password b) Response: i) 0|OK → the credentials are correct. ii) 1|Invalid Credentials iii) 2|Already Logged In → in case that the user is logged in from another client. c) This will help the server knowing which user is connected. d) The server should keep a list of connected clients, which should…arrow_forwardneed help on Linux for c program. This question might be really hard or easy as there is not enough documentation. man page might be helpful though. how can I check if a file is an AREGTYPE or REGTYPE using lstat() or fstat() in C program in Linux.arrow_forward
- Language: Java Rewrite the ADA source code in Java.Within the Java version of the code, change the second half of the first loop so that all assignments to the counting array 'Freq()' are updated in the EXCEPTION portion of the code. There should be no valid updates to 'Freq()' anywhere else in the loop.ADA source code:with Ada.Text_IO , Ada.Integer_Text_IO ;use Ada.Text_IO, Ada.Integer_Text_IO;procedure Grade_Distribution isFreq: array (1..10) of Integer := (others => 0);New_Grade : Natural;Index,Limit_1,Limit_2 : Integer;beginGrade_Loop:loopbeginGet(New_Grade);exceptionwhen Constraint_Error =>exit Grade_Loop;end;Index := New_Grade/10 + 1;beginFreq(Index) := Freq(Index) +1 ;exceptionwhen Constraint_Error =>if New_Grade = 100 thenFreq(10) := Freq(10) + 1;elsePut("Error -- new grade: ");Put(New_Grade);Put(" is out of range");New_Line;end if;end;end loop Grade_Loop;Put("Limits Frequency");New_Line; New_Line;for Index in 0..8 loopLimit_1 := 10 * Index;Limit_2 := Limit_1 + 9;if…arrow_forwardFill in the blank question- Only answer needed without explanation Q. To disbale execution of binaries use ____________ configuration in /etc/fstab.arrow_forwardPlease explain in C++arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education
Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education
Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON
Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON
C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON
Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning
Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education