title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Java Program to Convert int to long - GeeksforGeeks
09 Feb, 2022 Given a number of int datatype in Java, your task is to write a Java program to convert this given int datatype into a long datatype. Example: Input: intnum = 5 Output: longnum = 5 Input: intnum = 56 Output: longnum = 56 Int is a smaller data type than long. Int is a 32-bit integer while long is a 64-bit integer. They both are primitive data types and the usage depends on how large the number is. Java int can be converted to long in two simple ways: Using a simple assignment. This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types.Using valueOf() method of the Long wrapper class in java which converts int to long. Using a simple assignment. This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long. 1. Implicit type casting: In this, we are simply assigning an integer data type to a long data type. Since integer is a smaller data type compared to long, the compiler automatically converts int to long, this is known as Implicit type casting or type promotion. Java // Java program to demonstrate// use of implicit type casting import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { int intnum = 5; // Implicit type casting , automatic // type conversion by compiler long longnum = intnum; // printin the data-type of longnum System.out.println( "Converted type : " + ((Object)longnum).getClass().getName()); System.out.println("After converting into long:"); System.out.println(longnum); }} Converted type : java.lang.Long After converting into long: 5 2. Long.valueOf() method: In this, we are converting int to long using the valueOf() method of the Long Wrapper class. The valueOf() method accepts an integer as an argument and returns a long value after the conversion. Java // Java program to convert// int to long using valueOf() method import java.io.*; class GFG { public static void main(String[] args) { int intnum = 56; Long longnum = Long.valueOf(intnum); // printing the datatype to // show longnum is of type // long contains data of intnum System.out.println( "Converted type : " + ((Object)longnum).getClass().getName()); // accepts integer and // returns a long value System.out.println("After converting into long:" + "\n" + longnum); }} Converted type : java.lang.Long After converting into long: 56 nishkarshgandhi Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Iterate through List in Java
[ { "code": null, "e": 25237, "s": 25209, "text": "\n09 Feb, 2022" }, { "code": null, "e": 25371, "s": 25237, "text": "Given a number of int datatype in Java, your task is to write a Java program to convert this given int datatype into a long datatype." }, { "code": null, ...
Hadoop - File Blocks and Replication Factor - GeeksforGeeks
09 Mar, 2021 Hadoop Distributed File System i.e. HDFS is used in Hadoop to store the data means all of our data is stored in HDFS. Hadoop is also known for its efficient and reliable storage technique. So have you ever wondered how Hadoop is making its storage so much efficient and reliable? Yes, here what the concept of File blocks is introduced. The Replication Factor is nothing but it is a process of making replicate or duplicate’s of data so let’s discuss them one by one with the example for better understanding. What happens is whenever you import any file to your Hadoop Distributed File System that file got divided into blocks of some size and then these blocks of data are stored in various slave nodes. This is a kind of normal thing that happens in almost all types of file systems. By default in Hadoop1, these blocks are 64MB in size, and in Hadoop2 these blocks are 128MB in size which means all the blocks that are obtained after dividing a file should be 64MB or 128MB in size. You can manually change the size of the file block in hdfs-site.xml file. Let’s understand this concept of breaking down of file in blocks with an example. Suppose you have uploaded a file of 400MB to your HDFS then what happens is, this file got divided into blocks of 128MB + 128MB + 128MB + 16MB = 400MB size. Means 4 blocks are created each of 128MB except the last one. Hadoop doesn’t know or it doesn’t care about what data is stored in these blocks so it considers the final file blocks as a partial record. In the Linux file system, the size of a file block is about 4KB which is very much less than the default size of file blocks in the Hadoop file system. As we all know Hadoop is mainly configured for storing large size data which is in petabyte, this is what makes Hadoop file system different from other file systems as it can be scaled, nowadays file blocks of 128MB to 256MB are considered in Hadoop. Now let’s understand why these blocks are very huge. There are mainly 2 reason’s as discussed below: Hadoop File Blocks are bigger because if the file blocks are smaller in size then in that case there will be so many blocks in our Hadoop File system i.e. in HDFS. Storing lots of metadata in these small-size file blocks in a very huge amount becomes messy which can cause network traffic. Blocks are made bigger so that we can minimize the cost of seeking or finding. Because sometimes time taken to transfer the data from the disk can be more than the time taken to start these blocks. Advantages of File Blocks: Easy to maintain as the size can be larger than any of the single disk present in our cluster. We don’t need to take care of Metadata like any of the permission as they can be handled on different systems. So no need to store this Meta Data with the file blocks. Making Replicates of this data is quite easy which provides us fault tolerance and high availability in our Hadoop cluster. As the blocks are of a fixed configured size we can easily maintain its record. Replication ensures the availability of the data. Replication is nothing but making a copy of something and the number of times you make a copy of that particular thing can be expressed as its Replication Factor. As we have seen in File blocks that the HDFS stores the data in the form of various blocks at the same time Hadoop is also configured to make a copy of those file blocks. By default the Replication Factor for Hadoop is set to 3 which can be configured means you can change it Manually as per your requirement like in above example we have made 4 file blocks which means that 3 Replica or copy of each file block is made means total of 4×3 = 12 blocks are made for the backup purpose. Now you might be getting a doubt that why we need this replication for our file blocks this is because for running Hadoop we are using commodity hardware (inexpensive system hardware) which can be crashed at any time. We are not using a supercomputer for our Hadoop setup. That is why we need such a feature in HDFS which can make copies of that file blocks for backup purposes, this is known as fault tolerance. Now one thing we also need to notice that after making so many replica’s of our file blocks we are wasting so much of our storage but for the big brand organization the data is very much important than the storage. So nobody care for this extra storage. You can configure the Replication factor in you hdfs-site.xml file. Here, we have set the replication Factor to one as we have only a single system to work with Hadoop i.e. a single laptop, as we don’t have any Cluster with lots of the nodes. You need to simply change the value in dfs.replication property as per your need. How does Replication work? In the above image, you can see that there is a Master with RAM = 64GB and Disk Space = 50GB and 4 Slaves with RAM = 16GB, and disk Space = 40GB. Here you can observe that RAM for Master is more. It needs to be kept more because your Master is the one who is going to guide this slave so your Master has to process fast. Now suppose you have a file of size 150MB then the total file blocks will be 2 shown below. 128MB = Block 1 22MB = Block 2 As the replication factor by-default is 3 so we have 3 copies of this file block FileBlock1-Replica1(B1R1) FileBlock2-Replica1(B2R1) FileBlock1-Replica2(B1R2) FileBlock2-Replica2(B2R2) FileBlock1-Replica3(B1R3) FileBlock2-Replica3(B2R3) These blocks are going to be stored in our Slave as shown in the above diagram which means if suppose your Slave 1 crashed then in that case B1R1 and B2R3 get lost. But you can recover the B1 and B2 from other slaves as the Replica of this file blocks is already present in other slaves, similarly, if any other Slave got crashed then we can obtain that file block some other slave. Replication is going to increase our storage but Data is More necessary for us. sabir69261 Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hadoop MapReduce - Data Flow Hive - Alter Table Hadoop - Pros and Cons Hadoop - Schedulers and Types of Schedulers How to Create Table in Hive? Top 10 Hadoop Analytics Tools For Big Data MapReduce - Combiners Import and Export Data using SQOOP MapReduce - Understanding With Real-Life Example Hadoop - getmerge Command
[ { "code": null, "e": 25591, "s": 25563, "text": "\n09 Mar, 2021" }, { "code": null, "e": 26102, "s": 25591, "text": "Hadoop Distributed File System i.e. HDFS is used in Hadoop to store the data means all of our data is stored in HDFS. Hadoop is also known for its efficient and re...
Python - Drawing design using arrow keys in PyGame - GeeksforGeeks
22 Apr, 2020 Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this article we will see how we can make design in PyGame with help of keys such that design i.e marker moves horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves vertically when pressing up arrow key or down arrow key. We can do this by making a spot(marker) on the respective co-ordinates, which gets changes with the help of keys. Change in Co-ordinates of marker for respective keys pressed : Left arrow key: Decrement in x co-ordinate Right arrow key: Increment in x co-ordinate Up arrow key: Decrement in y co-ordinate Down arrow key: Increment in y co-ordinate Below is the implementation – # import pygame module in this programimport pygame # activate the pygame library . # initiate pygame and give permission # to use pygame's functionality. pygame.init() # create the display surface object # of specific dimension..e(500, 500). win = pygame.display.set_mode((500, 500)) # set the pygame window name pygame.display.set_caption("Moving rectangle") # marker current co-ordinates x = 200y = 200 # dimensions of the marker width = 10height = 10 # velocity / speed of movement vel = 10 # Indicates pygame is running run = True # infinite loop while run: # creates time delay of 10ms pygame.time.delay(10) # iterate over the list of Event objects # that was returned by pygame.event.get() method. for event in pygame.event.get(): # if event object type is QUIT # then quitting the pygame # and program both. if event.type == pygame.QUIT: # it will make exit the while loop run = False # stores keys pressed keys = pygame.key.get_pressed() # if left arrow key is pressed if keys[pygame.K_LEFT] and x > 0: # decrement in x co-ordinate x -= vel # if left arrow key is pressed if keys[pygame.K_RIGHT] and x < 500 - width: # increment in x co-ordinate x += vel # if left arrow key is pressed if keys[pygame.K_UP] and y > 0: # decrement in y co-ordinate y -= vel # if left arrow key is pressed if keys[pygame.K_DOWN] and y < 500 - height: # increment in y co-ordinate y += vel # drawing spot on screen which is rectangle here pygame.draw.rect(win, (255, 0, 0), (x, y, width, height)) # it refreshes the window pygame.display.update() # closes the pygame window pygame.quit() Output : Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n22 Apr, 2020" }, { "code": null, "e": 25849, "s": 25537, "text": "Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the P...
Multiply matrices of complex numbers using NumPy in Python - GeeksforGeeks
05 Sep, 2020 In this article, we will discuss how to multiply two matrices containing complex numbers using NumPy but first, let’s know what is a complex number. A Complex Number is any number that can be represented in the form of x+yj where x is the real part and y is the imaginary part. Multiplication of two complex numbers can be done using the below formula – NumPy provides the vdot() method that returns the dot product of vectors a and b. This function handles complex numbers differently than dot(a, b). Syntax: numpy.vdot(vector_a, vector_b) Example 1: Python3 # importing numpy as libraryimport numpy as np # creating matrix of complex numberx = np.array([2+3j, 4+5j])print("Printing First matrix:")print(x) y = np.array([8+7j, 5+6j])print("Printing Second matrix:")print(y) # vector dot product of two matricesz = np.vdot(x, y)print("Product of first and second matrices are:")print(z) Output: Printing First matrix: [2.+3.j 4.+5.j] Printing Second matrix: [8.+7.j 5.+6.j] Product of first and second matrices are: (87-11j) Example 2: Now suppose we have 2D matrix: Python3 # importing numpy as libraryimport numpy as np # creating matrix of complex numberx = np.array([[2+3j, 4+5j], [4+5j, 6+7j]])print("Printing First matrix:")print(x) y = np.array([[8+7j, 5+6j], [9+10j, 1+2j]])print("Printing Second matrix:")print(y) # vector dot product of two matricesz = np.vdot(x, y)print("Product of first and second matrices are:")print(z) Output: Printing First matrix: [[2.+3.j 4.+5.j] [4.+5.j 6.+7.j]] Printing Second matrix: [[8. +7.j 5. +6.j] [9.+10.j 1. +2.j]] Product of first and second matrices are: (193-11j) Python numpy-Matrix Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26405, "s": 26377, "text": "\n05 Sep, 2020" }, { "code": null, "e": 26760, "s": 26405, "text": "In this article, we will discuss how to multiply two matrices containing complex numbers using NumPy but first, let’s know what is a complex number. A Complex Numb...
Python | Miscellaneous | Question 1 - GeeksforGeeks
28 Jun, 2021 What is the output of the following program : print "Hello World"[::-1] (A) dlroW olleH(B) Hello Worl(C) d(D) ErrorAnswer: (A)Explanation: [::] depicts extended slicing in Python and [::-1] returns the reverse of the string.Quiz of this Question amartyaghoshgfg Miscellaneous Python-Quizzes Python-Quizzes-Miscellaneous Python-Quizzes Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python-Quizzes | Python List Quiz | Question 4 Python-Quizzes | Python Dictionary Quiz | Question 25 Python-Quizzes | Python List Quiz | Question 5 Python-Quizzes | Python Dictionary Quiz | Question 23 Python | Animated Banner showing 'GeeksForGeeks' Why do people prefer Selenium with Python? Output of Python Program - Dictionary (set 25) Python-Quizzes | Miscellaneous | Question 10 Python-Quizzes | Output Type | Question 10 Python-Quizzes | Data Type | Question 3
[ { "code": null, "e": 25271, "s": 25243, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25317, "s": 25271, "text": "What is the output of the following program :" }, { "code": "print \"Hello World\"[::-1]", "e": 25343, "s": 25317, "text": null }, { "c...
Java | Class and Object | Question 7 - GeeksforGeeks
28 Jun, 2021 Predict the output of the following program. class Test{ int a = 1; int b = 2; Test func(Test obj) { Test obj3 = new Test(); obj3 = obj; obj3.a = obj.a++ + ++obj.b; obj.b = obj.b; return obj3; } public static void main(String[] args) { Test obj1 = new Test(); Test obj2 = obj1.func(obj1); System.out.println("obj1.a = " + obj1.a + " obj1.b = " + obj1.b); System.out.println("obj2.a = " + obj2.a + " obj1.b = " + obj2.b); }} (A) obj1.a = 1 obj1.b = 2 obj2.a = 4 obj2.b = 3 (B) obj1.a = 4 obj1.b = 3 obj2.a = 4 obj2.b = 3 (C) Compilation errorAnswer: (B)Explanation:obj1 and obj2 refer to same memory address.Quiz of this QuestionPlease comment below if you find anything wrong in the above post Class and Object Java-Class and Object Java Quiz Java-Class and Object Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Java | Constructors | Question 5 Java | Functions | Question 1 Java | final keyword | Question 1 Java | Abstract Class and Interface | Question 2 Java | Exception Handling | Question 4 Java | Exception Handling | Question 3 Java | Exception Handling | Question 8 Java | Exception Handling | Question 7 Java | Inheritance | Question 8 Java | Exception Handling | Question 6
[ { "code": null, "e": 25633, "s": 25605, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25678, "s": 25633, "text": "Predict the output of the following program." }, { "code": "class Test{ int a = 1; int b = 2; Test func(Test obj) { Test obj3 = new Te...
Mean - GeeksforGeeks
11 Dec, 2018 Mean is average of a given set of data. Let us consider below example 2, 4, 4, 4, 5, 5, 7, 9 the mean (average) of a given set of data is 5 Fact about Mean : The mean (or average) is the most popular and well known measure of central tendency.It can be used with both discrete and continuous data, although its use is most often with continuous data.There are other types of means.Geometric mean, Harmonic mean and Arithmetic mean.Mean is the only measure of central tendency where the sum of the deviations of each value from the mean is always zero. The mean (or average) is the most popular and well known measure of central tendency. It can be used with both discrete and continuous data, although its use is most often with continuous data. There are other types of means.Geometric mean, Harmonic mean and Arithmetic mean. Mean is the only measure of central tendency where the sum of the deviations of each value from the mean is always zero. Formula of mean of ungrouped data :Formula of mean of grouped data : How to find Mean ?Given n size unsorted array, find its mean. Mean of an array = (sum of all elements) / (number of elements) Since the array is not sorted here, we sort the array first, then apply above formula. Examples: Input : {1, 3, 4, 2, 6, 5, 8, 7} Output : Mean = 4.5 Sum of the elements is 1 + 3 + 4 + 2 + 6 + 5 + 8 + 7 = 36 Mean = 36/8 = 4.5 Input : {4, 4, 4, 4, 4} Output : Mean = 4 Below is the code implementation: C++ Java Python3 C# PHP // CPP program to find mean#include <bits/stdc++.h>using namespace std; // Function for calculating meandouble findMean(int a[], int n){ int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n;} // Driver programint main(){ int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = sizeof(a) / sizeof(a[0]); cout << "Mean = " << findMean(a, n) << endl; return 0;} // Java program to find meanimport java.util.*; class GFG { // Function for calculating mean public static double findMean(int a[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n; } // Driver program public static void main(String args[]) { int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = a.length; System.out.println("Mean = " + findMean(a, n)); }} # Python3 program to find mean # Function for calculating meandef findMean(a, n): sum = 0 for i in range( 0, n): sum += a[i] return float(sum / n) # Driver programa = [ 1, 3, 4, 2, 7, 5, 8, 6 ]n = len(a)print("Mean =", findMean(a, n)) // C# program to find meanusing System; class GFG { // Function for // calculating mean public static double findMean(int[] a, int n) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n; } // Driver Code public static void Main() { int[] a = { 1, 3, 4, 2, 7, 5, 8, 6 }; int n = a.Length; Console.Write("Mean = " + findMean(a, n) + "\n"); }} <?php // PHP program to find mean // Function for calculating meanfunction findMean(&$a, $n){ $sum = 0; for ($i = 0; $i < $n; $i++) $sum += $a[$i]; return (double)$sum / (double)$n;} // Driver Code$a = array(1, 3, 4, 2, 7, 5, 8, 6);$n = sizeof($a);echo "Mean = " . findMean($a, $n)."\n"; ?> Mean = 4.5 Time Complexity to find mean = O(n) Basic Program related to Mean Find mean of subarray means in a given array Mean of array using recursion Find the mean vector of a Matrix Mean of range in array Mean and Median of a matrix Recent Articles on Mean! maths-mean statistical-algorithms Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Segment Tree | Set 1 (Sum of given range) Product of Array except itself Program to multiply two matrices Singular Value Decomposition (SVD) Generate all permutation of a set in Python Fizz Buzz Implementation Program to print prime numbers from 1 to N. Shortest path in a Binary Maze Expression Evaluation Josephus problem | Set 1 (A O(n) Solution)
[ { "code": null, "e": 25937, "s": 25909, "text": "\n11 Dec, 2018" }, { "code": null, "e": 26077, "s": 25937, "text": "Mean is average of a given set of data. Let us consider below example 2, 4, 4, 4, 5, 5, 7, 9 the mean (average) of a given set of data is 5" }, { "code": n...
Python IMDbPY - Getting list of movies performed by the actor - GeeksforGeeks
08 May, 2020 In this article we will see how we can get the list of movies in which actor has performed i.e an actor performs in various movies. IMDb has a database of almst every movie performed by verified actors. In order to get the list of all the movies performed by the actor we have to get the details of filmography of the actor Syntax : results = ia.get_person_filmography(ID)Here ia is the IMDb object Argument : It takes Id as argument Return : It returns dictionary This method returns the complicated dictionary which is hard to read in order to get the titles of the movie we use results['data']['filmography'][0]['actor'][index] Below is the implementation # importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # person idcode = "1372788" # printing person nameprint(ia.get_person(code)) # getting informationactor_results = ia.get_person_filmography(code) # printing movie namefor index in range(5): movie_name = actor_results['data']['filmography'][0]['actor'][index] print(movie_name) Output : Shahid Kapoor Jersey Hindi Remake Sachet Tandon: Bekhayali Kabir Singh The Insider's Watchlist Akhil Sachdeva & Tulsi Kumar: Tera Ban Jaunga Another example # importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # person idcode = "0001098" # printing person nameprint(ia.get_person(code)) # getting informationactor_results = ia.get_person_filmography(code) # printing movie namefor index in range(5): movie_name = actor_results['data']['filmography'][0]['actor'][index] print(movie_name) Output : Rodney Dangerfield Angels with Angles Still Standing Back by Midnight Phil of the Future The Electric Piper Python IMDbPY-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25853, "s": 25825, "text": "\n08 May, 2020" }, { "code": null, "e": 26056, "s": 25853, "text": "In this article we will see how we can get the list of movies in which actor has performed i.e an actor performs in various movies. IMDb has a database of almst ev...
Aptitude | Algebra | Question 1 - GeeksforGeeks
28 Jun, 2021 If x3 + y3 = 9 and x + y = 3, then the value of x4+y4 is,(A) 21(B) 0(C) 17(D) 25Answer: (C)Explanation: x3+y3 = (x + y) × (x2 − xy + y2) Putting given values of x3+y3 and (x + y) 9 = 3 × ((x+y)2 − 3xy) = 3 × (9 − 3xy) = 27 − 9xy 9xy = 18 xy = 2 x4 + y4 = (x2 + y2)2 - 2x2y2 = (x2 + y2)2 - 2*4 [Putting value of xy] = ((x + y)2 - 2xy)2 - 2*4 [Putting values of (x+y) and xy] = (9 - 4)2 - 2*4 = 17 Quiz of this Question Algebra QA - Placement Quizzes QA - Placement Quizzes-Algebra QA - Placement Quizzes Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. QA - Placement Quizzes | Work and Wages | Question 8 QA - Placement Quizzes | Permutation and Combination | Question 5 Count Distinct Rectangles in N*N Chessboard QA - Placement Quizzes | Permutation and Combination | Question 2 QA - Placement Quizzes | Permutation and Combination | Question 4 QA - Placement Quizzes | Work and Wages | Question 5 QA - Placement Quizzes | SP Contest 2 | Question 1 QA - Placement Quizzes | Numbers, LCM and HCF | Question 11 QA - Placement Quizzes | Profit and Loss | Question 14 QA - Placement Quizzes | Permutation and Combination | Question 10
[ { "code": null, "e": 25868, "s": 25840, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25972, "s": 25868, "text": "If x3 + y3 = 9 and x + y = 3, then the value of x4+y4 is,(A) 21(B) 0(C) 17(D) 25Answer: (C)Explanation:" }, { "code": null, "e": 26349, "s": 25972,...
How to sort a Vector in descending order using STL in C++? - GeeksforGeeks
18 Apr, 2022 Given a vector, sort this vector in descending order using STL in C++. Example: Input: vec = {1, 45, 54, 71, 76, 12} Output: {76, 71, 54, 45, 12, 1} Input: vec = {1, 7, 5, 4, 6, 12} Output: {12, 7, 6, 5, 4, 1} Approach: Sorting can be done with the help of sort() function provided in STL. Syntax: sort(arr, arr + n, greater<T>()); C++ // C++ program to sort Vector// in descending order// using sort() in STL #include <bits/stdc++.h>using namespace std; int main(){ // Get the vector vector<int> a = { 1, 45, 54, 71, 76, 12 }; // Print the vector cout << "Vector: "; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; // Sort the vector in descending order sort(a.begin(), a.end(), greater<int>()); // Print the reversed vector cout << "Sorted Vector in descending order:\n"; for (int i = 0; i < a.size(); i++) cout << a[i] << " "; cout << endl; return 0;} Output: Vector: 1 45 54 71 76 12 Sorted Vector in descending order: 76 71 54 45 12 1 surindertarika1234 43e81c364f cpp-vector STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ C++ Classes and Objects Bitwise Operators in C/C++ Virtual Function in C++ Constructors in C++ Templates in C++ with Examples Operator Overloading in C++ Socket Programming in C/C++ vector erase() and clear() in C++ Object Oriented Programming in C++
[ { "code": null, "e": 25659, "s": 25631, "text": "\n18 Apr, 2022" }, { "code": null, "e": 25730, "s": 25659, "text": "Given a vector, sort this vector in descending order using STL in C++." }, { "code": null, "e": 25740, "s": 25730, "text": "Example: " }, {...
How to add Toggle Button in an Android Application - GeeksforGeeks
19 Feb, 2021 ToggleButton is basically a stop / play or on/off button with indicator light indicating the current state of ToggleButton. ToggleButton is widely used, some examples are on/off audio, Bluetooth, WiFi, hot-spot etc. This is a subclass of Composite Button. ToggleButton allows users to change settings between two states from your phone’s Settings menu such as turning your WiFi, Bluetooth, etc. on / off. Since the Android 4.0 version (API level 14), it has another type of toggle button called switch which provides user slider control. Programmatically, isChecked() method is used to check the current state of the toggle button. This method returns a boolean value. If a toggle button is ON, this returns true otherwise it returns false. Below is the example in which toggle button is used. Approach Step 1: Create a new project and fill all the required details for the app like the app name, package name, etc.Select File -> New -> New Project -> fill required details and click “Finish” Select File -> New -> New Project -> fill required details and click “Finish” Step 2: In this step, open the XML file and add the code to display the toggle button and a textview.res -> Layout -> Activity_Main.xml (or) Main.xmlacticity_main.xmlacticity_main.xml<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:background="@color/white" tools:context=".MainActivity"> <ToggleButton android:id="@+id/toggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick="onToggleClick" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="100dp" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_above="@+id/toggleButton" android:textStyle="bold" android:textColor="@color/black"/> </RelativeLayout> res -> Layout -> Activity_Main.xml (or) Main.xml acticity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:background="@color/white" tools:context=".MainActivity"> <ToggleButton android:id="@+id/toggleButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick="onToggleClick" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="100dp" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_above="@+id/toggleButton" android:textStyle="bold" android:textColor="@color/black"/> </RelativeLayout> Step 3: In this step, open MainActivity and add the below code to initialize the toggle button and add onToggleClick method which will be invoked when the user clicks on the toggle button. This method changes the text in textview.Open the app -> Java -> Package -> Mainactivity.javaMainActivity.JavaMainActivity.Javaimport androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.TextView;import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { ToggleButton togglebutton; TextView textview; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); togglebutton = (ToggleButton)findViewById( R.id.toggleButton); textview = (TextView)findViewById( R.id.textView); } public void onToggleClick(View view) { if (togglebutton.isChecked()) { textview.setText("Toggle is ON"); } else { textview.setText("Toggle is OFF"); } }} Open the app -> Java -> Package -> Mainactivity.java MainActivity.Java import androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.TextView;import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { ToggleButton togglebutton; TextView textview; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); togglebutton = (ToggleButton)findViewById( R.id.toggleButton); textview = (TextView)findViewById( R.id.textView); } public void onToggleClick(View view) { if (togglebutton.isChecked()) { textview.setText("Toggle is ON"); } else { textview.setText("Toggle is OFF"); } }} Output: Now connect your device with USB cable and launch the application. You will see a toggle button. Click on the toggle button which will display the status of the toggle button. Android-Button Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Resource Raw Folder in Android Studio Broadcast Receiver in Android With Example Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples
[ { "code": null, "e": 26087, "s": 26059, "text": "\n19 Feb, 2021" }, { "code": null, "e": 26343, "s": 26087, "text": "ToggleButton is basically a stop / play or on/off button with indicator light indicating the current state of ToggleButton. ToggleButton is widely used, some examp...
jQuery :first-child Selector
The :first-child selector in jQuery is used to select all elements, which are the first child of their parent. The syntax is as follows − $(":first-child") Let us now see an example to implement the :first-child() selector − <!DOCTYPE html> <html> <head> <style> .demo { background-color: red; color: white; font-size: 16px; border: 2px blue dashed; } </style> <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <script> $(document).ready(function(){ $("p:first-child").addClass("demo"); }); </script> </head> <body> <p>This is the first line!</p> <p>This is the second line!</p> <p>This is the third line!</p> <hr> <div> <p>One</p> <p>Two</p> <p>Three</p> <p>Four</p> </div> <hr> <p>This is the last line.</p> </body> </html> This will produce the following output −
[ { "code": null, "e": 1173, "s": 1062, "text": "The :first-child selector in jQuery is used to select all elements, which are the first child of their parent." }, { "code": null, "e": 1200, "s": 1173, "text": "The syntax is as follows −" }, { "code": null, "e": 1218, ...
alignof operator in C++ - GeeksforGeeks
08 Jun, 2018 In C++11 the alignof operator used to returns the alignment, in bytes of the specified type.Syntax: alignof(type) Syntax Explanation: alignof: operator returns the alignment in byte, required for instances of type, which type is either complete type, array type or a reference type. array type: alignment requirement of the element type is returned. reference type: the operator returns the alignment of referenced type. Return Value: The alignof operator typically used to returns a value of type std::size_t. Program: // C++ program to demonstrate alignof operator#include <iostream>using namespace std; struct Geeks { int i; float f; char s;}; struct Empty {}; // driver codeint main(){ cout << "Alignment of char: " << alignof(char) << endl; cout << "Alignment of pointer: " << alignof(int*) << endl; cout << "Alignment of float: " << alignof(float) << endl; cout << "Alignment of class Geeks: " << alignof(Geeks) << endl; cout << "Alignment of Empty class: " << alignof(Empty) << endl; return 0;} Alignment of char: 1 Alignment of pointer: 8 Alignment of float: 4 Alignment of class Geeks: 4 Alignment of Empty class: 1 alignof vs sizeof:The alignof value is the same as the value for sizeof for basic types. Consider, this example: typedef struct { int a; double b; } S; // alignof(S) == 8 Above case, the alignof value is the alignment requirement of the largest element in the structure.Example program to demonstrate the difference between alignof and sizeof: // C++ program to demonstrate// alignof vs sizeof operator#include <iostream>using namespace std; struct Geeks { int i; float f; char s;}; int main(){ cout << "alignment of Geeks : " << alignof(Geeks) << '\n'; cout << "sizeof of Geeks : " << sizeof(Geeks) << '\n'; cout << "alignment of int : " << alignof(int) << '\n'; cout << "sizeof of int : " << sizeof(int) << '\n';} alignment of Geeks : 4 sizeof of Geeks : 12 alignment of int : 4 sizeof of int : 4 cpp-structure C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Convert string to char array in C++ Iterators in C++ STL Inline Functions in C++ List in C++ Standard Template Library (STL) Multithreading in C++
[ { "code": null, "e": 24098, "s": 24070, "text": "\n08 Jun, 2018" }, { "code": null, "e": 24198, "s": 24098, "text": "In C++11 the alignof operator used to returns the alignment, in bytes of the specified type.Syntax:" }, { "code": null, "e": 24212, "s": 24198, ...
Compute the value of F Cumulative Distribution Function in R Programming - pf() Function - GeeksforGeeks
25 Jun, 2020 pf() function in R Language is used to compute the density of F Cumulative Distribution Function over a sequence of numeric values. It also plots a density graph for F Cumulative Distribution. Syntax: pf(x, df1, df2) Parameters:x: Numeric Vectordf: Degree of Freedom Example 1: # R Program to compute # Cumulative F Density # Creating a sequence of x-valuesx <- seq(1, 30, by = 2) # Calling pf() Functiony <- pf(x, df1 = 2, df2 = 3)y Output: [1] 0.5352420 0.8075499 0.8891420 0.9258675 0.9460051 0.9584308 0.9667275 [8] 0.9725899 0.9769124 0.9802073 0.9827867 0.9848509 0.9865331 0.9879255 [15] 0.9890935 Example 2: # R Program to compute # Cumulative F Density # Creating a sequence of x-valuesx <- seq(1, 30, by = 0.2) # Calling pf() Functiony <- pf(x, df1 = 3, df2 = 7) # Plot a graphplot(y) Output: R Statistics-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? Group by function in R using Dplyr Remove rows with NA in one column of R DataFrame K-Means Clustering in R Programming How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 25156, "s": 25128, "text": "\n25 Jun, 2020" }, { "code": null, "e": 25349, "s": 25156, "text": "pf() function in R Language is used to compute the density of F Cumulative Distribution Function over a sequence of numeric values. It also plots a density graph f...
C++ Stack Library - stack() Function
The C++ constructor std::stack::stack() creates stack container and assigns copy of the ctnr argument to stack elements. If ctnr argument is not provided it constructs empty stack with zero element. Following is the declaration for std::stack::stack() constructor form std::stack header. explicit stack (const container_type& ctnr = container_type()); explicit stack (const container_type& ctnr); ctnr − Container type which is second parameter of class template. Constructor never returns value. This member function never throws exception. Linear i.e. O(n) The following example shows the usage of std::stack::stack() constructor. #include <iostream> #include <stack> #include <vector> using namespace std; int main(void) { stack<int> s1; vector<int> v = {1, 2, 3, 4, 5}; stack<int, vector<int>> s2(v); cout << "Size of stack s1 = " << s1.size() << endl; cout << "Contents of stack s2" << endl; while (!s2.empty()) { cout << s2.top() << endl; s2.pop(); } return 0; } Let us compile and run the above program, this will produce the following result − Size of stack s1 = 0 Contents of stack s2 5 4 3 2 1 Print Add Notes Bookmark this page
[ { "code": null, "e": 2802, "s": 2603, "text": "The C++ constructor std::stack::stack() creates stack container and assigns copy of the ctnr argument to stack elements. If ctnr argument is not provided it constructs empty stack with zero element." }, { "code": null, "e": 2891, "s": 28...
Array Declarations in Java (Single and Multidimensional) - GeeksforGeeks
21 Aug, 2017 Arrays in Java | Introduction One Dimensional Array : It is a collection of variables of same type which is used by a common name. Examples:One dimensional array declaration of variable: import java.io.*; class GFG { public static void main(String[] args) { int[] a; // valid declaration int b[]; // valid declaration int[] c; // valid declaration }} We can write it in any way. Now, if you declare your array like below: import java.io.*; class GFG { public static void main(String[] args) { // invalid declaration -- If we want to assign // size of array at the declaration time, it // gives compile time error. int a[5]; // valid declaration int b[]; }} Now, suppose we want to write multiple declaration of array variable then we can use it like this. import java.io.*; class GFG { public static void main(String[] args) { // valid declaration, both arrays are // one dimensional array. int a[], b[]; // invalid declaration int c[], [] d; // invalid declaration int[] e, [] f; }} When we are declaring multiple variable of same time at a time, we have to write variable first then declare that variable except first variable declaration. There is no restriction for the first variable. Now, when we are creating array it is mandatory to pass the size of array; otherwise we will get compile time error.You can use new operator for creating an array. import java.io.*; class GFG { public static void main(String[] args) { // invalid, here size of array is not given int[] a = new int[]; // valid, here creating 'b' array of size 5 int[] b = new int[5]; // valid int[] c = new int[0]; // gives runtime error int[] d = new int[-1]; }} Printing array : /* A complete Java program to demonstrate working of one dimensional arrays */class oneDimensionalArray { public static void main(String args[]) { int[] a; // one dimensional array declaration a = new int[3]; // creating array of size 3 for (int i = 0; i < 3; i++) { a[i] = 100; System.out.println(a[i]); } }} Output: 100 100 100 Two Dimensional Array Suppose, you want to create two dimensional array of int type data. So you can declare two dimensional array in many of the following ways: // Java program to demonstrate different ways// to create two dimensional array.import java.io.*; class GFG { public static void main(String[] args) { int a[][]; // valid int[][] b; // valid int[][] c; // valid int[] d[]; // valid int[][] e; // valid int[] f[]; // valid [][] int g; // invalid [] int[] h; // invalid }} Now, Suppose we want to write multiple declarations of array variable then you can use it like this. // Java program to demonstrate multiple declarations// of array variableimport java.io.*; class GFG {public static void main(String[] args) { // Here, 'a' is two dimensional array, 'b' // is two dimensional array int[] a[], b[]; // Here, 'c' is two dimensional array, 'd' // is two dimensional array int[] c[], d[]; // Here, 'e' is two dimensional array, 'f' // is three dimensional array int[][] e, f[]; // Here, 'g' is two dimensional array, // 'h' is one dimensional array int[] g[], h; }} Creating one dimensional array and two dimensional array without new operator: /* Java program for one and two dimensional arrays. without new operator*/class oneTwoDimensionalArray { public static void main(String args[]) { int[] a[] = { { 1, 1, 1 }, { 2, 2, 2 }, { 3, 3, 3 } }, b = { 20 }; // print 1D array System.out.println(b[0]); // print 2D array for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { a[i][j] = 100; System.out.println(a[i][j]); } } }} Output: 20 100 100 100 100 100 100 100 100 100 Creating one dimensional array and two dimensional array using new operator: /* Java program for one and two dimensional arrays. using new operator*/class oneTwoDimensionalArray { public static void main(String args[]) { int[] a[], b = { 20 }; a = new int[3][3]; b = new int[3]; // print 1D array for (int i = 0; i < 3; i++) System.out.println(b[i]); // print 2D array for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { a[i][j] = 100; System.out.println(a[i][j]); } } }} Output: 0 0 0 100 100 100 100 100 100 100 100 100 This article is contributed by Twinkle Patel. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Java-Arrays Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Different ways of Reading a text file in Java Constructors in Java Exceptions in Java Functional Interfaces in Java Generics in Java Comparator Interface in Java with Examples HashMap get() Method in Java Introduction to Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23973, "s": 23945, "text": "\n21 Aug, 2017" }, { "code": null, "e": 24003, "s": 23973, "text": "Arrays in Java | Introduction" }, { "code": null, "e": 24027, "s": 24003, "text": "One Dimensional Array :" }, { "code": null, "e":...
An example of overfitting and how to avoid it | by Gianluca Malato | Towards Data Science
Overfitting is a tremendous enemy for a data scientist trying to train a supervised model. It will affect performances in a dramatic way and the results can be very dangerous in a production environment. But what is overfitting exactly? In this article, I explain how to identify and avoid it. Overfitting occurs when your model learns too much from training data and isn’t able to generalize the underlying information. When this happens, the model is able to describe training data very accurately but loses precision on every dataset it has not been trained on. This is completely bad because we want our model to be reasonably good on data that it has never seen before. In machine learning, simplicity is the key. We want to generalize the information obtained from the training dataset, so we can surely say that we run the risk of overfitting if we use complex models. Complex models will likely over-learn from training data and will think that the random error that drifts training data from the underlying dynamics is actually worth learning from. That’s the exact point at which the model stops generalizing and starts overfitting. Complexity is often measured with the number of parameters used by your model during it’s learning procedure. For example, the number of parameters in linear regression, the number of neurons in a neural network, and so on. So, the lower the number of the parameters, the higher the simplicity and, reasonably, the lower the risk of overfitting. Let’s make a simple example with the help of some Python code. I’m going to create a set of 20 points that follow the formula: Each point will be added a normally distributed error with 0 mean and 0.05 standard deviation. In real-life data science, data always drifts from the “real” model by a random error. Once we have created this dataset, we are going to fit a polynomial model of higher and higher degree and see what happens both in the training set and in the test set. In real life, we don’t know the real model inside our dataset, so we must try different models and see which one fits better. We’ll take the first 12 points as the training set and the last 8 points as the test set. First, let’s import some useful libraries: import numpy as npimport matplotlib.pyplot as pltfrom sklearn.metrics import mean_squared_error Let’s now create the sample points: np.random.seed(0)x = np.arange(-1,1,0.1)y = -x**2 + np.random.normal(0,0.05,len(x))plt.scatter(x,y)plt.xlabel("x")plt.ylabel("y")plt.show() As you can see, there’s actually a little noise, just like in real-life fitting. Now, let’s split this dataset into training and test. X_train = x[0:12]y_train = y[0:12]X_test = x[12:]y_test = y[12:] We can now define a simple function that, given the training set and the degree of a polynomial, returns a function that represents the mathematical expression of the polynomial that best fits training data. def polynomial_fit(degree = 1): return np.poly1d(np.polyfit(X_train,y_train,degree)) Let’s now define another function that plots the dataset and the best fitting polynomial with a specific degree. def plot_polyfit(degree = 1): p = polynomial_fit(degree) plt.scatter(X_train,y_train,label="Training set") plt.scatter(X_test,y_test,label="Test set") curve_x = np.arange(min(x),max(x),0.01) plt.plot(curve_x,p(curve_x),label="Polynomial of degree {}".format(degree)) plt.xlim((-1,1)) plt.ylim((-1,np.max(y)+0.1)) plt.legend() plt.plot() Now, let’s see what happens with a polynomial of degree 1 plot_polyfit(1) As you can see, a polynomial of degree 1 fits training data better than test data, though it could fit better. We could say that the model is not learning properly from training, so it’s not good. Let’s see what happens in the opposite case, which is a very high degree polynomial. Here’s what happens with a polynomial of degree 7. Now the polynomial fits better the training points but it’s completely wrong about the test points. A higher degree seems to get us closer to overfitting training data and to low accuracy on test data. Remember that the higher the degree of a polynomial, the higher the number of parameters involved in the learning process, so a high-degree polynomial is a more complex model than a low-degree one. Let’s now see the overfitting explicitly. We have 12 training points and it’s easy to prove that the overfitting can be created with a polynomial of degree 11. It’s called Lagrange polynomial. Now it’s clear what happens. The polynomial fits training data perfectly but loses precision on the test set. It doesn’t even get close to test points. So, the higher the degree of the polynomial, the higher the interpolation precision on training data and the lower the performance on test data. The keyword is “interpolation”. We actually don’t want to interpolate our data, because doing so will make us fit the errors like they were useful data. We don’t want to learn from errors, we want to know the model which is inside errors. That’s why a perfect fit will make a very bad model on unseen data that follow the same dynamics of training data. How can we find the right degree of the polynomial? Here comes cross-validation. Since we want our model to perform well on unseen data, we can measure the Root Mean Squared Error of our polynomial with respect to the test data and choose the degree that minimizes this measure. With this simple code, we loop through all degrees and calculate RMSE for training and test sets. results = []for i in range(1,len(X_train)-1): p = polynomial_fit(i) rmse_training = np.sqrt(mean_squared_error(y_train,p(X_train))) rmse_test = np.sqrt(mean_squared_error(y_test,p(X_test))) results.append({'degree':i, 'rmse_training':rmse_training,'rmse_test':rmse_test})plt.scatter([x['degree'] for x in results],[x['rmse_training'] for x in results],label="RMSE on training")plt.scatter([x['degree'] for x in results],[x['rmse_test'] for x in results],label="RMSE on test")plt.yscale("log")plt.xlabel("Polynomial degree")plt.ylabel("RMSE")plt.legend()plt.show() Let’s see the results in the following plot: As you can see, we get the lower value of test set RMSE if we choose a polynomial of degree 2, which is the model our data is sampled from. We can now take a look at such a model and find out that it’s actually pretty good at describing both training and test data. So, if we want to generalize the underlying phenomena that gave birth to our data, we must cross-validate our model on a dataset it hasn’t been trained on. Only in this way we can be safer about overfitting. In this simple example, we have seen how overfitting affects model performance and how dangerous it can be if we don’t pay enough attention to cross-validation. Although there are training techniques that are very helpful when it comes to avoiding overfitting (like bagging), we always need to double-check our model in order to make sure it has been trained properly.
[ { "code": null, "e": 251, "s": 47, "text": "Overfitting is a tremendous enemy for a data scientist trying to train a supervised model. It will affect performances in a dramatic way and the results can be very dangerous in a production environment." }, { "code": null, "e": 341, "s": 2...
How to Create a Rating Visual in Power BI using DAX | by Nikola Ilic | Towards Data Science
In my previous article, I’ve explained how you can display images and icons on the axis and in the slicers, leveraging a very simple technique using UNICHAR() DAX function. Now, I wish to expand on that, and show how you can create ratings visual using simple DAX! Let me be immodest and say — using this trick you can freely say that you create your own custom visual! As in my previous post, I’ll use a dataset related to support agent interactions with the customers — as a reminder, agents communicate with the customers via chats, emails, and phone calls, and after the interaction is completed, customer can fill the survey and express her/his opinion. The customer is being asked to answer three questions: Resolution — was my problem resolved by the support agent? Satisfaction — am I satisfied with the resolution? Recommendation — would I recommend the company’s services to others? I’ll use the same dataset as previously, but focusing on survey results only. Here is the raw data imported in Power BI: Let’s first try to get some insight from this dataset — for example, how many customers were satisfied with the service, and how many of them would recommend the company’s services. I’ll go and create three measures that will count surveys with a positive response: Resolution YES = CALCULATE( COUNT(Surveys[Interaction ID]), Surveys[Resolution] = "Y" )Satisfaction YES = CALCULATE( COUNT(Surveys[Interaction ID]), Surveys[Satisfaction] = "Y" )Recommendation YES = CALCULATE( COUNT(Surveys[Interaction ID]), Surveys[Recommendation] = "Y" ) And if I drag these measures to my report, I can get some, at least basic, insight into the customer’s satisfaction: Not bad, but the first question that business will ask is: what percentage of customers were satisfied with our service? So, let’s go and create measures to calculate percentages of positive answers: Resolution % = DIVIDE([Resolution YES], [Total Surveys],0)Satisfaction % = DIVIDE([Satisfaction YES], [Total Surveys],0)Recommendation % = DIVIDE([Recommendation YES], [Total Surveys],0) Don’t forget to format these measures as Percentage:) And, after I’ve formatted my table, the report looks really nice: Ok, that serves the purpose, and report consumers can quickly see the percentage of satisfied customers. However, what if I want them to “feel” the rating experience — you know those nice stars on Amazon, Netflix, etc. showing you the ratings of the product. Power BI doesn’t offer ratings visual out-of-the-box. You can grab it from the App Source Marketplace (at least it existed there previously, I guess it’s still available), but... What if I tell you that you can create a ratings visual yourself by writing some simple DAX?! Let’s pull up our sleeves and start working on it. The idea is to display percentages as the stars in our report. Last time, we’ve created a column of icons, containing their Unicode values, as placeholders. This time, we want to build a measure, to express the numbers behind our customers’ satisfaction. Again, we will take advantage of UNICHAR() function, but in a slightly different manner. Here is how it should work: for each decade of a percentage value, I want to show one star — simply said, if the percentage value is, let’s say, 63%, I will show 6 stars...If the value is 72%, I’ll display 7 starts, and so on. Let me show you how can we achieve this. Percentages in my table are nothing more than decimal numbers, represented as a percentage. That means, 63.01% is essentially 0.63 (if we cut it to two decimal places), 58.93% is 0.59, etc. Now, I will duplicate these measures, but I’ll leave them formatted as decimal numbers: My table now shows both decimal values and percentages of the customer’s responses. I will now use UNICHAR() function to show the star symbol in my table. But, in order to display the proper number of stars — remember, 53% is 5 stars, 63% is 6 stars, etc. — I’ll have to perform some modifications on my measure. I will multiply the result by 10, so 0.78 will become 7.8, 0.56 will become 5.6, and so on. Then, I can retrieve the whole number value from the result and set the appearance of the star symbol! Resolution % Decimal Multiplied = [Resolution % Decimal] * 10 I will now use REPT() DAX function, which basically repeats the defined text, as many times as you specify in the second argument of this function. In my case, I wrote my measure like this: Stars v1 = REPT(UNICHAR(11088),[Resolution % Decimal Multiplied]) Let me stop for a second and explain what is so special about this measure: it will repeat the first argument, which is unichar representation of the Unicode value 11088, times of the number of decades in our percentage value. How cool is that! As you see, the function was “smart” enough to round a number of stars as you would expect — therefore, 77.66% is represented as 8 stars, while 58.33% and 56.21% are displayed with 6 stars. That was really awesome! But, what if I want to enable my users to immediately spot the ratings, without needing to count the stars. In other words, I want to display the maximum available value (which is 10 stars in our case), and then, depending on the percentages, some stars will stay empty. To simplify, if the percentage value is 77.66%, I want to display 8 yellow stars and 2 empty stars (same as Amazon, hehe). Let’s go and write our final measure: Stars v2 = [Stars v1]&(REPT(UNICHAR(10025),10-[Resolution % Decimal Multiplied])) So, what do we have here: the first part of the measure is exactly the same, as we want to display our positive stars. But, then, the magic happens: as REPT() function works with text values, we can simply concatenate the other part — and, in this part, we are displaying unichar symbol of the Unicode value 10025 (empty star), and then we want to repeat it as many times as it is the value of subtraction between 10 (which is the max value of the stars) and the number of our “positive” stars — so this remaining number of times will show the empty star symbol. Pretty awesome, isn’t it? As you may conclude looking at the illustration above, we’ve managed to do it! We created a custom visual for displaying ratings, using DAX only. I will repeat again: Power BI is an awesome tool, because it gives you the amazing amount of flexibility to tell your data story in multiple different ways. With little creativity and simple tweaking here and there, you can create an unforgettable experience for your users. In this article, I’ve shown you how you can achieve (im)possible and create your own custom visual by writing a few lines of DAX code! Thanks for reading! Become a member and read every story on Medium!
[ { "code": null, "e": 417, "s": 47, "text": "In my previous article, I’ve explained how you can display images and icons on the axis and in the slicers, leveraging a very simple technique using UNICHAR() DAX function. Now, I wish to expand on that, and show how you can create ratings visual using sim...
Python | Count occurrences of each word in given text file (Using dictionary)
08 Jun, 2022 Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the word is already present in the dictionary we increment its count by 1. Example #1: First we create a text file in which we want to count the words. Let this file be sample.txt with the following contents: Mango banana apple pear Banana grapes strawberry Apple pear mango banana Kiwi apple mango strawberry Note: Make sure the text file is in the same directory as the Python file. Python3 # Open the file in read modetext = open( & quot sample.txt", & quot r" ) # Create an empty dictionaryd = dict() # Loop through each line of the filefor line in text: # Remove the leading spaces and newline character line = line.strip() # Convert the characters in line to # lowercase to avoid case mismatch line = line.lower() # Split the line into words words = line.split( & quot & quot ) # Iterate over each word in line for word in words: # Check if the word is already in dictionary if word in d: # Increment count of word by 1 d[word] = d[word] + 1 else: # Add the word to dictionary with count 1 d[word] = 1 # Print the contents of dictionaryfor key in list(d.keys()): print(key, & quot: & quot, d[key]) Output: mango : 3 banana : 3 apple : 3 pear : 2 grapes : 1 strawberry : 2 kiwi : 1 Example #2: Consider a file sample.txt that has sentences with punctuation. Mango! banana apple pear. Banana, grapes strawberry. Apple- pear mango banana. Kiwi "apple" mango strawberry. Python3 import string # Open the file in read modetext = open(& quot sample.txt", & quot r" ) # Create an empty dictionaryd = dict() # Loop through each line of the filefor line in text: # Remove the leading spaces and newline character line = line.strip() # Convert the characters in line to # lowercase to avoid case mismatch line = line.lower() # Remove the punctuation marks from the line line = line.translate(line.maketrans(& quot & quot , & quot & quot, string.punctuation)) # Split the line into words words = line.split(& quot & quot ) # Iterate over each word in line for word in words: # Check if the word is already in dictionary if word in d: # Increment count of word by 1 d[word] = d[word] + 1 else: # Add the word to dictionary with count 1 d[word] = 1 # Print the contents of dictionaryfor key in list(d.keys()): print(key, & quot: & quot, d[key]) Output: mango : 3 banana : 3 apple : 3 pear : 2 grapes : 1 strawberry : 2 kiwi : 1 adedireadedapo19 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jun, 2022" }, { "code": null, "e": 425, "s": 54, "text": "Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count...
Android | Creating a Splash Screen
23 Jul, 2018 A splash screen is mostly the first screen of the app when it is opened. It is a constant screen which appears for a specific amount of time, generally shows for the first time when the app is launched. The Splash screen is used to display some basic introductory information such as the company logo, content, etc just before the app loads completely. Creating Splash screen using handler in Android Here we created two activities MainActivity showing the Splash Screen and SecondActivity in order to switch from MainActivity to SecondActivity. The main program is written in MainActivity, you can change activities as per your need. To remove the ActionBar, you need to make following changes in your styles.xml file.style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar" ... style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar" ... Use colors which is suitable for your application. No need to make any changes in your manifest file. Using the ‘postDelayed()’ function: public final boolean postDelayed(Runnable Object token, long delayMillisec) This function delays the process for a specified time. This is used with a handler which allows you to send and process Message and Runnable objects associated with a Thread’s MessageQueue. Each handler instance is a single thread. Below is the code for creating the splash screen: MainActivity.java package com.example.hp.splashscreen; import android.content.Intent;import android.os.Handler;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.WindowManager; public class MainActivity extends AppCompatActivity { private static int SPLASH_SCREEN_TIME_OUT=2000; #After completion of 2000 ms, the next activity will get started. @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //This method is used so that your splash activity //can cover the entire screen. setContentView(R.layout.activity_main); //this will bind your MainActivity.class file with activity_main. new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i=new Intent(MainActivity.this, SecondActivity.class); //Intent is used to switch from one activity to another. startActivity(i); //invoke the SecondActivity. finish(); //the current activity will get finished. } }, SPLASH_SCREEN_TIME_OUT); }} activity_main.xml: You can use any image for the splash screen and first paste it into the drawable folder. XML file is easy to generate by drag and drop approach, just use imageview and select the appropriate image. <?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.hp.splashscreen.MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="250dp" android:layout_height="200dp" app:srcCompat="@drawable/geeks" app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp" android:layout_marginRight="8dp" app:layout_constraintRight_toRightOf="parent" android:layout_marginLeft="8dp" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="8dp" app:layout_constraintVertical_bias="0.447" /></android.support.constraint.ConstraintLayout> Output: android Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Multidimensional Arrays in Java Set in Java Initializing a List in Java Collections in Java Stream In Java
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jul, 2018" }, { "code": null, "e": 405, "s": 52, "text": "A splash screen is mostly the first screen of the app when it is opened. It is a constant screen which appears for a specific amount of time, generally shows for the first ti...
Find Simple Closed Path for a given set of points
13 Jul, 2022 Given a set of points, connect the dots without crossing. Example: Input: points[] = {(0, 3), (1, 1), (2, 2), (4, 4), (0, 0), (1, 2), (3, 1}, {3, 3}}; Output: Connecting points in following order would not cause any crossing {(0, 0), (3, 1), (1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (0, 3)} We strongly recommend you to minimize your browser and try this yourself first.The idea is to use sorting. Find the bottom-most point by comparing y coordinate of all points. If there are two points with same y value, then the point with smaller x coordinate value is considered. Put the bottom-most point at first position. Consider the remaining n-1 points and sort them by polor angle in counterclockwise order around points[0]. If polor angle of two points is same, then put the nearest point first. Traversing the sorted array (sorted in increasing order of angle) yields simple closed path. How to compute angles? One solution is to use trigonometric functions. Observation: We don’t care about the actual values of the angles. We just want to sort by angle. Idea: Use the orientation to compare angles without actually computing them! Below is C++ implementation of above idea. C++ // A C++ program to find simple closed path for n points// for explanation of orientation()#include <bits/stdc++.h>using namespace std; struct Point{ int x, y;}; // A global point needed for sorting points with reference// to the first point. Used in compare function of qsort()Point p0; // A utility function to swap two pointsint swap(Point &p1, Point &p2){ Point temp = p1; p1 = p2; p2 = temp;} // A utility function to return square of distance between// p1 and p2int dist(Point p1, Point p2){ return (p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y);} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwiseint orientation(Point p, Point q, Point r){ int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clockwise or counterclock wise} // A function used by library function qsort() to sort// an array of points with respect to the first pointint compare(const void *vp1, const void *vp2){ Point *p1 = (Point *)vp1; Point *p2 = (Point *)vp2; // Find orientation int o = orientation(p0, *p1, *p2); if (o == 0) return (dist(p0, *p2) >= dist(p0, *p1))? -1 : 1; return (o == 2)? -1: 1;} // Prints simple closed path for a set of n points.void printClosedPath(Point points[], int n){ // Find the bottommost point int ymin = points[0].y, min = 0; for (int i = 1; i < n; i++) { int y = points[i].y; // Pick the bottom-most. In case of tie, chose the // left most point if ((y < ymin) || (ymin == y && points[i].x < points[min].x)) ymin = points[i].y, min = i; } // Place the bottom-most point at first position swap(points[0], points[min]); // Sort n-1 points with respect to the first point. // A point p1 comes before p2 in sorted output if p2 // has larger polar angle (in counterclockwise // direction) than p1 p0 = points[0]; qsort(&points[1], n-1, sizeof(Point), compare); // Now stack has the output points, print contents // of stack for (int i=0; i<n; i++) cout << "(" << points[i].x << ", " << points[i].y <<"), ";} // Driver program to test above functionsint main(){ Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}}; int n = sizeof(points)/sizeof(points[0]); printClosedPath(points, n); return 0;} Output: (0, 0), (3, 1), (1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (0, 3), Time complexity of above solution is O(n Log n) if we use a O(nLogn) sorting algorithm for sorting points.Auxiliary Space: O(1), since no extra space has been taken. Source: http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdfThis article is contributed by Aarti_Rathi and Rajeev Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Code_Mech sagar0719kumar _shinchancode rishav1329 Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jul, 2022" }, { "code": null, "e": 112, "s": 52, "text": "Given a set of points, connect the dots without crossing. " }, { "code": null, "e": 122, "s": 112, "text": "Example: " }, { "code": null, "e"...
return command in Linux with examples
24 May, 2019 return command is used to exit from a shell function. It takes a parameter [N], if N is mentioned then it returns [N] and if N is not mentioned then it returns the status of the last command executed within the function or script. N can only be a numeric value. Syntax: return [N] Example: Note: echo $? is used to display the last return status. Option: return –help : It displays help information. linux-command Linux-Shell-Commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 May, 2019" }, { "code": null, "e": 316, "s": 54, "text": "return command is used to exit from a shell function. It takes a parameter [N], if N is mentioned then it returns [N] and if N is not mentioned then it returns the status of ...
HTML Course | Structure of an HTML Document
06 Jul, 2022 INTRODUCTION As we all know HTML is a language of the web. It’s used to design the web pages or we can say structure the page layouts of a website. HTML stands for HYPERTEXT MARKUP LANGUAGE, as its full form suggests it’s not any programming language, a markup language. So, while the execution of HTML code we can’t face any such error. In real HTML code wasn’t compiled or interpreted because HTML code was rendered by the browser. which is similar to the compilation of a program. Html content is parched through the browser to display the content of HTML. Course Navigation HTML DOCUMENTS STRUCTURE Html used predefined tags and attributes to tell the browser how to display content, means in which format, style, font size, and images to display. Html is a case insensitive language. Case insensitive means there is no difference in upper case and lower case ( capital and small letters) both treated as the same, for r example ‘D’ and ‘d’ both are the same here. There are generally two types of tags in HTML: Paired Tags: These tags come in pairs. That is they have both opening(< >) and closing(</ >) tags.Empty Tags: These tags do not require to be closed. Paired Tags: These tags come in pairs. That is they have both opening(< >) and closing(</ >) tags. Empty Tags: These tags do not require to be closed. Below is an example of a (<b>) tag in HTML, which tells the browser to bold the text inside it. Tags and attributes: Tags are individuals of html structure, we have to open and close any tag with a forward slash like this <h1> </h1>. There are some variations with the tag some of them are self-closing tag which isn’t required to close and some are empty tag where we can add any attributes in it. Attributes are additional properties of html tags that define the property of any html tags. i.e. width, height, controls, loops, input, and autoplay. These attributes also help us to store information in meta tags by using name, content, and type attributes. Html documents structured mentioned below: An HTML Document is mainly divided into two parts: HEAD: This contains the information about the HTML document. For Example, the Title of the page, version of HTML, Meta Data, etc. BODY: This contains everything you want to display on the Web Page. HTML Document Structure Let us now have a look at the basic structure of HTML. That is the code that is a must for every webpage to have: HTML <!DOCTYPE html> <!-- Defines types of documents : Html 5.O --><!DOCTYPE html><!-- Defines types of documents : Html 5.O --><html lang="en"> <!-- DEfines languages of content : English --> <head> <!-- Information about website and creator --> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Defines the compatibility of version with browser --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- for make website responsive --> <meta name="author" content="Mr.X"> <meta name="Linkedin profile" content="WWW.linkedin.com/Mr.X_123" > <!-- To give information about author or owner --> <meta name="description " content="A better place to learn computer science"> <!-- to explain about website in few words --> <title>GeeksforGeeks</title> <!-- Name of website or content to display --></head><body> <!-- Main content of website --> <h1>GeeksforGeeks</h1><p>A computer science portal for geeks</p></body></html> Every Webpage must contain this code. Below is the complete explanation of each of the tags used in the above piece of HTML code:<!DOCTYPE html>: This tag is used to tells the HTML version. This currently tells that the version is HTML 5.0 <html> </html> : <html> is a root element of html. It’s a biggest and main element in complete html language, all the tags , elements and attributes enclosed in it or we can say wrap init , which is used to structure a web page. <html> tag is parent tag of <head> and <body> tag , other tags enclosed within <head > and <body>. In <html > tag we use “lang” attributes to define languages of html page such as <html lang=”en”> here en represents English language. some of them are : es = Spanish , zh-Hans = Chinese, fr= french and el= Greek etc.<head>: Head tag contains metadata, title, page CSS etc. Data stored in the <head> tag is not displayed to the user, it is just written for reference purposes and as a watermark of the owner. Note: for better understanding refer above code of html. <title> = to store website name or content to be displayed. <link> = To add/ link css( cascading style sheet) file. <meta> = 1. to store data about website, organisation , creator/ owner 2. for responsive website via attributes 3. to tell compatibility of html with browser <script> = to add javascript file. <body>: A body tag is used to enclose all the data which a web page has from texts to links. All the content that you see rendered in the browser is contained within this element. Following tags and elements used in the body. 1 . <h1> ,<h2> ,<h3> to <h6> 2. <p> 3. <div> and <span> 4. <b>, <i> and<u> 5. <li>,<ul>and<ol>. 6. <img> , <audio> , <video> and<iframe> 7. <table> <th> , <thead>and<tr>. 8. <form> 9. <label> and <input> others..........To learn more about an HTML Document structure, please visit: https://www.geeksforgeeks.org/html-introduction/ HTML is the foundation of web pages, and is used for webpage development by structuring websites and web apps. You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. 3daleks ghoshsuman0129 hardikkoriintern uditsharma333jj Kanchan_Ray bhawnachelani123 sumitgumber28 sagar0719kumar rkbhola5 varshagumber28 HTML-Basics HTML-course-basic CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 65, "s": 52, "text": "INTRODUCTION" }, { "code": null, "e": 614, "s": 65, "text": "As we all know HTML is a language of the web. It’s used to design the web pages or we can say ...
Python | Relative Layout in Kivy
09 Dec, 2021 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial – Learn Kivy with Examples. Relative layout is just similar to the FloatLayout the difference is that its child widget are positioned relative to the layout. This layout operates in the same way as FloatLayout does, but the positioning properties (x, y, center_x, right, y, center_y, and top) are relative to the Layout size and not the window size. In reality, regardless of absolute and relative positioning, the widgets are moved when the position of the layout changes. When the widget with position=(0, 0) is added to RelativeLayout, Now if the position of RelativeLayout is changed the child widget will also move. The Child widget coordinates remains same i.e (0, 0) as they are always relative to the parent layout. The available pos_hint keys (x, center_x, right, y, center_y, and top) are useful for aligning to edges or centering. For example: pos_hint: {‘center_x’:.5, ‘center_y’:.5} would align a Widget in the middle, no matter what the size of the window is. The first thing we need to do to use a RelativeLayout is to import it. from kivy.uix.relativelayout import RelativeLayout Note: This layout allows you to set relative coordinates for children. If you want absolute positioning, use the FloatLayout. In RelativeLayout each child widget size and position has to be given. This also does the dynamic placement. We can do relative positioning by: pos_hint: provide hint of position We can define upto 8 keys i.e. it takes arguments in form of dictionary. pos_hint = {“x”:1, “y”:1, “left”:1, “right”:1, "center_x":1, "center_y":1, “top”:1, “bottom”:1("top":0)} Note: Floatlayout and RelativeLayout both support absolute and relative positioning depending upon whether pos_hint or pos is used. But If you want absolute positioning, use the FloatLayout. Basic Approach to create Relative Layout: 1) import kivy 2) import kivyApp 3) import button 4) import Relativelayout 5) Set minimum version(optional) 6) create App class: - define build() function 7) return Layout/widget/Class(according to requirement) 8) Run an instance of the class Implementation of approach using pos : It simply assigns the position to the button. As Relativelayout does not depends on the window size it gets fixed to that position now if you do the window size small it may disappear rather than adjusting itself. Python3 # Sample Python application demonstrating the# working of RelativeLayout in Kivy # import modulesimport kivy # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # This layout allows you to set relative coordinates for children.from kivy.uix.relativelayout import RelativeLayout # To change the kivy default settings# we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # creating the App classclass MyApp(App): def build(self): # creating Relativelayout Rl = RelativeLayout() # creating button # a button 30 % of the width and 20 % # of the height of the layout and # positioned at (x, y), you can do # The position does not depend on window size # it just positioned at the given places: btn = Button(text ='Hello world', size_hint =(.2, .2), pos =(396.0, 298.0)) btn1 = Button(text ='Hello world !!!!!!!!!', size_hint =(.2, .2), pos =(-137.33, 298.0)) # adding widget i.e button Rl.add_widget(btn) Rl.add_widget(btn1) # return the layout return Rl # run the Appif __name__ == "__main__": MyApp().run() Output: Now if you want that the button adjusts itself according to window pos_hint is used. Implementation Approach by using pos_hint Python3 # Sample Python application demonstrating the# working of RelativeLayout in Kivy # import modulesimport kivy # base Class of your App inherits from the App class.# app:always refers to the instance of your applicationfrom kivy.app import App # creates the button in kivy# if not imported shows the errorfrom kivy.uix.button import Button # This layout allows you to set relative coordinates for children.from kivy.uix.relativelayout import RelativeLayout # To change the kivy default settings# we use this module configfrom kivy.config import Config # 0 being off 1 being on as in true / false# you can use 0 or 1 && True or FalseConfig.set('graphics', 'resizable', True) # creating the App classclass Relative_Layout(App): def build(self): # creating Relativelayout rl = RelativeLayout() # creating button # size of button is 20 % by height and width of layout # position is bottom left i.e x = 0, y = 0 b1 = Button(size_hint =(.2, .2), pos_hint ={'x':0, 'y':0}, text ="B1") # position is bottom right i.e right = 1, y = 0 b2 = Button(size_hint =(.2, .2), pos_hint ={'right':1, 'y':0}, text ="B2") b3 = Button(size_hint =(.2, .2), pos_hint ={'center_x':.5, 'center_y':.5}, text ="B3") b4 = Button(size_hint =(.2, .2), pos_hint ={'x':0, 'top':1}, text ="B4") b5 = Button(size_hint =(.2, .2), pos_hint ={'right':1, 'top':1}, text ="B5") # adding button to widget rl.add_widget(b1) rl.add_widget(b2) rl.add_widget(b3) rl.add_widget(b4) rl.add_widget(b5) # returning widget return rl# run the Appif __name__ == "__main__": Relative_Layout().run() Output: surindertarika1234 Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Dec, 2021" }, { "code": null, "e": 264, "s": 28, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux and Windows, etc. It is basically used to develop the Android application, but it do...
JavaScript Array pop() Method
01 Nov, 2021 Below is the example of Array pop() method. Example:<script> function func() { var arr = ['GFG', 'gfg', 'g4g', 'GeeksforGeeks']; // Popping the last element from the array document.write(arr.pop()); } func();</script> <script> function func() { var arr = ['GFG', 'gfg', 'g4g', 'GeeksforGeeks']; // Popping the last element from the array document.write(arr.pop()); } func();</script> Output:GeeksforGeeks GeeksforGeeks The arr.pop() method is used to remove the last element of the array and also returns the removed element. This function decreases the length of the array by 1. Syntax: arr.pop() Parameters: This method does not accept any parameter. Return value This method returns the removed element array. If the array is empty, then this function returns undefined. Below examples illustrate the JavaScript Array pop() method: Example 1: In this example the pop() method removes the last element from the array, which is 4 and returns it.var arr = [34, 234, 567, 4]; var popped = arr.pop(); print(popped); print(arr); Output:4 34,234,567 var arr = [34, 234, 567, 4]; var popped = arr.pop(); print(popped); print(arr); Output: 4 34,234,567 Example 2: In this example the function pop() tries to extract the last element of the array but since the array is empty therefore it returns undefined as the answer.var arr = []; var popped = arr.pop(); print(popped); Output:undefined var arr = []; var popped = arr.pop(); print(popped); Output: undefined More example codes for the above method are as follows: Program 1: <script>function func() { var arr = [34, 234, 567, 4]; // Popping the last element from the array var popped = arr.pop(); document.write(popped); document.write("<br>"); document.write(arr);}func();</script> Output: 4 34,234,567 Program 2: <script>function func() { var arr = []; // popping the last element var popped = arr.pop(); document.write(popped);}func();</script> Output: undefined Supported Browsers: The browsers supported by JavaScript Array pop() method are listed below: Google Chrome 1.0 and above Microsoft Edge 12 and above Mozilla Firefox 1.0 and above Safari 1 and above Opera 4 and above ysachin2314 javascript-array JavaScript-Methods JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2021" }, { "code": null, "e": 72, "s": 28, "text": "Below is the example of Array pop() method." }, { "code": null, "e": 309, "s": 72, "text": "Example:<script> function func() { var arr = ['GFG', '...
React animated loading/splash screen using ‘react-spinners’
30 Jun, 2021 Displaying a loading or splash screen during response time from the server is an excellent way to interact with the user. But making a loading/splash screen becomes difficult when we want to practically use an animated loader, where we need to make extra efforts to write down its styling file. To overcome this problem, we use a bunch of predefined loaders from the react-spinners module. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm i react-spinners Step 3: After creating the ReactJS application, Install the required module using the following command: npm i react-spinners Project Structure: It will look like the following. Project Structure Approach: Step 1: We will write our code in App.js, no need to make any other components for this project. For using the predefined spinners we need to import the ‘loader‘ component from ‘react-spinners‘. Step 2: Also we need useState to add a state to our functional component and useEffect is also needed. what we need to import Step 3: Add a state isLoading which will indicate that our page is loading or not. Step 4: Add a setTimeout() inside useEffect to make the splash screen appear for a certain time period. Step 5: Lastly we can use a custom CSS block to override its property and use it when isLoading is true i.e page is still loading. Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React, { useState, useEffect } from 'react'; // Importing loaderimport PacmanLoader from "react-spinners/PacmanLoader";import ClockLoader from "react-spinners/ClockLoader";import './App.css'; const App = () => { // Loading state const [isLoading, setIsLoading] = useState(true); useEffect(() => { // Wait for 3 seconds setTimeout(() => { setIsLoading(false); }, 3000); }, []); // Custom css for loader const override = ` display: block; margin: 0 auto; border-color: red;`; return isLoading ? // If page is still loading then splash screen <PacmanLoader color={'#36D7B7'} isLoading={isLoading} css={override} size={150} /> : <h1 className="App"> This is Main Page {<ClockLoader color={'#36D7B7'} isLoading={isLoading} css={override} size={150} />} </h1>} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://www.npmjs.com/package/react-spinners https://www.davidhu.io/react-spinners/ React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2021" }, { "code": null, "e": 442, "s": 52, "text": "Displaying a loading or splash screen during response time from the server is an excellent way to interact with the user. But making a loading/splash screen becomes difficult...
Introduction to Data Compression
27 Jul, 2021 In this article, we will discuss the overview of Data Compression and will discuss its method illustration, and also will cover the overview part entropy. Let’s discuss it one by one. Overview :One important area of research is data compression. It deals with the art and science of storing information in a compact form. One would have noticed that many compression packages are used to compress files. Compression reduces the cost of storage, increases the speed of algorithms, and reduces the transmission cost. Compression is achieved by removing redundancy, that is repetition of unnecessary data. Coding redundancy refers to the redundant data caused due to suboptimal coding techniques. Method illustration : To illustrate this method let’s assume that there are six symbols, and binary code is used to assign a unique address to each of these symbols, as shown in the following table Binary code requires at least three bits to encode six symbols. It can also be observed that binary codes 110 and 111 are not used at all. This clearly shows that binary code is not efficient, and hence an efficient code is required to assign a unique address. An efficient code is one that uses a minimum number of bits for representing any information. The disadvantage of binary code is that it is fixed code; a Huffman code is better, as it is a variable code. Coding techniques are related to the concepts of entropy and information content, which are studied as a subject called information theory. Information theory also deals with uncertainty present in a message is called the information content. The information content is given as log2 (1/pi) or -log2 pi . Entropy : Entropy is defined as a measure of orderliness that is present in the information. It is given as follows: H= - ∑ pi log2 pi Entropy is a positive quantity and specifies the minimum number of bits necessary to encode information. Thus, coding redundancy is given as the difference between the average number of bits used for coding and entropy. coding redundancy = Average number of bits - Entropy By removing redundancy, any information can be stored in a compact manner. This is the basis of data compression. Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) GSM in Wireless Communication Secure Socket Layer (SSL) Introduction of Mobile Ad hoc Network (MANET) Difference between MANET and VANET Difference between FDMA, TDMA and CDMA Advanced Encryption Standard (AES) Dynamic Host Configuration Protocol (DHCP) Difference between Virus, Worm and Trojan Horse
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jul, 2021" }, { "code": null, "e": 237, "s": 52, "text": "In this article, we will discuss the overview of Data Compression and will discuss its method illustration, and also will cover the overview part entropy. Let’s discuss it on...
Time Series analysis on multivariate data in Tensorflow | by Killol Govani | Towards Data Science
In layman’s term, a time series analysis deals with time-series data mostly used to forecast future values from its past values. The application could range from predicting prices of stock, a commodity like crude oil, sales of a product like a car, FMCG product like shampoo, to predicting Air Quality Index of a particular region. A time series can be classified into univariate and multivariate time series. A univariate time series data consists of only single observation recorded over time, while a multivariate time series consists of more than one observation, related to our subject of interest. The focus of this article will be on multivariate data. For performing Time Series analysis, we require data to build our model; for which we will refer to the publicly available datasets from kaggle. For this article, we will use the Air Quality Index data for the past five years of major Indian cities, provided in this link. To download the data directly into Google Colab, you can refer to the below links: www.kaggle.com towardsdatascience.com If you have followed the necessary steps, you should see the following files in your downloaded data. We are interested in city_day.csv file. Let us select the required data for the analysis. We will select data for the last two years corresponding to the city of Delhi. The data has 1948 rows and 15 columns including AQI for which we want to build a model. By inspecting the data, we observe that our data contains missing values. Hence we fill the missing values by the mean of each column, drop unnecessary columns, before starting the analysis. Now that we are equipped with the data, let’s move on to the next section. As the name suggests, a time-series data consists of single or multiple observations/variables, which are recorded sequentially in a definite time interval. There are various aspects to time-series data, which we will understand by performing some Exploratory Data Analysis: In Time Series data, seasonality refers to the cyclic variations which occur in the data at a regular interval usually less than a year. Some examples are, peak in retail/e-commerce sales during Christmas, increase in sale of warm clothes during winter, etc. Seasonality can be found out by looking at the graph itself. The code below renders a graph, looking at which we can say that despite several crest and trough, they do not occur at a regular interval and hence the data is not seasonal. In Time Series data, trend refers to the general tendency of the data, whether it is increasing or decreasing over time(long term direction). Looking at the above graph, we can say that the general trend of the data is neither increasing nor decreasing but a constant trend. Irregular or random components are the ones which cannot be predicted. Mostly they are of short duration and non-repeating and occur due to unforeseen events. When the rise and fall pattern exists, but not at a fixed interval then it is known as cyclicity. One example can be to consider the GDP numbers of a country when plotted on a graph versus time, it will see a huge dip during the time of recession like 1929, 2000 and 2008, but these intervals are not fixed. Hence from the above graph, we can say that our data is cyclical. It means the correlation of the present values with its past values. An autocorrelation function measures the degree of similarity of the present series with that of its lagged series (past values). The ACF graph for the AQI index shows spike above the blue region, which is an indication that the series is autocorrelated. Similarly, you can check autocorrelation for other series of the dataset also. A time series is said to be stationary if its corresponding statistical properties like mean, standard deviation and autocorrelation remain constant throughout the time. To check the stationarity of multivariate time series, we perform Johansen cointegration test on the time series which return the eigenvalues in the form of an array. If the eigenvalues are less than one than the series is said to be stationary. Since the values we get are less than one, the series is stationary. Recurrent Neural Networks (RNNs) are a type of Neural Networks that are used to the model sequence of data like time series and natural language. A regular Neural Network takes some information x as input and outputs a value y. The output of one layer is not fed into another layer. RNNs overcome this drawback by looping back the output of one layer into the other layer. This means that RNNs should be able to predict what comes next based on the context of the previous data, but in practice, RNNs solve this problem only when the gap between this context and the prediction is small and performs poorly if this gap becomes vast. Fortunately, Long-Short Term Memory (LSTMs) solve this problem, which is a special type of RNNs. RNNs, as mentioned above, remember every information, in the sequence which leads to the problem of vanishing gradient. During the backpropagation, the gradient becomes so small that the hidden layers learn very less when updated. LSTMs solve this problem while remembering only the relevant information and discarding other information. RNNs have just one activation function while LSTMs have a series activation function and gates through which they perform this task. Now that we have some idea about LSTMs and where they are used, let’s move forward to building our model. So far we have loaded over data into our machines for modelling. Upon some inspection, we see that our data does not contain any NULL or NaN values. As we are performing Time Series Analysis through machine learning modelling, we need to convert our data in the form of dependent (y) and independent variables (X). Here our dependent variable is AQI and rest variables like PM2.5, PM10, NO, NO2..... and so on are the independent variable. We will scale the data to process it faster and removing bias due to the range of data. Now we need to divide, the data into train and test data in the ratio 80:20. Note that since we are performing time series analysis, we cannot divide out data into train and test randomly, as we do while building other machine learning models, otherwise, the model will lode the most important essence, i.e. Time. We will use the Keras API on the top of the Tensorflow library to build our model. Following is a blueprint of our model architecture. model.add(LSTM(hidden_nodes, input_shape=(timesteps, input_dim)))model.add(Dropout(dropout_value))model.compile(loss, optimizer) hidden_nodes: The number of neurons in the hidden layer. We will take 250 neurons Dropout: It is used to reduce the overfitting of the model. Empirically it is set to 20%. Compile: The compile function will take parameters like loss and optimizer. Here we will take Mean Absolute Error as an error metric and Adam as an optimization algorithm. After fitting the model, we will check our model’s performance on the test data. As we normalized our data in the beginning before fitting the model, we will have to reverse scale it to get back values in the original scale. Now that we have our predicted values on the test data set and original test data, let us compare both by calculating the RMSE and plotting them together. Train RMSE: 41.096 Test RMSE: 30.493 It is a good indicator for our model that the RMSE on train and test data does not differ much. Note that you might get different values of RMSE each time you build and run the model. A time series forecasting can be said to be either single-step or multi-step forecasting depending on the number of time steps it is capable to predict in the future. Based on the model trained from our train data, we are predicting the future values for a time frame corresponding to the test data and hence it is multi-step forecasting. Remember the graph of AQI, we saw at the beginning of the article, with the prediction from the model, the graph looks like: In this article, we saw how we can use RNN-LSTM for building a multivariate time series model as they are good at extracting patterns from sequential data. In this article, we saw how we can use RNN-LSTM for building a multivariate time series model as they are good at extracting patterns from sequential data. 2. The time-series data should not be divided into train and test set randomly, as it will lose the most important essence of it i.e. Time. 3. Traditional methods for time series forecasting like ARIMA has its limitation as it can only be used for univariate data and one step forecasting. 4. It is observed in various studies that deep learning models outperform traditional forecasting methods on multivariate time series data. 5. As the provided data contains seasonality, we can further deseasonalize the data so that our model can focus on the underlying signal. You can find the full code for this article here
[ { "code": null, "e": 832, "s": 172, "text": "In layman’s term, a time series analysis deals with time-series data mostly used to forecast future values from its past values. The application could range from predicting prices of stock, a commodity like crude oil, sales of a product like a car, FMCG p...
Menu driven program for Voting System - GeeksforGeeks
18 Mar, 2021 In this article, we will write a menu-driven program to implement the Voting System. The program must contain the following properties: Cast votes. Display the count of votes of each candidate. Display the name of the candidate who has the most votes. Approach: Follow the steps below to solve the problem: Provide the following options to the person who is accessing as shown below:Vote for your favorite Candidate.Check the number of votes of each Candidate.Check the candidate who is leading and then Exit.The user chooses one of the options.If the user chooses 1, then the list of candidates is displayed and the user can now choose from this list of candidates.If the user chooses 2, then the list of candidates along with their current number of votes is displayed.If the user chooses 3, the name of the candidate with the maximum number of votes is displayed. If there is more than one candidate with maximum votes, display an error message stating “No winner”.This program continues until the user chooses 0 to exit(). Provide the following options to the person who is accessing as shown below:Vote for your favorite Candidate.Check the number of votes of each Candidate.Check the candidate who is leading and then Exit. Vote for your favorite Candidate. Check the number of votes of each Candidate. Check the candidate who is leading and then Exit. The user chooses one of the options. If the user chooses 1, then the list of candidates is displayed and the user can now choose from this list of candidates. If the user chooses 2, then the list of candidates along with their current number of votes is displayed. If the user chooses 3, the name of the candidate with the maximum number of votes is displayed. If there is more than one candidate with maximum votes, display an error message stating “No winner”. This program continues until the user chooses 0 to exit(). Below is the implementation of the above approach: C++ // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ int choice, i, N; // Stores the names of candidates vector<string> candidates = { "A", "B", "C", "D", "E" }; N = candidates.size(); // Stores the votes of candidates vector<int> votes(N); do { cout << "\n1. Vote for your " << "favorite Candidate.\n"; cout << "2. Check the number " << "of votes of each " "Candidate.\n"; cout << "3. Check the candidate " << "who is leading.\n"; cout << "0. Exit\n"; // Take input of options cout << "Enter Your choice: "; cin >> choice; cout << "\n"; // Switch Statement switch (choice) { case 1: { int candidatechoice; // Display the names of // all the candidates for (i = 0; i < N; i++) cout << i + 1 << "." << candidates[i] << "\n"; cout << "Choose your candidate: "; // Taking user's vote cin >> candidatechoice; cout << "\n"; // Update the vote of the // chosen candidate votes[candidatechoice - 1]++; break; } case 2: { // Display the name and votes // of each // candidate for (i = 0; i < N; i++) cout << i + 1 << "." << candidates[i] << " " << votes[i] << "\n"; break; } case 3: { int mx = 0; string winner; // Find the candidate with // maximum votes for (int i = 0; i < N; i++) if (votes[i] > mx) { mx = votes[i]; winner = candidates[i]; } int flag = 0; // Check whether there are // more than one candidates // with maximum votes for (int i = 0; i < N; i if (votes[i] == mx && winner != candidates[i]) { flag = 1; break; } if (!flag) cout << "The current winner is " << winner << ".\n"; else cout << "No clear winner\n"; } default: "Select a correct option"; } } while (choice != 0); return 0;} Output: Menu driven programs Technical Scripter 2020 C++ C++ Programs Project Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Sorting a vector in C++ Friend class and function in C++ Polymorphism in C++ List in C++ Standard Template Library (STL) Header files in C/C++ and its uses C++ Program for QuickSort How to return multiple values from a function in C or C++? Program to print ASCII Value of a character C++ program for hashing with chaining
[ { "code": null, "e": 23707, "s": 23679, "text": "\n18 Mar, 2021" }, { "code": null, "e": 23843, "s": 23707, "text": "In this article, we will write a menu-driven program to implement the Voting System. The program must contain the following properties:" }, { "code": null,...
How to empty a C# list?
To empty a C# list, use the Clear() method. Firstly, set a list and add elements − List<string> myList = new List<string>() { "one", "two", "three", "four", "five", "six" }; Now, let us empty the list − myList.Clear(); Live Demo using System; using System.Collections.Generic; public class Program { public static void Main() { List<string> myList = new List<string>() { "one", "two", "three", "four", "five", "six" }; foreach(string str in myList) { Console.WriteLine(str); } Console.WriteLine("Elements in the list = "+myList.Count); // this makes a list empty myList.Clear(); Console.WriteLine("Elements in the list after using Clear() = "+myList.Count); } } one two three four five six Elements in the list = 6 Elements in the list after using Clear() = 0
[ { "code": null, "e": 1106, "s": 1062, "text": "To empty a C# list, use the Clear() method." }, { "code": null, "e": 1145, "s": 1106, "text": "Firstly, set a list and add elements −" }, { "code": null, "e": 1254, "s": 1145, "text": "List<string> myList = new Li...
Tryit Editor v3.7
CSS Image Reflection Tryit: Image reflection to the right
[ { "code": null, "e": 30, "s": 9, "text": "CSS Image Reflection" } ]
K-means and PCA for Image Clustering: a Visual Analysis | by Sunny K. Tuladhar | Towards Data Science
What we will be doing here is train a K-means clustering model on the f-MNIST data so that it is able to cluster the images of the data-set with relative accuracy and the clusters have some logic to them which we can understand and interpret. We will then visually analyze the results of the clustering using matplotlib and plotly with reference to the actual labels (y) and draw a rough conclusion on how k-means clustering performs on an image data-set. The final code is available on the link at the end. The words features and components have been used interchangeably in this article. Get straight to the code on Github. Clustering is an unsupervised machine learning algorithm and it recognizes patterns without specific labels and clusters the data according to the features. In our case, we will see if a clustering algorithm (k-means) can find a pattern between different images of the apparel in f-MNIST without the labels (y). K-means clustering works by assigning a number of centroids based on the number of clusters given. Each data point is assigned to the cluster whose centroid is nearest to it. The algorithm aims to minimize the squared Euclidean distances between the observation and the centroid of cluster to which it belongs. Principal Component Analysis or PCA is a method of reducing the dimensions of the given dataset while still retaining most of its variance. Wikipedia defines it as, “PCA is defined as an orthogonal linear transformation that transforms the data to a new coordinate system such that the greatest variance by some scalar projection of the data comes to lie on the first coordinate (called the first principal component), the second greatest variance on the second coordinate, and so on.” Basically PCA reduces the dimensions of the dataset while conserving most of the information. For e.g. if a data-set has 500 features, it gets reduced to 200 features depending on the specified amount of variance retained. Higher the variance retained,more information is conserved, but more the resulting dimensions will be. Less dimensions means less time to train and test the model. In some cases models which use data-set with PCA perform better than the original dataset. The concept of PCA and the changes it causes on images by changing the retained variance is shown brilliantly here. So the plan is to perform k-means on the data-set but only after applying PCA on it. Load the data-set from kerasPre-process the data, flatten the data (from 60000 x 28 x 28 array to 60000 x 784 array)Apply PCA on it to reduce the dimensions (784 to 420 using 0.98 variance)Apply K-means clustering on the PC data-set (10 clusters)Observe and Analyze the results using matplotlib and plotly Load the data-set from keras Pre-process the data, flatten the data (from 60000 x 28 x 28 array to 60000 x 784 array) Apply PCA on it to reduce the dimensions (784 to 420 using 0.98 variance) Apply K-means clustering on the PC data-set (10 clusters) Observe and Analyze the results using matplotlib and plotly The f-MNIST dataset is a slightly advanced dataset compared to the MNIST numbers dataset and it consists of 28 x 28 pixel images of different variety of clothing with the numbers representing the following type of clothing. #Loading required librariesimport kerasfrom keras.datasets import fashion_mnist import numpy as npimport matplotlib.pyplot as pltfrom sklearn.preprocessing import StandardScalerfrom sklearn.cluster import KMeans#Loading the dataset(X_train,y_train), (X_test,y_test) = fashion_mnist.load_data() We reshape the data into 2D array from a 3D array by flattening the features into 1 dimension. Each image of 28 x 28 array is now a single array of 784 features. So our dataset becomes 60000, 784 array from the previous 60000,28,28. #Reshaping X to a 2D array for PCA and then k-meansX = X_train.reshape(-1,X_train.shape[1]*X_train.shape[2]) #We will only be using X for clustering. No need of y.print ("The shape of X is " + str(X.shape))print ("The shape of y is " + str(y.shape)) #We will be using y only to check our clusteringOutput:The shape of X is (60000, 784)The shape of y is (60000,) We will now use PCA on our dataset to reduce our dimensions. We will pick our retained variance of 0.98 (value selected through trial and error) and use it on our dataset. from sklearn.decomposition import PCA# Make an instance of the Modelvariance = 0.98 #The higher the explained variance the more accurate the model will remain, but more dimensions will be presentpca = PCA(variance)pca.fit(Clus_dataSet) #fit the data according to our PCA instanceprint("Number of components before PCA = " + str(X.shape[1]))print("Number of components after PCA 0.98 = " + str(pca.n_components_)) #dimension reduced from 784Output:Number of components before PCA = 784Number of components after PCA 0.98 = 420 We now transform the data according to the PCA instance Clus_dataSet = pca.transform(Clus_dataSet)print(“Dimension of our data after PCA = “ + str(Clus_dataSet.shape))Output:Dimension of our data after PCA = (60000, 420) We can also inverse transform the data to view how the data changes because of the PCA. approximation = pca.inverse_transform(Clus_dataSet)#image reconstruction using the less dimensioned dataplt.figure(figsize=(8,4));n = 500 #index value, change to view different data# Original Imageplt.subplot(1, 2, 1);plt.imshow(X[n].reshape(X_train.shape[1], X_train.shape[2]), cmap = plt.cm.gray,);plt.xlabel(str(X.shape[1])+’ components’, fontsize = 14)plt.title(‘Original Image’, fontsize = 20);# 196 principal componentsplt.subplot(1, 2, 2);plt.imshow(approximation[n].reshape(X_train.shape[1], X_train.shape[2]), cmap = plt.cm.gray,);plt.xlabel(str(Clus_dataSet.shape[1]) +’ components’, fontsize = 14)plt.title(str(variance * 100) + ‘% of Variance Retained’, fontsize = 20); Building the k-means models we need values for the following parameters. init: Initialization method of the centroids. Value will be: “k-means++”. k-means++: Selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. n_clusters: The number of clusters to form as well as the number of centroids to generate. Value will be: 10 ( we have 10 classes according to INDEX, might not be best but good enough for our context) n_init: Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. Value will be: 35 based on our inertia results (might not be the best but good enough for our context) So now we have our model and we fit it to our dataset. Try using the mentioned parameters first to check the results with this article. You can change them later and see different results. k_means = KMeans(init = “k-means++”, n_clusters = 10, n_init = 35)k_means.fit(Clus_dataSet) Now the model has been fit on our Image dataset on which we had performed PCA . The data is now divided into 10 clusters. Now we have to check what type of image ended up in each of these clusters and see if there is any pattern to it. Remember the distribution will be similar but the number(label) of the clusters might be different when you execute this. After the fit, we use the following code to visualize our clusters. G = len(np.unique(k_means_labels)) #Number of labels#2D matrix for an array of indexes of the given labelcluster_index= [[] for i in range(G)]for i, label in enumerate(k_means_labels,0): for n in range(G): if label == n: cluster_index[n].append(i) else: continue#Visualisation for clusters = clustplt.figure(figsize=(20,20));clust = 3 #enter label number to visualisenum = 100 #num of data to visualize from the clusterfor i in range(1,num): plt.subplot(10, 10, i); #(Number of rows, Number of column per row, item number) plt.imshow(X[cluster_index[clust][i+500]].reshape(X_train.shape[1], X_train.shape[2]), cmap = plt.cm.binary); plt.show() As you can see below this particular cluster ( 3 in my case) does a great job of clustering Ankle Boots. The code for the following bar-graph visualization is available on the link at the end. This uses the category labels from the y_train of the dataset and checks the quantity of a certain category in a given cluster. The graph will be same (if you used the same parameters) while the number(label) of the clusters might be different when you execute it. E.g. in mine a cluster labelled 0 seems to be a cluster of Sandals, in yours this cluster might be labelled 4. Note: Cluster Names are ABOVE the bargraph. Cluster 0 seems to have mostly Sandals. Cluster 1 seems random but mostly has only upper body clothes. (T-shirt, Pullover, Dress, Coat and Shirt) Cluster 2 also has upper body clothes but less varied.(Pullover,Shirt and Coat) Cluster 3 seems to have mostly Ankle Boots few Sneakers and sandals. Basically all are shoes. Similarly we can observe clusters 4 ~7.In both the clusters 6 and 7 (in my case) there seem to be majority of Bags . But upon using the visualization of the above clusters (shown below) we see a sensible pattern. One cluster has the bag handles lifted (among other things), the other does not. The clusters 8 and 9 shown below seem to be shoes. Cluster 8 has a few sandals and mostly Sneakers, Cluster 9 seems to have a few sandals and mostly Ankle Boots. We will be visualizing the clusters in 3D using plotly. Plotly is an advanced visualization library for python. Use the following code to obtain a 3D scatter plot of the clustered data. We will using only be 3 features from the 420 features in our dataset. This visualization helps to understand how well the clusters have formed and how far out a single cluster is spread into other clusters. #install these if you haven’t!pip install chart_studio !pip install plotlyimport plotly as pyimport plotly.graph_objs as goimport plotly.express as px#3D Plotly Visualization of Clusters using golayout = go.Layout( title='<b>Cluster Visualisation</b>', yaxis=dict( title='<i>Y</i>' ), xaxis=dict( title='<i>X</i>' ))colors = ['red','green' ,'blue','purple','magenta','yellow','cyan','maroon','teal','black']trace = [ go.Scatter3d() for _ in range(11)]for i in range(0,10): my_members = (k_means_labels == i) index = [h for h, g in enumerate(my_members) if g] trace[i] = go.Scatter3d( x=Clus_dataSet[my_members, 0],# 0 is a component among the 420 components. Feel free to change it y=Clus_dataSet[my_members, 1],# 1 is a component among the 420 components. Feel free to change it z=Clus_dataSet[my_members, 2],# 2 is a component among the 420 components. Feel free to change it mode='markers', marker = dict(size = 2,color = colors[i]), hovertext=index, name='Cluster'+str(i), )fig = go.Figure(data=[trace[0],trace[1],trace[2],trace[3],trace[4],trace[5],trace[6],trace[7],trace[8],trace[9]], layout=layout) py.offline.iplot(fig) Output: Since the data-set (with PCA) actually has 420 dimensions, this visualization only shows 3 of those features in the scatter plot. The component to be plotted can be changed in the code to get an idea of this in term of different components. (A further PCA can be done to reduce all the 784 components to 3 components to fully represent it in a 3D plot but a lot of the information will be lost while doing so) The clustering does seem to group similar items together. A cluster either contains upper-body clothes(T-shirt/top, pullover, Dress, Coat, Shirt) or shoes (Sandals/Sneakers/Ankle Boots) or Bags. The clustering however performs poorly on trousers and seems to group it together with dresses. But it distinguishes these two types of bags quite well. The pattern can be interpreted by us. One cluster has bags with raised handles, the other has the bags with unraised handles. Similarly in the two clusters shown below both have a majority of Ankle boots. But the ankle boots seems to be of different sizes and the smaller ones do look similar to the sneakers which are in the same cluster. Looking at the above results we can see the k -means algorithm distinguishes its clusters based on a reasonable pattern. Thus we can draw a rough conclusion that K-means clustering method after performing a Principal Component Analysis can get a decent result on classifying images without labels. Click here for the link to the code References [1] A. Ng, Machine Learning by Stanford University. (n.d.). Retrieved from https://www.coursera.org/learn/machine-learning [2] S Joel Franklin , K-Means Clustering for Image Classification(2020), Medium [3] Michael Galarnyk, PCA + Logistic Regression (MNIST)(2018), github
[ { "code": null, "e": 679, "s": 171, "text": "What we will be doing here is train a K-means clustering model on the f-MNIST data so that it is able to cluster the images of the data-set with relative accuracy and the clusters have some logic to them which we can understand and interpret. We will then...
Next.js - Dynamic Routing
In Next.js, we can create routes dynamically. In this example, we'll create pages on the fly and their routing. Step 1. Define [id].js file − [id].js represents the dynamic page where id will be relative path. Define this file in pages/post directory. Step 1. Define [id].js file − [id].js represents the dynamic page where id will be relative path. Define this file in pages/post directory. Step 2. Define lib/posts.js − posts.js represents the ids and contents. lib directory is to be created in root directory. Step 2. Define lib/posts.js − posts.js represents the ids and contents. lib directory is to be created in root directory. Update [id].js file with getStaticPaths() method which sets the paths and getStaticProps() method to get the contents based on id. import Link from 'next/link' import Head from 'next/head' import Container from '../../components/container' import { getAllPostIds, getPostData } from '../../lib/posts' export default function Post({ postData }) { return ( <Container> {postData.id} <br /> {postData.title} <br /> {postData.date} </Container> ) } export async function getStaticPaths() { const paths = getAllPostIds() return { paths, fallback: false } } export async function getStaticProps({ params }) { const postData = getPostData(params.id) return { props: { postData } } } posts.js contains getAllPostIds() to get the ids and getPostData() to get corresponding contents. export function getPostData(id) { const postOne = { title: 'One', id: 1, date: '7/12/2020' } const postTwo = { title: 'Two', id: 2, date: '7/12/2020' } if(id == 'one'){ return postOne; }else if(id == 'two'){ return postTwo; } } export function getAllPostIds() { return [{ params: { id: 'one' } }, { params: { id: 'two' } } ]; } Run the following command to start the server −. npm run dev > nextjs@1.0.0 dev \Node\nextjs > next ready - started server on http://localhost:3000 event - compiled successfully event - build page: / wait - compiling... event - compiled successfully event - build page: /next/dist/pages/_error wait - compiling... event - compiled successfully Open localhost:3000/posts/one in a browser and you will see the following output. Open localhost:3000/posts/two in a browser and you will see the following output. Print Add Notes Bookmark this page
[ { "code": null, "e": 2219, "s": 2107, "text": "In Next.js, we can create routes dynamically. In this example, we'll create pages on the fly and their routing." }, { "code": null, "e": 2359, "s": 2219, "text": "Step 1. Define [id].js file − [id].js represents the dynamic page wher...
Migrate PyQt5 app to PySide2 - GeeksforGeeks
27 Feb, 2020 One of the most advanced packages for Gui development in Python is PyQt5. According to Christian Tismer, the maintainer of Pyside2, PyQt5 has some 25,000 functions for you to use. That’s a really big library. However, if you want to distribute your app commercially, you need to purchase a license from the Qt company. Fortunately enough, PySide2 allows you the same liberty as Free/Libre Software. Let’s see how we can migrate a typical PyQt5 app to PySide2. import sysfrom PyQt5.QtWidgets import (QGridLayout)from PyQt5.QtWidgets import (QMainWindow)from PyQt5.QtWidgets import (QApplication)from PyQt5.QtWidgets import ( QWidget, QPushButton, QLabel, QLineEdit ) from PyQt5.QtCore import Qtfrom PyQt5.QtGui import (QPixmap,QIcon) class Window(QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.setWindowTitle('PyQt5 Demo App') self.initGui() def initGui(self): self.layout = QGridLayout() self.window = QWidget() self.window.setLayout(self.layout) self.setCentralWidget(self.window) self.num1_label = QLabel('Enter first number:') self.num1_label.setAlignment(Qt.AlignCenter) self.text_box1 = QLineEdit() self.num2_label = QLabel('Enter second number:') self.text_box2 = QLineEdit() self.get_answer = QPushButton() calculate_icon = QPixmap('path_to_image.png') self.get_answer.setIcon(QIcon(calculate_icon)) self.answer_label = QLabel('---') self.layout.addWidget(self.num1_label, 0, 0) self.layout.addWidget(self.text_box1, 1, 0) self.layout.addWidget(self.num2_label, 2, 0) self.layout.addWidget(self.text_box2, 3, 0) self.layout.addWidget(self.get_answer, 4, 0) self.layout.addWidget(self.answer_label, 5, 0) if __name__ == '__main__': app = QApplication(sys.argv) win = Window() win.show() sys.exit(app.exec_()) Output: We’ve deliberately made use of an example that uses QtWidget, QtCore and QtGui. One thing to do is to take on good practice. it about avoiding from X import *. Namespacing our imports has the advantage of learning what falls under what module. import sys from PyQt5 import QtWidgetsfrom PyQt5 import QtCorefrom PyQt5 import QtGui Now, change our code to the following where we namespaced our imports. QMainWindow becomes QtWidgets.QMainWindow and so on – class Window(QtWidgets.QMainWindow): def __init__(self, parent = None): super().__init__(parent) self.setWindowTitle('PyQt5 Demo App') self.initGui() def initGui(self): self.layout = QtWidgets.QGridLayout() self.window = QtWidgets.QWidget() self.window.setLayout(self.layout) self.setCentralWidget(self.window) self.num1_label = QtWidgets.QLabel('Enter first number:') self.num1_label.setAlignment(QtCore.Qt.AlignCenter) self.text_box1 = QtWidgets.QLineEdit() self.num2_label = QtWidgets.QLabel('Enter second number:') self.text_box2 = QtWidgets.QLineEdit() self.get_answer = QtWidgets.QPushButton() calculate_icon = QtGui.QPixmap('path_to_image.png') self.get_answer.setIcon(QtGui.QIcon(calculate_icon)) self.answer_label = QtWidgets.QLabel('---') self.layout.addWidget(self.num1_label, 0, 0) self.layout.addWidget(self.text_box1, 1, 0) self.layout.addWidget(self.num2_label, 2, 0) self.layout.addWidget(self.text_box2, 3, 0) self.layout.addWidget(self.get_answer, 4, 0) self.layout.addWidget(self.answer_label, 5, 0) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) win = Window() win.show() sys.exit(app.exec_()) Converting To Pyside2 Converting our app to PySide2 is as simple as changing our imports to import sys from PySide2 import QtWidgetsfrom PySide2 import QtCorefrom PySide2 import QtGui For most uses, migrating means adjusting imports, defining functions and using supported funcions only. One thing to look out is app.exec_. exec_ was used as exec is a Python2 keyword. Under Python3, PyQt5 allows the use of exec but not PySide2. PyQt5 supports both sys.exit(app.exec_()) and sys.exit(app.exec()) but PySide2 supports only app.exec_().The second thing is signal and slots. Under PyQt5 it’s QtCore.pyqtSignal and QtCore.pyqtSlot and under PySide2 it’s QtCore.Signal and QtCore.Slot .The third thing is loading Ui files. One thing to look out is app.exec_. exec_ was used as exec is a Python2 keyword. Under Python3, PyQt5 allows the use of exec but not PySide2. PyQt5 supports both sys.exit(app.exec_()) and sys.exit(app.exec()) but PySide2 supports only app.exec_(). The second thing is signal and slots. Under PyQt5 it’s QtCore.pyqtSignal and QtCore.pyqtSlot and under PySide2 it’s QtCore.Signal and QtCore.Slot . The third thing is loading Ui files. Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python sum() function in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24427, "s": 24399, "text": "\n27 Feb, 2020" }, { "code": null, "e": 24826, "s": 24427, "text": "One of the most advanced packages for Gui development in Python is PyQt5. According to Christian Tismer, the maintainer of Pyside2, PyQt5 has some 25,000 functions...
Delete middle element of a stack | Practice | GeeksforGeeks
Given a stack with push(), pop(), empty() operations, delete the middle of the stack without using any additional data structure. Middle: ceil((size_of_stack+1)/2) (1-based index) Example 1: Input: Stack = {1, 2, 3, 4, 5} Output: ModifiedStack = {1, 2, 4, 5} Explanation: As the number of elements is 5 , hence the middle element will be the 3rd element which is deleted Example 2: Input: Stack = {1 2 3 4} Output: ModifiedStack = {1 3 4} Explanation: As the number of elements is 4 , hence the middle element will be the 2nd element which is deleted Your Task: You don't need to read input or print anything. Complete the function deleteMid() which takes the stack and its size as input parameters and modifies the stack in-place. Note: The output shows the stack from top to bottom. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 2 ≤ size of stack ≤ 100 0 vishalsavade1 hour ago //This code is contributed by Vishal Savade // Easy way to understand recursion void foo(stack<int> &s, int cnt){ if(cnt == 0){ s.pop(); return;} int top = s.top(); s.pop(); foo(s, cnt-1); s.push(top); } void deleteMid(stack<int>&s, int sizeOfStack) { // code here.. int mid = 0; mid = (sizeOfStack/2); foo(s, mid); } +1 shubhamkhavare2 days ago Easy Java Code: int mid = sizeOfStack/2; if(sizeOfStack%2 == 0) { mid = mid - 1; } s.removeElementAt(mid); +1 adarshgupta4011 week ago Easy Recursive Java Code= class Solution { public void deleteMid(Stack<Integer>s,int sizeOfStack){ int middle = sizeOfStack/2; if(s.isEmpty()) return ; deleteMiddle( s, middle); } public void deleteMiddle(Stack<Integer> s, int middle ){ if( middle == 0 ) { s.pop(); return ; } int temp = s.pop(); deleteMiddle(s, middle-1 ); s.push(temp); return ; } } 0 madhajaswanth1 week ago public void deleteMid(Stack<Integer>s,int n){ Stack<Integer> stack = new Stack<>(); // removes middle -1 elements for(int i=0;i<m;i++){ stack.push(s.pop()); } // removes middle element s.pop(); // adds the first removed elements while(!stack.isEmpty()){ s.push(stack.pop()); } } 0 ns2847192 weeks ago void solve(stack<int>&s, int count , int size) { if(count == size/2) { s.pop(); return; } int num = s.top(); s.pop(); solve(s,count+1,size); s.push(num); } void deleteMid(stack<int>&s, int sizeOfStack) { // code here.. int count=0; solve(s,count,sizeOfStack); } -1 kunal chalotra2 weeks ago JAVA SOLUTION Stack<Integer> st= new Stack(); int middle=Math.abs(sizeOfStack/2); int count=0; while(!s.empty()) { st.push(s.pop()); count++; if(count==middle) { s.pop(); break; } } while(!s.empty()) { st.push(s.pop()); } while(!st.empty()) { s.push(st.pop()); } 0 dipanshusharma93134 weeks ago // java solution class Solution{ public void deleteMid(Stack<Integer>s,int sizeOfStack){ if(sizeOfStack%2==0){ if(sizeOfStack/2 == s.size()){ s.pop(); return; } } if(sizeOfStack%2!=0){ if((sizeOfStack/2)+1 == s.size()){ s.pop(); return; } } int temp = s.pop(); deleteMid(s, sizeOfStack); s.push(temp); } } 0 tarunkanade4 weeks ago 0.5/1.6 public void deleteMid(Stack<Integer>s,int sizeOfStack){ // code here int toBeDeleted = (int)Math.ceil((sizeOfStack+1)/2.0); ArrayDeque<Integer> t = new ArrayDeque<>(); int count = 1; while(count <= toBeDeleted){ if(count == toBeDeleted){ s.pop(); break; }else{ t.push(s.pop()); } count++; } while(!t.isEmpty()){ s.push(t.pop()); } } -1 sadiiqyare661 month ago public void deleteMid(Stack<Integer>s,int sizeOfStack){ // code here int n = (sizeOfStack/2)+1; ArrayList<Integer> arr = new ArrayList<Integer>(); for (int i = 0; i < n-1; i++ ){ int h = s.pop(); arr.add(h); } s.pop(); for (int i = arr.size()-1; i >= 0; i--){ s.push(arr.get(i)); } } 0 anujrai0408200201 month ago class Solution { //Function to delete middle element of a stack. public void deleteMid(Stack<Integer>s,int sizeOfStack){ s.removeElementAt((sizeOfStack-1)/2); } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 420, "s": 238, "text": "Given a stack with push(), pop(), empty() operations, delete the middle of the stack without using any additional data structure.\nMiddle: ceil((size_of_stack+1)/2) (1-based index)\n " }, { "code": null, "e": 431, "s": 420, "text": "Ex...
Random Forest Classifier in Python | by Joe Tran | Towards Data Science
Data Preprocessing (a trick to handle categorical features and NAs automatically)Train the RF classifierEvaluate the classifier (accuracy, recall, precision, ROC AUC, confusion matrix, plotting)Feature ImportanceTune the hyper-parameters with Random Search Data Preprocessing (a trick to handle categorical features and NAs automatically) Train the RF classifier Evaluate the classifier (accuracy, recall, precision, ROC AUC, confusion matrix, plotting) Feature Importance Tune the hyper-parameters with Random Search Now let’s get started, folks! In this article, I am using the dataset taken from my real technical test with a tech company for a data science position. You can get the data here (click Download ZIP). Disclaimer: all the information described in the data are not real. The exit_status here is the response variable. Note that we are only given train.csv and test.csv. Thetest.csvdoes not have exit_status, i.e. it is only for prediction. Hence the approach is that we need to split the train.csv into the training and validating set to train the model. Then use the model to predict theexit_status in the test.csv. This is a typical Data Science technical test where you are given around 30 minutes to produce a detailed jupyter notebook and result. import pandas as pdimport numpy as npimport matplotlib.pyplot as pltdata = pd.read_csv('train.csv') Oops, we saw NaN, let’s check how many NaN we have data.isnull().sum() Since there are 2600 rows in total, the number of rows with NAs here is relatively small. However, I do not remove NAs here because what if the test.csv dataset also has NAs, then removing the NAs in the train data will not enable us to predict the customers' behaviour where there are NAs. However, if the test.csv does not have any NAs, then we can go ahead and remove the NAs in the train dataset. But let’s first check out the test.csv test = pd.read_csv('test.csv')test.isnull().sum() As expected, there are NAs in test.csv. Hence, we will treat NAs as a category and assume it contributes to the response variable exit_status. exit_status_map = {'Yes': 1, 'No': 0}data['exit_status'] = data['exit_status'].map(exit_status_map) This step is useful later because the response variable must be an numeric array to input into RF classifier. Like I mentioned earlier, RF model is unable to read strings or any non-numeric datatypes. y = data.pop('exit_status')X = data.drop('id',axis = 1) The id column does not add any meaning to our work because it will not affect whether the customer chose to stay or exit, so we should just remove it. seed = 50 # so that the result is reproduciblefrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.333, random_state = seed) Now, it is time to make NA a category. In Python, NaN is considered NAs. When encoded, those NaN will be ignored. Hence, it is useful to replace NaN with na, which is now a category called ‘na’. This will be taken into account when encoding later on. X_train = X_train.fillna('na')X_test = X_test.fillna('na') X_train.dtypes Now, let’s create a list of categorical variables features_to_encode = list(X_train.select_dtypes(include = ['object']).columns) # Or alternatively, features_to_encode = X_train.columns[X_train.dtypes==object].tolist() This is my favorite step because by recreating this new constructor, I do not need to do any transformation for any X dataframe when passing into the model. This constructor will automatically handle the categorical variables and leave numeric variables untouched. How convenient!!! from sklearn.preprocessing import OneHotEncoderfrom sklearn.compose import make_column_transformercol_trans = make_column_transformer( (OneHotEncoder(),features_to_encode), remainder = "passthrough" ) The remainder = 'passthrough' allows the constructor to ignore those variables that are not included in features_to_encode. Now our inputs are ready. Let’s train the RF classifier. Let’s first create our first model. Of course one can start with rf_classifier = RandomForestClassifier(). However, most of the time this base model will not perform really well (from my experience at least, yours might differ). So I always start with the following set of parameters as my first model. from sklearn.ensemble import RandomForestClassifierrf_classifier = RandomForestClassifier( min_samples_leaf=50, n_estimators=150, bootstrap=True, oob_score=True, n_jobs=-1, random_state=seed, max_features='auto') I would recommend to always start with the model where oob_score = True because it is better to use out-of-bag samples to estimate the generalization accuracy. An oob error estimate is almost identical to that obtained by k-fold cross-validation. Unlike many other nonlinear estimators, random forests can be fit in one sequence, with cross-validation being performed along the way. Now, let’s combine our classifier and the constructor that we created earlier, by using Pipeline from sklearn.pipeline import make_pipelinepipe = make_pipeline(col_trans, rf_classifier)pipe.fit(X_train, y_train) pipe is a new black box created with 2 components: 1. A constructor to handle inputs with categorical variables and transform into a correct type, and 2. A classifier that receives those newly transformed inputs from the constructor. y_pred = pipe.predict(X_test) from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, roc_auc_score, roc_curve, f1_score Accuracy = (TP + TN) / (TP+TN+FP+FN) Recall = TP / (TP + FN) Precision = TP / (TP + FP) F1-score = 2 * Precision * Recall / (Precision+Recall) In this example, 1 is Positive and 0 is Negative I will not go through the meaning of each term above because this article is not meant to be a detailed document of Random Forest algorithms. I assume we all know what these terms mean. Of course, if you are unsure, feel free to ask me in the comment section. accuracy_score(y_test, y_pred)print(f"The accuracy of the model is {round(accuracy_score(y_test,y_pred),3)*100} %")The accuracy of the model is 91.1% train_probs = pipe.predict_proba(X_train)[:,1] probs = pipe.predict_proba(X_test)[:, 1]train_predictions = pipe.predict(X_train) predict_proba(dataframe)[:,1] gives the predicted probability distribution of class label 1 from the dataframe. This is important to calculate ROC_AUC score. You may ask why class label 1 and not 0. Here is what I got from sklearn document: For y_score, ‘The binary case ... the scores must be the scores of the class with the greater label’. That is why we need to get label 1 instead of label 0. print(f'Train ROC AUC Score: {roc_auc_score(y_train, train_probs)}')print(f'Test ROC AUC Score: {roc_auc_score(y_test, probs)}')Train ROC AUC Score: 0.9678578659647703 Test ROC AUC Score: 0.967591183178179 Now, we need to plot the ROC curve def evaluate_model(y_pred, probs,train_predictions, train_probs): baseline = {} baseline['recall']=recall_score(y_test, [1 for _ in range(len(y_test))]) baseline['precision'] = precision_score(y_test, [1 for _ in range(len(y_test))]) baseline['roc'] = 0.5 results = {} results['recall'] = recall_score(y_test, y_pred) results['precision'] = precision_score(y_test, y_pred) results['roc'] = roc_auc_score(y_test, probs) train_results = {} train_results['recall'] = recall_score(y_train, train_predictions) train_results['precision'] = precision_score(y_train, train_predictions) train_results['roc'] = roc_auc_score(y_train, train_probs) for metric in ['recall', 'precision', 'roc']: print(f'{metric.capitalize()} Baseline: {round(baseline[metric], 2)} Test: {round(results[metric], 2)} Train: {round(train_results[metric], 2)}') # Calculate false positive rates and true positive rates base_fpr, base_tpr, _ = roc_curve(y_test, [1 for _ in range(len(y_test))]) model_fpr, model_tpr, _ = roc_curve(y_test, probs) plt.figure(figsize = (8, 6)) plt.rcParams['font.size'] = 16 # Plot both curves plt.plot(base_fpr, base_tpr, 'b', label = 'baseline') plt.plot(model_fpr, model_tpr, 'r', label = 'model') plt.legend(); plt.xlabel('False Positive Rate'); plt.ylabel('True Positive Rate'); plt.title('ROC Curves'); plt.show();evaluate_model(y_pred,probs,train_predictions,train_probs)Recall Baseline: 1.0 Test: 0.92 Train: 0.93 Precision Baseline: 0.48 Test: 0.9 Train: 0.91 Roc Baseline: 0.5 Test: 0.97 Train: 0.97 The result looks good. There is very little difference between Test and Train result, indicating that our model does not overfit the data. One can just simply type confusion_matrix(y_test, y_pred) to get the confusion matrix. However, let’s take a more advanced approach. Here, I create a function to plot confusion matrix, which prints and plots the confusion matrix. (Adapted from Source of the code) import itertoolsdef plot_confusion_matrix(cm, classes, normalize = False, title='Confusion matrix', cmap=plt.cm.Greens): # can change color plt.figure(figsize = (10, 10)) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title, size = 24) plt.colorbar(aspect=4) tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45, size = 14) plt.yticks(tick_marks, classes, size = 14) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. # Label the plot for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), fontsize = 20, horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.grid(None) plt.tight_layout() plt.ylabel('True label', size = 18) plt.xlabel('Predicted label', size = 18)# Let's plot it outcm = confusion_matrix(y_test, y_pred)plot_confusion_matrix(cm, classes = ['0 - Stay', '1 - Exit'], title = 'Exit_status Confusion Matrix') First, let’s inspect how many feature importance values are there in the model print(rf_classifier.feature_importances_)print(f" There are {len(rf_classifier.feature_importances_)} features in total")[7.41626071e-04 6.12165359e-04 1.42322746e-03 6.93254520e-03 2.93650843e-04 1.96706074e-04 1.85830433e-03 2.67517842e-03 1.02110066e-05 2.99006245e-05 6.15325794e-03 1.66647237e-02 4.49100748e-03 3.37963818e-05 1.87449830e-03 1.00225588e-03 3.72119245e-04 1.39558189e-02 8.28073088e-04 3.41692010e-04 1.71733193e-04 7.60943914e-02 1.09485070e-02 1.78380970e-02 1.63392715e-02 2.93397339e-03 1.46445733e-02 1.34849432e-01 1.33144331e-02 4.42753783e-02 3.13204793e-03 4.97894324e-03 6.17692498e-03 2.70959923e-02 1.61849449e-03 7.57024010e-02 2.31468190e-02 4.66247828e-01] There are 38 features in total There are 38 features in total. However, there are only 15 columns in X_train. This is because the model pipe automatically encodes the categorical variables in X_train. For example, the gender column in X_train is transformed into 2 columns Female and Male. Therefore, to match the features to their feature importance values derived from rf_classifier, we need to get all those corresponding columns in the encoded X_train. Question: We only have an array of feature importances, but there are both categorical and numerical features, how do we know which value belongs to which feature? Remember the col_trans, the constructor we created earlier? The col_trans.fit_transform(X_train) will give the encoded X_train. # Let's look at the first rowprint(col_trans.fit_transform(X_train)[0,:])[ 0. 1. 0. 0. 0. 1. 1. 0. 0. 1. 1. 0. 0. 0. 1. 0. 0. 0. 1. 0. 0. 1. 0. 0. 1. 0. 0. 1. 0. 0. 0. 1. 0. 1. 0. 30. 74.75 14. ]# And the first row of X_trainX_train.iloc[0,:] gender Maleage >60dependents Nolifetime 30phone_services Yesinternet_services 3Gonline_streaming Major Usermultiple_connections Nopremium_plan Noonline_protect Nocontract_plan Month-to-monthebill_services Yesdefault_payment Online Transfermonthly_charges 74.75issues 14Name: 1258, dtype: object For X_train, there are 3 numeric variables, with values being 30, 70.75 and 14 respectively. For the encoded X_train, these 3 numeric values are placed after all the categorical variables. This means that for the rf_classifier.feature_importances_ all the encoded categorical variables are shown first, followed by the numeric variables Ok, now that we know, let’s create a proper encoded X_train. def encode_and_bind(original_dataframe, features_to_encode): dummies = pd.get_dummies(original_dataframe[features_to_encode]) res = pd.concat([dummies, original_dataframe], axis=1) res = res.drop(features_to_encode, axis=1) return(res)X_train_encoded = encode_and_bind(X_train, features_to_encode) The function encode_and_bind encodes the categorical variables and then combine them with the original dataframe. Cool, now we have 38 columns, which is exactly the same as the 38 features shown in the rf_classifier.feature_importances_ earlier. feature_importances = list(zip(X_train_encoded, rf_classifier.feature_importances_))# Then sort the feature importances by most important firstfeature_importances_ranked = sorted(feature_importances, key = lambda x: x[1], reverse = True)# Print out the feature and importances[print('Feature: {:35} Importance: {}'.format(*pair)) for pair in feature_importances_ranked]; # Plot the top 25 feature importancefeature_names_25 = [i[0] for i in feature_importances_ranked[:25]]y_ticks = np.arange(0, len(feature_names_25))x_axis = [i[1] for i in feature_importances_ranked[:25]]plt.figure(figsize = (10, 14))plt.barh(feature_names_25, x_axis) #horizontal barplotplt.title('Random Forest Feature Importance (Top 25)', fontdict= {'fontname':'Comic Sans MS','fontsize' : 20})plt.xlabel('Features',fontdict= {'fontsize' : 16})plt.show() Since the model performs very well, with high accuracy, precision and recall, there is actually little need to tune the model. However, if our first model did not perform well, the steps below can be taken to tune the model. Let’s look at the parameters used currently from pprint import pprintprint('Parameters currently in use:\n')pprint(rf_classifier.get_params()) Now, I create a grid of parameters for the model to randomly pick and train, hence the name Random Search. from sklearn.model_selection import RandomizedSearchCVn_estimators = [int(x) for x in np.linspace(start = 100, stop = 700, num = 50)]max_features = ['auto', 'log2'] # Number of features to consider at every splitmax_depth = [int(x) for x in np.linspace(10, 110, num = 11)] # Maximum number of levels in treemax_depth.append(None)min_samples_split = [2, 5, 10] # Minimum number of samples required to split a nodemin_samples_leaf = [1, 4, 10] # Minimum number of samples required at each leaf nodebootstrap = [True, False] # Method of selecting samples for training each treerandom_grid = {'n_estimators': n_estimators, 'max_features': max_features, 'max_depth': max_depth, 'min_samples_split': min_samples_split, 'min_samples_leaf': min_samples_leaf, 'max_leaf_nodes': [None] + list(np.linspace(10, 50, 500).astype(int)), 'bootstrap': bootstrap} Now, I first create a base model, then use random grid to select the best model, based on the ROC_AUC score, hence scoring = 'roc_auc'. # Create base model to tunerf = RandomForestClassifier(oob_score=True)# Create random search model and fit the datarf_random = RandomizedSearchCV( estimator = rf, param_distributions = random_grid, n_iter = 100, cv = 3, verbose=2, random_state=seed, scoring='roc_auc')rf_random.fit(X_train_encoded, y_train)rf_random.best_params_rf_random.best_params_{'n_estimators': 206, 'min_samples_split': 5, 'min_samples_leaf': 10, 'max_leaf_nodes': 44, 'max_features': 'auto', 'max_depth': 90, 'bootstrap': True} We will do 100 iterations with 3-fold cross validation. More information about the arguments can be found here. Alternatively, we can use pipe again, so that we don’t need to encode the data rf = RandomForestClassifier(oob_score=True, n_jobs=-1)rf_random = RandomizedSearchCV( estimator = rf, param_distributions = random_grid, n_iter = 50, cv = 3, verbose=1, random_state=seed, scoring='roc_auc')pipe_random = make_pipeline(col_trans, rf_random)pipe_random.fit(X_train, y_train)rf_random.best_params_ Note that the 2 methods might give slightly diffferent answers. This is due to the randomness in selecting the parameters. # To look at nodes and depths of trees use on averagen_nodes = []max_depths = []for ind_tree in best_model.estimators_: n_nodes.append(ind_tree.tree_.node_count) max_depths.append(ind_tree.tree_.max_depth)print(f'Average number of nodes {int(np.mean(n_nodes))}') print(f'Average maximum depth {int(np.mean(max_depths))}') Average number of nodes 82 Average maximum depth 9 Evaluate the best model # Use the best model after tuningbest_model = rf_random.best_estimator_pipe_best_model = make_pipeline(col_trans, best_model)pipe_best_model.fit(X_train, y_train)y_pred_best_model = pipe_best_model.predict(X_test) The same codes used in Section 3 can be applied here again for ROC and Confusion matrix. train_rf_predictions = pipe_best_model.predict(X_train)train_rf_probs = pipe_best_model.predict_proba(X_train)[:, 1]rf_probs = pipe_best_model.predict_proba(X_test)[:, 1]# Plot ROC curve and check scoresevaluate_model(y_pred_best_model, rf_probs, train_rf_predictions, train_rf_probs)Recall Baseline: 1.0 Test: 0.94 Train: 0.95 Precision Baseline: 0.48 Test: 0.9 Train: 0.91 Roc Baseline: 0.5 Test: 0.97 Train: 0.98 This set of parameters make the model perform just slightly better than our original model. The difference is not huge. This is understandable because our original model already performed well with higher scores (accuracy, precision, recall). So tuning some hyperparameters might not add any significant improvement to the model. # Plot Confusion matrixplot_confusion_matrix(confusion_matrix(y_test, y_pred_best_model), classes = ['0 - Stay', '1 - Exit'],title = 'Exit_status Confusion Matrix') Now that we have the best model, let’s use it for predictions and compile our final answer to submit. test = pd.read_csv('test.csv')test_withoutID = test.copy().drop('id', axis = 1)test_withoutID = test_withoutID.fillna('na')final_y = pipe_best_model.predict(test_withoutID)#pipe model only takes in dataframe without ID column.final_report = testfinal_report['exit_status'] = final_yfinal_report = final_report.loc[:,['id','exit_status']]# Replace 1-0 with Yes-No to make it interpretablefinal_report= final_report.replace(1, 'Yes')final_report= final_report.replace(0, 'No') We see all No. Let’s check to make sure there are Yes in the column too. final_report.exit_status.value_counts()No 701Yes 638Name: exit_status, dtype: int64 Okay, we are safe~ final_report.to_csv('submissions.csv', index=False) I hope this can be a helpful reference guide for you guys as well. You can use this guide to prepare for probably some technical tests or use it as a cheatsheet to brush up on how to implement Random Forest Classifier in Python. I will definitely keep on updating this as I find more useful functions or tricks that I think can help everyone tackle many data science problems fast, without much need to look up on platforms like StackOverflow, especially when sitting for a technical test, where time is limited. If there are any other tricks or functions that you think are important, please let me know in the comment section below. Also, I welcome any constructive feedback from everyone. Thank you for your read. Have a great day and happy programming!
[ { "code": null, "e": 428, "s": 171, "text": "Data Preprocessing (a trick to handle categorical features and NAs automatically)Train the RF classifierEvaluate the classifier (accuracy, recall, precision, ROC AUC, confusion matrix, plotting)Feature ImportanceTune the hyper-parameters with Random Searc...
Logical Operators | Practice | GeeksforGeeks
Logical operators are used when we want to check the truth value of certain statements. Logical operators help us in checking multiple statements together for their truthness. Here we will learn logical operators like AND(&&), OR(||), NOT(!). These operators produce either a true or a false as an output. Example: Input: a = 6 b = 7 Output:1 1 0 Explanation:a && b = 1 a || b = 1 (!a) && (!b) = 0 Your Task: Your task is to complete the provided function. Constraints: 1 <= a, b,<= 100 Video: YouTubeGeeksforGeeks502K subscribersC++ Programming Language Tutorial | Operators in C / C++ | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.Full screen is unavailable. Learn MoreYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WFy9SFJsAWQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 0 nraj38853 months ago https://www.techdark.in 0 nraj38853 months ago https://www.techdark.in 0 jsannauniv11123 months ago 0 yadavprashant10163 months ago It's Simple in C++ : void logicOp(int a, int b) {cout<<(a && b)<<" “<<(a || b)<< ” "<<(!a) && (!b); cout<<endl; } 0 swnkhurana6 months ago void logicOp(int a, int b){ /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/ bool x = a&&b; bool y = a||b; bool z = (!a) && (!b); cout<< x <<" "<< y <<" "<< z << endl;} 0 martial9 months ago martial https://uploads.disquscdn.c... https://uploads.disquscdn.c... 0 Yogeshwari Harode10 months ago Yogeshwari Harode Logical Operators https://github.com/yogeshwa...programs/blob/master/C++/Logical%20Operators.cpp 0 yogeshwari harode11 months ago yogeshwari harode Logical Operators (Simplest way)https://github.com/yogeshwa... +1 SACHIN KUMAR1 year ago SACHIN KUMAR void logicOp(int a, int b){ /*output (a&&b), (a||b), and ((!a)&&(!b))separated by spaces*/ cout<< (a && b)<<" "; cout<< (a||b)<<" "; cout<<(!a); cout<<endl; }=""> 0 Saurabh Yadav2 years ago Saurabh Yadav why its working when I write endl statement at the end of code.... if i write at the starting its showing error We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 402, "s": 226, "text": "Logical operators are used when we want to check the truth value of certain statements. Logical operators help us in checking multiple statements together for their truthness." }, { "code": null, "e": 532, "s": 402, "text": "Here we wi...
Java Program to generate random numbers string
At first, create a character array − static char num[] = { '0', '1', '2', '3', '4', '5' }; Now, let’s say you want to a string with length. Create a StringBuilder and use append() to create random numbers string out of it − int len = 5; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < len; i++) { strBuilder.append(randomNum()); } Above, we created a randomNum() function that returns the random numbers string − public static char randomNum() { return num[(int) Math.floor(Math.random() * 5)]; } Live Demo public class Demo { static char num[] = { '0', '1', '2', '3', '4', '5' }; public static char randomNum() { return num[(int) Math.floor(Math.random() * 5)]; } public static void main(String[] args) { int len = 5; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < len; i++) { strBuilder.append(randomNum()); } System.out.println("Random numbers string = "+strBuilder.toString()); } } Random numbers string = 23024
[ { "code": null, "e": 1099, "s": 1062, "text": "At first, create a character array −" }, { "code": null, "e": 1153, "s": 1099, "text": "static char num[] = { '0', '1', '2', '3', '4', '5' };" }, { "code": null, "e": 1286, "s": 1153, "text": "Now, let’s say you w...
Chef - Client Setup
In order to make Chef node communicate with Chef server, you need to set up Chef client on the node. This is one of the key components of Chef node, which retrieves the cookbooks from the Chef server and executes them on the node. It is also known as the Chef provisioner. Here, we will use Vagrant to manage VM. Vagrant can also be configured with the provisioner such as Shell script, Chef and Puppet to get VM into a desired state. In our case, we will use Vagrant to manage VMs using VirtualBox and Chef client as a provisioner. Step 1 − Download and install VirtualBox from https://www.virtualbox.org/wiki/downlod Step 2 − Download and install Vagrant at http://downloads.vagrantup.com Step 3 − Install Vagrant Omnibus plugin to enable Vagrant to install Chef client on the VM. $ vagrant plugin install vagrant-omnibus Step 1 − We can download the required Vagrant box from the Opscode vagrant repo. Download the opscode-ubuntu-12.04 box from the following URL https://opscode-vmbento.s3.amazonaws.com/vagrant/opscode_ubuntu-12.04_provisionerless.box Step 2 − Once you have the Vagrant file, download the path you need to edit the Vagrant file. vipin@laptop:~/chef-repo $ subl Vagrantfile Vagrant.configure("2") do |config| config.vm.box = "opscode-ubuntu-12.04" config.vm.box_url = https://opscode-vm-bento.s3.amazonaws.com/ vagrant/opscode_ubuntu-12.04_provisionerless.box config.omnibus.chef_version = :latest config.vm.provision :chef_client do |chef| chef.provisioning_path = "/etc/chef" chef.chef_server_url = "https://api.opscode.com/ organizations/<YOUR_ORG>" chef.validation_key_path = "/.chef/<YOUR_ORG>-validator.pem" chef.validation_client_name = "<YOUR_ORG>-validator" chef.node_name = "server" end end In the above program, you need to update the <YOUR_ORG> name with the correct or required organization name. Step 3 − Next step after the configuration is, to get the vagrant box up. For this, you need to move to the location where Vagrant box is located and run the following command. $ vagrant up Step 4 − Once the machine is up, you can login to the machine using the following command. $ vagrant ssh In the above command, vagrantfile is written in a Ruby Domain Specific Language (DSL) for configuring the vagrant virtual machine. In the vagrant file, we have the config object. Vagrant will use this config object to configure the VM. Vagrant.configure("2") do |config| ....... End Inside the config block, you will tell vagrant which VM image to use, in order to boot the node. config.vm.box = "opscode-ubuntu-12.04" config.vm.box_url = https://opscode-vm-bento.s3.amazonaws.com/ vagrant/opscode_ubuntu-12.04_provisionerless.box In the next step, you will tell Vagrant to download the omnibus plugin. config.omnibus.chef_version = :latest After selecting the VM box to boot, configure how to provision the box using Chef. config.vm.provision :chef_client do |chef| ..... End Inside this, you need to set up instruction on how to hook up the virtual node to the Chef server. You need to tell Vagrant where you need to store all the Chef stuff on the node. chef.provisioning_path = "/etc/chef" Print Add Notes Bookmark this page
[ { "code": null, "e": 2481, "s": 2380, "text": "In order to make Chef node communicate with Chef server, you need to set up Chef client on the node." }, { "code": null, "e": 2653, "s": 2481, "text": "This is one of the key components of Chef node, which retrieves the cookbooks fro...
Principle of Information System Security - GeeksforGeeks
15 Jan, 2020 Information System Security or INFOSEC refers to the process of providing protection to the computers, networks and the associated data. With the advent of technology, the more the information is stored over wide networks, the more crucial it gets to protect it from the unauthorized which might misuse the same. Every organisation has the data sets that contain confidential information about its activities. The major reason of providing security to the information systems is not just one fold but 3 fold: 1. Confidentiality 2. Integrity 3. Availability Together, these tiers form the CIA triangle that happened to be known as the foremost necessity of securing the information system. These three levels justify the principle of information system security. Let us go through the same one by one: Confidentiality:The main essence of this feature lies in the fact that only the authorized personnel should be allowed the access to the data and system. The unauthorised individuals must be kept away from the information. This is ensured by checking the authorisation of every individual who tries to access the database.For eg. An organisation’s administration must not be allowed to access the private information of the employees.Integrity:Integrity is ensured when the presented data is untouched or rather, is not altered by any unauthorized power. The information thus can be referred with the eyes closed. The integrity of the information can be altered in either unintentional or intentional ways. Intentionally, information can be passed through malicious content by any individual. Rather, unintentionally, any authorized individual might himself hamper the information for example, he might delete any specific important part of information.Availability:This feature means that the information can be accessed and modified by any authorized personnel within a given time frame. The point here to be noted is that the accessibility of the information in limited. The time frame within which it can be accessed is different for every organisation. Confidentiality:The main essence of this feature lies in the fact that only the authorized personnel should be allowed the access to the data and system. The unauthorised individuals must be kept away from the information. This is ensured by checking the authorisation of every individual who tries to access the database.For eg. An organisation’s administration must not be allowed to access the private information of the employees. For eg. An organisation’s administration must not be allowed to access the private information of the employees. Integrity:Integrity is ensured when the presented data is untouched or rather, is not altered by any unauthorized power. The information thus can be referred with the eyes closed. The integrity of the information can be altered in either unintentional or intentional ways. Intentionally, information can be passed through malicious content by any individual. Rather, unintentionally, any authorized individual might himself hamper the information for example, he might delete any specific important part of information. Availability:This feature means that the information can be accessed and modified by any authorized personnel within a given time frame. The point here to be noted is that the accessibility of the information in limited. The time frame within which it can be accessed is different for every organisation. Balancing Information Security and Access:It is the sole purpose of the organisation to protect the interests of the users and to provide them with appropriate amount of information whenever necessary. Also, at the same time, it is necessary to provide adequate security to the information so that not anyone can access it. The need for maintaining the perfect balance of information security and accessibility arises from the fact that information security can never be absolute. It would be harmful to provide free access to a piece of information and it would be hard to restrict any accessibility. So, one needs to make sure that the exact required balance is maintained so that both the users and the security professionals are happy. Tools of Information Security:There are various tools which are or which can be used by various organisations in order to ensure the maximum information system security. These tools however, do not guarantee the absolute security, but as stated above, helps in forming the crucial balance of information access and security. Let us study these tools one by one: Authentication:This is the foremost important tool that needs to be kept in mind before starting the crucial process of ensuring security. The process of authentication is when the system identifies someone with one or more than one factors. These factors must be unique for most of the users. For example, ID and password combinations, face recognition, thumb impression etc.These factors can not always be trusted as one could lose them or it might be accessed by any outsider. For these circumstances, one can use multi factor authorisation which is done by combining any two or more of the above factors.Access Control:After ensuring that the right individual gets the access to information, one has to make sure that only the appropriate information reaches him or her. By using the tool of access control, the system judges that which user must be able to re4ad or write or modify certain piece of information. For this it generally maintains a list of all the users. One could find two type of lists :Access Control List (ACL) – This is just the list of individuals who are eligible to access the informationRole- Based access Control List (RBAC) – This list comprises of the names of authorized personnel and their respective actions they are authorized to perform over the information.Encryption:Sometimes the information is transmitted over the internet so the risk of anyone accessing it increases and now the tools have to be strong to avoid it. In this scenario, the information can be easily accessed and modified by anyone. To avoid this, a new tool is put to work, Encryption. Using encryption, one can put the confidential information into bits of unreadable characters that are difficult to decrypt and only the authorised receivers of the information can read it easily. Authentication:This is the foremost important tool that needs to be kept in mind before starting the crucial process of ensuring security. The process of authentication is when the system identifies someone with one or more than one factors. These factors must be unique for most of the users. For example, ID and password combinations, face recognition, thumb impression etc.These factors can not always be trusted as one could lose them or it might be accessed by any outsider. For these circumstances, one can use multi factor authorisation which is done by combining any two or more of the above factors. These factors can not always be trusted as one could lose them or it might be accessed by any outsider. For these circumstances, one can use multi factor authorisation which is done by combining any two or more of the above factors. Access Control:After ensuring that the right individual gets the access to information, one has to make sure that only the appropriate information reaches him or her. By using the tool of access control, the system judges that which user must be able to re4ad or write or modify certain piece of information. For this it generally maintains a list of all the users. One could find two type of lists :Access Control List (ACL) – This is just the list of individuals who are eligible to access the informationRole- Based access Control List (RBAC) – This list comprises of the names of authorized personnel and their respective actions they are authorized to perform over the information. Access Control List (ACL) – This is just the list of individuals who are eligible to access the information Role- Based access Control List (RBAC) – This list comprises of the names of authorized personnel and their respective actions they are authorized to perform over the information. Encryption:Sometimes the information is transmitted over the internet so the risk of anyone accessing it increases and now the tools have to be strong to avoid it. In this scenario, the information can be easily accessed and modified by anyone. To avoid this, a new tool is put to work, Encryption. Using encryption, one can put the confidential information into bits of unreadable characters that are difficult to decrypt and only the authorised receivers of the information can read it easily. cryptography Information-Security Computer Networks Technical Scripter cryptography Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C RSA Algorithm in Cryptography Differences between TCP and UDP Data encryption standard (DES) | Set 1 Types of Network Topology Socket Programming in Python Types of Transmission Media UDP Server-Client implementation in C TCP 3-Way Handshake Process Differences between IPv4 and IPv6
[ { "code": null, "e": 23909, "s": 23881, "text": "\n15 Jan, 2020" }, { "code": null, "e": 24319, "s": 23909, "text": "Information System Security or INFOSEC refers to the process of providing protection to the computers, networks and the associated data. With the advent of technol...
How to implement ActionEvent using method reference in JavaFX?
The javafx.event package provides a framework for Java FX events. The Event class serves as the base class for JavaFX events and associated with each event is an event source, an event target, and an event type. An ActionEvent widely used when a button is pressed. In the below program, we can implement an ActionEvent for a button by using method reference. import javafx.application.*; import javafx.beans.property.*; import javafx.event.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; import javafx.scene.effect.*; public class MethodReferenceJavaFXTest extends Application { private Label label; public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { Pane root = new StackPane(); label = new Label("Method Reference"); Button clickMe = new Button("Click Me"); clickMe.setOnAction(this::handleClickMe); // method reference root.getChildren().addAll(label, clickMe); primaryStage.setTitle("Method Reference Test"); primaryStage.setScene(new Scene(root, 300, 200)); primaryStage.show(); } private void handleClickMe(ActionEvent event) { if(label.getEffect() == null) { label.setEffect(new BoxBlur()); } else { label.setEffect(null); } } }
[ { "code": null, "e": 1327, "s": 1062, "text": "The javafx.event package provides a framework for Java FX events. The Event class serves as the base class for JavaFX events and associated with each event is an event source, an event target, and an event type. An ActionEvent widely used when a button ...
Find records with a specific last digit in column with MySQL
For this, use the RIGHT() method to fetch records with a specific last digit. Let us first create a table − mysql> create table DemoTable823(Value varchar(100)); Query OK, 0 rows affected (0.54 sec) Insert some records in the table using insert command − mysql> insert into DemoTable823 values('9847826'); Query OK, 1 row affected (0.52 sec) mysql> insert into DemoTable823 values('84747464'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable823 values('9899889883'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable823 values('123456'); Query OK, 1 row affected (0.10 sec) Display all records from the table using select statement − mysql> select *from DemoTable823; This will produce the following output − +------------+ | Value | +------------+ | 9847826 | | 84747464 | | 9899889883 | | 123456 | +------------+ 4 rows in set (0.00 sec) Following is the query to find records with a specific last digit − mysql> select *from DemoTable823 where right(Value,1)='6'; This will produce the following output − +---------+ | Value | +---------+ | 9847826 | | 123456 | +---------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1170, "s": 1062, "text": "For this, use the RIGHT() method to fetch records with a specific last digit. Let us first create a table −" }, { "code": null, "e": 1261, "s": 1170, "text": "mysql> create table DemoTable823(Value varchar(100));\nQuery OK, 0 rows af...
Getting Started with Python Pre-commit Hooks | by Edward Krueger | Towards Data Science
By: Edward Krueger and Douglas Franklin Here is the template for this project. We use poetry for package management. This article is focused on pre-commit hooks. github.com Pre-commit hooks are a subset of Git hooks. Git-hooks are scripts that run automatically every time a particular event occurs in a Git repository. A “pre-commit hook” runs before a commit takes place. These Python hooks are considered a method of static analysis. Static code analysis is a method of debugging done by examining code without executing it. Pre-commit hooks are often used to make sure code is linted and formatted properly before being published. In our project, we use four pre-commit hooks, black, check-large-files, pylint and our custom hookcreate-requirements. We specify these Python hooks in a YAML file called pre-commit-config.yaml. YAML is a human-readable data-serialization language that is commonly used for configuration files. YAML files contain lists and dictionaries with key/value pairs. Confusingly, there is also a Python package called pre-commit. Pre-commit is a management tool for pre-commit hooks. This package manages the installation and execution hooks before every commit. We will need thispre-commit package as a dev-requirement. Additionally, the hook check-added-large-files is from this pre-commit package, as you can see in our .yamlfile later. Notice that under[tool.poetry.dev-dependecies]you find pre-commit. Setting up git hooks is surprisingly easy with the package pre-commit. All we need to do is create and format a .pre-commit-config.yaml file within our project. Then the packagepre-commit looks for this .yamlfile when you run: > pre-commit install Since Python our Python hooks are stored as YAML in the source code, they are distributed automatically when we upload this file to Git. This makes setting up a project’s pre-commit hooks on a new machine is as easy as cloning the repo and running the above line. This process is more complicated if you are not using the Python package, pre-commit, and the standard format they have made available to us. This is a good general use pre-commit-config.yaml. We can see that under repos is a list of dictionaries with key/value pairs to specify hooks and their behaviors. This YAML contains hooks for formatting, a file size filter, a linter, and our custom hook. Each hook has an accompanying id, seen on lines 5, 9, 12, and 18. This is a standard .yaml format. You can see the repo keys nested within repos. Each of these repo keys is followed by the value (URL) of the required hook code. Lines 2 and 6 have URLs that correspond to Github repositories. On line 10, we specify that the following hooks arelocal ones. This means that locally we run pylint using the bash code on line 14 and create-requirements with the code on line 20. Running pylint locally gives us more control over the lining behavior because we can specify how the bash command works. This saves us time with debugging pylint issues and allows for more transparency and customization. Additionally, running pylint locally means you are using the version of pylint in your environment. It is worth noting that on lines 3 and 7 we use rev to specify versions of the hooks we want to use. These versions may not be in sync with the versions in your virtual environment. You will have to keep these versions in sync manually. If this is an issue, you can run all your hooks locally to ensure the hooks are using the same version you've specified in your virtual environment. We run poetry run pre-commit install to initialize the git hooks. Now our pre-commit hooks will run when we commit code. The terminal output here is straightforward. We see that each hook has a skipped,passed, or failed result. Black is skipped as there are no changed Python files to run formatting on. The hook check-added-large-files passes because there are no files over 5Mb being committed. pylint fails to find any linting errors in our Python files. Lastly, we notice that our custom hook fails because our requirements.txt file is not in sync with our pyproject.toml. Let's say we’ve made the changes needed so that all of our pre-commit hooks pass (or skip) and we/ve used git add include the changes in our commit. Now when we run git commit our output looks slightly different. Since all of our pre-commit Python hooks have passed or skipped the commit will be completed and staged. Note that when a hook fails so does the commit. This is how pre-commit hooks save us from making bad commits when our code is not up to our standards. Now we can git push and make the changes to our source code knowing that our commit is devoid of syntax errors, unnecessary large files, or an outdated requirements.txt file. Remember, a“pre-commit hook” runs before a commit takes place. Pre-commit, the Python package, makes it easy for us to manage and run the hooks we need to ensure code is linted and formatted properly before being published. With minimal setup, pre-commit hooks can save you time by avoiding mistaken commits. Pre-commit hooks like black ensure the code you publish is clean and professional. Pylint shows us errors before we add them to a codebase. The large-file-check warns you before you accidentally commit large files to git. It’s very hard to reverse such an accidental commit, so it’s better to prevent it in advance. You can even code your own pre-commit hooks as bash scripts for custom needs. For example, you can require tests to run before code is committed. For more information on using bash to code your own pre-commit hooks check out this article!
[ { "code": null, "e": 212, "s": 172, "text": "By: Edward Krueger and Douglas Franklin" }, { "code": null, "e": 334, "s": 212, "text": "Here is the template for this project. We use poetry for package management. This article is focused on pre-commit hooks." }, { "code": nu...
Post and Pre incremented of arrays in C language
Explaining the array post and pre incremented concept with the help of C program. Increment operator (++) − It is used to increment the value of a variable by 1 It is used to increment the value of a variable by 1 There two types of increment operators − pre increment and post increment. There two types of increment operators − pre increment and post increment. Increment operator is placed before the operand in preincrement and the value is first incremented and then operation is performed on it. Increment operator is placed before the operand in preincrement and the value is first incremented and then operation is performed on it. eg: z = ++a; a= a+1 z=a Increment operator is placed after the operand in post increment and the value is incremented after the operation is performed. Increment operator is placed after the operand in post increment and the value is incremented after the operation is performed. eg: z = a++; z=a a= a+1 Let’s consider an example to access particular elements in memory locations by using pre- and post-increment. Declare an array of size 5 and do compile time initialization. After that try to assign a pre incremented value to ‘a’ variable. a=++arr[1] // arr[1]=arr[1]+1 a=arr[1] b=arr[1]++// b=arr[1] arr[1]+1 Live Demo #include<stdio.h> int main(){ int a, b, c; int arr[5] = {1, 2, 3, 25, 7}; a = ++arr[1]; b = arr[1]++; c = arr[a++]; printf("%d--%d--%d", a, b, c); return 0; } 4--3--25 here, a = ++arr[1]; i.e a = 3 //arr[2]; b = arr[1]++; i.e b = 3 //arr[2]; c = arr[a++]; i.e c = 25 //arr[4]; printf("%d--%d--%d",a, b, c); printf("%d--%d--%d",4, 3, 25); Thus 4--3--25 is outputted Consider another example to know more about pre- and post-incremented of array. Live Demo #include<stdio.h> int main(){ int a, b, c; int arr[5] = {1, 2, 3, 25, 7}; a = ++arr[3]; b = arr[3]++; c = arr[a++]; printf("%d--%d--%d", a, b, c); return 0; } 27--26—0
[ { "code": null, "e": 1144, "s": 1062, "text": "Explaining the array post and pre incremented concept with the help of C program." }, { "code": null, "e": 1170, "s": 1144, "text": "Increment operator (++) −" }, { "code": null, "e": 1223, "s": 1170, "text": "It ...
C# - if Statement
An if statement consists of a boolean expression followed by one or more statements. The syntax of an if statement in C# is − if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } If the boolean expression evaluates to true, then the block of code inside the if statement is executed. If boolean expression evaluates to false, then the first set of code after the end of the if statement(after the closing curly brace) is executed. using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* local variable definition */ int a = 10; /* check the boolean condition using if statement */ if (a < 20) { /* if condition is true then print the following */ Console.WriteLine("a is less than 20"); } Console.WriteLine("value of a is : {0}", a); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result − a is less than 20; value of a is : 10 119 Lectures 23.5 hours Raja Biswas 37 Lectures 13 hours Trevoir Williams 16 Lectures 1 hours Peter Jepson 159 Lectures 21.5 hours Ebenezer Ogbu 193 Lectures 17 hours Arnold Higuit 24 Lectures 2.5 hours Eric Frick Print Add Notes Bookmark this page
[ { "code": null, "e": 2355, "s": 2270, "text": "An if statement consists of a boolean expression followed by one or more statements." }, { "code": null, "e": 2396, "s": 2355, "text": "The syntax of an if statement in C# is −" }, { "code": null, "e": 2493, "s": 2396...
Python | os.dup() method - GeeksforGeeks
13 Jul, 2021 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. A file descriptor is small integer value that corresponds to a file or other input/output resource, such as a pipe or network socket. A File descriptor is an abstract indicator of a resource and act as handle to perform various lower level I/O operations like read, write, send etc. For Example: Standard input is usually file descriptor with value 0, standard output is usually file descriptor with value 1 and standard error is usually file descriptor with value 2. Further files opened by the current process will get the value 3, 4, 5 an so on. os.dup() method in Python is used to duplicate the given file descriptor. The duplicated file descriptor is non-inheritable, But on Windows platform, file descriptor associated with standard stream (standard input: 0, standard output: 1, standard error: 2) which can be inherited by child processes. Inheritable file descriptor means if the parent process has a file descriptor 4 in use for a particular file and parent creates a child process then the child process will also have file descriptor 4 in use for that same file. Syntax: os.dup(fd) Parameter: fd: A file descriptor, which is to be duplicated. Return Type: This method returns the duplicated file descriptor, which is an integer value. Code: Use of os.dup() method to duplicate a file descriptor Python3 # Python3 program to explain os.dup() method # importing os moduleimport os # File pathpath = "/home/ihritik/Desktop/file.txt" # open the file and get# the file descriptor associated# with it using os.open() methodfd = os.open(path, os.O_WRONLY) # Print the value of# file descriptorprint("Original file descriptor:", fd) # Duplicate the file descriptordup_fd = os.dup(fd) # The duplicated file will have# different value but it# will correspond to the same# file to which original file# descriptor was referring # Print the value of# duplicated file descriptorprint("Duplicated file descriptor:", dup_fd) # Get the list of all# file Descriptors Used# by the current Process# (below code works on UNIX systems)pid = os.getpid()os.system("ls -l/proc/%s/fd" %pid) # Close file descriptorsos.close(fd)os.close(dup_fd) print("File descriptor duplicated successfully") Original file descriptor: 3 Duplicated file descriptor: 4 total 0 lrwx------ 1 ihritik ihritik 64 Jun 14 06:45 0 -> /dev/pts/0 lrwx------ 1 ihritik ihritik 64 Jun 14 06:45 1 -> /dev/pts/0 lrwx------ 1 ihritik ihritik 64 Jun 14 06:45 2 -> /dev/pts/0 l-wx------ 1 ihritik ihritik 64 Jun 14 06:45 3 -> /home/ihritik/Desktop/file.txt l-wx------ 1 ihritik ihritik 64 Jun 14 06:45 4 -> /home/ihritik/Desktop/file.txt File descriptor duplicated successfully kalrap615 python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n13 Jul, 2021" }, { "code": null, "e": 24511, "s": 24292, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable...
Decision Trees — Machine Learning in Python | Towards Data Science
In this article, we will look into Decision Trees, another basic and important Machine Learning algorithm to have in your ML algorithms toolbox. We will start by looking into what it does and how it works. We won’t be looking into the mathematics part as it’s another article on its own. We will then implement it using scikit-learn What are Decision Trees Python Implementation (Dummy Data) Python Implementation (Real-World Dataset) Plotting the Decision Tree Applications Conclusion What you can do Other ML Algorithms This is part of my 30-Day Article Writing Challenge. Feel free to check out the articles on my pledge post: nouman10.medium.com A Decision Tree is a machine learning algorithm used for classification as well as regression purposes (although, in this article, we will be focusing on classification). As the name suggests, it does behave just like a tree. It works on the basis of conditions. Every condition breaks the training data into two or more smaller sets of training data. For instance, if we are building an application that decides whether a person’s application for a loan should be accepted or not. We can start by checking the credit score of the applicant. If it’s below some threshold, we reject the application. Otherwise, we check for other things, all the way down until everything is checked and we accept the application. An example for that would be as follows: Let’s start by implementing Decision trees on some dummy data. We start by importing the tree module from scikit-learn and initializing the dummy data and the classifier. We fit the classifier to the data and predict using some new data. The classifier predicts the new data as 1. Let’s plot using the built-in plot_tree in the tree module tree.plot_tree(clf) This plots the following tree: At the root node, we have 5 samples. It checks for the first value in X and if it's less than or equal to 0.5, it classifies the sample as 0. If it’s not, then it checks if the first value in X is less than or equal to 1.5, in which case it assigns the label 1 to it, otherwise 2. Note that the decision tree doesn’t include any check on the second value in X. This is not an error as the second value is not needed in this case. If the decision tree is able to make all the classifications without the need for all the features, then it can ignore other features. Let’s now implement it using the iris dataset. The code is the same as above, except we load the iris dataset using scikit-learn The accuracy, in this case, is 100% as the decision tree is able to build a tree that classifies all the training data accurately. We won’t be using the built-in plot_tree function for plotting the tree here. In the next section, we will be using graphviz to plot the decision tree instead. Let’s plot the tree for the above classifier using graphviz . graphviz allows us to create a decision tree that is more aesthetically pleasing and is easily understandable by even a non-technical person, who hasn’t heard about decision trees before. We will use the following code to plot the decision tree: We call the export_graphviz function from the tree module and give it the feature and class names. We can even save the tree to a file but we aren’t doing it in this case. This is the output from the above code: See how you can easily interpret the decision tree One of the applications of decision trees involves evaluating prospective growth opportunities for businesses based on historical data. Another application of decision trees is in the use of demographic data to find prospective clients. Lenders also use decision trees to predict the probability of a customer defaulting on a loan, by applying predictive model generation using the client’s past data. Let’s conclude what we have done in this article: We started with a general explanation of how Decision Trees work We then implemented it in Python on some dummy data and later on a dataset We then plotted the decision trees built using scikit-learn Finally, we looked into the applications of decision trees. Try to implement Decision Trees from scratch. For this, you need to understand the maths behind Decision Trees Compare your implementation to the one in scikit-learn Test the above code on various other datasets. Feel free to reach out to me if you have any questions. Do follow me as I plan to cover more Machine Learning algorithms in the future Linear Regression — Machine Learning Algorithms with Implementation in Python medium.com K-Nearest Neighbors — Machine Learning Algorithms with Implementation in Python nouman10.medium.com K-Means — Machine Learning Algorithms with Implementation in Python towardsdatascience.com If you feel that above content was useful for you, do share it and feel free to support me ->
[ { "code": null, "e": 316, "s": 171, "text": "In this article, we will look into Decision Trees, another basic and important Machine Learning algorithm to have in your ML algorithms toolbox." }, { "code": null, "e": 504, "s": 316, "text": "We will start by looking into what it doe...
Create the marquee text effect using JavaScript - GeeksforGeeks
17 Mar, 2021 In this article, we will be creating marquee text using JavaScript. This effect can be achieved using the <marquee> tag, but the marquee has been deprecated and the new websites do not use this tag. Still some browsers support this tag but to be on the safe side you should not use this tag. Here is the example below of how the marque tag works. Example: In this example we will use the HTML marquee tag. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Marquee tag example</title></head> <body> <marquee> GeeksForGeeks | A computer science portal for geeks </marquee> <br><br><br><br> <marquee direction="right"> GeeksForGeeks | A computer science portal for geeks </marquee> <br><br><br><br> <marquee direction="up"> GeeksForGeeks | A computer science portal for geeks </marquee> <br><br><br><br> <marquee direction="down"> GeeksForGeeks | A computer science portal for geeks </marquee> </body> </html> Output: Note: Do not use the marquee tag inside your code because it is deprecated and can break your code in the future. Using Javascript : To avoid the deprecation of the marquee tag you can implement your own JavaScript code to achieve this effect. First, we create an HTML skeleton. Create a div tag and inside the div tag create some <p> tags that hold your text. HTML Code: HTML <!DOCTYPE html><html><body> <div id="main"> <p class="para" id="para1"> Geeksforgeeks | A computer science portal for geeks </p> <p class="para" id="para2"> This is another text </p> <p class="para" id="para3"> This is the third line of the example line of the example. </p> </div></body> </html> CSS Code: Now add some CSS to the code. Here in the wrapper div (In which all the <p> tags reside) make the overflow hidden (This is necessary) and set the background color, border, width of your choice. And in the <p> tag there should be three necessary properties white-space, float, and clear. The white-space should be set to nowrap, float to be left, and clear to be both and other designing properties of your choice. CSS <style> #main{ border: 1px solid; background: yellow; width: 100%; overflow: hidden; } .para{ color: black; font-weight: bold; white-space: nowrap; clear: both; float: left; }</style> JavaScript Code: Now the main part of adding logic to move the text. What we do is decrease the margin-left property of the <p> elements, When the element becomes invisible we again assign the margin-left equal to the width of the parent element of the <p> element. These are the step-by-step process to implement this logic. Create a variable named elementWidth and assign the offsetWidth of the <p> element Create a variable name parentWidth and assign the offsetWidth of the parent element of the <p> element. Create flag variable and initialize it with 0 Create a setInterval with a 10-millisecond refresh rate. At every Interval decrease the flag value and set that value to the margin-left property. If the negative value of the flag is equal to the element’s width then set the value of margin-left equal to the parent’s width. Javascript const para1 = document.getElementById("para1");const para2 = document.getElementById("para2");const para3 = document.getElementById("para3"); animate(para1);animate(para2);animate(para3); function animate(element) { let elementWidth = element.offsetWidth; let parentWidth = element.parentElement.offsetWidth; let flag = 0; setInterval(() => { element.style.marginLeft = --flag + "px"; if (elementWidth == -flag) { flag = parentWidth; } }, 10);} Output: After combining above three section we will see something like this. CSS-Properties HTML-Tags JavaScript-Questions CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n17 Mar, 2021" }, { "code": null, "e": 25723, "s": 25376, "text": "In this article, we will be creating marquee text using JavaScript. This effect can be achieved using the <marquee> tag, but the marquee has been deprecated and th...
CSS - Fade Out Up Effect
The image come or cause to come gradually into or out of view, or to merge into another shot. @keyframes fadeOutUp { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-20px); } } Transform − Transform applies to 2d and 3d transformation to an element. Transform − Transform applies to 2d and 3d transformation to an element. Opacity − Opacity applies to an element to make translucence. Opacity − Opacity applies to an element to make translucence. <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s; animation-duration: 10s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes fadeOutUp { 0% { opacity: 1; -webkit-transform: translateY(0); } 100% { opacity: 0; -webkit-transform: translateY(-20px); } } @keyframes fadeOutUp { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-20px); } } .fadeOutUp { -webkit-animation-name: fadeOutUp; animation-name: fadeOutUp; } </style> </head> <body> <div id = "animated-example" class = "animated fadeOutUp"></div> <button onclick = "myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html> It will produce the following result − Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who is Who Print Add Notes Bookmark this page
[ { "code": null, "e": 2720, "s": 2626, "text": "The image come or cause to come gradually into or out of view, or to merge into another shot." }, { "code": null, "e": 2878, "s": 2720, "text": "@keyframes fadeOutUp {\n 0% {\n opacity: 1;\n transform: translateY(0);\n ...
Setting up Environment for Machine Learning with R Programming - GeeksforGeeks
22 Jul, 2020 Machine Learning is a subset of Artificial Intelligence (AI), which is used to create intelligent systems that are able to learn without being programmed explicitly. In machine learning, we create algorithms and models which is used by an intelligent system to predict outcomes based on particular patterns or trends which are observed from the given data. Machine learning follows a unique principle of using data and the outcomes from the data to predict the rules which are stored in a model. This model is then used to predict outcomes from a different set of data. In R programming the environment for machine learning can be set easily through RStudio. Step 1: Install Anaconda (Linux, Windows) and launch the navigator. Step 2: Open Anaconda Navigator and click the Install button for Rstudio. Step 3: After installation, create a new environment. Anaconda will then send a prompt asking to enter a name for the new environment and the lunch the R studio. Method 1: R commands can run from the console provided in R studio. After opening Rstudio simply type R commands to the console. Method 2: R commands can be stored in a file and can be executed in an anaconda prompt. This can be achieved by the following steps. Open an anaconda promptGo to the directory where the R file is locatedActivate the anaconda environment by using the command:conda activate <ENVIRONMENT_NAME>Run the file by using the command: Rscript <FILE_NAME>.R Open an anaconda prompt Go to the directory where the R file is located Activate the anaconda environment by using the command:conda activate <ENVIRONMENT_NAME> conda activate <ENVIRONMENT_NAME> Run the file by using the command: Rscript <FILE_NAME>.R Rscript <FILE_NAME>.R Packages help make code easier to write as they contain a set of predefined functions that perform various tasks. The most used machine learning packages are Caret, e1071, net, kernlab, and randomforest. There are two methods that can be used to install these packages for your R program. Method 1: Installing Packages through Rstudio Open Rstudio and click the Install Packages option under Tools which is present in the menubar.Enter the names of all the packages you want to install separated by spaces or commas and then click install.Method 2: Installing Packages through Anaconda prompt/Rstudio consoleOpen an Anaconda prompt.Switch the environment to the environment you used for Rstudio using the command:conda activate <ENVIRONMENT_NAME>Enter the command r to open the R console.Install the required packages using the command:install.packages(c("<PACKAGE_1>", "<PACKAGE_2>", ..., "<PACKAGE_N>"))While downloading the packages you might be prompted to choose a CRAN mirror. It is recommended to choose the location closest to you for a faster download.Machine Learning packages in RThere are many R libraries that contain a host of functions, tools, and methods to manage and analyze data. Each of these libraries has a particular focus with some libraries managing image and textual data, data manipulation, data visualization, web crawling, machine learning, and so on. Here let’s discuss some of the important machine learning packages by demonstrating an example.Example:Preparing the Data Set:Before using these packages first of all import the data set into RStudio, cleaning the data set, and split the data into train and test data set. Download the CSV file from this link.# Import the data setData <- read.csv("GenderClassification.csv", stringsAsFactors = TRUE)# Using set.seed()# Generating random numberset.seed(10) # Cleaning the data setData$Favorite.Color <- as.numeric (Data$Favorite.Color)Data$Favorite.Music.Genre <- as.numeric (Data$Favorite.Music.Genre)Data$Favorite.Beverage <- as.numeric (Data$Favorite.Beverage)Data$Favorite.Soft.Drink <- as.numeric (Data$Favorite.Soft.Drink) # Split into train and test data setTrainingSize <- createDataPartition(Data$Gender, p = 0.8, list = FALSE)TrainingData <- Data[TrainingSize,]TestingData <- Data[-TrainingSize,]CARET: Caret stands for classification and regression training. The CARET package is used for performing classification and for regression tasks. It consists of many other built-in packages.# Using CARET package # Importing the librarylibrary(caret) # Using the train() available in# Caret packagemodel <- train(Gender ~ ., data = TrainingData, method = "svmPoly", na.action = na.omit, preProcess = c("scale", "center"), trControl = trainControl(method = "none"), tuneGrid = data.frame(degree = 1, scale = 1, C = 1))model.cv <- train(Gender ~ ., data = TrainingData, method = "svmPoly", na.action = na.omit, preProcess = c("scale", "center"), trControl = trainControl(method = "cv", number = 6), tuneGrid = data.frame(degree = 1, scale = 1, C = 1)) # Printing the modelsprint(model)print(model.cv)Output:ggplot2: R is most famous for its visualization library ggplot2. It provides an aesthetic set of graphics that are also interactive. The ggplot2 package is used for creating plots and for visualising data.# Using ggplot2 # Creating a bar plot from the # Data's Favorite.Color attributeggplot(Data, aes(Favorite.Color)) + geom_bar(fill = "#0073C2FF")Output:randomForest: The randomForest package allows us to use the random forest algorithm easily.# Using randomforset # Importing the randomForest packagelibrary(randomForest) # Using the randomForest function # From the randomForest packagemodel <- randomForest(formula = Gender ~ ., data = Data)print(model)Output:nnet: The nnet package uses neural networks in deep learning to create layers which help in training and predicting models. The loss (the difference between the actual value and predicted value) decreases after every iteration of training.# Using nnet # Importing the nnet packagelibrary(nnet) # Using the nnet function# In the nnet package model <- nnet(formula = Gender ~ ., data = Data, size = 30)print(model)Output:e1071: The e1071 package is used to implement the support vector machines, naive bayes algorithm and many other algorithms.# Using e1071 # Importing the e1071 packagelibrary(e1071) # Using the svm function # In the e1071 packagemodel <- svm(formula = Gender ~ ., data = Data)print(model)Output:rpart: The rpart package is used to partition data. It is used for classification and regression tasks. The resultant model is in the form of a binary tree.# Using rpart # Importing the rpart packagelibrary(rpart) # Using the rpart function# To partition datapartition <- rpart(formula = Gender~., data = Data)plot(partition)Output:dplyr: Like rpart the dplyr package is also a data manipulation package. It helps manipulate data by using functions such as filter, select, and arrange.# Using dplyr # Importing the dplyr packagelibrary(dplyr) # Using the filter function# From the dplyr package Data %>% filter(Gender == "M")Output:My Personal Notes arrow_drop_upSave Open Rstudio and click the Install Packages option under Tools which is present in the menubar. Enter the names of all the packages you want to install separated by spaces or commas and then click install.Method 2: Installing Packages through Anaconda prompt/Rstudio consoleOpen an Anaconda prompt.Switch the environment to the environment you used for Rstudio using the command:conda activate <ENVIRONMENT_NAME>Enter the command r to open the R console.Install the required packages using the command:install.packages(c("<PACKAGE_1>", "<PACKAGE_2>", ..., "<PACKAGE_N>"))While downloading the packages you might be prompted to choose a CRAN mirror. It is recommended to choose the location closest to you for a faster download.Machine Learning packages in RThere are many R libraries that contain a host of functions, tools, and methods to manage and analyze data. Each of these libraries has a particular focus with some libraries managing image and textual data, data manipulation, data visualization, web crawling, machine learning, and so on. Here let’s discuss some of the important machine learning packages by demonstrating an example.Example:Preparing the Data Set:Before using these packages first of all import the data set into RStudio, cleaning the data set, and split the data into train and test data set. Download the CSV file from this link.# Import the data setData <- read.csv("GenderClassification.csv", stringsAsFactors = TRUE)# Using set.seed()# Generating random numberset.seed(10) # Cleaning the data setData$Favorite.Color <- as.numeric (Data$Favorite.Color)Data$Favorite.Music.Genre <- as.numeric (Data$Favorite.Music.Genre)Data$Favorite.Beverage <- as.numeric (Data$Favorite.Beverage)Data$Favorite.Soft.Drink <- as.numeric (Data$Favorite.Soft.Drink) # Split into train and test data setTrainingSize <- createDataPartition(Data$Gender, p = 0.8, list = FALSE)TrainingData <- Data[TrainingSize,]TestingData <- Data[-TrainingSize,]CARET: Caret stands for classification and regression training. The CARET package is used for performing classification and for regression tasks. It consists of many other built-in packages.# Using CARET package # Importing the librarylibrary(caret) # Using the train() available in# Caret packagemodel <- train(Gender ~ ., data = TrainingData, method = "svmPoly", na.action = na.omit, preProcess = c("scale", "center"), trControl = trainControl(method = "none"), tuneGrid = data.frame(degree = 1, scale = 1, C = 1))model.cv <- train(Gender ~ ., data = TrainingData, method = "svmPoly", na.action = na.omit, preProcess = c("scale", "center"), trControl = trainControl(method = "cv", number = 6), tuneGrid = data.frame(degree = 1, scale = 1, C = 1)) # Printing the modelsprint(model)print(model.cv)Output:ggplot2: R is most famous for its visualization library ggplot2. It provides an aesthetic set of graphics that are also interactive. The ggplot2 package is used for creating plots and for visualising data.# Using ggplot2 # Creating a bar plot from the # Data's Favorite.Color attributeggplot(Data, aes(Favorite.Color)) + geom_bar(fill = "#0073C2FF")Output:randomForest: The randomForest package allows us to use the random forest algorithm easily.# Using randomforset # Importing the randomForest packagelibrary(randomForest) # Using the randomForest function # From the randomForest packagemodel <- randomForest(formula = Gender ~ ., data = Data)print(model)Output:nnet: The nnet package uses neural networks in deep learning to create layers which help in training and predicting models. The loss (the difference between the actual value and predicted value) decreases after every iteration of training.# Using nnet # Importing the nnet packagelibrary(nnet) # Using the nnet function# In the nnet package model <- nnet(formula = Gender ~ ., data = Data, size = 30)print(model)Output:e1071: The e1071 package is used to implement the support vector machines, naive bayes algorithm and many other algorithms.# Using e1071 # Importing the e1071 packagelibrary(e1071) # Using the svm function # In the e1071 packagemodel <- svm(formula = Gender ~ ., data = Data)print(model)Output:rpart: The rpart package is used to partition data. It is used for classification and regression tasks. The resultant model is in the form of a binary tree.# Using rpart # Importing the rpart packagelibrary(rpart) # Using the rpart function# To partition datapartition <- rpart(formula = Gender~., data = Data)plot(partition)Output:dplyr: Like rpart the dplyr package is also a data manipulation package. It helps manipulate data by using functions such as filter, select, and arrange.# Using dplyr # Importing the dplyr packagelibrary(dplyr) # Using the filter function# From the dplyr package Data %>% filter(Gender == "M")Output:My Personal Notes arrow_drop_upSave Method 2: Installing Packages through Anaconda prompt/Rstudio console Open an Anaconda prompt.Switch the environment to the environment you used for Rstudio using the command:conda activate <ENVIRONMENT_NAME>Enter the command r to open the R console.Install the required packages using the command:install.packages(c("<PACKAGE_1>", "<PACKAGE_2>", ..., "<PACKAGE_N>")) Open an Anaconda prompt. Switch the environment to the environment you used for Rstudio using the command:conda activate <ENVIRONMENT_NAME> conda activate <ENVIRONMENT_NAME> Enter the command r to open the R console. Install the required packages using the command:install.packages(c("<PACKAGE_1>", "<PACKAGE_2>", ..., "<PACKAGE_N>")) install.packages(c("<PACKAGE_1>", "<PACKAGE_2>", ..., "<PACKAGE_N>")) While downloading the packages you might be prompted to choose a CRAN mirror. It is recommended to choose the location closest to you for a faster download. There are many R libraries that contain a host of functions, tools, and methods to manage and analyze data. Each of these libraries has a particular focus with some libraries managing image and textual data, data manipulation, data visualization, web crawling, machine learning, and so on. Here let’s discuss some of the important machine learning packages by demonstrating an example. Preparing the Data Set:Before using these packages first of all import the data set into RStudio, cleaning the data set, and split the data into train and test data set. Download the CSV file from this link. # Import the data setData <- read.csv("GenderClassification.csv", stringsAsFactors = TRUE)# Using set.seed()# Generating random numberset.seed(10) # Cleaning the data setData$Favorite.Color <- as.numeric (Data$Favorite.Color)Data$Favorite.Music.Genre <- as.numeric (Data$Favorite.Music.Genre)Data$Favorite.Beverage <- as.numeric (Data$Favorite.Beverage)Data$Favorite.Soft.Drink <- as.numeric (Data$Favorite.Soft.Drink) # Split into train and test data setTrainingSize <- createDataPartition(Data$Gender, p = 0.8, list = FALSE)TrainingData <- Data[TrainingSize,]TestingData <- Data[-TrainingSize,] CARET: Caret stands for classification and regression training. The CARET package is used for performing classification and for regression tasks. It consists of many other built-in packages. # Using CARET package # Importing the librarylibrary(caret) # Using the train() available in# Caret packagemodel <- train(Gender ~ ., data = TrainingData, method = "svmPoly", na.action = na.omit, preProcess = c("scale", "center"), trControl = trainControl(method = "none"), tuneGrid = data.frame(degree = 1, scale = 1, C = 1))model.cv <- train(Gender ~ ., data = TrainingData, method = "svmPoly", na.action = na.omit, preProcess = c("scale", "center"), trControl = trainControl(method = "cv", number = 6), tuneGrid = data.frame(degree = 1, scale = 1, C = 1)) # Printing the modelsprint(model)print(model.cv) Output: ggplot2: R is most famous for its visualization library ggplot2. It provides an aesthetic set of graphics that are also interactive. The ggplot2 package is used for creating plots and for visualising data. # Using ggplot2 # Creating a bar plot from the # Data's Favorite.Color attributeggplot(Data, aes(Favorite.Color)) + geom_bar(fill = "#0073C2FF") Output: randomForest: The randomForest package allows us to use the random forest algorithm easily. # Using randomforset # Importing the randomForest packagelibrary(randomForest) # Using the randomForest function # From the randomForest packagemodel <- randomForest(formula = Gender ~ ., data = Data)print(model) Output: nnet: The nnet package uses neural networks in deep learning to create layers which help in training and predicting models. The loss (the difference between the actual value and predicted value) decreases after every iteration of training. # Using nnet # Importing the nnet packagelibrary(nnet) # Using the nnet function# In the nnet package model <- nnet(formula = Gender ~ ., data = Data, size = 30)print(model) Output: e1071: The e1071 package is used to implement the support vector machines, naive bayes algorithm and many other algorithms. # Using e1071 # Importing the e1071 packagelibrary(e1071) # Using the svm function # In the e1071 packagemodel <- svm(formula = Gender ~ ., data = Data)print(model) Output: rpart: The rpart package is used to partition data. It is used for classification and regression tasks. The resultant model is in the form of a binary tree. # Using rpart # Importing the rpart packagelibrary(rpart) # Using the rpart function# To partition datapartition <- rpart(formula = Gender~., data = Data)plot(partition) Output: dplyr: Like rpart the dplyr package is also a data manipulation package. It helps manipulate data by using functions such as filter, select, and arrange. # Using dplyr # Importing the dplyr packagelibrary(dplyr) # Using the filter function# From the dplyr package Data %>% filter(Gender == "M") Output: Picked R Machine-Learning R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Adding elements in a vector in R programming - append() method Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Convert Factor to Numeric and Numeric to Factor in R Programming How to Change Axis Scales in R Plots? Remove rows with NA in one column of R DataFrame
[ { "code": null, "e": 29044, "s": 29016, "text": "\n22 Jul, 2020" }, { "code": null, "e": 29703, "s": 29044, "text": "Machine Learning is a subset of Artificial Intelligence (AI), which is used to create intelligent systems that are able to learn without being programmed explicitl...
Program for sum of cos(x) series - GeeksforGeeks
31 Mar, 2021 Given n and x, where n is the number of terms in the series and x is the value of the angle in degree. Program to calculate the value of cosine of x using series expansion formula and compare the value with the library function’s output. Formula Used : cos x = 1 – (x2 / 2 !) + (x4 / 4 !) – (x6 / 6 !) +... Examples : Input : n = 3 x = 90 Output : Sum of the cosine series is = -0.23 The value using library function is = -0.000204 Input : n = 4 x = 45 Output : Sum of the cosine series is = 0.71 The value using library function is = 0.707035 C++ Java Python3 C# PHP Javascript // CPP program to find the// sum of cos(x) series#include <bits/stdc++.h>using namespace std; const double PI = 3.142; double cosXSertiesSum(double x, int n){ // here x is in degree. // we have to convert it to radian // for using it with series formula, // as in series expansion angle is in radian x = x * (PI / 180.0); double res = 1; double sign = 1, fact = 1, pow = 1; for (int i = 1; i < 5; i++) { sign = sign * -1; fact = fact * (2 * i - 1) * (2 * i); pow = pow * x * x; res = res + sign * pow / fact; } return res;} // Driver Codeint main(){ float x = 50; int n = 5; cout << cosXSertiesSum(x, 5); return 0;} // Java program to find// the sum of cos(x) seriesimport java.lang.Math.*; class GFG{ static final double PI = 3.142; static double cosXSertiesSum(double x, int n) { // here x is in degree. // we have to convert it to radian // for using it with series formula, // as in series expansion angle is in radian x = x * (PI / 180.0); double res = 1; double sign = 1, fact = 1, pow = 1; for (int i = 1; i < 5; i++) { sign = sign * -1; fact = fact * (2 * i - 1) * (2 * i); pow = pow * x * x; res = res + sign * pow / fact; } return res; } // Driver Code public static void main(String[] args) { float x = 50; int n = 5; System.out.println((float)( cosXSertiesSum(x, 5) * 1000000) / 1000000.00); }} // This code is contributed by Smitha. # Python3 program to find the# sum of cos(x) series PI = 3.142; def cosXSertiesSum(x, n): # here x is in degree. # we have to convert it to radian # for using it with series formula, # as in series expansion angle is in radian x = x * (PI / 180.0); res = 1; sign = 1; fact = 1; pow = 1; for i in range(1,5): sign = sign * (-1); fact = fact * (2 * i - 1) * (2 * i); pow = pow * x * x; res = res + sign * pow / fact; return res; # Driver Codex = 50;n = 5;print(round(cosXSertiesSum(x, 5), 6)); # This code is contributed by mits // C# program to find the// sum of cos(x) seriesusing System; class GFG{ static double PI = 3.142; static double cosXSertiesSum(double x, int n) { // here x is in degree. // we have to convert it to radian // for using it with series formula, // as in series expansion angle is in radian x = x * (PI / 180.0); double res = 1; double sign = 1, fact = 1, pow = 1; for (int i = 1; i < 5; i++) { sign = sign * -1; fact = fact * (2 * i - 1) * (2 * i); pow = pow * x * x; res = res + sign * pow / fact; } return res; } // Driver Code public static void Main() { float x = 50; int n = 5; Console.Write((float)(cosXSertiesSum(x, n) * 1000000) / 1000000.00); }} // This code is contributed by Smitha. <?php// PHP program to find the// sum of cos(x) series $PI = 3.142; function cosXSertiesSum($x, $n){ global $PI; // here x is in degree. // we have to convert it to radian // for using it with series formula, // as in series expansion angle is in radian $x = $x * ($PI / 180.0); $res = 1; $sign = 1; $fact = 1; $pow = 1; for ( $i = 1; $i < 5; $i++) { $sign = $sign * -1; $fact = $fact * (2 * $i - 1) * (2 * $i); $pow = $pow * $x * $x; $res = $res + $sign * $pow / $fact; } return $res;} // Driver Code$x = 50;$n = 5;echo cosXSertiesSum($x, 5); // This code is contributed by aj_36?> <script> // Javascript program to find// the sum of cos(x) series const PI = 3.142; function cosXSertiesSum( x, n) { // here x is in degree. // we have to convert it to radian // for using it with series formula, // as in series expansion angle is in radian x = x * (PI / 180.0); let res = 1; let sign = 1, fact = 1, pow = 1,i; for ( i = 1; i < 5; i++) { sign = sign * -1; fact = fact * (2 * i - 1) * (2 * i); pow = pow * x * x; res = res + sign * pow / fact; } return res; } // Driver Code let x = 50; let n = 5; document.write( ((cosXSertiesSum(x, 5) * 1000000) / 1000000.00).toFixed(6)); // This code is contributed by shikhasingrajput </script> 0.642701 Note that we can also find cos(x) using library function. C++ C Java Python3 C# PHP Javascript // C++ code to illustrate// the use of cos function#include <bits/stdc++.h>using namespace std; #define PI 3.14159265 int main (){ double x, ret, val; x = 60.0; val = PI / 180.0; ret = cos(x * val); cout << "The cosine of " << fixed << setprecision(6) << x << " is "; cout << fixed << setprecision(6) << ret << " degrees" << endl; x = 90.0; val = PI / 180.0; ret = cos(x * val); cout << "The cosine of " << fixed << setprecision(6) << x << " is "; cout << fixed << setprecision(6) << ret << " degrees" << endl; return(0);} // This code is contributed by shubhamsingh10 // C code to illustrate// the use of cos function#include <stdio.h>#include <math.h> #define PI 3.14159265 int main (){double x, ret, val; x = 60.0;val = PI / 180.0;ret = cos( x * val );printf("The cosine of %lf is ", x);printf("%lf degrees\n", ret); x = 90.0;val = PI / 180.0;ret = cos( x*val );printf("The cosine of %lf is ", x);printf("%lf degrees\n", ret); return(0);} // Java code to illustrate// the use of cos functionimport java.io.*; class GFG{static final double PI = 3.142;public static void main (String[] args){ double x, ret, val; x = 60.0; val =(int)PI / 180.0; ret = Math.cos(x * val); System.out.print("The cosine of " + x + " is "); System.out.print(ret); System.out.println(" degrees"); x = 90.0; val = (int)PI / 180.0; ret = Math.cos( x*val ); System.out.print("The cosine of " + x + " is "); System.out.print(ret); System.out.println(" degrees");}} // This code is contributed// by ajit # Python3 code to illustrate# the use of cos functionimport math if __name__=='__main__': PI = 3.14159265 x = 60.0 val = PI / 180.0 ret = math.cos(x * val) print("The cosine of is ", x, end=" ") print(" degrees", ret) x = 90.0 val = PI / 180.0 ret = math.cos(x * val) print("The cosine of is ", x, end=" ") print("degrees", ret) # This code is contributed by# Sanjit_Prasad // C# code to illustrate// the use of cos functionusing System; class GFG{ // Constant PI Declarationstatic double PI = 3.142; // Driver Codestatic public void Main (){ double x, ret, val; x = 60.0; val = (int)PI / 180.0; ret = Math.Cos(x * val); Console.Write("The cosine of " + x + " is "); Console.Write(ret); Console.WriteLine(" degrees"); x = 90.0; val = (int)PI / 180.0; ret = Math.Cos(x * val); Console.Write("The cosine of " + x + " is "); Console.Write(ret); Console.WriteLine(" degrees");}} // This code is contributed// by akt_mit <?php//PHP code to illustrate// the use of cos function $PI =3.14159265; $x; $ret; $val; $x = 60.0;$val = $PI / 180.0;$ret = cos( $x * $val );echo "The cosine of is ", $x;echo "degrees", $ret;echo "\n"; $x = 90.0;$val = $PI / 180.0;$ret = cos( $x * $val );echo "The cosine of is ", $x;echo "degrees ", $ret; // This code is contributed by aj_36?> <script> // javascript code to illustrate// the use of cos function var PI = 3.142; var x, ret, val; x = 60.0; val = PI / 180.0; ret = Math.cos(x * val); document.write("The cosine of " + x + " is "); document.write(ret.toFixed(5)); document.write(" degrees"); document.write("<br>") x = 90.0; val = PI / 180.0; ret = parseInt(Math.cos( x*val )); document.write("The cosine of " + x + " is "); document.write(ret.toFixed(5)); document.write(" degrees"); // This code contributed by shikhasingrajput </script> The cosine of 60.000000 is 0.500000 degrees The cosine of 90.000000 is 0.000000 degrees Smitha Dinesh Semwal jit_t Sanjit_Prasad Mithun Kumar SHUBHAMSINGH10 kumarv456 shikhasingrajput series-sum Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Print all possible combinations of r elements in a given array of size n Operators in C / C++ Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26035, "s": 26007, "text": "\n31 Mar, 2021" }, { "code": null, "e": 26273, "s": 26035, "text": "Given n and x, where n is the number of terms in the series and x is the value of the angle in degree. Program to calculate the value of cosine of x using series e...
Sum of first N terms of Quadratic Sequence 3 + 7 + 13 + ... - GeeksforGeeks
08 Apr, 2021 Given a quadratic series as given below, the task is to find sum of first n terms of this series. Sn = 3 + 7 + 13 + 21 + 31 + ..... + upto n terms Examples: Input: N = 3 Output: 23 Input: N = 4 Output: 44 Approach: Let the series be represented as Sn = 3 + 7 + 13 + ... + tn where Sn represents the sum of the series till n terms. tn represents the nth term of the series. Now, to formulate the series, the elements need to be formed by taking the difference of the consecutive elements of the series. Equation 1: Sn = 3 + 7 + 13 + 21 + 31 +.....+ tn-1 + tn Equation 2: Sn = 0 + 3 + 7 + 13 + 21 + 31 + ...... + tn-1 + tn (writing the above series by shifting all elements to right by 1 position) Now, Subtract Equation 2 from Equation 1 i.e. (Equation 1 – Equation 2) Sn – Sn = (3 – 0) + (7 – 3) + (13 – 7) + (31 – 21) + ...... + (tn- tn-1) – tn => 0 = 3 + 4 + 6 + 8 + 10 + ...... + (tn – tn-1) – tn In above series, leaving 3 aside, terms starting from 4 to (tn – tn-1) will form an A.P.Since formula of sum of n terms of A.P. is: Sn = n*(2*a + (n – 1)*d)/2 which implies, In series: 4 + 6 + 8 + ... + (tn – tn-1) AP is formed with (n-1) terms. Hence, Sum of this series: (n-1)*(2*4 + (n-2)*2)/2 Therefore, the original series: 0 = 3 + (n-1)*(2*4 + (n-2)*2)/2 – tn where tn = n^2 + n + 1 which is the nth term.Therefore, Sum of first n terms of series will be:tn = n^2 + n + 1 Sn = (n^2) + n + (1) Sn = n*(n+1)*(n+2)/6 + n*(n+1)/2 + n Sn = n*(n^2 + 3*n + 5)/3 Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ program to find sum of first n terms #include <bits/stdc++.h>using namespace std; int calculateSum(int n){ // Sum = n*(n^2 + 3*n + 5)/3 return n * (pow(n, 2) + 3 * n + 5) / 3;} int main(){ // number of terms to be included in the sum int n = 3; // find the Sum cout << "Sum = " << calculateSum(n); return 0;} // Java program to find sum of first n termsimport java.util.*; class solution{//function to calculate sum of n terms of the seriesstatic int calculateSum(int n){ // Sum = n*(n^2 + 3*n + 5)/3 return n * (int) (Math.pow(n, 2) + 3 * n + 5 )/ 3;} public static void main(String arr[]){ // number of terms to be included in the sum int n = 3; // find the Sum System.out.println("Sum = " +calculateSum(n)); }} # Python 3 program to find sum# of first n termsfrom math import pow def calculateSum(n): # Sum = n*(n^2 + 3*n + 5)/3 return n * (pow(n, 2) + 3 * n + 5) / 3 if __name__ == '__main__': # number of terms to be included # in the sum n = 3 # find the Sum print("Sum =", int(calculateSum(n))) # This code is contributed by# Sanjit_Prasad // C# program to find sum of first n termsusing System;class gfg{ public double calculateSum(int n) { // Sum = n*(n^2 + 3*n + 5)/3 return (n * (Math.Pow(n, 2) + 3 * n + 5) / 3); }} //driver codeclass geek{ public static int Main() { gfg g = new gfg(); // number of terms to be included in the sum int n = 3; //find the Sum Console.WriteLine( "Sum = {0}", g.calculateSum(n)); return 0; }} <?php// PHP program to find sum// of first n terms function calculateSum($n){ // Sum = n*(n^2 + 3*n + 5)/3 return $n * (pow($n, 2) + 3 * $n + 5) / 3;} // Driver Code // number of terms to be// included in the sum$n = 3; // find the Sumecho "Sum = " . calculateSum($n); // This code is contributed by mits?> <script> // Javascript program to find sum of first n terms // Function to find the quadratic// equation whose roots are a and bfunction calculateSum(n){ // Sum = n*(n^2 + 3*n + 5)/3 return n * (Math.pow(n, 2) + 3 * n + 5 ) / 3;} // Driver Code // Number of terms to be// included in the sumvar n = 3; // Find the Sum document.write("Sum = " + calculateSum(n)); // This code is contributed by Ankita saini </script> Sum = 23 SURENDRA_GANGWAR SoumikMondal Mithun Kumar Sanjit_Prasad Akanksha_Rai ankita_saini series series-sum Mathematical School Programming Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Sieve of Eratosthenes Program to find GCD or HCF of two numbers Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26386, "s": 26358, "text": "\n08 Apr, 2021" }, { "code": null, "e": 26484, "s": 26386, "text": "Given a quadratic series as given below, the task is to find sum of first n terms of this series." }, { "code": null, "e": 26533, "s": 26484, "...
Java Math IEEEremainder() method with Examples - GeeksforGeeks
16 Apr, 2018 The java.lang.Math.IEEEremainder() method computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.The remainder value is mathematically equal to f1 – f2 x n, where n is the mathematical integer closest to the exact mathematical value of the quotient f1/f2, and if two mathematical integers are equally close to f1/f2, then n is the integer that is even.Note : If the remainder is zero, its sign is the same as the sign of the first argument. If either argument is NaN, or the first argument is infinite, or the second argument is positive zero or negative zero, then the result is NaN. If the first argument is finite and the second argument is infinite, then the result is the same as the first argument. Syntax: public static double IEEEremainder(double dividend, double divisor) Parameter: dividend : the dividend. divisor : the divisor. Return : This method returns the remainder when dividend is divided by divisor. Example 1: To show working of java.lang.Math.IEEEremainder() method. // Java program to demonstrate working// of java.lang.Math.IEEEremainder() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double did1 = 31.34; double dis1 = 2.2; System.out.println(Math.IEEEremainder(did1, dis1)); double did2 = -21.0; double dis2 = 7.0; // Sign of did2 is negative, Output is negative zero System.out.println(Math.IEEEremainder(did2, dis2)); double did3 = 1.0 / 0; double dis3 = 0.0; // First argument is infinity and Second argument is zero // Output NaN System.out.println(Math.IEEEremainder(did3, dis3)); double did4 = -2.34; double dis4 = 1.0 / 0; // First argument finite and Second argument is infinity // Output first argument System.out.println(Math.IEEEremainder(did4, dis4)); }} Output: 0.5399999999999974 -0.0 NaN -2.34 Java-lang package java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. HashMap in Java with Examples Stream In Java Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Multithreading in Java
[ { "code": null, "e": 25651, "s": 25623, "text": "\n16 Apr, 2018" }, { "code": null, "e": 26044, "s": 25651, "text": "The java.lang.Math.IEEEremainder() method computes the remainder operation on two arguments as prescribed by the IEEE 754 standard.The remainder value is mathemati...
JavaScript Interview Questions and Answers | Set-2 - GeeksforGeeks
05 Nov, 2019 We have already discussed some questions in JavaScript Interview Questions and Answers | Set-1 . Below are some more related questions:What are all the looping structures in JavaScript ?while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.for loop: A for loop provides a concise way of writing the loop structure. Unlike a while loop, for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.do while: A do-while loop is similar to while loop with the only difference that it checks the condition after executing the statements, and therefore is an example of Exit Control Loop. How can style/class of an element be changed ?To change the style/class of an element there are two possible ways.document.getElementById("myText").style.fontSize = "16px;document.getElementById("myText").className = "class"; Explain how to read and write a file using JavaScript ?The readFile() functions is used for reading operation.readFile( Path, Options, Callback)The writeFile() functions is used for writing operation.writeFile( Path, Data, Callback) What is called Variable typing in JavaScript ?The variable typing is the type of variable used to store a number and using that same variable to assign a “string”.Geeks = 42; Geeks = "GeeksforGeeks"; How to convert the string of any base to integer in JavaScript ?In JavaScript, parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function. The parseInt() function returns Nan (not a number) when the string doesn’t contain number. Explain how to detect the operating system on the client machine ?To detect the operating system on the client machine, one can simply use navigator.appVersion or navigator.userAgent property. The Navigator appVersion property is a read-only property and it returns the string that represents the version information of the browser. What are the types of Pop up boxes available in JavaScript ?There are three types of pop boxes available in JavaScript.AlertConfirmPrompt What is the difference between an alert box and a confirmation box ?An alert box will display only one button which is the OK button. It is used to inform the user about the agreement has to agree. But a Confirmation box displays two buttons OK and cancel, where the user can decide to agree or not. What is the disadvantage of using innerHTML in JavaScript ?There are lots of disadvantages of using the innerHTML in JavaScript like the content will replace everywhere. If you use += like “innerHTML = innerHTML + ‘html'” still the old content is replaced by HTML. It preserves event handlers attached to any DOM elements. What is the use of void(0) ?The void(0) is used to call another method without refreshing the page during the calling time parameter “zero” will be passed. What are JavaScript Cookies ?Cookies are small files that are stored on a user’s computer. They are used to hold a modest amount of data specific to a particular client and website and can be accessed either by the web server or by the client computer. When cookies were invented, they were basically little documents containing information about you and your preferences. For instance, when you select your language in which you want to view your website, the website would save the information in a document called a cookie on your computer, and the next time when you visit the website, it would be able to read a cookie saved earlier. How to create a cookie using JavaScript ?To create a cookie by using JavaScript you just need to assign a string value to the document.cookie object.document.cookie = "key1 = value1; key2 = value2; expires = date"; How to read a cookie using JavaScript ?The value of the document.cookie is used to create a cookie. Whenever you want to access the cookie you can use the string. The document.cookie string keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and the value is its string value. How to delete a cookie using JavaScript ?Deleting cookie is much easier than creating or reading a cookie, you just need to set the expires = “past time” and make sure one thing defines the right cookie path unless few will not allow you to delete the cookie. What are escape characters and escape() function ?Escape character: This character is required when you want to work with some special characters like single and double quotes, apostrophes and ampersands. All the special character plays an important role in JavaScript, to ignore that or to print that special character, you can use the escape character backslash “\”. It will normally ignores and behave like a normal character.// Need escape character document.write("GeeksforGeeks: A Computer Science Portal "for Geeks" ") document.write("GeeksforGeeks: A Computer Science Portal \"for Geeks\" ")escape() function: The escape() function takes a string as a parameter and encodes it so that it can be transmitted to any computer in any network which supports ASCII characters. Whether JavaScript has a concept level scope ?JavaScript is not concept level scope, its declared the variable inside any function has scope inside the function. How generic objects can be created in JavaScript ?To create a generic object in JavaScript usevar I = new object(); Which keywords are used to handle exceptions ?When executing JavaScript code, errors will almost definitely occur. These errors can occur due to the fault from the programmer’s side due to the wrong input or even if there is a problem with the logic of the program. But all errors can be solved by using the below commands.The try statement lets you test a block of code to check for errors.The catch statement lets you handle the error if any are present.The throw statement lets you make your own errors. What is the use of the blur function ?It is used to remove focus from the selected element. This method starts the blur event or it can be attached a function to run when a blur event occurs. What is the unshift method in JavaScript ?It is used to insert elements in the front of an array. It is like a push method that insert elements at the beginning of the array. We have already discussed some questions in JavaScript Interview Questions and Answers | Set-1 . Below are some more related questions: What are all the looping structures in JavaScript ?while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.for loop: A for loop provides a concise way of writing the loop structure. Unlike a while loop, for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.do while: A do-while loop is similar to while loop with the only difference that it checks the condition after executing the statements, and therefore is an example of Exit Control Loop. while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. for loop: A for loop provides a concise way of writing the loop structure. Unlike a while loop, for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping. do while: A do-while loop is similar to while loop with the only difference that it checks the condition after executing the statements, and therefore is an example of Exit Control Loop. How can style/class of an element be changed ?To change the style/class of an element there are two possible ways.document.getElementById("myText").style.fontSize = "16px;document.getElementById("myText").className = "class"; document.getElementById("myText").style.fontSize = "16px; document.getElementById("myText").style.fontSize = "16px; document.getElementById("myText").className = "class"; document.getElementById("myText").className = "class"; Explain how to read and write a file using JavaScript ?The readFile() functions is used for reading operation.readFile( Path, Options, Callback)The writeFile() functions is used for writing operation.writeFile( Path, Data, Callback) The readFile() functions is used for reading operation.readFile( Path, Options, Callback) readFile( Path, Options, Callback) The writeFile() functions is used for writing operation.writeFile( Path, Data, Callback) writeFile( Path, Data, Callback) What is called Variable typing in JavaScript ?The variable typing is the type of variable used to store a number and using that same variable to assign a “string”.Geeks = 42; Geeks = "GeeksforGeeks"; Geeks = 42; Geeks = "GeeksforGeeks"; How to convert the string of any base to integer in JavaScript ?In JavaScript, parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function. The parseInt() function returns Nan (not a number) when the string doesn’t contain number. Explain how to detect the operating system on the client machine ?To detect the operating system on the client machine, one can simply use navigator.appVersion or navigator.userAgent property. The Navigator appVersion property is a read-only property and it returns the string that represents the version information of the browser. What are the types of Pop up boxes available in JavaScript ?There are three types of pop boxes available in JavaScript.AlertConfirmPrompt Alert Confirm Prompt What is the difference between an alert box and a confirmation box ?An alert box will display only one button which is the OK button. It is used to inform the user about the agreement has to agree. But a Confirmation box displays two buttons OK and cancel, where the user can decide to agree or not. What is the disadvantage of using innerHTML in JavaScript ?There are lots of disadvantages of using the innerHTML in JavaScript like the content will replace everywhere. If you use += like “innerHTML = innerHTML + ‘html'” still the old content is replaced by HTML. It preserves event handlers attached to any DOM elements. What is the use of void(0) ?The void(0) is used to call another method without refreshing the page during the calling time parameter “zero” will be passed. What are JavaScript Cookies ?Cookies are small files that are stored on a user’s computer. They are used to hold a modest amount of data specific to a particular client and website and can be accessed either by the web server or by the client computer. When cookies were invented, they were basically little documents containing information about you and your preferences. For instance, when you select your language in which you want to view your website, the website would save the information in a document called a cookie on your computer, and the next time when you visit the website, it would be able to read a cookie saved earlier. How to create a cookie using JavaScript ?To create a cookie by using JavaScript you just need to assign a string value to the document.cookie object.document.cookie = "key1 = value1; key2 = value2; expires = date"; document.cookie = "key1 = value1; key2 = value2; expires = date"; How to read a cookie using JavaScript ?The value of the document.cookie is used to create a cookie. Whenever you want to access the cookie you can use the string. The document.cookie string keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and the value is its string value. How to delete a cookie using JavaScript ?Deleting cookie is much easier than creating or reading a cookie, you just need to set the expires = “past time” and make sure one thing defines the right cookie path unless few will not allow you to delete the cookie. What are escape characters and escape() function ?Escape character: This character is required when you want to work with some special characters like single and double quotes, apostrophes and ampersands. All the special character plays an important role in JavaScript, to ignore that or to print that special character, you can use the escape character backslash “\”. It will normally ignores and behave like a normal character.// Need escape character document.write("GeeksforGeeks: A Computer Science Portal "for Geeks" ") document.write("GeeksforGeeks: A Computer Science Portal \"for Geeks\" ")escape() function: The escape() function takes a string as a parameter and encodes it so that it can be transmitted to any computer in any network which supports ASCII characters. Escape character: This character is required when you want to work with some special characters like single and double quotes, apostrophes and ampersands. All the special character plays an important role in JavaScript, to ignore that or to print that special character, you can use the escape character backslash “\”. It will normally ignores and behave like a normal character.// Need escape character document.write("GeeksforGeeks: A Computer Science Portal "for Geeks" ") document.write("GeeksforGeeks: A Computer Science Portal \"for Geeks\" ") // Need escape character document.write("GeeksforGeeks: A Computer Science Portal "for Geeks" ") document.write("GeeksforGeeks: A Computer Science Portal \"for Geeks\" ") escape() function: The escape() function takes a string as a parameter and encodes it so that it can be transmitted to any computer in any network which supports ASCII characters. Whether JavaScript has a concept level scope ?JavaScript is not concept level scope, its declared the variable inside any function has scope inside the function. How generic objects can be created in JavaScript ?To create a generic object in JavaScript usevar I = new object(); var I = new object(); Which keywords are used to handle exceptions ?When executing JavaScript code, errors will almost definitely occur. These errors can occur due to the fault from the programmer’s side due to the wrong input or even if there is a problem with the logic of the program. But all errors can be solved by using the below commands.The try statement lets you test a block of code to check for errors.The catch statement lets you handle the error if any are present.The throw statement lets you make your own errors. The try statement lets you test a block of code to check for errors. The catch statement lets you handle the error if any are present. The throw statement lets you make your own errors. What is the use of the blur function ?It is used to remove focus from the selected element. This method starts the blur event or it can be attached a function to run when a blur event occurs. What is the unshift method in JavaScript ?It is used to insert elements in the front of an array. It is like a push method that insert elements at the beginning of the array. interview-preparation JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26385, "s": 26357, "text": "\n05 Nov, 2019" }, { "code": null, "e": 32869, "s": 26385, "text": "We have already discussed some questions in JavaScript Interview Questions and Answers | Set-1 . Below are some more related questions:What are all the looping str...
Performance metrics for image steganography - GeeksforGeeks
28 Oct, 2021 Overview :Various methods are used to evaluate the quality of image steganography. Each of these methods assesses a different aspect of the result obtained after steganography. Some of the well-known methods are Mean Square Error(MSE), Peak Signal to Noise Ratio(PSNR), Structured Similarity Index Measure(SSIM), Payload Capacity. Payload capacity : Payload capacity refers to the measure of the volume of information present within the cover image. This measure is important in a steganographic system as the communication overhead depends on the maximum payload capacity. It is measured in Bits Per Pixel(BPP). BPP = NUMBER OF SECRET BITS EMBEDDED/ TOTAL NUMBER OF PIXELS Mean Square Error(MSE): Mean Square Error is the averaged value of the square of the pixel-by-pixel difference between the original image and stego-image. It gives us a measure of the error produced in the cover image due to the data embedding process. MSE=(mxn)-1∑mi=1 ∑ni=1I[I(i,j)-k(I,j)]2 Description –A lower value of MSE indicates a good quality embedding. m,n = Dimensions of the image I = Original Image K = stego-image Peak Signal to Noise Ratio(PSNR) : PSNR is another popular way to measure the degree of distortion in the cover image due to embedding. It is the ratio between the maximum possible value of a signal and the power of distortion noise(MSE). It is measured in dB’s. A higher value of PSNR indicates a better quality embedding. PSNR = 10xlog(MAX2/MSE) Description – MAX = 255 for a 8-bit grayscale image Structured Similarity Index Measurement(SSIM): SSIM is a metric of comparison to check the similarity between the cover image and stego-image. It measures the perceptual difference between the two images. SSIM=(2μxμy + c1)(2σxy +c2)/((μx)2+(μy)2 +c1)((σx)2 +(σy)2 + c2) Description – c1 = (k1l)2 c2 = (k2l)2 μx and μy are the mean intensity values of images x and y. (σx)2 is the variance of x, (σy)2 is the variance of y (σxy)2 is the covariance of x and y. c1 and c2 are the two stabilizing parameters, L is the dynamic range of pixel values (2#bits per pixel - 1) the contents k1=0.01 and k2=0.03. SSIM value close to 1 indicates good quality. saurabh1990aror Image-Processing Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Advanced Encryption Standard (AES) Intrusion Detection System (IDS) Introduction and IPv4 Datagram Header Secure Socket Layer (SSL) Cryptography and its Types Multiple Access Protocols in Computer Network Congestion Control in Computer Networks Routing Information Protocol (RIP) Architecture of Internet of Things (IoT) Block Cipher modes of Operation
[ { "code": null, "e": 25755, "s": 25727, "text": "\n28 Oct, 2021" }, { "code": null, "e": 26086, "s": 25755, "text": "Overview :Various methods are used to evaluate the quality of image steganography. Each of these methods assesses a different aspect of the result obtained after s...
SQL Query to Find Number of Employees According to Gender Whose DOB is Between a Given Range - GeeksforGeeks
19 Apr, 2021 Query in SQL is like a statement that performs a task. Here, we need to write a query that will find the number of employees according to gender whose DOB is in the given range. We will first create a database named “geeks” then we will create a table “department” in that database. Use the below SQL statement to create a database called geeks: CREATE DATABASE geeks; USE geeks; We have the following department table in our geeks database : CREATE TABLE department( ID int, NAME Varchar(20), Gender Varchar(5), DateOfBirth Date); You can use the below statement to query the description of the created table: EXEC sp_columns department; The date data type uses the format ‘YYYY-MM-DD‘. Use the below statement to add data to the department table: INSERT INTO department VALUES (1,'Neha','F','1994-06-03'); INSERT INTO department VALUES (2,'Harsh','M','1996-03-12'); INSERT INTO department VALUES (3,'Harsh','M','1995-05-01'); INSERT INTO department VALUES (4,'Rupali','F',1996-11-11'); INSERT INTO department VALUES (5,'Rohan','M','1992-03-08'); To verify the contents of the table use the below statement: SELECT * FROM department Get the number of employees according to their gender whose DOB is between a given range. Here, we will assume the DOB range to be from 1995-01-01 to 1996-12-31. Now we will use the below syntax to query for the number of employees according to gender whose DOB is between a given range: Syntax: SELECT column_name1, count(column_name1) FROM table_name WHERE column_name2 between value1 and value2 GROUP BY column_name1; So the query for our table goes as shown below: SELECT Gender,count(Gender) FROM department WHERE DateOfBirth between '1995-01-01' and '1996-12-31' GROUP BY gender; Output: Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT SQL using Python How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25538, "s": 25510, "text": "\n19 Apr, 2021" }, { "code": null, "e": 25716, "s": 25538, "text": "Query in SQL is like a statement that performs a task. Here, we need to write a query that will find the number of employees according to gender whose DOB is in th...
Increment odd positioned elements by 1 and decrement even positioned elements by 1 in an Array - GeeksforGeeks
29 Sep, 2021 Given an array arr[], the task is increment all the odd positioned elements by 1 and decrement all the even positioned elements by 1. Examples: Input: arr[] = {3, 6, 8} Output: 4 5 9 Input: arr[] = {9, 7, 3} Output: 10 6 4 Approach: Traverse the array element by element and if the current element’s position is odd then increment it by 1 else decrement it by 1. Print the contents of the updated array in the end. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Utility function to print// the contents of an arrayvoid printArr(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Function to increment all the odd// positioned elements by 1 and decrement// all the even positioned elements by 1void updateArr(int arr[], int n){ for (int i = 0; i < n; i++) // If current element is odd positioned if ((i + 1) % 2 == 1) arr[i]++; // If even positioned else arr[i]--; // Print the updated array printArr(arr, n);} // Driver codeint main(){ int arr[] = { 3, 6, 8 }; int n = sizeof(arr) / sizeof(arr[0]); updateArr(arr, n); return 0;} // Java implementation of the approachclass GfG{ // Utility function to print// the contents of an arraystatic void printArr(int arr[], int n){ for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");} // Function to increment all the odd// positioned elements by 1 and decrement// all the even positioned elements by 1static void updateArr(int arr[], int n){ for (int i = 0; i < n; i++) // If current element is odd positioned if ((i + 1) % 2 == 1) arr[i]++; // If even positioned else arr[i]--; // Print the updated array printArr(arr, n);} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 6, 8 }; int n = arr.length; updateArr(arr, n); }} // This code is contributed by Prerna Saini # Python3 implementation of the approach # Utility function to print# the contents of an arraydef printArr(arr, n): for i in range(0, n): print(arr[i], end = " "); # Function to increment all the odd# positioned elements by 1 and decrement# all the even positioned elements by 1def updateArr(arr, n): for i in range(0, n): # If current element is odd positioned if ((i + 1) % 2 == 1): arr[i] += 1; # If even positioned else: arr[i] -= 1; # Print the updated array printArr(arr, n); # Driver codeif __name__ == '__main__': arr = [3, 6, 8]; n = len(arr); updateArr(arr, n); # This code contributed by PrinciRaj1992 // C# implementation of the approachclass GfG{ // Utility function to print// the contents of an arraystatic void printArr(int []arr, int n){ for (int i = 0; i < n; i++) System.Console.Write(arr[i] + " ");} // Function to increment all the odd// positioned elements by 1 and decrement// all the even positioned elements by 1static void updateArr(int []arr, int n){ for (int i = 0; i < n; i++) // If current element is odd positioned if ((i + 1) % 2 == 1) arr[i]++; // If even positioned else arr[i]--; // Print the updated array printArr(arr, n);} // Driver codestatic void Main(){ int []arr = { 3, 6, 8 }; int n = arr.Length; updateArr(arr, n); }} // This code is contributed by mits <?php// PHP implementation of the approach // Utility function to print// the contents of an arrayfunction printArr($arr, $n){ for ($i = 0; $i < $n; $i++) echo $arr[$i] . " ";} // Function to increment all the odd// positioned elements by 1 and decrement// all the even positioned elements by 1function updateArr($arr, $n){ for ($i = 0; $i < $n; $i++) // If current element is odd positioned if (($i + 1) % 2 == 1) $arr[$i]++; // If even positioned else $arr[$i]--; // Print the updated array printArr($arr, $n);} // Driver code$arr = array( 3, 6, 8 );$n = count($arr);updateArr($arr, $n); // This code is contributed by mits?> <script> // javascript implementation of the approach // Utility function to print// the contents of an arrayfunction printArr(arr, n){ var i; for (i = 0; i < n; i++) document.write(arr[i] + " ");} // Function to increment all the odd// positioned elements by 1 and decrement// all the even positioned elements by 1function updateArr(arr, n){ var i; for (i = 0; i < n; i++) // If current element is odd positioned if ((i + 1) % 2 == 1) arr[i]++; // If even positioned else arr[i]--; // Print the updated array printArr(arr, n);} // Driver code var arr = [3, 6, 8]; var n = arr.length; updateArr(arr, n); </script> 4 5 9 Time Complexity: O(n) Auxiliary Space: O(1) prerna saini Mithun Kumar princiraj1992 subham348 bgangwar59 anikakapoor school-programming Algorithms Arrays Arrays Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms How to Start Learning DSA? Difference between NP hard and NP complete problem Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26583, "s": 26555, "text": "\n29 Sep, 2021" }, { "code": null, "e": 26717, "s": 26583, "text": "Given an array arr[], the task is increment all the odd positioned elements by 1 and decrement all the even positioned elements by 1." }, { "code": null, ...
Selfish Round Robin CPU Scheduling - GeeksforGeeks
01 Apr, 2021 Prerequisite – Program for Round Robin scheduling In the traditional Round Robin scheduling algorithm, all processes were treated equally for processing. The objective of the Selfish Round Robin is to give better service to processes that have been executing for a while than to newcomers. It’s a more logical and superior implementation compared to the normal Round Robin algorithm. Implementation:- Processes in the ready list are partitioned into two lists: NEW and ACCEPTED. The New processes wait while Accepted processes are serviced by the Round Robin. Priority of a new process increases at rate ‘a’ while the priority of an accepted process increases at rate ‘b’. When the priority of a new process reaches the priority of an accepted process, that new process becomes accepted. If all accepted processes finish, the highest priority new process is accepted. Let’s trace out the general working of this algorithm:- STEP 1: Assume that initially there are no ready processes, when the first one, A, arrives. It has priority 0, to begin with. Since there are no other accepted processes, A is accepted immediately. STEP 2: After a while, another process, B, arrives. As long as b / a < 1, B’s priority will eventually catch up to A’s, so it is accepted; now both A and B have the same priority. STEP 3: All accepted processes share a common priority (which rises at rate b ); that makes this policy easy to implement i.e any new process’s priority is bound to get accepted at some point. So no process has to experience starvation. STEP 4: Even if b / a > 1, A will eventually finish, and then B can be accepted. Adjusting the parameters a and b : -> If b / a >= 1, a new process is not accepted until all the accepted processes have finished, so SRR becomes FCFS. -> If b / a = 0, all processes are accepted immediately, so SRR becomes RR. -> If 0 < b / a < 1, accepted processes are selfish, but not completely. Example on Selfish Round Robin – Solution (where a = 2 and b = 1) – Explanation – Process A gets accepted as soon as it comes at time t = 0. So its priority is increased only by ‘b’ i.e ‘1’ after each second. B enters at time t = 1 and goes to the waiting queue. So its priority gets increased by ‘a’ i.e. ‘2’ at time t = 2. At this point priority of A = priority of B = 2. So now both processes A & B are in the accepted queue and are executed in a round-robin fashion. At time t = 3 process C enters the waiting queue. At time t = 6 the priority of process C catches up to the priority of process B and then they start executing in a Round Robin manner. When B finishes execution at time t = 10, D is automatically promoted to the accepted queue. Similarly, when D finishes execution at time t = 15, E is automatically promoted to the accepted queue. aniket978654 cpu-scheduling Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Memory Management in Operating System File Allocation Methods Logical and Physical Address in Operating System Difference between Internal and External fragmentation File Access Methods in Operating System Memory Hierarchy Design and its Characteristics File Systems in Operating System Process Table and Process Control Block (PCB) States of a Process in Operating Systems Introduction of Process Management
[ { "code": null, "e": 25763, "s": 25735, "text": "\n01 Apr, 2021" }, { "code": null, "e": 25814, "s": 25763, "text": "Prerequisite – Program for Round Robin scheduling " }, { "code": null, "e": 26149, "s": 25814, "text": "In the traditional Round Robin scheduli...
Samsung Semiconductor Institute of Research (SSIR software) intern/FTE | Set-1 - GeeksforGeeks
04 Aug, 2021 There are N fishing spots and 3 gates. At each gate there are some fishermen waiting to reach the nearest unoccupied fishing spot. (Total no of fisherman <=N) Distance between consecutive spots = distance between gate and nearest spot = 1 m Only 1 gate can be opened at a time and all fishermen of that gate must occupy the spots before the next gate is opened. Distance is calculated as gate to nearest spot + nearest spot to closest vacant spot. Find the total sum of minimum distances need to walk for all the fishermen.Inputs to be taken: Number of fishing spots Position of the gates Number of fishermen at each gates Follow this example: Total number of fishing spots= 10 5 fisherman at gate 1 located at position 4, 2 fishermen at gate 2 located at position 6, 2 fishermen at gate 3 located at position 10,If gates are opened in order G1->G2->G3 The arrangement will be: Distance is calculated as gate to nearest spot + nearest spot to closest vacant spot. After G1 gate is opened, fishermen are placed at spots marked with 1. Distance = 11m After G2 gate is opened, fishermen are placed at spots marked with 2. Distance = 5m After G3 gate is opened, fishermen are placed at spots marked with 3. Distance = 3m Total distance in this order : 11 + 5 + 3 = 19 If gates are opened in order G2->G1->G3Case1 – Last fisherman of gate 2 is placed at position 7 the final arrangement will be: After G2 gate is opened, fishermen are placed at spots marked with 2. Distance = 3m After G1 gate is opened, fishermen are placed at spots marked with 1. Distance = 12m After G3 gate is opened, fishermen are placed at spots marked with 3. Distance = 3m Total distance in this order : 3+12+3 = 18 Case2 – Last fisherman of gate 2 is placed at position 5 the final arrangement will be: After G2 gate is opened, fishermen are placed at spots marked with 2. Distance = 3m After G1 gate is opened, fishermen are placed at spots marked with 1. Distance = 14m After G3 gate is opened, fishermen are placed at spots marked with 3. Distance = 3m Total distance in this order : 3+14+3 = 20Other cases are redundant so minimum distance is 18 Solution: Generate all combinations and assigns fishermen in all gate combinations to calculate minimum walking distance. Generating combination can be done in both recursive and iterative way. Now to eliminate unnecessary permutations we can conclude that, for minimum walking distances, fishermen from a particular gate must stay together i.e they should occupy consecutive fishing spots. Thus we can visualise the problem as 3 blocks(group of fisherman) sliding through the entire fishing range. The minimum of which is the answer. C++ C #define _CRT_SECURE_NO_WARNINGS#include<iostream>using namespace std;#define MAX 3 int fishspot[100]; // fishing spotsint gate[MAX]; // position of gatesint fishermen[MAX]; // no of fishermen at each gateint N; // total no of fishing spotsint visited[MAX]; // occupied fishing spotsint Answer; // result // To unmark spots occupied by fishermen of gate# indexclass GFG{public :void reset_fishspot(int index){ int i; for (i = 1; i <= N; i++) if (fishspot[i] == index + 1) fishspot[i] = 0;} // Calculate minimum distance while// allotting spots to fishermen of gate# index.// Returns number of positions possible// with minimum distance.// pos1, pos2 is used to return positionsint calculate_distance(int index, int*pos1, int *pos2, int *score){ int i, sum = 0, left_min = 999999, right_min = 999999, left, right, npos = 0; *pos1 = *pos2 = *score = 0; left = right = gate[index]; // Allot spots to all fishermen except // last based on minimum distance for (i = 1; i < fishermen[index]; i++) { if (fishspot[gate[index]] == 0) { sum++; fishspot[gate[index]] = index + 1; } else { left_min = right_min = 999999; while ((left > 0) && (fishspot[left] > 0)) left--; while ((right <= N) && (fishspot[right] > 0)) right++; if ((left > 0) && (fishspot[left] == 0)) left_min = gate[index] - left + 1; if ((right <= N) && (fishspot[right] == 0)) right_min = right - gate[index] + 1; if (right_min == left_min) { // Place 2 fishermen, if available if ((fishermen[index] - i - 1) > 1) { fishspot[left] = fishspot[right] = index + 1; sum += (2 * left_min); i++; // If all fishermen are alloted spots if (i == fishermen[index]) { npos = 1; *score = sum; return npos; } } else { sum += left_min; fishspot[left] = index + 1; } } else if (left_min < right_min) { sum += left_min; fishspot[left] = index + 1; } else if (right_min < left_min) { sum += right_min; fishspot[right] = index + 1; } } } left_min = right_min = 99999; // Allot spot to last fishermen while ((left > 0) && (fishspot[left] > 0)) left--; if ((left > 0) && (fishspot[left] == 0)) left_min = gate[index] - left + 1; while ((right <= N) && (fishspot[right] > 0)) right++; if ((right <= N) && (fishspot[right] == 0)) right_min = right - gate[index] + 1; if ((sum + left_min) == (sum + right_min)) { npos = 2; *pos1 = left; *pos2 = right; *score = sum + left_min; } else if ((sum + left_min) > (sum + right_min)) { npos = 1; *score = sum + right_min; fishspot[right] = index + 1; } else if ((sum + left_min) < (sum + right_min)) { npos = 1; *score = sum + left_min; fishspot[left] = index + 1; } return npos;} // Solve is used to select next gate// and generate all combinations.void solve(int index, int sum, int count){ int npos, pos1, pos2, score, i; visited[index] = 1; if (sum > Answer) return; npos = calculate_distance(index, &pos1, &pos2, &score); sum += score; if (count == MAX) { if (Answer > sum) Answer = sum; return; } if (npos == 1) { for (i = 0; i < MAX; i++) { if (visited[i] == 0) { solve(i, sum, count + 1); visited[i] = 0; reset_fishspot(i); } } } else if (npos == 2) { fishspot[pos1] = index + 1; for (i = 0; i < MAX; i++) { if (visited[i] == 0) { solve(i, sum, count + 1); visited[i] = 0; reset_fishspot(i); } } fishspot[pos1] = 0; fishspot[pos2] = index + 1; for (i = 0; i < MAX; i++) { if (visited[i] == 0) { solve(i, sum, count + 1); visited[i] = 0; reset_fishspot(i); } } fishspot[pos2] = 0; }}}; // Driver Codeint main(){ GFG g; int i; /*scanf("%d", &N); // for input for (i = 0; i < MAX; i++) { scanf("%d %d", &gate[i], &fishermen[i]); visited[i] = 0; }*/ N = 10; // total no of fishing spots // position of gates(1-based indexing) gate[0] = 4; gate[1] = 6; gate[2] = 10; //no of fishermen at each gate fishermen[0] = 5; //gate1 fishermen[1] = 2; //gate 2 fishermen[2] = 2; //gate 3 for (i = 1; i <= N; i++) fishspot[i] = 0; Answer = 999999; for (i = 0; i < MAX; i++) { g.solve(i, 0, 1); visited[i] = 0; g.reset_fishspot(i); } cout << Answer << endl; return 0;} // This code is contributed by SoM15242 #define _CRT_SECURE_NO_WARNINGS#include<stdio.h> #define MAX 3 int fishspot[100]; // fishing spotsint gate[MAX]; // position of gatesint fishermen[MAX]; // no of fishermen at each gateint N; // total no of fishing spotsint visited[MAX]; // occupied fishing spotsint Answer; // result //To unmark spots occupied by fishermen of gate# indexvoid reset_fishspot(int index){ int i; for (i = 1; i <= N; i++) if (fishspot[i] == index + 1) fishspot[i] = 0;} // Calculate minimum distance while allotting spots to// fishermen of gate# index.// Returns number of positions possible with minimum distance.// pos1, pos2 is used to return positionsint calculate_distance(int index, int*pos1, int *pos2, int *score){ int i, sum = 0, left_min = 999999, right_min = 999999, left, right, npos = 0; *pos1 = *pos2 = *score = 0; left = right = gate[index]; // Allot spots to all fishermen except last based on // minimum distance for (i = 1; i < fishermen[index]; i++) { if (fishspot[gate[index]] == 0) { sum++; fishspot[gate[index]] = index + 1; } else { left_min = right_min = 999999; while ((left > 0) && (fishspot[left] > 0)) left--; while ((right <= N) && (fishspot[right] > 0)) right++; if ((left > 0) && (fishspot[left] == 0)) left_min = gate[index] - left + 1; if ((right <= N) && (fishspot[right] == 0)) right_min = right - gate[index] + 1; if (right_min == left_min) { // Place 2 fishermen, if available if ((fishermen[index] - i - 1) > 1) { fishspot[left] = fishspot[right] = index + 1; sum += (2 * left_min); i++; // If all fishermen are alloted spots if (i == fishermen[index]) { npos = 1; *score = sum; return npos; } } else { sum += left_min; fishspot[left] = index + 1; } } else if (left_min < right_min) { sum += left_min; fishspot[left] = index + 1; } else if (right_min < left_min) { sum += right_min; fishspot[right] = index + 1; } } } left_min = right_min = 99999; // Allot spot to last fishermen while ((left > 0) && (fishspot[left] > 0)) left--; if ((left > 0) && (fishspot[left] == 0)) left_min = gate[index] - left + 1; while ((right <= N) && (fishspot[right] > 0)) right++; if ((right <= N) && (fishspot[right] == 0)) right_min = right - gate[index] + 1; if ((sum + left_min) == (sum + right_min)) { npos = 2; *pos1 = left; *pos2 = right; *score = sum + left_min; } else if ((sum + left_min) > (sum + right_min)) { npos = 1; *score = sum + right_min; fishspot[right] = index + 1; } else if ((sum + left_min) < (sum + right_min)) { npos = 1; *score = sum + left_min; fishspot[left] = index + 1; } return npos;} // Solve is used to select next gate and generate all combinations.void solve(int index, int sum, int count){ int npos, pos1, pos2, score, i; visited[index] = 1; if (sum > Answer) return; npos = calculate_distance(index, &pos1, &pos2, &score); sum += score; if (count == MAX) { if (Answer > sum) Answer = sum; return; } if (npos == 1) { for (i = 0; i < MAX; i++) { if (visited[i] == 0) { solve(i, sum, count + 1); visited[i] = 0; reset_fishspot(i); } } } else if (npos == 2) { fishspot[pos1] = index + 1; for (i = 0; i < MAX; i++) { if (visited[i] == 0) { solve(i, sum, count + 1); visited[i] = 0; reset_fishspot(i); } } fishspot[pos1] = 0; fishspot[pos2] = index + 1; for (i = 0; i < MAX; i++) { if (visited[i] == 0) { solve(i, sum, count + 1); visited[i] = 0; reset_fishspot(i); } } fishspot[pos2] = 0; }} int main()// driver function{ int i; /*scanf("%d", &N); // for input for (i = 0; i < MAX; i++) { scanf("%d %d", &gate[i], &fishermen[i]); visited[i] = 0; }*/ N=10; // total no of fishing spots //position of gates(1-based indexing) gate[0]=4; gate[1]=6; gate[2]=10; //no of fishermen at each gate fishermen[0]=5; //gate1 fishermen[1]=2; //gate 2 fishermen[2]=2; //gate 3 for (i = 1; i <= N; i++) fishspot[i] = 0; Answer = 999999; for (i = 0; i < MAX; i++) { solve(i, 0, 1); visited[i] = 0; reset_fishspot(i); } printf("%d\n", Answer); return 0;} Output: 18 Samsung Internship Interview Experiences Samsung Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021 Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus) Zoho Interview Experience (Off-Campus ) 2022 Resume Writing For Internship Difference Between ON Page and OFF Page SEO Amazon Interview Questions Commonly Asked Java Programming Interview Questions | Set 2 Amazon Interview Experience for SDE-1 (Off-Campus) Amazon AWS Interview Experience for SDE-1 Difference between ANN, CNN and RNN
[ { "code": null, "e": 26493, "s": 26465, "text": "\n04 Aug, 2021" }, { "code": null, "e": 27117, "s": 26493, "text": "There are N fishing spots and 3 gates. At each gate there are some fishermen waiting to reach the nearest unoccupied fishing spot. (Total no of fisherman <=N) Dist...
HTML <i> Tag - GeeksforGeeks
17 Mar, 2022 The <i> tag in HTML is used to display the content in italic style. This tag is generally used to display the technical term, phrase, the important word in a different language. The <i> tag is a container tag that contains the opening tag, content & closing tag. Syntax: <i> Contents</i> Accepted Attributes: This is a Global attribute, and can be used on any HTML element. Below code examples illustrate the use of <i> tag in HTML. Example 1: This is a simple example illustrating the <i> tag to make the italic text in HTML. HTML <!DOCTYPE html><html><head> <title>HTML i Tag</title></head> <body> <h1>GeeksforGeeks</h1> <h3>HTML i tag</h3> <div> <p> <i>A Computer Science portal for geeks.</i> It contains well written, well thought and well explained computer science and programming articles </p> </div></body></html> Output: HTML <i> Tag Example 2: In this example, we have used <i> tag & <p> tag to illustrate the difference in the text appearance while rendering it. HTML <!DOCTYPE html><html><head> <title>HTML Italic Tag</title></head> <body> <h1>GeeksforGeeks</h1> <h3>HTML i tag</h3> <p>This is normal text written inside p tag</p> <!--HTML <i>(italic) tag is used here--> <i>This text is in italic font style</i> </body></html> Output: Italic font-style using HTML <i> Tag Example 3: A text can be written in italics using CSS also. When the CSS font-style property is set to italic, then the text can be seen as follows: HTML <!DOCTYPE html><html><head> <title>HTML Italic Tag</title></head> <body> <h1>GeeksforGeeks</h1> <h3>HTML i tag</h3> <!--Example for font-style: italic --> <p style="font-style: italic;"> This text content is in italic font. </p> <h5>Note:This example is only possible when the font-style property is kept "italic" in CSS </h5> </body></html> Output: Setting font-style to italic using font-style Property Usage: Use the <i> tag for words that you want to show differently from the normal phrase for readability purposes The tags like <i> and <b> now define semantics rather than typographic appearance. So to display text in italic type, users can use the CSS font-style property. Use <i> tag only when it is not marked up with these elements: <em><strong><mark><cite><dfn> <em> <strong> <mark> <cite> <dfn> Supported Browsers: Google Chrome 93.0 Internet Explorer 11.0 Microsoft Edge 93.0 Firefox 92.0 Opera 78.0 Safari 14.1 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. shubhamyadav4 bhaskargeeksforgeeks HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 24326, "s": 24298, "text": "\n17 Mar, 2022" }, { "code": null, "e": 24589, "s": 24326, "text": "The <i> tag in HTML is used to display the content in italic style. This tag is generally used to display the technical term, phrase, the important word in a diffe...
UGC-NET | UGC-NET CS 2017 Nov - III | Question 25 - GeeksforGeeks
19 Mar, 2018 Suppose we want to download text documents at the rate of 100 pages per second. Assume that a page consists of an average of 24 lines with 80 characters in each line. What is the required bit rate of the channel? (A) 192 kbps(B) 512 kbps(C) 1.248 Mbps(D) 1.536 MbpsAnswer: (D)Explanation: We have 100 pages, each page is having 24 line and in each line there are 80 character and each character is of 8 bits.Now we have to calculate no of bits can be downloaded:ie. Downloading rate = 100 pages = 100 pages *24 line * 80 character * 8 bits = 1536000 bits per second ie 1.536 Mbps. So, option (D) is correct.Quiz of this Question UGC-NET Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. UGC-NET | UGC NET CS 2015 Dec - II | Question 36 UGC-NET | UGC NET CS 2017 Jan - III | Question 63 UGC-NET | UGC NET CS 2015 Jun - III | Question 32 UGC-NET | UGC NET CS 2014 Dec - II | Question 2 UGC-NET | UGC NET CS 2018 July - II | Question 33 UGC-NET | UGC-NET CS 2017 Dec 2 | Question 48 UGC-NET | UGC NET CS 2015 Dec - II | Question 29 UGC-NET | UGC NET CS 2017 Jan - II | Question 21 NTA UGC NET 2021 - Computer Science and Applications (087) UGC-NET | UGC NET CS 2017 Jan - III | Question 49
[ { "code": null, "e": 26457, "s": 26429, "text": "\n19 Mar, 2018" }, { "code": null, "e": 26670, "s": 26457, "text": "Suppose we want to download text documents at the rate of 100 pages per second. Assume that a page consists of an average of 24 lines with 80 characters in each li...
Basics of SOAP - Simple Object Access Protocol - GeeksforGeeks
27 Sep, 2019 Introduction:Simple Object Access Protocol(SOAP) is a network protocol for exchanging structured data between nodes. It uses XML format to transfer messages. It works on top of application layer protocols like HTML and SMTP for notations and transmission. SOAP allows processes to communicate throughout platforms, languages and operating systems, since protocols like HTTP are already installed on all platforms.SOAP was designed by Bob Atkinson, Don Box, Dave Winer, and Mohsen Al-Ghosein at Microsoft in 1998. SOAP was maintained by the XML Protocol Working Group of the World Wide Web Consortium until 2009. Message Format: Information about message structure and instructions on processing it. Encoding instructions for application defined data types. Information about Remote Procedure Calls and their responses. The message in XML format contains three partsEnvelope:It specifies that the XML message is a SOAP message. A SOAP message can be defined as an XML document containing header and body encapsulated in the envelope. The fault is within the body of the message.Header:This part is not mandatory. But when it is present it can provide crucial information about the applications.Body:It contains the actual message that is being transmitted. Fault is contained within the body tags.Fault:This section contains the status of the application and also contains errors in the application. This section is also optional. It should not appear more than once in a SOAP message. Envelope:It specifies that the XML message is a SOAP message. A SOAP message can be defined as an XML document containing header and body encapsulated in the envelope. The fault is within the body of the message. Header:This part is not mandatory. But when it is present it can provide crucial information about the applications. Body:It contains the actual message that is being transmitted. Fault is contained within the body tags. Fault:This section contains the status of the application and also contains errors in the application. This section is also optional. It should not appear more than once in a SOAP message. Sample Message: Content-Type: application/soap+xml<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"> <env:Header> <m:GetLastTradePrice xmlns:m="Some-URI" /> </env:Header> <env:Body> <symbol xmlns:p="Some-URI" >DIS</symbol> </env:Body></env:Envelope> Source: https://tools.ietf.org/html/rfc4227 Advantages of SOAPSOAP is a light weight data interchange protocol because it is based on XML.SOAP was designed to be OS and Platform independent.It is built on top of HTTP which is installed in most systems.It is suggested by W3 consortium which is like a governing body for the Web.SOAP is mainly used for Web Services and Application Programming Interfaces (APIs). SOAP is a light weight data interchange protocol because it is based on XML. SOAP was designed to be OS and Platform independent. It is built on top of HTTP which is installed in most systems. It is suggested by W3 consortium which is like a governing body for the Web. SOAP is mainly used for Web Services and Application Programming Interfaces (APIs). Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML and XML Web technologies-HTML and XML Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript How to create footer to stay at the bottom of a Web page? Differences between Functional Components and Class Components in React Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to apply style to parent if it has child with CSS?
[ { "code": null, "e": 26211, "s": 26183, "text": "\n27 Sep, 2019" }, { "code": null, "e": 26823, "s": 26211, "text": "Introduction:Simple Object Access Protocol(SOAP) is a network protocol for exchanging structured data between nodes. It uses XML format to transfer messages. It wo...
How to implement a Stack using list in C++ STL - GeeksforGeeks
14 Jul, 2021 In this article, we will discuss how to implement a Stack using list in C++ STL. Stack is a linear data structure which follows. LIFO(Last In First Out) or FILO(First In Last Out). It mainly supports 4 major operations:1. Push: Push an element into the stack.2. Pop: Removes the element by following the LIFO order.3. Top: Returns the element present at the top of the stack.4. Empty: Returns whether the stack is empty or not. Below is the implementation of the above approach: C++ // C++ implementation of stack// using list STL#include <bits/stdc++.h>using namespace std; template <typename T>// templating it so that any data type can be used class Stack {public: list<T> l; int cs = 0; // current size of the stack // pushing an element into the stack void push(T d) { cs++; // increasing the current size of the stack l.push_front(d); } // popping an element from the stack void pop() { if (cs <= 0) { // cannot pop us stack does not contain an // elements cout << "Stack empty" << endl; } else { // decreasing the current size of the stack cs--; l.pop_front(); } } // if current size is 0 then stack is empty bool empty() { return cs == 0; } // getting the element present at the top of the stack T top() { return l.front(); } int size() { // getting the size of the stack return cs; } // printing the elements of the stack void print() { for (auto x: l) { cout << x << endl; } }};int main(){ Stack<int> s; s.push(10); // pushing into the stack s.push(20); s.push(30); s.push(40); cout << "Current size of the stack is " << s.size() << endl; cout << "The top element of the stack is " << s.top() << endl; s.pop(); // popping from the stack cout << "The top element after 1 pop operation is " << s.top() << endl; // printing the top of the stack s.pop(); // popping cout << "The top element after 2 pop operations is " << s.top() << endl; cout << "Size of the stack after 2 pop operations is " << s.size() << endl; return 0;} Current size of the stack is 4 The top element of the stack is 40 The top element after 1 pop operation is 30 The top element after 2 pop operations is 20 Size of the stack after 2 pop operations is 2 Time Complexity: O(1) for both push and pop operations in the stack.Auxiliary Space: O(N) cpp-list STL C++ Stack Stack STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) Stack Data Structure (Introduction and Program) Stack Class in Java Stack in Python Check for Balanced Brackets in an expression (well-formedness) using Stack Stack | Set 2 (Infix to Postfix)
[ { "code": null, "e": 25447, "s": 25419, "text": "\n14 Jul, 2021" }, { "code": null, "e": 25528, "s": 25447, "text": "In this article, we will discuss how to implement a Stack using list in C++ STL." }, { "code": null, "e": 25876, "s": 25528, "text": "Stack is ...
MySQL - JSON_ARRAYAGG() Function
In general, aggregation is a consideration of a collection of objects that are bound together as a single entity. MySQL provides a set of aggregate functions that perform operations on all the entities of the column of a table considering them as a single unit. The MySQL JSON_ ARRAYAGG() function aggregates the contents of the specified column (or, given expression) as a single array. If the specified columns have no rows this function returns NULL. Following is the syntax of this function – JSON_ARRAYAGG(expr); Assume we have created a table and populated it using the following queries – mysql> CREATE TABLE Test(ID INT,value VARCHAR(100)); mysql> INSERT INTO Test values(1, '110001'); mysql> INSERT INTO Test values(2, '11101'); mysql> INSERT INTO Test values(2, '11100001'); Following query lists the entities of the column value, as a single JSON array – mysql> SELECT JSON_ARRAYAGG(value) from test; +---------------------------------+ | JSON_ARRAYAGG(value) | +---------------------------------+ | ["110001", "11101", "11100001"] | +---------------------------------+ 1 row in set (0.00 sec) Following is an example demonstrating the usage of this function. Assume we have created a table with name MyPlayers in MySQL database using CREATE statement as shown below – mysql> CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Socre_In_Exhibiiton_match INT, COUNTRY VARCHAR(100), PRIMARY KEY (ID) ); This table stores the first and last names, country, scores in an exhibition match of a player. Now, we will insert 7 records in MyPlayers table using INSERT statements − insert into MyPlayers values(1, 'Shikhar', 'Dhawan', 95, 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', 50, 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', 25, 'Sri Lanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', 50, 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', 25, 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', 15, 'India'); insert into MyPlayers values(7, 'James', 'Anderson', 15, 'England'); Following query lists scores of all the players in an exhibition match in the form of a single JSON array – mysql> SELECT JSON_ARRAYAGG(Socre_In_Exhibiiton_match) as Scores from MyPlayers; +------------------------------+ | Scores | +------------------------------+ | [95, 50, 25, 50, 25, 15, 15] | +------------------------------+ 1 row in set (0.00 sec) You can also use GROUP BY clause with this function as shown below – mysql> SELECT Country, JSON_ARRAYAGG(Socre_In_Exhibiiton_match) as Scores from MyPlayers group by country; +-------------+------------------+ | Country | Scores | +-------------+------------------+ | England | [15] | | India | [95, 50, 25, 15] | | SouthAfrica | [50] | | Sri Lanka | [25] | +-------------+------------------+ 4 rows in set (0.00 sec) Following is another example of this function. Assume we have created another table named employee_tbl and inserted records in it as follows – mysql> CREATE TABLE employee_tbl ( id INT, name VARCHAR(255), Work_date INT, daily_typing_pages INT ); mysql> insert into employee_tbl values(1, John, DATE('2007-01-24'), 250); mysql> insert into employee_tbl values(2, 'Ram', DATE('2007-05-27'), 220); mysql> insert into employee_tbl values(3, 'Jack', DATE('2007-05-06'), 170); mysql> insert into employee_tbl values(3, 'Jack', DATE('2007-04-06'), 100); mysql> insert into employee_tbl values(4, 'Jill', DATE('2007-04-06'), 220); mysql> insert into employee_tbl values(5, 'Zara', DATE('2007-06-06'), 300); mysql> insert into employee_tbl values(5, 'Zara', DATE('2007-02-06'), 350); Now, suppose based on the above table you want to retrieve the daily typing pages of all the employees as a single JSON array you can do so as shown below − mysql> SELECT JSON_ARRAYAGG(daily_typing_pages) FROM employee_tbl; +-------------------------------------+ | JSON_ARRAYAGG(daily_typing_pages) | +-------------------------------------+ | [220, 170, 100, 220, 300, 350, 250] | +-------------------------------------+ 1 row in set (0.00 sec) You can also list the JASON array for a grouped columns as shown below – mysql> SELECT Name, JSON_ARRAYAGG(daily_typing_pages) FROM employee_tbl GROUP BY name; +------+-----------------------------------+ | NAme | JSON_ARRAYAGG(daily_typing_pages) | +------+-----------------------------------+ | Jack | [170, 100] | | Jill | [220] | | John | [250] | | Ram | [220] | | Zara | [300, 350] | +------+-----------------------------------+ 5 rows in set (0.00 sec) Let us create a table named student and inserted records into it using CREATE and INSERT statements as shown below – mysql> CREATE TABLE student (name VARCHAR(15), marks INT, grade CHAR); mysql> INSERT INTO student VALUES ('Raju', 80, 'A'); mysql> INSERT INTO student VALUES ('Rahman', 60, 'B'); mysql> INSERT INTO student VALUES ('Robert', 45, 'C'); Following query prints the values of the marks column of the student table as a JSON array – mysql> SELECT JSON_ARRAYAGG(marks) from student; +----------------------+ | JSON_ARRAYAGG(marks) | +----------------------+ | [80, 60, 45] | +----------------------+ 1 row in set (0.00 sec) Using the GROUP BY clause – mysql> SELECT name, JSON_ARRAYAGG(marks) from student GROUP BY name; +--------+----------------------+ | name | JSON_ARRAYAGG(marks) | +--------+----------------------+ | Rahman | [60] | | Raju | [80] | | Robert | [45] | +--------+----------------------+ 3 rows in set (0.00 sec) Assume we have created and populated a table with name Sales. mysql> CREATE TABLE sales( ID INT, ProductName VARCHAR(255), CustomerName VARCHAR(255), DispatchDate date, DeliveryTime time, Price INT, Location VARCHAR(255) ); Query OK, 0 rows affected (2.22 sec) INSERT INTO SALES values(1, 'Key-Board', 'Raja', DATE('2019-09-01'), TIME('11:00:00'), 7000, 'Hyderabad'); INSERT INTO SALES values(2, 'Earphones', 'Roja', DATE('2019-05-01'), TIME('11:00:00'), 2000, 'Vishakhapatnam'); INSERT INTO SALES values(3, 'Mouse', 'Puja', DATE('2019-03-01'), TIME('10:59:59'), 3000, 'Vijayawada'); INSERT INTO SALES values(4, 'Mobile', 'Vanaja', DATE('2019-03-01'), TIME('10:10:52'), 9000, 'Chennai'); INSERT INTO SALES values(5, 'Headset', 'Jalaja', DATE('2019-04-06'), TIME('11:08:59'), 6000, 'Goa'); Following query prints the JASON array consisting the price values – mysql> SELECT JSON_ARRAYAGG(Price) FROM SALES; +--------------------------------+ | JSON_ARRAYAGG(Price) | +--------------------------------+ | [7000, 2000, 3000, 9000, 6000] | +--------------------------------+ 1 row in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2447, "s": 2333, "text": "In general, aggregation is a consideration of a collection of objects that are bound together as a single entity." }, { "code": null, "e": 2595, "s": 2447, "text": "MySQL provides a set of aggregate functions that perform operations ...
Ansible - Variables
Variable in playbooks are very similar to using variables in any programming language. It helps you to use and assign a value to a variable and use that anywhere in the playbook. One can put conditions around the value of the variables and accordingly use them in the playbook. - hosts : <your hosts> vars: tomcat_port : 8080 In the above example, we have defined a variable name tomcat_port and assigned the value 8080 to that variable and can use that in your playbook wherever needed. Now taking a reference from the example shared. The following code is from one of the roles (install-tomcat) − block: - name: Install Tomcat artifacts action: > yum name = "demo-tomcat-1" state = present register: Output always: - debug: msg: - "Install Tomcat artifacts task ended with message: {{Output}}" - "Installed Tomcat artifacts - {{Output.changed}}" Here, the output is the variable used. Let us walk through all the keywords used in the above code − block − Ansible syntax to execute a given block. block − Ansible syntax to execute a given block. name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed. name − Relevant name of the block - this is used in logging and helps in debugging that which all blocks were successfully executed. action − The code next to action tag is the task to be executed. The action again is a Ansible keyword used in yaml. action − The code next to action tag is the task to be executed. The action again is a Ansible keyword used in yaml. register − The output of the action is registered using the register keyword and Output is the variable name which holds the action output. register − The output of the action is registered using the register keyword and Output is the variable name which holds the action output. always − Again a Ansible keyword , it states that below will always be executed. always − Again a Ansible keyword , it states that below will always be executed. msg − Displays the message. msg − Displays the message. This will read the value of variable Output. Also as it is used in the msg tab, it will print the value of the output variable. Additionally, you can use the sub properties of the variable as well. Like in the case checking {{Output.changed}} whether the output got changed and accordingly use it. Exception handling in Ansible is similar to exception handling in any programming language. An example of the exception handling in playbook is shown below. tasks: - name: Name of the task to be executed block: - debug: msg = 'Just a debug message , relevant for logging' - command: <the command to execute> rescue: - debug: msg = 'There was an exception.. ' - command: <Rescue mechanism for the above exception occurred) always: - debug: msg = "this will execute in all scenarios. Always will get logged" Following is the syntax for exception handling. rescue and always are the keywords specific to exception handling. rescue and always are the keywords specific to exception handling. Block is where the code is written (anything to be executed on the Unix machine). Block is where the code is written (anything to be executed on the Unix machine). If the command written inside the block feature fails, then the execution reaches rescue block and it gets executed. In case there is no error in the command under block feature, then rescue will not be executed. If the command written inside the block feature fails, then the execution reaches rescue block and it gets executed. In case there is no error in the command under block feature, then rescue will not be executed. Always gets executed in all cases. Always gets executed in all cases. So if we compare the same with java, then it is similar to try, catch and finally block. So if we compare the same with java, then it is similar to try, catch and finally block. Here, Block is similar to try block where you write the code to be executed and rescue is similar to catch block and always is similar to finally. Here, Block is similar to try block where you write the code to be executed and rescue is similar to catch block and always is similar to finally. Below is the example to demonstrate the usage of Loops in Ansible. The tasks is to copy the set of all the war files from one directory to tomcat webapps folder. Most of the commands used in the example below are already covered before. Here, we will concentrate on the usage of loops. Initially in the 'shell' command we have done ls *.war. So, it will list all the war files in the directory. Output of that command is taken in a variable named output. To loop, the 'with_items' syntax is being used. with_items: "{{output.stdout_lines}}" --> output.stdout_lines gives us the line by line output and then we loop on the output with the with_items command of Ansible. Attaching the example output just to make one understand how we used the stdout_lines in the with_items command. --- #Tsting - hosts: tomcat-node tasks: - name: Install Apache shell: "ls *.war" register: output args: chdir: /opt/ansible/tomcat/demo/webapps - file: src: '/opt/ansible/tomcat/demo/webapps/{{ item }}' dest: '/users/demo/vivek/{{ item }}' state: link with_items: "{{output.stdout_lines}}" The playbook in totality is broken into blocks. The smallest piece of steps to execute is written in block. Writing the specific instruction in blocks helps to segregate functionality and handle it with exception handling if needed. Example of blocks is covered in variable usage,exception handling and loops above. Conditionals are used where one needs to run a specific step based on a condition. --- #Tsting - hosts: all vars: test1: "Hello Vivek" tasks: - name: Testing Ansible variable debug: msg: "Equals" when: test1 == "Hello Vivek" In this case, Equals will be printed as the test1 variable is equal as mentioned in the when condition. when can be used with a logical OR and logical AND condition as in all the programming languages. Just change the value of test1 variable from Hello Vivek to say Hello World and see the output. 41 Lectures 5 hours AR Shankar 11 Lectures 58 mins Musab Zayadneh 59 Lectures 15.5 hours Narendra P 11 Lectures 1 hours Sagar Mehta 39 Lectures 4 hours Vikas Yadav 4 Lectures 3.5 hours GreyCampus Inc. Print Add Notes Bookmark this page
[ { "code": null, "e": 2069, "s": 1791, "text": "Variable in playbooks are very similar to using variables in any programming language. It helps you to use and assign a value to a variable and use that anywhere in the playbook. One can put conditions around the value of the variables and accordingly u...
Tryit Editor v3.6 - Show C++
using namespace std; ​ int main() { int x; cout << "Type a number: "; // Type a number and press enter cin >> x; // Get user input from the keyboard cout << "Your number is: " << x;
[ { "code": null, "e": 41, "s": 20, "text": "using namespace std;" }, { "code": null, "e": 43, "s": 41, "text": "​" }, { "code": null, "e": 56, "s": 43, "text": "int main() {" }, { "code": null, "e": 65, "s": 56, "text": " int x;" }, { ...
Solve the Sherlock and Array problem in JavaScript
Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right. We have to write this function, it should take in an array of Numbers, and any such number exists in the array, it should return its index, otherwise it should return -1. So, let’s write the code for this function − const arr = [1, 2, 3, 4, 5, 7, 3]; const arr2 = [4, 6, 3, 4, 5, 2, 1]; const isSherlockArray = arr => { let sum = arr.reduce((acc, val) => acc+val); let leftSum = 0; for(let i = 0; i < arr.length; i++){ sum -= arr[i]; if(sum === leftSum){ return i; }; leftSum += arr[i]; }; return -1; }; console.log(isSherlockArray(arr)); console.log(isSherlockArray(arr2)); The output in the console will be − 4 -1
[ { "code": null, "e": 1274, "s": 1062, "text": "Watson gives Sherlock an array A of length N. Then he asks him to determine if there exists an\nelement in the array such that the sum of the elements on its left is equal to the sum of the\nelements on its right." }, { "code": null, "e": 14...
Sliding Window Maximum in C++
Suppose we have an array called nums, there is a sliding window of size k which is moving from the left of the array to the right. We can only see the k numbers in the window. Each time the sliding window moves to the right side by one position. We have to find the max sliding window. So if the input is like −[1,3,-1,-3,5,3,6,8] and k is 3, then the window will be like − To solve this, we will follow these steps − Define an array ans Define an array ans Define one double ended queue dq Define one double ended queue dq if size of nums is same as 0, then, return ans if size of nums is same as 0, then, return ans for initializing i := 0, when i<k, increase i by 1 do −while dq is not empty and nums[last element of dq] <nums[i], dodelete last element of dqinsert i at the end of dq for initializing i := 0, when i<k, increase i by 1 do − while dq is not empty and nums[last element of dq] <nums[i], dodelete last element of dq while dq is not empty and nums[last element of dq] <nums[i], do delete last element of dq delete last element of dq insert i at the end of dq insert i at the end of dq for initializing i := k, when i<nums.size(, increase i by 1 do −insert (nums[front element of dq]) into answhile dq is not empty and front element of dq < (i-k + 1), do −delete front element from dqwhile dq is not empty and nums[last element of dq] < nums[i], do −delete last element of dqinsert i at the end of dq for initializing i := k, when i<nums.size(, increase i by 1 do − insert (nums[front element of dq]) into ans insert (nums[front element of dq]) into ans while dq is not empty and front element of dq < (i-k + 1), do −delete front element from dq while dq is not empty and front element of dq < (i-k + 1), do − delete front element from dq delete front element from dq while dq is not empty and nums[last element of dq] < nums[i], do −delete last element of dq while dq is not empty and nums[last element of dq] < nums[i], do − delete last element of dq delete last element of dq insert i at the end of dq insert i at the end of dq insert nums[front element of dq] into ans at the end insert nums[front element of dq] into ans at the end return ans return ans Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } void print_vector(vector<vector<auto> > v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << "["; for(int j = 0; j <v[i].size(); j++){ cout << v[i][j] << ", "; } cout << "],"; } cout << "]"<<endl; } class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector <int> ans; deque <int> dq; if(nums.size()==0)return ans; for(int i =0;i<k;i++){ while(!dq.empty() && nums[dq.back()]<nums[i])dq.pop_back(); dq.push_back(i); } for(int i = k;i<nums.size();i++){ ans.push_back(nums[dq.front()]); while(!dq.empty() && dq.front()<(i-k + 1))dq.pop_front(); while(!dq.empty() && nums[dq.back()]<nums[i])dq.pop_back(); dq.push_back(i); } ans.push_back(nums[dq.front()]); return ans; } }; main(){ Solution ob; vector<int> v = {1,3,-1,-3,5,3,6,8}; print_vector(ob.maxSlidingWindow(v,3)); } {1,3,-1,-3,5,3,6,8} [3, 3, 5, 5, 6, 8, ]
[ { "code": null, "e": 1436, "s": 1062, "text": "Suppose we have an array called nums, there is a sliding window of size k which is moving from the left of the array to the right. We can only see the k numbers in the window. Each time the sliding window moves to the right side by one position. We have...
Powershell - Rename Folder
Rename-Item cmdlet is used to rename a folder by passing the path of the folder to be renamed and target name. In this example, we'll rename a folder D:\Temp\Test to D:\Temp\Test1 Type the following command in PowerShell ISE Console Rename-Item D:\temp\Test D:\temp\Test1 You can see the Test directory as Test1 directory now. There should not be another folder with same name already in the temp directory otherwise PowerShell command will fail. 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2145, "s": 2034, "text": "Rename-Item cmdlet is used to rename a folder by passing the path of the folder to be renamed and target name." }, { "code": null, "e": 2214, "s": 2145, "text": "In this example, we'll rename a folder D:\\Temp\\Test to D:\\Temp\\Test...
How to move a column from other position to first position in an R data frame?
A column’s position in an R data frame is crucial specially when we are dealing with a large data set. As the first column appears first, it becomes necessary that we should have columns of the data frame in an order that helps us to look at the important columns easily. For this purpose, we might want to change the position of columns. To change the position of a column to first position we can use single square brackets. Consider the below data frame − > set.seed(99) > x1<-rnorm(20) > x2<-rpois(20,10) > x3<-rpois(20,5) > x4<-runif(20,1,5) > x5<-sample(1:5,20,replace=TRUE) > x6<-LETTERS[1:20] > df<-data.frame(x1,x2,x3,x4,x5,x6) > df x1 x2 x3 x4 x5 x6 1 0.2139625022 13 3 3.750865 3 A 2 0.4796581346 12 2 2.381080 2 B 3 0.0878287050 9 4 3.360354 3 C 4 0.4438585075 8 2 1.559041 3 D 5 -0.3628379205 10 7 1.631011 3 E 6 0.1226740295 11 2 2.877371 1 F 7 -0.8638451881 12 7 4.636257 3 G 8 0.4896242667 8 3 2.198420 4 H 9 -0.3641169125 5 5 4.987447 2 I 10 -1.2942420067 9 3 3.608834 2 J 11 -0.7457690454 8 3 2.349861 1 K 12 0.9215503620 11 9 1.992435 2 L 13 0.7500543504 13 5 1.754099 5 M 14 -2.5085540159 14 4 1.908080 2 N 15 -3.0409340953 13 1 2.406410 1 O 16 0.0002658005 11 2 2.741166 1 P 17 -0.3940189942 9 7 4.956848 4 Q 18 -1.7450276608 16 6 2.818134 5 R 19 0.4986314508 10 2 3.686916 2 S 20 0.2709537888 4 6 2.313132 4 T Suppose we want to change the position of column 6 (x6) to position 1, then it can be done as shown below − > df<-df[,c(6,1,2,3,4,5)] > df x6 x1 x2 x3 x4 x5 1 A 0.2139625022 13 3 3.750865 3 2 B 0.4796581346 12 2 2.381080 2 3 C 0.0878287050 9 4 3.360354 3 4 D 0.4438585075 8 2 1.559041 3 5 E -0.3628379205 10 7 1.631011 3 6 F 0.1226740295 11 2 2.877371 1 7 G -0.8638451881 12 7 4.636257 3 8 H 0.4896242667 8 3 2.198420 4 9 I -0.3641169125 5 5 4.987447 2 10 J -1.2942420067 9 3 3.608834 2 11 K -0.7457690454 8 3 2.349861 1 12 L 0.9215503620 11 9 1.992435 2 13 M 0.7500543504 13 5 1.754099 5 14 N -2.5085540159 14 4 1.908080 2 15 O -3.0409340953 13 1 2.406410 1 16 P 0.0002658005 11 2 2.741166 1 17 Q -0.3940189942 9 7 4.956848 4 18 R -1.7450276608 16 6 2.818134 5 19 S 0.4986314508 10 2 3.686916 2 20 T 0.2709537888 4 6 2.313132 4 In the same way, we can make more changes in the positions as shown below − > df<-df[,c(6,2,3,5,1,4)] > df x5 x1 x2 x4 x6 x3 1 3 0.2139625022 13 3.750865 A 3 2 2 0.4796581346 12 2.381080 B 2 3 3 0.0878287050 9 3.360354 C 4 4 3 0.4438585075 8 1.559041 D 2 5 3 -0.3628379205 10 1.631011 E 7 6 1 0.1226740295 11 2.877371 F 2 7 3 -0.8638451881 12 4.636257 G 7 8 4 0.4896242667 8 2.198420 H 3 9 2 -0.3641169125 5 4.987447 I 5 10 2 -1.2942420067 9 3.608834 J 3 11 1 -0.7457690454 8 2.349861 K 3 12 2 0.9215503620 11 1.992435 L 9 13 5 0.7500543504 13 1.754099 M 5 14 2 -2.5085540159 14 1.908080 N 4 15 1 -3.0409340953 13 2.406410 O 1 16 1 0.0002658005 11 2.741166 P 2 17 4 -0.3940189942 9 4.956848 Q 7 18 5 -1.7450276608 16 2.818134 R 6 19 2 0.4986314508 10 3.686916 S 2 20 4 0.2709537888 4 2.313132 T 6
[ { "code": null, "e": 1489, "s": 1062, "text": "A column’s position in an R data frame is crucial specially when we are dealing with a large data set. As the first column appears first, it becomes necessary that we should have columns of the data frame in an order that helps us to look at the importa...
How to get services based on multiple conditional parameters in PowerShell?
To filter out services with both start-type “Automatic” and Status “stopped” we need to use the -AND comparison operator. Here, services will be displayed only when both conditions are matching. Get-Service | where{($_.StartType -eq "Automatic") -and ($_.Status -eq "Stopped")} | Select Name, StartType, Status Name StartType Status ---- --------- ------ gpsvc Automatic Stopped gupdate Automatic Stopped MapsBroker Automatic Stopped To get services with start-type manual or disabled we will use -OR operator. Get-Service | where{($_.StartType -eq "Manual") -or ($_.StartType -eq "Disabled")} | Sort-Object Starttype | Select Name, StartType, Status LxpSvc Manual Stopped lmhosts Manual Running KtmRm Manual Stopped IpxlatCfgSvc Manual Stopped FontCache3.0.0.0 Manual Running KeyIso Manual Running klvssbridge64_20.0 Manual Stopped UevAgentService Disabled Stopped tzautoupdate Disabled Stopped NetTcpPortSharing Disabled Stopped ssh-agent Disabled Stopped shpamsvc Disabled Stopped RemoteRegistry Disabled Stopped AppVClient Disabled Stopped svcdemo Disabled Stopped
[ { "code": null, "e": 1257, "s": 1062, "text": "To filter out services with both start-type “Automatic” and Status “stopped” we need to use the -AND comparison operator. Here, services will be displayed only when both conditions are matching." }, { "code": null, "e": 1373, "s": 1257, ...
Data Preprocessing and Model Comparison Techniques you must know | by Fan Yuan | Towards Data Science
As we all know, when doing data science projects, it’s always more than fitting the model on data and getting the model performance. Actually, in terms of good projects, it’s more about exploring the data, cleaning, preprocessing data and finally comparing several models’ perform to get the best one. In this post, I’ll use U.S. census data taken from the UCI Machine Learning Repository and go through the full process. At the end of the process, we’ll solve the following several problems: Construct a model that accurately predicts whether an individual makes more than $50,000.What are the key factors contributing to high vs. low income?Are there any significant gaps in these Census attributes by gender or race?Any underneath clusters (group) based on census data? Construct a model that accurately predicts whether an individual makes more than $50,000. What are the key factors contributing to high vs. low income? Are there any significant gaps in these Census attributes by gender or race? Any underneath clusters (group) based on census data? Have a quick check on whether there’s any huge missing value in columns or rows which may largely affect the later analysis. The result above shows there’s no `null` value in the dataset. But according to data notes provided, unknown data was converted into ‘?’. Therefore, next, we’ll convert ‘?’ to NaNs. Since the missing data ‘?’ is in a small volume, here I choose to just remove the unknown data which flagged as ‘?’ here. But if the missing data is in a large volume, need to consider imputing NaNs with more advanced methods. The largest missing percentage by column level is 5% in the dataset, and most columns are complete enough. Therefore, here I’ll remove the NaN values instead of manually imputing. The goal is to identify if an individual has an income over 50k or not, so first, have an overlook at how the income distributes in the data set. A cursory investigation of the dataset will determine how many individuals fit into each group and will tell us about the percentage of these individuals making more than $50,000. Here I’ll generate some variables to help analysis as below:- The total number of records- The number of individuals making more than $50,000 annually- The number of individuals making at most $50,000 annually- The percentage of individuals making more than $50,000 annually Note:Since in EDA process, we don’t need the test data, I’ll combine the train and test data in this section just for getting a better and more general distribution of data From the graph above, we can see that most of ‘>50K’ group are people in middle career and the male is a bit more than female in ‘>50K’ especially around 50 years old. We can see the top three biggest groups for people who have income larger 50K are professional in Exec-managerial, Prof-specialty, and Sales. Since the race is a little bit unbalanced in the data set, White accounts most of ‘>50K’ group. And within each race, ‘<50K’ population is much larger than ‘>50K’. Then we take a quick view of how education correlates to the income level. We can see the biggest group is Bachelors following by HS-grad and Some-college. And after moving the missing value: Total number of records: 45222Individuals making more than $50,000: 11208Individuals making at most $50,000: 34014Percentage of individuals making more than $50,000: 24.78% Before data can be used as input for machine learning algorithms, it often must be cleaned, formatted, and restructured. After processing the missing entries, there are some qualities about certain features that must be adjusted. This preprocessing can help tremendously with the outcome and predictive power of nearly all learning algorithms. Skewness may violate model assumptions or may impair the interpretation of feature importance. Therefore, here I will apply the logarithmic transformation on the skewed data. As shown in the graph, there seems skewness in ‘capital-gain’ and ‘capital-loss’ features. Use the quantitative result to confirm if I need to transform skewness in these two variables. In addition to performing transformations on features that are highly skewed, here will perform some type of scaling on numerical features. Applying a scaling to the data does not change the shape of each feature’s distribution (such as ‘capital-gain’ or ‘capital-loss’ above); however, it is useful to scale the input attributes for a model that relies on the magnitude of values, such as distance measures used in k-nearest neighbors and in the preparation of coefficients in regression. There are several features for each record that are non-numeric. Typically, learning algorithms expect the input to be numeric, which requires that non-numeric features (called *categorical variables*) be converted. Here convert categorical variables by using the **one-hot encoding** scheme. Additionally, as with the non-numeric features, I need to convert the non-numeric target label, `’income’` to numerical values for the learning algorithm to work. Since there are only two possible categories for this label (“<=50K” and “>50K”), we can simply encode these two categories as `0` and `1`, respectively. Therefore, we will Use `sklearn.OneHotEncoder` to perform one-hot encoding on the `’features_log_minmax_transform’` data. — Note: Since the test data is separate, in case there are unseen categories in test data which will fail the model, here use sklearn.OneHotEncoder rather the pd.get_dummies()Convert the target label `’income_raw’` to numerical entries. Set records with “<=50K” to `0` and records with “>50K” to `1`. Use `sklearn.OneHotEncoder` to perform one-hot encoding on the `’features_log_minmax_transform’` data. — Note: Since the test data is separate, in case there are unseen categories in test data which will fail the model, here use sklearn.OneHotEncoder rather the pd.get_dummies() Convert the target label `’income_raw’` to numerical entries. Set records with “<=50K” to `0` and records with “>50K” to `1`. In this section, I will investigate five different algorithms, and determine which is best at modeling the data. Four of these algorithms will be supervised learners, and the fifth algorithm is known as a naive predictor. Generate a naive predictor to show what a base model without any intelligence would look like. That is if we chose a model that always predicted an individual made more than $50,000, what would that model’s accuracy and F-score be on this dataset? Here assume that we consider more about to correctly predict individual who has income over 50K. Therefore, a model’s ability to precisely predict those that make more than $50,000 is more important than the model’s ability to recall those individuals. We can use F-beta score as a metric that considers both precision and recall: Apart from the bench mark model, I’ll choose four other models Logistic Regression, Random Forest, Ensemble Methods (AdaBoost) and Support Vector Machines (SVM) as a candidate to build the predictive model. Logistic RegressionRandom ForestEnsemble Methods — AdaBoostSupport Vector Machines (SVM) Logistic Regression Random Forest Ensemble Methods — AdaBoost Support Vector Machines (SVM) To properly evaluate the performance of each model chosen above more efficiently, it’s helpful to create a training and predicting pipeline that can quickly and effectively train models using various sizes of training data and perform predictions on the testing data. The pipeline will: — Fit the learner to the sampled training data and record the training time. — Perform predictions on the test data `X_test`, and also on the first 300 training points `X_train[:300]`. — Record the total prediction time. — Calculate the accuracy score for both the training subset and the testing set. — Calculate the F-score for both the training subset and the testing set. Next, I will choose from the four supervised learning models the *best* model to use on the test data. I will then perform a grid search optimization for the model over the entire training set (`X_train` and `y_train`) to improve upon the untuned model’s F-score. According to the model performance graph above, although the Random Forest performs best on the training set the AdaBoost Classifier finally predicts best on testing data. Although the accuracy of AdaBoost Classifier is quite similar to the performance of other models, F-score of AdaBoost is better on both training and testing data when the model is applied to the whole data set. Also, in contrast to Support Vector Classifier which takes dramatically more time to train and predict, the AdaBoost is faster. In terms of binary classification, AdaBoost will also perform well in this case. Fine-tune the chosen model. Use grid search (`GridSearchCV`). Use the entire training set for this. The optimized model’s accuracy on testing data is 0.8701 and F-score is 0.7518. Both of those scores are better than the unoptimized model. Also, the optimized model performs much better than the benchmarks Generally, it’s useful to know which features provide the most predictive power when performing supervised learning on a dataset like the census data here. In this case, it means we wish to identify a small number of features that most strongly predict whether an individual makes at most or more than $50,000. Here will choose a scikit-learn classifier (e.g., adaboost, random forests) that has a `feature_importance_` attribute. Fit this classifier to training set and use this attribute to determine the top 5 most important features for the census dataset. From the result, the feature importance put ‘capital-loss’ the most important feature. It’s probably because the bigger capital loss means that the person has to have that volume of money to invest. The ‘age’ ranks the second one which may because the elder the people the more salary they will have to the donor. The ‘hours-per-week’ and ‘sex_Female’ ranks the forth and fifth which probably because it’s not that sure cases. It’s true since maybe the person works longer but have a lower unit salary. From the visualization above, we see that the top five most important features contribute more than half of the importance of all features present in the data. This hints that we can attempt to reduce the feature space and simplify the information required for the model to learn. The code cell below will use the same optimized model found earlier, and train it on the same training set with only the top five important features. As a result above show, the model performs a bit worse if I only used important features. The accuracy is 5% lower and the f-score is 7% lower, so in this case, I’ll still choose to use all feature to build the model unless when the time for fitting model matters a lot. For a more detailed view of my analysis, feel free to check out my corresponding GitHub repository:
[ { "code": null, "e": 473, "s": 171, "text": "As we all know, when doing data science projects, it’s always more than fitting the model on data and getting the model performance. Actually, in terms of good projects, it’s more about exploring the data, cleaning, preprocessing data and finally comparin...
Splunk - Calculated Fields
Many times, we will need to make some calculations on the fields that are already available in the Splunk events. We also want to store the result of these calculations as a new field to be referred later by various searches. This is made possible by using the concept of calculated fields in Splunk search. A simplest example is to show the first three characters of a week day instead of the complete day name. We need to apply certain Splunk function to achieve this manipulation of the field and store the new result under a new field name. The Web_application log file has two fields named bytes and date_wday. The value in the bytes field is the number of bytes. We want to display this value as GB. This will require the field to be divided by 1024 to get the GB value. We need to apply this calculation to the bytes field. Similarly, the date_wday displays complete name of the week day. But we need to display only the first three characters. The existing values in these two fields is shown in the image below − To create calculated field, we use the eval function. This function stores the result of the calculation in a new field. We are going to apply the below two calculations − # divide the bytes with 1024 and store it as a field named byte_in_GB Eval byte_in_GB = (bytes/1024) # Extract the first 3 characters of the name of the day. Eval short_day = substr(date_wday,1,3) We add new fields created above to the list of fields we display as part of the search result. To do this, we choose All fields options and tick check mark against the name of these new fields as shown in below image − After choosing the fields above, we are able to see the calculated fields in the search result as shown below. The search query displays the calculated fields as shown below − Print Add Notes Bookmark this page
[ { "code": null, "e": 2669, "s": 2361, "text": "Many times, we will need to make some calculations on the fields that are already available in the Splunk events. We also want to store the result of these calculations as a new field to be referred later by various searches. This is made possible by us...
Display two different columns from two different tables with ORDER BY?
For this, you can use UNION along with the ORDER BY clause. Let us first create a table − mysql> create table DemoTable1 ( Amount int ); Query OK, 0 rows affected (0.63 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1 values(234); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1 values(567); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1 values(134); Query OK, 1 row affected (0.43 sec) Display all records from the table using select statement − mysql> select *from DemoTable1; This will produce the following output − +--------+ | Amount | +--------+ | 234 | | 567 | | 134 | +--------+ 3 rows in set (0.00 sec) Here is the query to create the second table − mysql> create table DemoTable2 ( Price int ); Query OK, 0 rows affected (0.73 sec) Insert some records in the table using insert command − mysql> insert into DemoTable2 values(134); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable2 values(775); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable2 values(121); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable2 values(882); Query OK, 1 row affected (0.09 sec) Display all records from the table using select statement − mysql> select *from DemoTable2; This will produce the following output − +-------+ | Price | +-------+ | 134 | | 775 | | 121 | | 882 | +-------+ 4 rows in set (0.00 sec) Following is the query to display two different columns from two different tables with ORDER BY − mysql> select distinct Amount from DemoTable1 UNION select distinct Price from DemoTable2 order by Amount; This will produce the following output − +--------+ | Amount | +--------+ | 121 | | 134 | | 234 | | 567 | | 775 | | 882 | +--------+ 6 rows in set (0.00 sec)
[ { "code": null, "e": 1152, "s": 1062, "text": "For this, you can use UNION along with the ORDER BY clause. Let us first create a table −" }, { "code": null, "e": 1239, "s": 1152, "text": "mysql> create table DemoTable1\n(\n Amount int\n);\nQuery OK, 0 rows affected (0.63 sec)" ...
SQL - Using Joins
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each. Consider the following two tables − Table 1 − CUSTOMERS Table +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Table 2 − ORDERS Table +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables in our SELECT statement as shown below. SQL> SELECT ID, NAME, AGE, AMOUNT FROM CUSTOMERS, ORDERS WHERE CUSTOMERS.ID = ORDERS.CUSTOMER_ID; This would produce the following result. +----+----------+-----+--------+ | ID | NAME | AGE | AMOUNT | +----+----------+-----+--------+ | 3 | kaushik | 23 | 3000 | | 3 | kaushik | 23 | 1500 | | 2 | Khilan | 25 | 1560 | | 4 | Chaitali | 25 | 2060 | +----+----------+-----+--------+ Here, it is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal to symbol. There are different types of joins available in SQL − INNER JOIN − returns rows when there is a match in both tables. INNER JOIN − returns rows when there is a match in both tables. LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table. LEFT JOIN − returns all rows from the left table, even if there are no matches in the right table. RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left table. RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left table. FULL JOIN − returns rows when there is a match in one of the tables. FULL JOIN − returns rows when there is a match in one of the tables. SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement. CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or more joined tables. CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or more joined tables. Let us now discuss each of these joins in detail. 42 Lectures 5 hours Anadi Sharma 14 Lectures 2 hours Anadi Sharma 44 Lectures 4.5 hours Anadi Sharma 94 Lectures 7 hours Abhishek And Pukhraj 80 Lectures 6.5 hours Oracle Master Training | 150,000+ Students Worldwide 31 Lectures 6 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2627, "s": 2453, "text": "The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each." }, { "code": null, "e": 2663, "s": 2627, "text": "Consider...
How to Copy Local Files to AWS EC2 instance Manually ?
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws It is a very frequent scenario to copy local files to AWS EC2 instance while you are developing an application on your local machine. One of the possible solutions to do – you can push the code into your GIT repository and pull them from your EC2 instance, but to do it, we have to install GIT on EC2 instance. In this tutorial, we are going to see how can we manually copy the local files to AWS EC2 instance without using GIT or any other remote repositories. WinSCP is a very good tool for Windows users to move files locally to remote machines. Download the WinSCP and install it, the installation process is pretty straightforward. After installation, open the WinSCP, then you could see the below the login window. Provide your ec2 instance user login details and click on the Login button and you could be landed into WinSCP home page. On the left-hand side you can see your local file and right-hand side it is the remote machine. You can simply drag and drop the files, from local to remote like below. On the above screen, I am trying to copy parse_csv.py to remote ec2 /opt/dotw/ folder. Linux or Mac users can directly copy local files to ec2 instance using scp command, without installing any new software. Open the terminal and locate to your ec2 .pem file give the below command. $scp -i ./my-ec2.pem /home/chandra/data.py ec2-user@ec2-32-174-195-130.compute-1.amazonaws.com:/tmp Now you can see your files in ec2 instance. How to connect AWS EC2 using PuTTY Happy Learning 🙂 How to clear PuTTY Sessions on Windows How to install PuTTY on windows 10 Step by Step – How to push the project into GIT Repository Where can I find Python PIP in windows ? How to upgrade Python PIP version on Windows How to connect AWS EC2 Instance using PuTTY How add files to S3 Bucket using Shell Script How to push docker image to docker hub ? How to Export MySQL Tables to a file from command line How to setup or install MongoDB on Windows 10 Hibernate Download and Setup How to Install Kubernetes on Ubuntu 18.04 Java How to create Jar File ? How to add dynamic files to JTree Java 8 walk How to Read all files in a folder How to clear PuTTY Sessions on Windows How to install PuTTY on windows 10 Step by Step – How to push the project into GIT Repository Where can I find Python PIP in windows ? How to upgrade Python PIP version on Windows How to connect AWS EC2 Instance using PuTTY How add files to S3 Bucket using Shell Script How to push docker image to docker hub ? How to Export MySQL Tables to a file from command line How to setup or install MongoDB on Windows 10 Hibernate Download and Setup How to Install Kubernetes on Ubuntu 18.04 Java How to create Jar File ? How to add dynamic files to JTree Java 8 walk How to Read all files in a folder Δ Install Java on Mac OS Install AWS CLI on Windows Install Minikube on Windows Install Docker Toolbox on Windows Install SOAPUI on Windows Install Gradle on Windows Install RabbitMQ on Windows Install PuTTY on windows Install Mysql on Windows Install Hibernate Tools in Eclipse Install Elasticsearch on Windows Install Maven on Windows Install Maven on Ubuntu Install Maven on Windows Command Add OJDBC jar to Maven Repository Install Ant on Windows Install RabbitMQ on Windows Install Apache Kafka on Ubuntu Install Apache Kafka on Windows
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, ...
C# | Get or set the element at the specified index in ArrayList - GeeksforGeeks
01 Feb, 2019 ArrayList.Item[Int32] Property is used to get or set the element at the specified index in ArrayList. Syntax: public virtual object this[int index] { get; set; } Here, index is the zero-based index of the element to get or set. Return Value: It returns the element of Object type at the specified index. Exception: This property will throw ArgumentOutOfRangeException if the index is less than zero or is equal to or greater than Count. Below programs illustrate the use of above-discussed property: Example 1: // C# code to get or set the element at// the specified index in ArrayListusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList myList.Add("A"); myList.Add("B"); myList.Add("C"); myList.Add("D"); myList.Add("E"); myList.Add("F"); // Displaying the elements // in the ArrayList foreach(string str in myList) { Console.WriteLine(str); } Console.WriteLine("After Item[int32] Property: "); // setting the value at index 2 myList[2] = "Z"; // Displaying the elements // in the ArrayList foreach(string str in myList) { Console.WriteLine(str); } }} A B C D E F After Item[int32] Property: A B Z D E F Example 2: // C# code to get or set the element at// the specified index in ArrayListusing System;using System.Collections;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating an ArrayList ArrayList myList = new ArrayList(); // Adding elements to ArrayList // Adding elements to ArrayList myList.Add(2); myList.Add(4); myList.Add(6); myList.Add(8); myList.Add(10); myList.Add(12); myList.Add(14); myList.Add(16); myList.Add(18); myList.Add(20); // Displaying the elements // in the ArrayList foreach(int i in myList) { Console.WriteLine(i); } Console.WriteLine("After Item[int32] Property: "); // setting the value at index 8 // this will give error as index // is greater than count myList[10] = 56; // Displaying the elements // in the ArrayList foreach(int j in myList) { Console.WriteLine(j); } }} Runtime Error: Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.item?view=netframework-4.7.2 CSharp-Collections-ArrayList CSharp-Collections-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# C# | Delegates C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Class and Object C# | Abstract Classes C# | Data Types HashSet in C# with Examples C# | Encapsulation
[ { "code": null, "e": 24494, "s": 24466, "text": "\n01 Feb, 2019" }, { "code": null, "e": 24596, "s": 24494, "text": "ArrayList.Item[Int32] Property is used to get or set the element at the specified index in ArrayList." }, { "code": null, "e": 24604, "s": 24596, ...
Face and Hand Landmarks Detection using Python - Mediapipe, OpenCV - GeeksforGeeks
03 Nov, 2021 In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all the face and hand landmarks. We will be also seeing how we can access different landmarks of the face and hands which can be used for different computer vision applications such as sign language detection, drowsiness detection, etc. Mediapipe is a cross-platform library developed by Google that provides amazing ready-to-use ML solutions for computer vision tasks. OpenCV library in python is a computer vision library that is widely used for image analysis, image processing, detection, recognition, etc. Installing required libraries pip install opencv-python mediapipe msvc-runtime Below is the step-wise approach for Face and Hand landmarks detection STEP-1: Import all the necessary libraries, In our case only two libraries are required. Python3 # Import Librariesimport cv2import timeimport mediapipe as mp STEP-2: Initializing Holistic model and Drawing utils for detecting and drawing landmarks on the image. Python3 # Grabbing the Holistic Model from Mediapipe and# Initializing the Modelmp_holistic = mp.solutions.holisticholistic_model = mp_holistic.Holistic( min_detection_confidence=0.5, min_tracking_confidence=0.5) # Initializing the drawng utils for drawing the facial landmarks on imagemp_drawing = mp.solutions.drawing_utils Let us look into the parameters for the Holistic Model: Holistic( static_image_mode=False, model_complexity=1, smooth_landmarks=True, min_detection_confidence=0.5, min_tracking_confidence=0.5 ) static_image_mode: It is used to specify whether the input images must be treated as static images or as a video stream. The default value is False. model_complexity: It is used to specify the complexity of the pose landmark model: 0, 1, or 2. As the model complexity of the model increases the landmark accuracy and latency increase. The default value is 1. smooth_landmarks: This parameter is used to reduce the jitter in the prediction by filtering pose landmarks across different input images. The default value is True. min_detection_confidence: It is used to specify the minimum confidence value with which the detection from the person-detection model needs to be considered as successful. Can specify a value in [0.0,1.0]. The default value is 0.5. min_tracking_confidence: It is used to specify the minimum confidence value with which the detection from the landmark-tracking model must be considered as successful. Can specify a value in [0.0,1.0]. The default value is 0.5. STEP-3: Detecting Face and Hand landmarks from the image. Holistic model processes the image and produces landmarks for Face, Left Hand, Right Hand and also detects the Pose of the Capture the frames continuously from the camera using OpenCV.Convert the BGR image to an RGB image and make predictions using initialized holistic model.The predictions made by the holistic model are saved in the results variable from which we can access the landmarks using results.face_landmarks, results.right_hand_landmarks, results.left_hand_landmarks respectively.Draw the detected landmarks on the image using the draw_landmarks function from drawing utils.Display the resulting Image. Capture the frames continuously from the camera using OpenCV. Convert the BGR image to an RGB image and make predictions using initialized holistic model. The predictions made by the holistic model are saved in the results variable from which we can access the landmarks using results.face_landmarks, results.right_hand_landmarks, results.left_hand_landmarks respectively. Draw the detected landmarks on the image using the draw_landmarks function from drawing utils. Display the resulting Image. Python3 # (0) in VideoCapture is used to connect to your computer's default cameracapture = cv2.VideoCapture(0) # Initializing current time and precious time for calculating the FPSpreviousTime = 0currentTime = 0 while capture.isOpened(): # capture frame by frame ret, frame = capture.read() # resizing the frame for better view frame = cv2.resize(frame, (800, 600)) # Converting the from from BGR to RGB image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Making predictions using holistic model # To improve performance, optionally mark the image as not writable to # pass by reference. image.flags.writable = False results = holistic_model.process(image) image.flags.writable = True # Converting back the RGB image to BGR image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Drawing the Facial Landmarks mp_drawing.draw_landmarks( image, results.face_landmarks, mp_holistic.FACE_CONNECTIONS, mp_drawing.DrawingSpec( color=(255,0,255), thickness=1, circle_radius=1 ), mp_drawing.DrawingSpec( color=(0,255,255), thickness=1, circle_radius=1 ) ) # Drawing Right hand Land Marks mp_drawing.draw_landmarks( image, results.right_hand_landmarks, mp_holistic.HAND_CONNECTIONS ) # Drawing Left hand Land Marks mp_drawing.draw_landmarks( image, results.left_hand_landmarks, mp_holistic.HAND_CONNECTIONS ) # Calculating the FPS currentTime = time.time() fps = 1 / (currentTime-previousTime) previousTime = currentTime # Displaying FPS on the image cv2.putText(image, str(int(fps))+" FPS", (10, 70), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2) # Display the resulting image cv2.imshow("Facial and Hand Landmarks", image) # Enter key 'q' to break the loop if cv2.waitKey(5) & 0xFF == ord('q'): break # When all the process is done# Release the capture and destroy all windowscapture.release()cv2.destroyAllWindows() The holistic model produces 468 Face landmarks, 21 Left-Hand landmarks, and 21 Right-Hand landmarks. The individual landmarks can be accessed by specifying the index of the required landmark. Example: results.left_hand_landmarks.landmark[0]. You can get the index of all the individual landmarks using the below code: Python3 # Code to access landmarksfor landmark in mp_holistic.HandLandmark: print(landmark, landmark.value) print(mp_holistic.HandLandmark.WRIST.value) HandLandmark.WRIST 0 HandLandmark.THUMB_CMC 1 HandLandmark.THUMB_MCP 2 HandLandmark.THUMB_IP 3 HandLandmark.THUMB_TIP 4 HandLandmark.INDEX_FINGER_MCP 5 HandLandmark.INDEX_FINGER_PIP 6 HandLandmark.INDEX_FINGER_DIP 7 HandLandmark.INDEX_FINGER_TIP 8 HandLandmark.MIDDLE_FINGER_MCP 9 HandLandmark.MIDDLE_FINGER_PIP 10 HandLandmark.MIDDLE_FINGER_DIP 11 HandLandmark.MIDDLE_FINGER_TIP 12 HandLandmark.RING_FINGER_MCP 13 HandLandmark.RING_FINGER_PIP 14 HandLandmark.RING_FINGER_DIP 15 HandLandmark.RING_FINGER_TIP 16 HandLandmark.PINKY_MCP 17 HandLandmark.PINKY_PIP 18 HandLandmark.PINKY_DIP 19 HandLandmark.PINKY_TIP 20 0 Hand Landmarks and their Indices OUTPUT: anikaseth98 sagar0719kumar Image-Processing OpenCV Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Support Vector Machine Algorithm k-nearest neighbor algorithm in Python Singular Value Decomposition (SVD) Difference between Informed and Uninformed Search in AI Intuition of Adam Optimizer Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24370, "s": 24342, "text": "\n03 Nov, 2021" }, { "code": null, "e": 24765, "s": 24370, "text": "In this article, we will use mediapipe python library to detect face and hand landmarks. We will be using a Holistic model from mediapipe solutions to detect all t...
Basics of Apache Spark Configuration Settings | by Halil Ertan | Towards Data Science
Apache Spark is one of the most popular open-source distributed computing platforms for in-memory batch and stream processing. It, though promises to process millions of records very fast in a general manner, might cause unacceptable results concerning memory and CPU usage if it is initially configured improperly. Resource utilization of a Spark application is very crucial in especially cloud platforms like AWS. Unnecessarily usage of memory and CPU resources and long duration of working processes might augment the cost dramatically. To make Spark work with high performance, two different points come up which are based on configuration level and code level. While the former is to configure the Spark correctly at the initial level, the latter is to develop/review the code by taking into account performance issues. In this post, I aim to give an insight into configuration settings. I also intend to write another writing about the best practices in coding. This post is mainly for Pyspark applications running with YARN in cluster mode. Before continuing further, I will mention Spark architecture and terminology in brief. Spark uses a master/slave architecture with a central coordinator called Driver and a set of executable workflows called Executors that are located at various nodes in the cluster. Resource Manager is the decision-maker unit about the allocation of resources between all applications in the cluster, and it is a part of Cluster Manager. Cluster Manager is a process that controls, governs, and reserves computing resources in the form of containers on the cluster. There are lots of cluster manager options for Spark applications, one of them is Hadoop YARN. When a Spark application launches, Resource Manager starts Application Master(AM) and allocates one container for it. AM coordinates the execution of all tasks within its application. AM can be considered as a non-executor container with the special capability of requesting containers from YARN, takes up resources of its own. Once AM launches, it asks for containers and resource requests of containers from Resource Manager. After successfully receiving the containers, AM launches them. Inside the containers, it runs the user application code via Driver. After completion of the application, AM releases the resources back to Resource Manager. If AM crashes or becomes unavailable, Resource Manager can create another container and restart AM on it. Driver is placed inside AM in cluster mode and responsible for converting a user application to smaller execution units called tasks and then schedules them to run on executors. These tasks are executed on the worker nodes and then return results to the Driver. Driver also informs AM of the executor’s needs for the application. It runs in its own JVM. Executors are the processes(computing units) at the worker’s nodes, whose job is to complete the assigned tasks. One executor container is just one JVM. Spark Context is the main entry point into Spark functionality. Spark Context also tracks executors in real-time by sending regular heartbeat messages. Spark Context is created by Driver for each Spark application when it is first submitted by the user. It exists throughout the lifetime of the Spark application. Spark Context stops working after the Spark application is finished. There are two different running modes available for Spark jobs — client mode and cluster mode. The difference basically depends on where Driver is running. While it runs in the client process in client mode, it runs in the AM in cluster mode. In production, cluster mode makes sense, the client can go away after initializing the application. One of the leading cluster management frameworks for Spark is YARN. In YARN terminology, executors and AM run inside containers. A container is an allocation of memory and CPU simply. When a Spark application is submitted through YARN in the cluster mode, the resources will be allocated in the form of containers by the Resource Manager. In the yarn-site.xml file, adjusting the following parameters is a good starting point if Spark is used together with YARN as a cluster management framework. In the case of running Spark applications with non-spark applications in the same cluster, firstly setting these YARN parameters correctly is very important. In a way, these parameters will define the borders of your Spark applications within the cluster. The followings are the basic YARN parameters to be set correctly. yarn.nodemanager.resource.memory-mb yarn.scheduler.maximum-allocation-mb yarn.scheduler.minimum-allocation-mb yarn.nodemanager.resource.cpu-vcores yarn.scheduler.maximum-allocation-vcores yarn.scheduler.minimum-allocation-vcores yarn.nodemanager.resource.memory-mb simply refers to the amount of physical memory that can be allocated for containers in a single node. It must be something lower than the total RAM value of the node considering the OS daemons and other running processes in the node. yarn.scheduler.minimum-allocation-mb and yarn.scheduler.maximum-allocation-mb parameters state minimum and maximum memory allocation values respectively a single container can get. Similar reasoning is valid for CPU allocation of containers. yarn.nodemanager.resource.cpu-vcores determines total available vcores allocated for all containers in a single node. And each container gets vcores within the values of yarn.scheduler.minimum-allocation-vcores and yarn.scheduler.maximum-allocation-vcores parameters as the lower and upper limit. Memory utilization is a bit more tricky compared to CPU utilization in Spark. Before deep dive into the configuration tuning, it would be useful to look at what is going on under the hood in memory management. A good summarization for memory management in Spark is depicted in the following diagram. Executor container (it is one JVM) allocates a memory part that consists of three sections. They are Heap memory, Off-Heap memory, and Overhead memory respectively. Off-Heap memory is disabled by default with the property spark.memory.offHeap.enabled. To use off-heap memory, the size of off-heap memory can be set by spark.memory.offHeap.size after enabling it. A detailed explanation about the usage of off-heap memory in Spark applications, and the pros and cons can be found here. Memory overhead can be set with spark.executor.memoryOverhead property and it is 10% of executor memory with a minimum of 384MB by default. It basically covers expenses like VM overheads, interned strings, other native overheads, etc. And the heap memory where the fun starts. All objects in heap memory are bound by the garbage collector(GC), unlike off-heap memory. For the sake of simplicity, it might be considered that it consists of 3 different regions, Reserved Memory, User Memory, and a unified region including execution and storage memory. Reserved memory is reserved to store internal objects. It is hardcoded and equal to 300MB. User Memory is reserved for user data structures, internal metadata in Spark, and safeguarding against OOM errors in the case of sparse and unusually large records. It is simply estimated by the following formula using spark.memory.fraction property. It determines how much JVM heap space is used for Spark execution memory. This property is recommended with a default value that is 0.6. So, User Memory is equal to 40% of JVM Executor Memory (Heap Memory). User Memory = (Heap Size-300MB)*(1-spark.memory.fraction)# where 300MB stands for reserved memory and spark.memory.fraction propery is 0.6 by default. In Spark, execution and storage share a unified region. When no execution memory is used, storage can acquire all available memory and vice versa. In necessary conditions, execution may evict storage until a certain limit which is set by spark.memory.storageFraction property. Beyond this limit, execution can not evict storage in any case. The default value for this property is 0.5. This tuning process is called as dynamic occupancy mechanism. This unified memory management is the default behavior of Spark since 1.6. The initial values for execution and storage memory are calculated through the following formulas. Execution memory = Usable Memory * spark.memory.fraction*(1-spark.memory.storageFraction)Storage memory = Usable Memory * spark.memory.fraction*spark.memory.storageFraction Execution memory is used to store temporary data in the shuffle, join, aggregation, sort, etc. Note that, the data manipulations are actually handled in this part. On the other hand, storage memory is used to store caching and broadcasting data. Execution memory has priority over storage memory as expected. The execution of a task is more important than cached data. The whole job can crash in case of insufficient execution memory. Additionally, it is important to keep in mind that the eviction process comes with a cost while adjusting parameters for the dynamic occupancy mechanism. This cost of memory eviction depends on the storage level of the cached data like MEMORY_ONLY and MEMORY_AND_DISK_SER. A clear explanation of memory management in Spark can be found here. Additionally, you can find another memory management view here in terms of garbage collection. After setting corresponding YARN parameters and understanding memory management in Spark, we pass to the next section — setting internal Spark parameters. Setting the configuration parameters listed below correctly is very important and determines the source consumption and performance of Spark basically. Let's take a look at them. spark.executor.instances: Number of executors for the spark application. spark.executor.memory: Amount of memory to use for each executor that runs the task. spark.executor.cores: Number of concurrent tasks an executor can run. spark.driver.memory: Amount of memory to use for the driver. spark.driver.cores: Number of virtual cores to use for the driver process. spark.sql.shuffle.partitions: Number of partitions to use when shuffling data for joins or aggregations. spark.default.parallelism: Default number of partitions in resilient distributed datasets (RDDs) returned by transformations like join and aggregations. To understand the reasoning behind the configuration setting through an example is better. Let’s assume, we have a cluster consists of 3 nodes with the specified capacity values like depicted in the following visual. The first step is the set spark.executor.cores that is mostly a straightforward property. Assigning a large number of vcores to each executor cause decrease in the number of executors, and so decrease the parallelism. On the other hand, assigning a small number of vcores to each executor cause large numbers of executors, and so might increase I/O cost in the application. In the lighting of the above-mentioned criteria, it is generally set as 5 as a rule of thumb. The second step is to decide on the spark.executor.instances property. To calculate this property, we initially determine the executor number per node. One vcore per node might be reserved for Hadoop and OS daemons. It is not a rule of thumb, you might ask for help from system admins to decide on these values. executor_per_node = (vcore_per_node-1)/spark.executor.coresexecutor_per_node = (16–1)/5 = 3spark.executor.instances = (executor_per_node * number_of_nodes)-1 spark.executor.instances = (3*3)-1 = 8 The third step is to decide on the spark.executor.memory property. To deduce for it, total available executor memory is firstly calculated and then memory overhead is taken into consideration and subtracted from total available memory. Similarly, 1 GB per node might be reserved for Hadoop and OS daemons. Note that running executors with too much memory often results in excessive garbage collection delays. total_executor_memory = (total_ram_per_node -1) / executor_per_nodetotal_executor_memory = (64–1)/3 = 21(rounded down)spark.executor.memory = total_executor_memory * 0.9spark.executor.memory = 21*0.9 = 18 (rounded down)memory_overhead = 21*0.1 = 3 (rounded up) spark.driver.memory can be set as the same as spark.executor.memory, just like spark.driver.cores is set as the same as spark.executors.cores. Another prominent property is spark.default.parallelism, and can be estimated with the help of the following formula. It is recommended 2–3 tasks per CPU core in the cluster. Spark reutilizes one executor JVM across many tasks, and efficiently supports tasks taking around 200 ms. Therefore, the level of parallelism can be set bigger than the number of cores in the cluster. Although the result of the formula gives a clue, it is encouraged to take into account the partition size to adjust the parallelism value. Recommended partition size is around 128MB. By using repartition and/or coalesce, this property can be defined based on the need during shuffle operations. If the data volumes in shuffle operations are very different scale. During the flow in Spark execution, spark.default.parallelism might not be set at the session level spark.default.parallelism = spark.executor.instances * spark.executor.cores * 2spark.default.parallelism = 8 * 5 * 2 = 80 In the case of data frames, spark.sql.shuffle.partitions can be set along with spark.default.parallelism property. Note that all the configuration settings approaches are based on maximizing the utilization of available resources. However, what about if multiple Spark applications are live on the same cluster, and share a common resource pool? At that point, taking advantage of spark.dynamicAllocation.enabled property might be an alternative. It is used together with spark.dynamicAllocation.initialExecutors, spark.dynamicAllocation.minExecutors, and spark.dynamicAllocation.maxExecutors . As it can be understood from the property names, applications start with an initial executor number and then increase the executor number in a case of high execution requirement or decrease the execution number in a case of the idle position of executors within the upper and lower limits. Another point of view might be applying an experimental methodology for the environments where running multiple Spark applications. To clarify it better, start with a configuration that validates the restrictions like working time duration. For instance, a scheduled Spark application runs every 10 minutes and is not expected to last more than 10 minutes. And then, decrease resources step by step as long as not violating restrictions. I also highly encourage you to take a look at fair scheduler in YARN if you have an environment in which lots of Spark applications are running. It gives a higher abstraction to manage the sharing of resources by multiple Spark applications. The goal is to make all the applications get a more or less equal share of resources over a period of time, and not penalize the applications with shorter execution time. Its configuration is maintained in two files: yarn-site.xml and fair-schedular.xml. In fair scheduler, resource management is done by utilizing queues in terms of memory and CPU usage. The resources are shared fairly between these queues. The principal properties of queues might be counted as minResources, maxResources, weights, and schedulingPolicy. To make it more clear, let's assume you have the same environment for developing new models and running scheduling applications in production for a reason. Separate queues might be defined for dev and prod applications, similarly, different queues might be defined for applications triggered by different users. Moreover, different weights might be assigned for different queues, so applications in the corresponding queues get the resources proportionally with the weights. You might get a simple answer here to the question about using both fair schedular and Spark configuration properties together.
[ { "code": null, "e": 711, "s": 171, "text": "Apache Spark is one of the most popular open-source distributed computing platforms for in-memory batch and stream processing. It, though promises to process millions of records very fast in a general manner, might cause unacceptable results concerning me...
MVC Framework - First Application
Let us jump in and create our first MVC application using Views and Controllers. Once we have a small hands-on experience on how a basic MVC application works, we will learn all the individual components and concepts in the coming chapters. Step 1 − Start your Visual Studio and select File → New → Project. Select Web → ASP.NET MVC Web Application and name this project as FirstMVCApplicatio. Select the Location as C:\MVC. Click OK. Step 2 − This will open the Project Template option. Select Empty template and View Engine as Razor. Click OK. Now, Visual Studio will create our first MVC project as shown in the following screenshot. Step 3 − Now we will create the first Controller in our application. Controllers are just simple C# classes, which contains multiple public methods, known as action methods. To add a new Controller, right-click the Controllers folder in our project and select Add → Controller. Name the Controller as HomeController and click Add. This will create a class file HomeController.cs under the Controllers folder with the following default code. using System; using System.Web.Mvc; namespace FirstMVCApplication.Controllers { public class HomeController : Controller { public ViewResult Index() { return View(); } } } The above code basically defines a public method Index inside our HomeController and returns a ViewResult object. In the next steps, we will learn how to return a View using the ViewResult object. Step 4 − Now we will add a new View to our Home Controller. To add a new View, rightclick view folder and click Add → View. Step 5 − Name the new View as Index and View Engine as Razor (SCHTML). Click Add. This will add a new cshtml file inside Views/Home folder with the following code − @{ Layout = null; } <html> <head> <meta name = "viewport" content = "width = device-width" /> <title>Index</title> </head> <body> <div> </div> </body> </html> Step 6 − Modify the above View's body content with the following code − <body> <div> Welcome to My First MVC Application (<b>From Index View</b>) </div> </body> Step 7 − Now run the application. This will give you the following output in the browser. This output is rendered based on the content in our View file. The application first calls the Controller which in turn calls this View and produces the output. In Step 7, the output we received was based on the content of our View file and had no interaction with the Controller. Moving a step forward, we will now create a small example to display a Welcome message with the current time using an interaction of View and Controller. Step 8 − MVC uses the ViewBag object to pass data between Controller and View. Open the HomeController.cs and edit the Index function to the following code. public ViewResult Index() { int hour = DateTime.Now.Hour; ViewBag.Greeting = hour < 12 ? "Good Morning. Time is" + DateTime.Now.ToShortTimeString() : "Good Afternoon. Time is " + DateTime.Now.ToShortTimeString(); return View(); } In the above code, we set the value of the Greeting attribute of the ViewBag object. The code checks the current hour and returns the Good Morning/Afternoon message accordingly using return View() statement. Note that here Greeting is just an example attribute that we have used with ViewBag object. You can use any other attribute name in place of Greeting. Step 9 − Open the Index.cshtml and copy the following code in the body section. <body> <div> @ViewBag.Greeting (<b>From Index View</b>) </div> </body> In the above code, we are accessing the value of Greeting attribute of the ViewBag object using @ (which would be set from the Controller). Step 10 − Now run the application again. This time our code will run the Controller first, set the ViewBag and then render it using the View code. Following will be the output. 44 Lectures 4.5 hours Kaushik Roy Chowdhury 42 Lectures 18 hours SHIVPRASAD KOIRALA 57 Lectures 3.5 hours University Code 55 Lectures 4.5 hours University Code 40 Lectures 2.5 hours University Code 140 Lectures 9 hours Bhrugen Patel Print Add Notes Bookmark this page
[ { "code": null, "e": 2266, "s": 2025, "text": "Let us jump in and create our first MVC application using Views and Controllers. Once we have a small hands-on experience on how a basic MVC application works, we will learn all the individual components and concepts in the coming chapters." }, { ...
Create a Quote generator web app with pure JavaScript using an API
14 Apr, 2021 In this tutorial we are going to create a web app that fetches motivational and inspirational quotes using an API. Application Requirements: Bootstrap 4 CDNAPI : https://type.fit/api/quotesJavaScriptHTML Bootstrap 4 CDN API : https://type.fit/api/quotes JavaScript HTML Steps: Follow the below steps to create a quote generator. Step 1 Fetch: We are using inbuilt fetch Function of JavaScript for fetching the data from API. This function return a promise. We will be using innerHTML function of JavaScript to populate the data from API on a web pagescript.jsscript.jsfetch(url).then(function (response) { return response.json();}).then(function (data) { return response.json();} Step 1 Fetch: We are using inbuilt fetch Function of JavaScript for fetching the data from API. This function return a promise. We will be using innerHTML function of JavaScript to populate the data from API on a web page script.js fetch(url).then(function (response) { return response.json();}).then(function (data) { return response.json();} Step 2 Button for Next and Previous: We are incrementing and decrementing values set by us in a variable to switch from one quote to Another.script.jsscript.jslet nextthought = document.getElementById("nextthought"); nextthought.addEventListener("click", function () { let countnum = document.getElementById("countnum"); countnum.value = ++a; displaythought(countnum.value, data); }); let previousthought = document.getElementById("previousthought"); previousthought.addEventListener("click", function () { let countnum = document.getElementById("countnum"); if (countnum.value < 0) { let thought = document.getElementById("thought"); thought.innerHTML = `<b><i>You are at first quote</i></b>`; } else { a = --countnum.value; displaythought(a, data); } }); Step 2 Button for Next and Previous: We are incrementing and decrementing values set by us in a variable to switch from one quote to Another. script.js let nextthought = document.getElementById("nextthought"); nextthought.addEventListener("click", function () { let countnum = document.getElementById("countnum"); countnum.value = ++a; displaythought(countnum.value, data); }); let previousthought = document.getElementById("previousthought"); previousthought.addEventListener("click", function () { let countnum = document.getElementById("countnum"); if (countnum.value < 0) { let thought = document.getElementById("thought"); thought.innerHTML = `<b><i>You are at first quote</i></b>`; } else { a = --countnum.value; displaythought(a, data); } }); Step 3 Button for Searching: For the search button we are taking a value input from the user to search that particular number in our data set provided by the API and then display it on our web page.script.jsscript.jslet searchbtn=document.getElementById('searchbtn');searchbtn.addEventListener('click',function(){ let countnum=document.getElementById('countnum'); let inputsearch=document.getElementById('inputsearch'); a=inputsearch.value; countnum.value=inputsearch.value; displaythought(a,data);}) Step 3 Button for Searching: For the search button we are taking a value input from the user to search that particular number in our data set provided by the API and then display it on our web page. script.js let searchbtn=document.getElementById('searchbtn');searchbtn.addEventListener('click',function(){ let countnum=document.getElementById('countnum'); let inputsearch=document.getElementById('inputsearch'); a=inputsearch.value; countnum.value=inputsearch.value; displaythought(a,data);}) Now we will create the HTML structure and combine all the above js sections to perform the fetching and manipulating the API data. index.html <!DOCTYPE html><html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"/> <link href="https://fonts.googleapis.com/css2?family=Chelsea+Market&display=swap" rel="stylesheet"/> <title>My Quotes</title> <style> body { font-family: "Chelsea Market", cursive; } </style> </head> <body style="background-color: black; color: white"> <div class="container"> <div class="jumbotron text-center bg-dark mt-4"> <h1 class="display-4">My Quotes</h1> <p class="lead">Motivational, Inspirational and more !</p> <hr class="my-4" /> <div id="thought"></div> <div class="row"> <div class="col-lg-10"> <input type="number" min="0" class="form-control" id="inputsearch" placeholder="numbers (1/1642)" onkeypress="return event.charCode >= 48 && event.charCode <= 57"/> </div> <button type="button" class="btn btn-outline-success col-lg-2" id="searchbtn"> Search </button> </div> <div class="container mt-3"> <button class="btn btn-outline-danger btn-lg" role="button" id="previousthought"> Previous </button> <span>----</span> <input id="countnum" type="hidden" /> <button class="btn btn-outline-primary btn-lg" role="button" id="nextthought"> Next==> </button> </div> </div> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"> </script> <script src="script.js"></script> </body></html> script.js let url = "https://type.fit/api/quotes";fetch(url) .then(function (response) { return response.json(); }) .then(function (data) { let a = 0; let searchbtn = document.getElementById("searchbtn"); searchbtn.addEventListener("click", function () { let countnum = document.getElementById("countnum"); let inputsearch = document.getElementById("inputsearch"); a = inputsearch.value; countnum.value = inputsearch.value; displaythought(a, data); }); let nextthought = document.getElementById("nextthought"); nextthought.addEventListener("click", function () { let countnum = document.getElementById("countnum"); countnum.value = ++a; displaythought(countnum.value, data); }); let previousthought = document.getElementById("previousthought"); previousthought.addEventListener("click", function () { let countnum = document.getElementById("countnum"); if (countnum.value < 0) { let thought = document.getElementById("thought"); thought.innerHTML = `<b><i>You are at first quote</i></b>`; } else { a = --countnum.value; displaythought(a, data); } }); displaythought(0, data); }); function displaythought(index, data) { let thought = document.getElementById("thought"); if (data[index].author == null) { data[index].author = "unknown"; } let htmlthought = `<div class="alert alert-outline-primary"> ${data[index].text}<br> <span style="color:#00ffc5;"> ${data[index].author} </span> </div>`; thought.innerHTML = htmlthought;} Output: HTML-DOM JavaScript-Methods JavaScript-Questions JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Apr, 2021" }, { "code": null, "e": 169, "s": 54, "text": "In this tutorial we are going to create a web app that fetches motivational and inspirational quotes using an API." }, { "code": null, "e": 195, "s": 169, ...
Check if email address valid or not in Python
08 Aug, 2021 Prerequisite: Regex in Python Given a string, write a Python program to check if the string is a valid email address or not. An email is a string (a subset of ASCII characters) separated into two parts by @ symbol, a “personal_info” and a domain, that is personal_info@domain. Examples: Input: ankitrai326@gmail.com Output: Valid Email Input: my.ownsite@ourearth.org Output: Valid Email Input: ankitrai326.com Output: Invalid Email In this program, we are using the search() method of re module. so let’s see the description of it.re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. Let’s see the Python program to validate an Email : Python3 # Python program to validate an Email # import re module # re module provides support# for regular expressionsimport re # Make a regular expression# for validating an Emailregex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' # Define a function for# for validating an Email def check(email): # pass the regular expression # and the string into the fullmatch() method if(re.fullmatch(regex, email)): print("Valid Email") else: print("Invalid Email") # Driver Codeif __name__ == '__main__': # Enter the email email = "ankitrai326@gmail.com" # calling run function check(email) email = "my.ownsite@our-earth.org" check(email) email = "ankitrai326.com" check(email) Valid Email Valid Email Invalid Email nagarjunarpa01 1kxezxl2vey1kouem4mpf6i5l9cpb5n9c5r7sryp ritiedu7 atulsilori armanschwarz Python Regex-programs python-regex Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Aug, 2021" }, { "code": null, "e": 82, "s": 52, "text": "Prerequisite: Regex in Python" }, { "code": null, "e": 329, "s": 82, "text": "Given a string, write a Python program to check if the string is a valid emai...
Closures in Golang
23 Mar, 2020 Go language provides a special feature known as an anonymous function. An anonymous function can form a closure. A closure is a special type of anonymous function that references variables declared outside of the function itself. It is similar to accessing global variables which are available before the declaration of the function. Example: // Golang program to illustrate how// to create a Closurepackage main import "fmt" func main() { // Declaring the variable GFG := 0 // Assigning an anonymous // function to a variable counter := func() int { GFG += 1 return GFG } fmt.Println(counter()) fmt.Println(counter()) } Output: 1 2 Explanation: The variable GFG was not passed as a parameter to the anonymous function but the function has access to it. In this example, there is a slight problem as any other function which will be defined in the main has access to the global variable GFG and it can change it without calling counter function. Thus closure also provides another aspect which is data isolation. // Golang program to illustrate how// to create data isolationpackage main import "fmt" // newCounter function to // isolate global variablefunc newCounter() func() int { GFG := 0 return func() int { GFG += 1 return GFG }}func main() { // newCounter function is // assigned to a variable counter := newCounter() // invoke counter fmt.Println(counter()) // invoke counter fmt.Println(counter()) } Output: 1 2 Explanation: The closure references the variable GFG even after the newCounter() function has finished running but no other code outside of the newCounter() function has access to this variable. This is how data persistency is maintained between function calls while also isolating the data from other code. Picked Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Mar, 2020" }, { "code": null, "e": 362, "s": 28, "text": "Go language provides a special feature known as an anonymous function. An anonymous function can form a closure. A closure is a special type of anonymous function that referen...
How to print % using printf()?
28 May, 2017 Asked by Tanuj Here is the standard prototype of printf function in C. int printf(const char *format, ...); The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of argument (and it is an error if insufficiently many arguments are given). The character % is followed by one of the following characters. The flag characterThe field widthThe precisionThe length modifierThe conversion specifier: See http://swoolley.org/man.cgi/3/printf for details of all the above characters. The main thing to note in the standard is the below line about conversion specifier. A `%' is written. No argument is converted. The complete conversion specification is`%%'. So we can print “%” using “%%” /* Program to print %*/#include<stdio.h>/* Program to print %*/int main(){ printf("%%"); getchar(); return 0;} We can also print “%” using below. printf("%c", '%');printf("%s", "%"); C-Input and Output Quiz c-puzzle C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 May, 2017" }, { "code": null, "e": 67, "s": 52, "text": "Asked by Tanuj" }, { "code": null, "e": 123, "s": 67, "text": "Here is the standard prototype of printf function in C." }, { "code": null, "e":...
Python | sympy.det() method
29 Jun, 2019 With the help of sympy.det() method, we can find the determinant of a matrix by using sympy.det() method. Syntax : sympy.det()Return : Return determinant of a matrix. Example #1 :In this example, we can see that by using sympy.det() method, we are able to find the determinant of a matrix. # import sympyfrom sympy import * # Use sympy.det() methodmat = Matrix([[1, 0, 1], [2, -1, 3], [4, 3, 2]])d = mat.det() print(d) Output : -1 Example #2 : # import sympyfrom sympy import * # Use sympy.det() methodmat = Matrix([[1, 5, 1], [12, -1, 31], [4, 33, 2]])d = mat.det() print(d) Output : -125 SymPy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python OOPs Concepts How to iterate through Excel rows in Python? Python Classes and Objects Introduction To PYTHON Decorators in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jun, 2019" }, { "code": null, "e": 134, "s": 28, "text": "With the help of sympy.det() method, we can find the determinant of a matrix by using sympy.det() method." }, { "code": null, "e": 195, "s": 134, "text": "...
Timer Application using PyQt5
04 May, 2020 In this article we will see how we can create a timer application in PyQt5. A timer is a specialized type of clock used for measuring specific time intervals, for the given time we have to decrease the time until times become zero i.e counting downwards. GUI Implementation steps : 1. Create a push button to open pop up for getting time and set its geometry2. Create label to show time and complete status3. Set label geometry, font size and align its text to center4. Create three push button for starting the timer, pausing the timer and for resetting the timer5. Set the geometry of each button Back-end Implementation steps : 1. Create count variable and flag to know if counter is stopped or running2. Add action to each button3. Inside the get second button action get the value of second using input dialog box and make the flag false4. Inside the start action make flag true but if count is zero make if false5. Inside pause action make flag false6. Inside the reset action make flag false, set count value to zero and set text to the label7. Make a timer object which calls its method after every 100 milliseconds8. Inside the timer action check for the flag then decrement the value of count and set text to the label Below is the implementation # importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 400, 600) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # variables # count variable self.count = 0 # start flag self.start = False # creating push button to get time in seconds button = QPushButton("Set time(s)", self) # setting geometry to the push button button.setGeometry(125, 100, 150, 50) # adding action to the button button.clicked.connect(self.get_seconds) # creating label to show the seconds self.label = QLabel("//TIMER//", self) # setting geometry of label self.label.setGeometry(100, 200, 200, 50) # setting border to the label self.label.setStyleSheet("border : 3px solid black") # setting font to the label self.label.setFont(QFont('Times', 15)) # setting alignment ot the label self.label.setAlignment(Qt.AlignCenter) # creating start button start_button = QPushButton("Start", self) # setting geometry to the button start_button.setGeometry(125, 350, 150, 40) # adding action to the button start_button.clicked.connect(self.start_action) # creating pause button pause_button = QPushButton("Pause", self) # setting geometry to the button pause_button.setGeometry(125, 400, 150, 40) # adding action to the button pause_button.clicked.connect(self.pause_action) # creating reset button reset_button = QPushButton("Reset", self) # setting geometry to the button reset_button.setGeometry(125, 450, 150, 40) # adding action to the button reset_button.clicked.connect(self.reset_action) # creating a timer object timer = QTimer(self) # adding action to timer timer.timeout.connect(self.showTime) # update the timer every tenth second timer.start(100) # method called by timer def showTime(self): # checking if flag is true if self.start: # incrementing the counter self.count -= 1 # timer is completed if self.count == 0: # making flag false self.start = False # setting text to the label self.label.setText("Completed !!!! ") if self.start: # getting text from count text = str(self.count / 10) + " s" # showing text self.label.setText(text) # method called by the push button def get_seconds(self): # making flag false self.start = False # getting seconds and flag second, done = QInputDialog.getInt(self, 'Seconds', 'Enter Seconds:') # if flag is true if done: # changing the value of count self.count = second * 10 # setting text to the label self.label.setText(str(second)) def start_action(self): # making flag true self.start = True # count = 0 if self.count == 0: self.start = False def pause_action(self): # making flag false self.start = False def reset_action(self): # making flag false self.start = False # setting count value to 0 self.count = 0 # setting label text self.label.setText("//TIMER//") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : PyQt-exercise Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Stack in Python Python Dictionary sum() function in Python Print lists in Python (5 Different Ways) Different ways to create Pandas Dataframe Queue in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n04 May, 2020" }, { "code": null, "e": 283, "s": 28, "text": "In this article we will see how we can create a timer application in PyQt5. A timer is a specialized type of clock used for measuring specific time intervals, for the given ti...
Shell Script to Remove Temporary Files
27 Apr, 2021 Temporary files in a linux environment are world-writable and world-readable which means that any user in the system can read and write to the temporary directory. In most of the Linux systems “/tmp” directory is used as a temporary directory and any user or process in the system can use this directory to store any temporary data. But any program/user should not assume that data stored in “/tmp” directory to be persisted over time, it should only be used for a temporary purpose. This shell script demonstrates the number of temporary files in “/tmp” directory and clearing the “/tmp” directory Approach: We will count the number of temporary files present in the temporary directory i.e “/tmp” directory and display the count to the user before and after deleting the temporary files. We calculate the no. of files by ‘ls’ command. “ls” command gives a list of all the files present in the directory, and we use “wc” command to count how many lines are printed by “ls” command. ls /tmp | wc -l Finally, the removal of temporary files is completed by running “rm” command this command takes the argument “-rf” that tells “rm” command to remove all files recursively and forcefully. We check the return code of the remove command to check if the command is successfully executed. In bash return code of the previous command can be checked b “$?” variable, if the value of this variable is equal to zero then the previous command is executed successfully else the previous command failed with some other return code. The remove command may fail if there is some file that is being currently open or some process has acquired lock on that file at the time we are running the remove command. We will count the number of temporary files present in the temporary directory i.e “/tmp” directory and display the count to the user before and after deleting the temporary files. We calculate the no. of files by ‘ls’ command. “ls” command gives a list of all the files present in the directory, and we use “wc” command to count how many lines are printed by “ls” command. ls /tmp | wc -l Finally, the removal of temporary files is completed by running “rm” command this command takes the argument “-rf” that tells “rm” command to remove all files recursively and forcefully. We check the return code of the remove command to check if the command is successfully executed. In bash return code of the previous command can be checked b “$?” variable, if the value of this variable is equal to zero then the previous command is executed successfully else the previous command failed with some other return code. The remove command may fail if there is some file that is being currently open or some process has acquired lock on that file at the time we are running the remove command. Code: #!/bin/bash # Script name script.sh # Script for removing all temporary files from temporary directory TMP_DIR="/tmp" echo "Removing all temporary files from $TMP_DIR" # Counting the number of temporary files files=`ls -l $TMP_DIR | wc -l` echo "There are total $files temporary files/directory in $TMP_DIR" rm -rf $TMP_DIR/* if [[ "$?" == "0" ]];then echo "All temporary files successfully deleted" else echo "Failed to delete temporary files" fi # Counting the number of temporary files files=`ls -l $TMP_DIR | wc -l` echo "There are total $files temporary files/directory in $TMP_DIR directory" Output: Executing the script Before execution assigns the permission of these scripts: chmod +x script.sh Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Apr, 2021" }, { "code": null, "e": 216, "s": 52, "text": "Temporary files in a linux environment are world-writable and world-readable which means that any user in the system can read and write to the temporary directory." }, { ...
ReactJS useCallback Hook
16 Mar, 2022 The useCallback hook is used when you have a component in which the child is rerendering again and again without need. Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders. Syntax: const memoizedCallback = useCallback( () => { doSomething(a, b); }, [a, b], ); Creating React Application: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Project Structure: It will look like the following. Without useCallback Hook: The problem is that once the counter is updated, all three functions are recreated again. The alert increases by three at a time but if we update some states all the functions related to that states should only re-instantiated. If another state value is unchanged, it should not be touched. Here, the filename is App.js Javascript import React, { useState, useCallback } from 'react'const funccount = new Set();const App = () => { const [count, setCount] = useState(0) const [number, setNumber] = useState(0) const incrementCounter = () => { setCount(count + 1) } const decrementCounter = () => { setCount(count - 1) } const incrementNumber = () => { setNumber(number + 1) } funccount.add(incrementCounter);funccount.add(decrementCounter);funccount.add(incrementNumber);alert(funccount.size); return ( <div> Count: {count} <button onClick={incrementCounter}> Increase counter </button> <button onClick={decrementCounter}> Decrease Counter </button> <button onClick={incrementNumber}> increase number </button> </div> )} export default App; With useCallback hook: To solve this problem we can use the useCallback hook. Here, the filename is App.js. Javascript import React, { useState, useCallback } from 'react'var funccount = new Set();const App = () => { const [count, setCount] = useState(0) const [number, setNumber] = useState(0) const incrementCounter = useCallback(() => { setCount(count + 1)}, [count])const decrementCounter = useCallback(() => { setCount(count - 1)}, [count])const incrementNumber = useCallback(() => { setNumber(number + 1)}, [number]) funccount.add(incrementCounter);funccount.add(decrementCounter);funccount.add(incrementNumber);alert(funccount.size); return ( <div> Count: {count} <button onClick={incrementCounter}> Increase counter </button> <button onClick={decrementCounter}> Decrease Counter </button> <button onClick={incrementNumber}> increase number </button> </div> )} export default App; Output: As we can see from the below output when we change the state ‘count’ then two functions will re-instantiated so the set size will increase by 2 and when we update the state ‘number’ then only one function will re-instantiated and the size of the set will increase by only one. surindertarika1234 sujaypatil1901 Picked React-Hooks ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Mar, 2022" }, { "code": null, "e": 172, "s": 53, "text": "The useCallback hook is used when you have a component in which the child is rerendering again and again without need." }, { "code": null, "e": 475, "s": 172,...
Union-Find Algorithm | (Union By Rank and Find by Optimized Path Compression)
28 Nov, 2021 Check whether a given graph contains a cycle or not.Example: Input: Output: Graph contains Cycle. Input: Output: Graph does not contain Cycle. Prerequisites: Disjoint Set (Or Union-Find), Union By Rank and Path CompressionWe have already discussed union-find to detect cycle. Here we discuss find by path compression, where it is slightly modified to work faster than the original method as we are skipping one level each time we are going up the graph. Implementation of find function is iterative, so there is no overhead involved.Time complexity of optimized find function is O(log*(n)), i.e iterated logarithm, which converges to O(1) for repeated calls.Refer this link for Proof of log*(n) complexity of Union-Find Explanation of find function: Take Example 1 to understand find function:(1)call find(8) for first time and mappings will be done like this: It took 3 mappings for find function to get the root of node 8. Mappings are illustrated below: From node 8, skipped node 7, Reached node 6. From node 6, skipped node 5, Reached node 4. From node 4, skipped node 2, Reached node 0.(2)call find(8) for second time and mappings will be done like this: It took 2 mappings for find function to get the root of node 8. Mappings are illustrated below: From node 8, skipped node 5, node 6 and node 7, Reached node 4. From node 4, skipped node 2, Reached node 0.(3)call find(8) for third time and mappings will be done like this: Finally, we see it took only 1 mapping for find function to get the root of node 8. Mappings are illustrated below: From node 8, skipped node 5, node 6, node 7, node 4, and node 2, Reached node 0. That is how it converges path from certain mappings to single mapping.Explanation of example 1:Initially array size and Arr look like: Arr[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8} size[9] = {1, 1, 1, 1, 1, 1, 1, 1, 1}Consider the edges in the graph, and add them one by one to the disjoint-union set as follows: Edge 1: 0-1 find(0)=>0, find(1)=>1, both have different root parent Put these in single connected component as currently they doesn’t belong to different connected components. Arr[1]=0, size[0]=2;Edge 2: 0-2 find(0)=>0, find(2)=>2, both have different root parent Arr[2]=0, size[0]=3;Edge 3: 1-3 find(1)=>0, find(3)=>3, both have different root parent Arr[3]=0, size[0]=3;Edge 4: 3-4 find(3)=>1, find(4)=>4, both have different root parent Arr[4]=0, size[0]=4;Edge 5: 2-4 find(2)=>0, find(4)=>0, both have same root parent Hence, There is a cycle in graph. We stop further checking for cycle in graph. C++ Java Python3 C# Javascript // CPP program to implement Union-Find with union// by rank and path compression.#include <bits/stdc++.h>using namespace std; const int MAX_VERTEX = 101; // Arr to represent parent of index iint Arr[MAX_VERTEX]; // Size to represent the number of nodes// in subgxrph rooted at index iint size[MAX_VERTEX]; // set parent of every node to itself and// size of node to onevoid initialize(int n){ for (int i = 0; i <= n; i++) { Arr[i] = i; size[i] = 1; }} // Each time we follow a path, find function// compresses it further until the path length// is greater than or equal to 1.int find(int i){ // while we reach a node whose parent is // equal to itself while (Arr[i] != i) { Arr[i] = Arr[Arr[i]]; // Skip one level i = Arr[i]; // Move to the new level } return i;} // A function that does union of two nodes x and y// where xr is root node of x and yr is root node of yvoid _union(int xr, int yr){ if (size[xr] < size[yr]) // Make yr parent of xr { Arr[xr] = Arr[yr]; size[yr] += size[xr]; } else // Make xr parent of yr { Arr[yr] = Arr[xr]; size[xr] += size[yr]; }} // The main function to check whether a given// gxrph contains cycle or notint isCycle(vector<int> adj[], int V){ // Itexrte through all edges of gxrph, find // nodes connecting them. // If root nodes of both are same, then there is // cycle in gxrph. for (int i = 0; i < V; i++) { for (int j = 0; j < adj[i].size(); j++) { int x = find(i); // find root of i int y = find(adj[i][j]); // find root of adj[i][j] if (x == y) return 1; // If same parent _union(x, y); // Make them connect } } return 0;} // Driver progxrm to test above functionsint main(){ int V = 3; // Initialize the values for arxry Arr and Size initialize(V); /* Let us create following gxrph 0 | \ | \ 1-----2 */ vector<int> adj[V]; // Adjacency list for gxrph adj[0].push_back(1); adj[0].push_back(2); adj[1].push_back(2); // call is_cycle to check if it contains cycle if (isCycle(adj, V)) cout << "Gxrph contains Cycle.\n"; else cout << "Gxrph does not contain Cycle.\n"; return 0;} // Java program to implement Union-Find with union// by rank and path compressionimport java.util.*; class GFG {static int MAX_VERTEX = 101; // Arr to represent parent of index istatic int []Arr = new int[MAX_VERTEX]; // Size to represent the number of nodes// in subgxrph rooted at index istatic int []size = new int[MAX_VERTEX]; // set parent of every node to itself and// size of node to onestatic void initialize(int n){ for (int i = 0; i <= n; i++) { Arr[i] = i; size[i] = 1; }} // Each time we follow a path, find function// compresses it further until the path length// is greater than or equal to 1.static int find(int i){ // while we reach a node whose parent is // equal to itself while (Arr[i] != i) { Arr[i] = Arr[Arr[i]]; // Skip one level i = Arr[i]; // Move to the new level } return i;} // A function that does union of two nodes x and y// where xr is root node of x and yr is root node of ystatic void _union(int xr, int yr){ if (size[xr] < size[yr]) // Make yr parent of xr { Arr[xr] = Arr[yr]; size[yr] += size[xr]; } else // Make xr parent of yr { Arr[yr] = Arr[xr]; size[xr] += size[yr]; }} // The main function to check whether a given// gxrph contains cycle or notstatic int isCycle(Vector<Integer> adj[], int V){ // Itexrte through all edges of gxrph, // find nodes connecting them. // If root nodes of both are same, // then there is cycle in gxrph. for (int i = 0; i < V; i++) { for (int j = 0; j < adj[i].size(); j++) { int x = find(i); // find root of i // find root of adj[i][j] int y = find(adj[i].get(j)); if (x == y) return 1; // If same parent _union(x, y); // Make them connect } } return 0;} // Driver Codepublic static void main(String[] args) { int V = 3; // Initialize the values for arxry Arr and Size initialize(V); /* Let us create following gxrph 0 | \ | \ 1-----2 */ // Adjacency list for graph Vector<Integer> []adj = new Vector[V]; for(int i = 0; i < V; i++) adj[i] = new Vector<Integer>(); adj[0].add(1); adj[0].add(2); adj[1].add(2); // call is_cycle to check if it contains cycle if (isCycle(adj, V) == 1) System.out.print("Graph contains Cycle.\n"); else System.out.print("Graph does not contain Cycle.\n"); }} // This code is contributed by PrinciRaj1992 # Python3 program to implement Union-Find # with union by rank and path compression. # set parent of every node to itself # and size of node to one def initialize(n): global Arr, size for i in range(n + 1): Arr[i] = i size[i] = 1 # Each time we follow a path, find # function compresses it further # until the path length is greater # than or equal to 1. def find(i): global Arr, size # while we reach a node whose # parent is equal to itself while (Arr[i] != i): Arr[i] = Arr[Arr[i]] # Skip one level i = Arr[i] # Move to the new level return i # A function that does union of two # nodes x and y where xr is root node # of x and yr is root node of y def _union(xr, yr): global Arr, size if (size[xr] < size[yr]): # Make yr parent of xr Arr[xr] = Arr[yr] size[yr] += size[xr] else: # Make xr parent of yr Arr[yr] = Arr[xr] size[xr] += size[yr] # The main function to check whether # a given graph contains cycle or not def isCycle(adj, V): global Arr, size # Itexrte through all edges of gxrph, # find nodes connecting them. # If root nodes of both are same, # then there is cycle in gxrph. for i in range(V): for j in range(len(adj[i])): x = find(i) # find root of i y = find(adj[i][j]) # find root of adj[i][j] if (x == y): return 1 # If same parent _union(x, y) # Make them connect return 0 # Driver CodeMAX_VERTEX = 101 # Arr to represent parent of index i Arr = [None] * MAX_VERTEX # Size to represent the number of nodes # in subgxrph rooted at index i size = [None] * MAX_VERTEX V = 3 # Initialize the values for arxry # Arr and Size initialize(V) # Let us create following gxrph # 0 # | \ # | \ # 1-----2 # Adjacency list for graph adj = [[] for i in range(V)] adj[0].append(1) adj[0].append(2) adj[1].append(2) # call is_cycle to check if it # contains cycle if (isCycle(adj, V)): print("Graph contains Cycle.") else: print("Graph does not contain Cycle.") # This code is contributed by PranchalK // C# program to implement Union-Find // with union by rank and path compressionusing System;using System.Collections.Generic; class GFG {static int MAX_VERTEX = 101; // Arr to represent parent of index istatic int []Arr = new int[MAX_VERTEX]; // Size to represent the number of nodes// in subgxrph rooted at index istatic int []size = new int[MAX_VERTEX]; // set parent of every node to itself // and size of node to onestatic void initialize(int n){ for (int i = 0; i <= n; i++) { Arr[i] = i; size[i] = 1; }} // Each time we follow a path, // find function compresses it further // until the path length is greater than // or equal to 1.static int find(int i){ // while we reach a node whose // parent is equal to itself while (Arr[i] != i) { Arr[i] = Arr[Arr[i]]; // Skip one level i = Arr[i]; // Move to the new level } return i;} // A function that does union of // two nodes x and y where xr is // root node of x and yr is root node of ystatic void _union(int xr, int yr){ if (size[xr] < size[yr]) // Make yr parent of xr { Arr[xr] = Arr[yr]; size[yr] += size[xr]; } else // Make xr parent of yr { Arr[yr] = Arr[xr]; size[xr] += size[yr]; }} // The main function to check whether // a given graph contains cycle or notstatic int isCycle(List<int> []adj, int V){ // Itexrte through all edges of graph, // find nodes connecting them. // If root nodes of both are same, // then there is cycle in graph. for (int i = 0; i < V; i++) { for (int j = 0; j < adj[i].Count; j++) { int x = find(i); // find root of i // find root of adj[i][j] int y = find(adj[i][j]); if (x == y) return 1; // If same parent _union(x, y); // Make them connect } } return 0;} // Driver Codepublic static void Main(String[] args) { int V = 3; // Initialize the values for // array Arr and Size initialize(V); /* Let us create following graph 0 | \ | \ 1-----2 */ // Adjacency list for graph List<int> []adj = new List<int>[V]; for(int i = 0; i < V; i++) adj[i] = new List<int>(); adj[0].Add(1); adj[0].Add(2); adj[1].Add(2); // call is_cycle to check if it contains cycle if (isCycle(adj, V) == 1) Console.Write("Graph contains Cycle.\n"); else Console.Write("Graph does not contain Cycle.\n"); }} // This code is contributed by Rajput-Ji <script> // Javascript program to implement Union-Find with union// by rank and path compression. var MAX_VERTEX = 101; // Arr to represent parent of index ivar Arr = Array(MAX_VERTEX).fill(0); // Size to represent the number of nodes// in subgxrph rooted at index ivar size = Array(MAX_VERTEX).fill(0); // set parent of every node to itself and// size of node to onefunction initialize(n){ for (var i = 0; i <= n; i++) { Arr[i] = i; size[i] = 1; }} // Each time we follow a path, find function// compresses it further until the path length// is greater than or equal to 1.function find(i){ // while we reach a node whose parent is // equal to itself while (Arr[i] != i) { Arr[i] = Arr[Arr[i]]; // Skip one level i = Arr[i]; // Move to the new level } return i;} // A function that does union of two nodes x and y// where xr is root node of x and yr is root node of yfunction _union(xr, yr){ if (size[xr] < size[yr]) // Make yr parent of xr { Arr[xr] = Arr[yr]; size[yr] += size[xr]; } else // Make xr parent of yr { Arr[yr] = Arr[xr]; size[xr] += size[yr]; }} // The main function to check whether a given// gxrph contains cycle or notfunction isCycle(adj, V){ // Itexrte through all edges of gxrph, find // nodes connecting them. // If root nodes of both are same, then there is // cycle in gxrph. for (var i = 0; i < V; i++) { for (var j = 0; j < adj[i].length; j++) { var x = find(i); // find root of i var y = find(adj[i][j]); // find root of adj[i][j] if (x == y) return 1; // If same parent _union(x, y); // Make them connect } } return 0;} // Driver progxrm to test above functionsvar V = 3; // Initialize the values for arxry Arr and Sizeinitialize(V);/* Let us create following gxrph 0 | \ | \ 1-----2 */var adj = Array.from(Array(V), ()=>Array()); // Adjacency list for gxrphadj[0].push(1);adj[0].push(2);adj[1].push(2); // call is_cycle to check if it contains cycleif (isCycle(adj, V)) document.write("Graph contains Cycle.<br>");else document.write("Graph does not contain Cycle.<br>"); // This code is contributed by rutvik_56.</script> Output: Graph contains Cycle. Time Complexity(Find) : O(log*(n)) Time Complexity(union) : O(1) PranchalKatiyar rahul_15 princiraj1992 Rajput-Ji rutvik_56 union-find Advanced Data Structure Graph Graph union-find Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree) Ordered Set and GNU C++ PBDS 2-3 Trees | (Search, Insert and Deletion) Segment Tree | Set 2 (Range Minimum Query) Extendible Hashing (Dynamic approach to DBMS) Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Graph and its representations
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Nov, 2021" }, { "code": null, "e": 117, "s": 54, "text": "Check whether a given graph contains a cycle or not.Example: " }, { "code": null, "e": 125, "s": 117, "text": "Input: " }, { "code": null, "e...
Styling Django Forms with django-crispy-forms
23 Oct, 2020 Django by default doesn’t provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solves this problem for us. It will let you control the rendering behavior of your Django forms in a very elegant and DRY way. django : django install django-crispy-forms pip install django-crispy-forms Configuring Django settings: Add ‘crispy_forms’ to the INSTALLED_APPS in settings.py, and also add CRISPY_TEMPLATE_PACK = 'bootstrap4' after INSTALLED_APPS. Till now we have configured settings needed for django-crispy-forms. Using django-crispy-forms in Django templates: First, we need to load django-crispy-forms tags in our django template. For loading django-crispy-forms tags, add {%load crispy_forms_tags %} on the top of your django template Now to style any form with django-crispy-forms , replace {{ form }} with {{ form|crispy }} Bingo, you have successfully styled your form with django-crispy-forms. Now you can see changes in your Django form by running server python manage.py runserver Example of Signup page styled using django-crispy-forms Django-forms Python Django Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Oct, 2020" }, { "code": null, "e": 349, "s": 52, "text": "Django by default doesn’t provide any Django form styling method due to which it takes a lot of effort and precious time to beautifully style a form. django-crispy-forms solv...
HTML | <iframe> sandbox Attribute
17 Jun, 2022 The sandbox attribute permits an additional set of restrictions for the content within the iframe.When the sandbox attribute exists, and it will: treat the content as being from a singular origin It blocks form submission It blocks script execution It disables APIs It also preventing links from targeting other browsing contexts It stop the content to navigate its top-level browsing context block automatically triggered features (such as automatically playing a video or automatically focusing a form control) The value of the sandbox attribute will either be simply sandboxed (then all restrictions are applied) or a space-separated list of pre-defined values which will take away the actual restrictions. Syntax: <iframe sandbox="value"> Attribute Values no-values: applies all restriction allow-forms: Re-enables form submission allow-pointer-lock: Re-enables APIs allow-popups: Re-enables popups allow-same-origin: It allows the content of iframe to be treated as being from same origin allow-scripts: Re-enables scripts allow-top-navigation: It Allows the content of iframe to navigate its top-level browsing context Example: html <!DOCTYPE html><html> <head> <title> HTML Iframe sandbox Attribute </title></head> <body> <h1>GeeksforGeeks</h1> <h2>HTML IFrame sandbox Attribute</h2> <br> <br> <iframe id="GFGFrame" src="https://ide.geeksforgeeks.org/tryit.php" width="400" height="200" sandbox> </iframe></body> </html> Output: Supported Browsers:The browsers supported by HTML IFrame sandbox Attribute are listed below Google Chrome 4.0 and above Edge 12.0 and above Firefox 17.0 and above Internet Explorer 10.0 and above Opera 15.0 and above Safari 5.0 and above hritikbhatnagar2182 simmytarika5 satyamm09 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet) How to Insert Form Data into Database using PHP ? HTTP headers | Content-Type Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2022" }, { "code": null, "e": 176, "s": 28, "text": "The sandbox attribute permits an additional set of restrictions for the content within the iframe.When the sandbox attribute exists, and it will: " }, { "code": null,...
EasyMock - Quick Guide
Mocking is a way to test the functionality of a class in isolation. Mocking does not require a database connection or properties file read or file server read to test a functionality. Mock objects do the mocking of the real service. A mock object returns a dummy data corresponding to some dummy input passed to it. EasyMock facilitates creating mock objects seamlessly. It uses Java Reflection in order to create mock objects for a given interface. Mock objects are nothing but proxy for actual implementations. Consider a case of Stock Service which returns the price details of a stock. During development, the actual stock service cannot be used to get real-time data. So we need a dummy implementation of the stock service. EasyMock can do the same very easily as its name suggests. No Handwriting − No need to write mock objects on your own. No Handwriting − No need to write mock objects on your own. Refactoring Safe − Renaming interface method names or reordering parameters will not break the test code as Mocks are created at runtime. Refactoring Safe − Renaming interface method names or reordering parameters will not break the test code as Mocks are created at runtime. Return value support − Supports return values. Return value support − Supports return values. Exception support − Supports exceptions. Exception support − Supports exceptions. Order check support − Supports check on order of method calls. Order check support − Supports check on order of method calls. Annotation support − Supports creating mocks using annotation. Annotation support − Supports creating mocks using annotation. Consider the following code snippet. package com.tutorialspoint.mock; import java.util.ArrayList; import java.util.List; import org.EasyMock.EasyMock; public class PortfolioTester { public static void main(String[] args){ //Create a portfolio object which is to be tested Portfolio portfolio = new Portfolio(); //Creates a list of stocks to be added to the portfolio List<Stock> stocks = new ArrayList<Stock>(); Stock googleStock = new Stock("1","Google", 10); Stock microsoftStock = new Stock("2","Microsoft",100); stocks.add(googleStock); stocks.add(microsoftStock); //Create the mock object of stock service StockService stockServiceMock = EasyMock.createMock(StockService.class); // mock the behavior of stock service to return the value of various stocks EasyMock.expect(stockServiceMock.getPrice(googleStock)).andReturn(50.00); EasyMock.expect(stockServiceMock.getPrice(microsoftStock)).andReturn(1000.00); EasyMock.replay(stockServiceMock); //add stocks to the portfolio portfolio.setStocks(stocks); //set the stockService to the portfolio portfolio.setStockService(stockServiceMock); double marketValue = portfolio.getMarketValue(); //verify the market value to be //10*50.00 + 100* 1000.00 = 500.00 + 100000.00 = 100500 System.out.println("Market value of the portfolio: "+ marketValue); } } Let's understand the important concepts of the above program. The complete code is available in the chapter First Application. Portfolio − An object to carry a list of stocks and to get the market value computed using stock prices and stock quantity. Portfolio − An object to carry a list of stocks and to get the market value computed using stock prices and stock quantity. Stock − An object to carry the details of a stock such as its id, name, quantity, etc. Stock − An object to carry the details of a stock such as its id, name, quantity, etc. StockService − A stock service returns the current price of a stock. StockService − A stock service returns the current price of a stock. EasyMock.createMock(...) − EasyMock created a mock of stock service. EasyMock.createMock(...) − EasyMock created a mock of stock service. EasyMock.expect(...).andReturn(...) − Mock implementation of getPrice method of stockService interface. For googleStock, return 50.00 as price. EasyMock.expect(...).andReturn(...) − Mock implementation of getPrice method of stockService interface. For googleStock, return 50.00 as price. EasyMock.replay(...) − EasyMock prepares the Mock object to be ready so that it can be used for testing. EasyMock.replay(...) − EasyMock prepares the Mock object to be ready so that it can be used for testing. portfolio.setStocks(...) − The portfolio now contains a list of two stocks. portfolio.setStocks(...) − The portfolio now contains a list of two stocks. portfolio.setStockService(...) − Assigns the stockService Mock object to the portfolio. portfolio.setStockService(...) − Assigns the stockService Mock object to the portfolio. portfolio.getMarketValue() − The portfolio returns the market value based on its stocks using the mock stock service. portfolio.getMarketValue() − The portfolio returns the market value based on its stocks using the mock stock service. This chapter takes you through the process of setting up EasyMock on Windows and Linux based systems. EasyMock can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation. Let us now proceed with the steps to install EasyMock. First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Open command console and type: \>java –version java version "11.0.11" 2021-04-20 LTS Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode) Open command terminal and type: $java –version java version "11.0.11" 2021-04-20 LTS Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode) We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system. We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Windows Set JAVA_HOME to C:\ProgramFiles\java\jdk11.0.11 Linux Export JAVA_HOME = /usr/local/java-current Append the full path of Java compiler location to the System Path. Windows Append the String "C:\Program Files\Java\jdk11.0.11\bin" to the end of the system variable PATH. Linux Export PATH = $PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Download the latest version of EasyMock from https://easymock.org/ and unzip its contents to a folder from where the required libraries can be linked to your Java program. Let us assume the files are collected in a folder on C drive. Add the complete path of the required jars as shown below to the CLASSPATH. Windows Append the following strings to the end of the user variable CLASSPATH − C:\easymock\easymock-4.3.jar; Linux Export CLASSPATH = $CLASSPATH: /usr/share/easymock\easymock-4.3.tar: Download the latest version of JUnit jar file from Github. Save the folder at the location C:\>Junit. Set the JUNIT_HOME environment variable to point to the base directory location where JUnit jars are stored on your machine. The following table shows how to set this environment variable on different operating systems, assuming we've stored junit4.13.2.jar and hamcrest-core-1.3.jar at C:\>Junit. Set the CLASSPATH environment variable to point to the JUNIT jar location. The following table shows how it is done on different operating systems. Before going into the details of the EasyMock Framework, let’s see an application in action. In this example, we've created a mock of Stock Service to get the dummy price of some stocks and unit tested a java class named Portfolio. The process is discussed below in a step-by-step manner. Step 1: Create a JAVA class to represent the Stock File: Stock.java public class Stock { private String stockId; private String name; private int quantity; public Stock(String stockId, String name, int quantity){ this.stockId = stockId; this.name = name; this.quantity = quantity; } public String getStockId() { return stockId; } public void setStockId(String stockId) { this.stockId = stockId; } public int getQuantity() { return quantity; } public String getTicker() { return name; } } Step 2: Create an interface StockService to get the price of a stock. File: StockService.java public interface StockService { public double getPrice(Stock stock); } Step 3: Create a class Portfolio to represent the portfolio of any client. File: Portfolio.java import java.util.List; public class Portfolio { private StockService stockService; private List<Stock> stocks; public StockService getStockService() { return stockService; } public void setStockService(StockService stockService) { this.stockService = stockService; } public List<Stock> getStocks() { return stocks; } public void setStocks(List<Stock> stocks) { this.stocks = stocks; } public double getMarketValue(){ double marketValue = 0.0; for(Stock stock:stocks){ marketValue += stockService.getPrice(stock) * stock.getQuantity(); } return marketValue; } } Step 4: Test the Portfolio class Let's test the Portfolio class, by injecting in it a mock of stockservice. Mock will be created by EasyMock. File: PortfolioTester.java import java.util.ArrayList; import java.util.List; import org.easymock.EasyMock; public class PortfolioTester { Portfolio portfolio; StockService stockService; public static void main(String[] args){ PortfolioTester tester = new PortfolioTester(); tester.setUp(); System.out.println(tester.testMarketValue()?"pass":"fail"); } public void setUp(){ //Create a portfolio object which is to be tested portfolio = new Portfolio(); //Create the mock object of stock service stockService = EasyMock.createMock(StockService.class); //set the stockService to the portfolio portfolio.setStockService(stockService); } public boolean testMarketValue(){ //Creates a list of stocks to be added to the portfolio List<Stock> stocks = new ArrayList<Stock>(); Stock googleStock = new Stock("1","Google", 10); Stock microsoftStock = new Stock("2","Microsoft",100); stocks.add(googleStock); stocks.add(microsoftStock); //add stocks to the portfolio portfolio.setStocks(stocks); // mock the behavior of stock service to return the value of various stocks EasyMock.expect(stockService.getPrice(googleStock)).andReturn(50.00); EasyMock.expect(stockService.getPrice(microsoftStock)).andReturn(1000.00); // activate the mock EasyMock.replay(stockService); double marketValue = portfolio.getMarketValue(); return marketValue == 100500.0; } } Step 5: Verify the result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Stock.java StockService.java Portfolio.java PortfolioTester.java Now run the PortfolioTester to see the result − C:\EasyMock_WORKSPACE>java PortfolioTester Verify the Output pass In this chapter, we'll learn how to integrate JUnit and EasyMock together. Here we will create a Math Application which uses CalculatorService to perform basic mathematical operations such as addition, subtraction, multiply, and division. We'll use EasyMock to mock the dummy implementation of CalculatorService. In addition, we've made extensive use of annotations to showcase their compatibility with both JUnit and EasyMock. The process is discussed below in a step-by-step manner. Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); } } Step 4: Create a class to execute to test cases. Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true To learn more about JUnit, please refer to JUnit Tutorial at Tutorials Point. EasyMock adds a functionality to a mock object using the methods expect() and expectLassCall(). Take a look at the following code snippet. //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); Here we've instructed EasyMock to give a behavior of adding 10 and 20 to the add method of calcService and as a result, to return the value of 30.00. At this point of time, Mock simply recorded the behavior but it is not working as a mock object. After calling replay, it works as expected. //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); //activate the mock //EasyMock.replay(calcService); Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; //@RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify the class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); //activate the mock //EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\>EasyMock_WORKSPACE to execute the test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. testAdd(MathApplicationTester): expected:<0.0> but was:<30.0> false Step 1: Create an interface called CalculatorService to provide mathematical functions. File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication. File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); // @Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ // add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); //activate the mock EasyMock.replay(calcService); // test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\>EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result. C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true EasyMock can ensure whether a mock is being used or not. It is done using the verify() method. Take a look at the following code snippet. //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ //return calcService.add(input1, input2); return input1 + input2; } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not //EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result. C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true Step 1: Create an interface CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ //return calcService.add(input1, input2); return input1 + input2; } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. testAdd(MathApplicationTester): Expectation failure on verify: CalculatorService.add(10.0, 20.0): expected: 1, actual: 0 false EasyMock provides a special check on the number of calls that can be made on a particular method. Suppose MathApplication should call the CalculatorService.serviceUsed() method only once, then it should not be able to call CalculatorService.serviceUsed() more than once. //add the behavior of calc service to add two numbers and serviceUsed. EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); calcService.serviceUsed(); //limit the method call to 1, no less and no more calls are allowed EasyMock.expectLastCall().times(1); Create CalculatorService interface as follows. File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); public void serviceUsed(); } Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); public void serviceUsed(); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ calcService.serviceUsed(); return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); // @Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); calcService.serviceUsed(); EasyMock.expectLastCall().times(1); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true Step 1: Create an interface CalculatorService to provide mathematical functions. File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); public void serviceUsed(); } Step 2: Create a JAVA class to represent MathApplication. File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ calcService.serviceUsed(); calcService.serviceUsed(); return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); calcService.serviceUsed(); EasyMock.expectLastCall().times(1); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACEto execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac CalculatorService.java MathApplication.java MathApplicationTester.java TestRunner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. testAdd(com.tutorialspoint.mock.MathApplicationTester): Unexpected method call CalculatorService.serviceUsed(): CalculatorService.add(10.0, 20.0): expected: 1, actual: 0 CalculatorService.serviceUsed(): expected: 1, actual: 2 false Step 1: Create an interface Calculator Service to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); public void serviceUsed(); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); calcService.serviceUsed(); EasyMock.expectLastCall().times(1); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. testAdd(com.tutorialspoint.mock.MathApplicationTester): Expectation failure on verify: CalculatorService.serviceUsed(): expected: 1, actual: 0 false EasyMock provides the following additional methods to vary the expected call counts. times (int min, int max) − expects between min and max calls. times (int min, int max) − expects between min and max calls. atLeastOnce () − expects at least one call. atLeastOnce () − expects at least one call. anyTimes () − expects an unrestricted number of calls. anyTimes () − expects an unrestricted number of calls. Step 1: Create an interface CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); public void serviceUsed(); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ calcService.serviceUsed(); calcService.serviceUsed(); calcService.serviceUsed(); return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); calcService.serviceUsed(); EasyMock.expectLastCall().times(1,3); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s) File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); public void serviceUsed(); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ calcService.serviceUsed(); calcService.serviceUsed(); return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); calcService.serviceUsed(); EasyMock.expectLastCall().atLeastOnce(); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); public void serviceUsed(); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ calcService.serviceUsed(); calcService.serviceUsed(); return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test public void testAdd(){ //add the behavior of calc service to add two numbers EasyMock.expect(calcService.add(10.0,20.0)).andReturn(30.00); calcService.serviceUsed(); EasyMock.expectLastCall().anyTimes(); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac Calculator Service.java Math Application.java Math Application Tester.java Test Runner.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true EasyMock provides the capability to a mock to throw exceptions, so exception handling can be tested. Take a look at the following code snippet. //add the behavior to throw exception EasyMock.expect(calc Service.add(10.0,20.0)).and Throw(new Runtime Exception("Add operation not implemented")); Here we've added an exception clause to a mock object. MathApplication makes use of calcService using its add method and the mock throws a RuntimeException whenever calcService.add() method is invoked. Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.easymock.Mock; import org.easymock.TestSubject; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; // @RunWith attaches a runner with the test class to initialize the test data @RunWith(EasyMockRunner.class) public class MathApplicationTester { // @TestSubject annotation is used to identify class which is going to use the mock object @TestSubject MathApplication mathApplication = new MathApplication(); //@Mock annotation is used to create the mock object to be injected @Mock CalculatorService calcService; @Test(expected = RuntimeException.class) public void testAdd(){ //add the behavior to throw exception EasyMock.expect(calcService.add(10.0,20.0)).andThrow( new RuntimeException("Add operation not implemented") ); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(10.0, 20.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac MathApplicationTester.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true So far, we've used annotations to create mocks. EasyMock provides various methods to create mock objects. EasyMock.createMock() creates mocks without bothering about the order of method calls that the mock is going to make in due course of its action. calcService = EasyMock.createMock(CalculatorService.class); Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. Here we've added two mock method calls, add() and subtract(), to the mock object via expect(). However during testing, we've called subtract() before calling add(). When we create a mock object using EasyMock.createMock(), the order of execution of the method does not matter. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(EasyMockRunner.class) public class MathApplicationTester { private MathApplication mathApplication; private CalculatorService calcService; @Before public void setUp(){ mathApplication = new MathApplication(); calcService = EasyMock.createMock(CalculatorService.class); mathApplication.setCalculatorService(calcService); } @Test public void testAddAndSubtract(){ //add the behavior to add numbers EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0); //subtract the behavior to subtract numbers EasyMock.expect(calcService.subtract(20.0,10.0)).andReturn(10.0); //activate the mock EasyMock.replay(calcService); //test the subtract functionality Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0); //test the add functionality Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac MathApplicationTester.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. true EasyMock.createStrictMock() creates a mock and also takes care of the order of method calls that the mock is going to make in due course of its action. calcService = EasyMock.createStrictMock(CalculatorService.class); Step 1: Create an interface called CalculatorService to provide mathematical functions File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. Here we've added two mock method calls, add() and subtract(), to the mock object via expect(). However during testing, we've called subtract() before calling add(). When we create a mock object using EasyMock.createStrictMock(), the order of execution of the method does matter. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(EasyMockRunner.class) public class MathApplicationTester { private MathApplication mathApplication; private CalculatorService calcService; @Before public void setUp(){ mathApplication = new MathApplication(); calcService = EasyMock.createStrictMock(CalculatorService.class); mathApplication.setCalculatorService(calcService); } @Test public void testAddAndSubtract(){ //add the behavior to add numbers EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0); //subtract the behavior to subtract numbers EasyMock.expect(calcService.subtract(20.0,10.0)).andReturn(10.0); //activate the mock EasyMock.replay(calcService); //test the subtract functionality Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0); //test the add functionality Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac MathApplicationTester.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output. testAddAndSubtract(com.tutorialspoint.mock.MathApplicationTester): Unexpected method call CalculatorService.subtract(20.0, 10.0): CalculatorService.add(20.0, 10.0): expected: 1, actual: 0 false EasyMock.createNiceMock() creates a mock and sets the default implementation of each method of the mock. If EasyMock.createMock() is used, then invoking the mock method throws assertion error. calcService = EasyMock.createNiceMock(CalculatorService.class); Step 1: Create an interface called CalculatorService to provide mathematical functions. File: CalculatorService.java public interface CalculatorService { public double add(double input1, double input2); public double subtract(double input1, double input2); public double multiply(double input1, double input2); public double divide(double input1, double input2); } Step 2: Create a JAVA class to represent MathApplication File: MathApplication.java public class MathApplication { private CalculatorService calcService; public void setCalculatorService(CalculatorService calcService){ this.calcService = calcService; } public double add(double input1, double input2){ return calcService.add(input1, input2); } public double subtract(double input1, double input2){ return calcService.subtract(input1, input2); } public double multiply(double input1, double input2){ return calcService.multiply(input1, input2); } public double divide(double input1, double input2){ return calcService.divide(input1, input2); } } Step 3: Test the MathApplication class Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock. Here we've added one mock method call, add(), via expect(). However during testing, we've called subtract() and other methods as well. When we create a mock object using EasyMock.createNiceMock(), the default implementation with default values are available. File: MathApplicationTester.java import org.easymock.EasyMock; import org.easymock.EasyMockRunner; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(EasyMockRunner.class) public class MathApplicationTester { private MathApplication mathApplication; private CalculatorService calcService; @Before public void setUp(){ mathApplication = new MathApplication(); calcService = EasyMock.createNiceMock(CalculatorService.class); mathApplication.setCalculatorService(calcService); } @Test public void testCalcService(){ //add the behavior to add numbers EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0); //activate the mock EasyMock.replay(calcService); //test the add functionality Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0); //test the subtract functionality Assert.assertEquals(mathApplication.subtract(20.0, 10.0),0.0,0); //test the multiply functionality Assert.assertEquals(mathApplication.divide(20.0, 10.0),0.0,0); //test the divide functionality Assert.assertEquals(mathApplication.multiply(20.0, 10.0),0.0,0); //verify call to calcService is made or not EasyMock.verify(calcService); } } Step 4: Execute test cases Create a java class file named TestRunner inC:\> EasyMock_WORKSPACE to execute Test case(s). File: TestRunner.java import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.Failure; public class TestRunner { public static void main(String[] args) { Result result = JUnitCore.runClasses(MathApplicationTester.class); for (Failure failure : result.getFailures()) { System.out.println(failure.toString()); } System.out.println(result.wasSuccessful()); } } Step 5: Verify the Result Compile the classes using javac compiler as follows − C:\EasyMock_WORKSPACE>javac MathApplicationTester.java Now run the Test Runner to see the result − C:\EasyMock_WORKSPACE>java TestRunner Verify the output.
[ { "code": null, "e": 2359, "s": 2043, "text": "Mocking is a way to test the functionality of a class in isolation. Mocking does not require a database connection or properties file read or file server read to test a functionality. Mock objects do the mocking of the real service. A mock object return...
Bound, unbound, and static methods in Python
31 Dec, 2019 Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can be Bound, Unbound or Static method. The static methods are one of the types of Unbound method. These types are explained in detail below. If a function is an attribute of class and it is accessed via the instances, they are called bound methods. A bound method is one that has ‘self‘ as its first argument. Since these are dependent on the instance of classes, these are also known as instance methods. The methods inside the classes would take at least one argument. To make them zero-argument methods, ‘decorators‘ has to be used. Different instances of a class have different values associated with them. For example, if there is a class “Fruits”, and instances like apple, orange, mango are possible. Each instance may have different size, color, taste, and nutrients in it. Thus to alter any value for a specific instance, the method must have ‘self’ as an argument that allows it to alter only its property. Example: class sample(object): # Static variable for object number objectNo = 0 def __init__(self, name1): # variable to hold name self.name = name1 # Increment static variable for each object sample.objectNo = sample.objectNo + 1 # each object's unique number that can be # considered as ID self.objNumber = sample.objectNo def myFunc(self): print("My name is ", self.name, "from object ", self.objNumber) def alterIt(self, newName): self.name = newName def myFunc2(): print("I am not a bound method !!!") # creating first instance of class sample samp1 = sample("A")samp1.myFunc() # unhide the line below to see the error# samp1.myFunc2() #----------> error line # creating second instance of class sample samp2 = sample("B")samp2.myFunc()samp2.alterIt("C")samp2.myFunc()samp1.myFunc() Output: My name is A from object 1 My name is B from object 2 My name is C from object 2 My name is A from object 1 In the above example two instances namely samp1 and samp2 are created. Note that when the function alterIt() is applied to the second instance, only that particular instance’s value is changed. The line samp1.myFunc() will be expanded as sample.myFunc(samp1). For this method no explicit argument is required to be passed. The instance samp1 will be passed as argument to the myFunc(). The line samp1.myFunc2() will generate the error : Traceback (most recent call last): File "/home/4f130d34a1a72402e0d26bab554c2cf6.py", line 26, in samp1.myFunc2() #----------> error line TypeError: myFunc2() takes 0 positional arguments but 1 was given It means that this method is unbound. It does not accept any instance as an argument. These functions are unbound functions. Methods that do not have an instance of the class as the first argument are known as unbound methods. As of Python 3.0, the unbound methods have been removed from the language. They are not bounded with any specific object of the class. To make the method myFunc2() work in the above class it should be made into a static method Static methods are similar to class methods but are bound completely to class instead of particular objects. They are accessed using class names. Not all the methods need to alter the instances of a class. They might serve any common purpose. A method may be a utility function also. For example, When we need to use certain mathematical functions, we use the built in class Math. The methods in this class are made static because they have nothing to do with specific objects. They do common actions. Thus each time it is not an optimized way to write as: math=Math() math.ceil(5.23) So they can be simply accessed using their class name as Math.ceil(5.23). A method can be made static in two ways: Using staticmethod()Using decorator Using staticmethod() Using decorator Using staticmethod(): The staticmethod() function takes the function to be converted as its argument and returns the static version of that function. A static function knows nothing about the class, it just works with the parameters passed to it. Example: class sample(): def myFunc2(x): print("I am", x, "from the static method") sample.myFunc2 = staticmethod(sample.myFunc2)sample.myFunc2("A") Output: I am A from the static method Using decorators: These are features of Python used for modifying one part of the program using another part of the program at the time of compilation. The decorator that can be used to make a method static is @staticmethod This informs the built-in default metaclass not to create any bound methods for this method. Once this line is added before a function, the function can be called using the class name. Consider the example taken for the Bound method where we encountered an error. To overcome that, it can be written as: class sample(object): # Static variable for object number objectNo = 0 def __init__(self, name1): # variable to hold name self.name = name1 # Increment static variable for each object sample.objectNo = sample.objectNo + 1 # each object's unique number that can be # considered as ID self.objNumber = sample.objectNo def myFunc(self): print("My name is ", self.name, "from object ", self.objNumber) def alterIt(self, newName): self.name = newName # using decorator to make the method static @staticmethod def myFunc2(): print("I am not a bound method !!!") # creating first instance of class sample samp1 = sample("A")samp1.myFunc() sample.myFunc2() #----------> error line # creating second instance of class sample samp2 = sample("B")samp2.myFunc()samp2.alterIt("C")samp2.myFunc()samp1.myFunc() Output: My name is A from object 1 I am not a bound method !!! My name is B from object 2 My name is C from object 2 My name is A from object 1 Here, the line sample.myFunc2() runs without any error and the print() within it works perfectly and gives the output I am not a bound method!!! python-oop-concepts Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n31 Dec, 2019" }, { "code": null, "e": 364, "s": 52, "text": "Methods in Python are like functions except that it is attached to an object.The methods are called on objects and it possibly make changes to that object. These methods can ...
Minimum number of jumps | Practice | GeeksforGeeks
Given an array of N integers arr[] where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then you cannot move through that element. Note: Return -1 if you can't reach the end of the array. Example 1: Input: N = 11 arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} Output: 3 Explanation: First jump from 1st element to 2nd element with value 3. Now, from here we jump to 5th element with value 9, and from here we will jump to the last. Example 2: Input : N = 6 arr = {1, 4, 3, 2, 6, 7} Output: 2 Explanation: First we jump from the 1st to 2nd element and then jump to the last element. Your task: You don't need to read input or print anything. Your task is to complete function minJumps() which takes the array arr and it's size N as input parameters and returns the minimum number of jumps. If not possible return -1. Expected Time Complexity: O(N) Expected Space Complexity: O(1) Constraints: 1 ≤ N ≤ 107 0 ≤ arri ≤ 107 0 parkarshreyas7718 hours ago //Efficient JAVA Solution class Solution{ static int minJumps(int[] arr){ int i = 0; int n = arr.length; if((n==0) || (n==1)){ return 0; } int nextStep = 0; int step = 0; int jump = 0; while(i<n-1){ step = Math.max(step,i+arr[i]); if(i == nextStep){ nextStep = step; jump++; } if( nextStep >= arr.length-1 ) return jump; i++; } return -1; } } 0 dipanshusharma93131 day ago // java solution class Solution{ static int minJumps(int[] arr){ // your code here int ans = -1; if(arr.length == 1){ return 0; } if(arr[0] == 0){ return ans; } int maxrange = arr[0], step = 0, jumps = 0; for(int i=0;i<arr.length;i++){ step = Math.max(step,i+arr[i]); if(i == maxrange){ maxrange = step; jumps++; } if(maxrange >=arr.length-1){ return jumps+1; } } return ans; }} 0 badgujarsachin831 day ago int minJumps(int arr[], int n){ // code here if(n<=1){ return 0; }else if(arr[0]==0){ return -1; }else{ int jump=0,position=0,range=0; for(int i=0;i<n-1;i++){ range=max(range,i+arr[i]); if(i==position){ jump++; if(i>=range){ return -1; } position=range; } } return jump; } } 0 ashfaqhussainmd152 days ago C++ Easy and Simple Approach int minJumps(int arr[], int n){ // Your code here if(n<=1) { return 0; } if(arr[0]==0) return -1; int jump=0; int position=0; int maxReach=0; for(int i=0;i<n-1;i++) { maxReach=max(maxReach,i+arr[i]); if(i==position) { jump++; if(i>=maxReach) return -1; position=maxReach; } } return jump; } -2 ankitabxrt2 days ago What is compilation error 😐 0 vijethareddykasala3 days ago class Solution{ public: int minJumps(int arr[], int n){ int jump; if(n>1 && arr[0]!=0) jump=arr[0]; else if(n==1 && arr[0]==0) return 0; else return -1; int maxreach=arr[0]; int count=1; for(int i=1;i<n;i++){ jump--; maxreach=max(maxreach,arr[i]+i); if(i==n-1) return count; if(jump==0 && i<maxreach){ count++; jump=maxreach-i; } if(i>=maxreach) return -1; } }}; +1 vaibhavkhanna8bp3 days ago can anybody please tell where is this solution failing it is passing 138/141 cases dont know where it is failing class Solution{public: int minJumps(int a[], int n) { int count = 0, i = 0; while (i < n) { if (a[i] == 0) { if (i != n - 1) { return -1; } else { return count; } } if (i + a[i] >= n - 1) { count++; return count; } int current = i + 1; int iterator = 1; int nextMaxIndex = current; int nextMax = INT_MIN; while (iterator <= a[i]) { if (current + a[current] >= n - 1) { return count + 2; } else if (a[current] >= nextMax) { nextMaxIndex = current; nextMax = a[current]; } current++; iterator++; } count++; i = nextMaxIndex; // cout << "Taken " << count << " steps and reached at index : " << nextMaxIndex << endl; } }}; +1 amobala984 days ago JAVA GREEDY SOLUTION : class Solution{ static int minJumps(int[] arr){ int ans= -1; if( arr.length == 0 ) return ans; if( arr.length==1 ) return 0; int maxReach = arr[0], jump = 0 , val = 0; for( int i = 0 ; i < arr.length ; i++){ val = Math.max( val, i+arr[i]); if( i == maxReach) { maxReach = val; jump++; } if( maxReach >= arr.length-1 ) return jump+1; } return ans; } } +2 rathodumang3196 days ago Java Solution: class Solution{ static int minJumps(int[] arr){ int maxR = arr[0]; int step = arr[0]; int jump=1; int n = arr.length; // Base case if(arr.length==1 && arr[0]==0){ return 0; } else if(arr[0]==0){ return -1; } else if(arr.length==1){ return 0; } // ************************************ // for(int i=1; i<n; i++){ if(i==n-1){ return jump; } maxR = Math.max(maxR, i+arr[i]); step--; if(step==0){ jump++; if(i>=maxR){ return -1; } step = maxR - i; } } return jump; } } +1 chetandas20011 week ago Can someone please explain what's wrong in this code... I am getting segmentation fault int help(int i,int n,int a[],vector<int> &dp) { if(i>=n-1) return 0; if(a[i]==0) return 1e8; if(dp[i]!=-1) return dp[i]; else { int minjmps=1e8; for(int k=1;k<=a[i];k++) { int temp=1+help(i+k,n,a,dp); minjmps=min(minjmps,temp); } return dp[i]=minjmps; } } int minJumps(int a[], int n){ // Your code here if(n==1) return 0; else if(a[0]==0) return -1; vector<int> dp(n,-1); int ans=help(0,n,a,dp); if(ans>=1e8) return -1; return ans; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 590, "s": 238, "text": "Given an array of N integers arr[] where each element represents the max number of steps that can be made forward from that element. Find the minimum number of jumps to reach the end of the array (starting from the first element). If an element is 0, then...
Recursive solution to count substrings with same first and last characters
23 Jun, 2022 We are given a string S, we need to find count of all contiguous substrings starting and ending with same character. Examples : Input : S = "abcab" Output : 7 There are 15 substrings of "abcab" a, ab, abc, abca, abcab, b, bc, bca bcab, c, ca, cab, a, ab, b Out of the above substrings, there are 7 substrings : a, abca, b, bcab, c, a and b. Input : S = "aba" Output : 4 The substrings are a, b, a and aba We have discussed different solutions in below post.Count substrings with same first and last charactersIn this article, a simple recursive solution is discussed. C++ Java Python3 C# PHP Javascript // c++ program to count substrings with same// first and last characters#include <iostream>#include <string>using namespace std; /* Function to count substrings with same first and last characters*/int countSubstrs(string str, int i, int j, int n){ // base cases if (n == 1) return 1; if (n <= 0) return 0; int res = countSubstrs(str, i + 1, j, n - 1) + countSubstrs(str, i, j - 1, n - 1) - countSubstrs(str, i + 1, j - 1, n - 2); if (str[i] == str[j]) res++; return res;} // driver codeint main(){ string str = "abcab"; int n = str.length(); cout << countSubstrs(str, 0, n - 1, n);} // Java program to count substrings// with same first and last characters class GFG{ // Function to count substrings // with same first and // last characters static int countSubstrs(String str, int i, int j, int n) { // base cases if (n == 1) return 1; if (n <= 0) return 0; int res = countSubstrs(str, i + 1, j, n - 1) + countSubstrs(str, i, j - 1, n - 1) - countSubstrs(str, i + 1, j - 1, n - 2); if (str.charAt(i) == str.charAt(j)) res++; return res; } // Driver code public static void main (String[] args) { String str = "abcab"; int n = str.length(); System.out.print(countSubstrs(str, 0, n - 1, n)); }} // This code is contributed by Anant Agarwal. # Python 3 program to count substrings with same# first and last characters # Function to count substrings with same first and# last charactersdef countSubstrs(str, i, j, n): # base cases if (n == 1): return 1 if (n <= 0): return 0 res = (countSubstrs(str, i + 1, j, n - 1) + countSubstrs(str, i, j - 1, n - 1) - countSubstrs(str, i + 1, j - 1, n - 2)) if (str[i] == str[j]): res += 1 return res # driver codestr = "abcab"n = len(str)print(countSubstrs(str, 0, n - 1, n)) # This code is contributed by Smitha // C# program to count substrings// with same first and last charactersusing System; class GFG { // Function to count substrings // with same first and // last characters static int countSubstrs(string str, int i, int j, int n) { // base cases if (n == 1) return 1; if (n <= 0) return 0; int res = countSubstrs(str, i + 1, j, n - 1) + countSubstrs(str, i, j - 1, n - 1) - countSubstrs(str, i + 1, j - 1, n - 2); if (str[i] == str[j]) res++; return res; } // Driver code public static void Main () { string str = "abcab"; int n = str.Length; Console.WriteLine( countSubstrs(str, 0, n - 1, n)); }} // This code is contributed by vt_m. <?php// PHP program to count// substrings with same// first and last characters //Function to count substrings// with same first and// last charactersfunction countSubstrs($str, $i, $j, $n){ // base cases if ($n == 1) return 1; if ($n <= 0) return 0; $res = countSubstrs($str, $i + 1, $j, $n - 1) + countSubstrs($str, $i, $j - 1, $n - 1) - countSubstrs($str, $i + 1, $j - 1, $n - 2); if ($str[$i] == $str[$j]) $res++; return $res;} // Driver Code$str = "abcab";$n = strlen($str);echo(countSubstrs($str, 0, $n - 1, $n)); // This code is contributed by Ajit.?> <script> // Javascript program to count substrings// with same first and last characters // Function to count substrings// with same first and// last charactersfunction countSubstrs(str, i, j, n){ // Base cases if (n == 1) return 1; if (n <= 0) return 0; let res = countSubstrs(str, i + 1, j, n - 1) + countSubstrs(str, i, j - 1, n - 1) - countSubstrs(str, i + 1, j - 1, n - 2); if (str[i] == str[j]) res++; return res;} // Driver codelet str = "abcab";let n = str.length; document.write(countSubstrs(str, 0, n - 1, n)); // This code is contributed by rameshtravel07 </script> 7 The time complexity of above solution is exponential. In Worst case, we may end up doing O(3n) operations. Auxiliary Space: O(n), where n is the length of string. This is because when string is passed in the function it creates a copy of itself in stack. There is also a divide and conquer recursive approach The idea is to split the string in half until we get one element and have our base case return 2 things 1 – a map containing the character to the number of occurrences (i.e a:1 since its the base case) 2 – 1 (This is the total number of substring with start and end with the same char. Since the base case is a string of size one, it starts and ends with the same character) Then combine the solutions of the left and right division of the string, then return a new solution based on left and right. This new solution can be constructed by multiplying the common characters between the left and right set and adding to the solution count from left and right, and returning a map containing element occurrence count and solution count Python3 # codedef countSubstr(s): if len(s) == 0: return 0 charMap, numSubstr = countSubstrHelper(s, 0, len(s)-1) return numSubstr def countSubstrHelper(string, start, end): if start >= end: # our base case for the recursion. When we have one character return {string[start]: 1}, 1 mid = (start + end)//2 mapLeft, numSubstrLeft = countSubstrHelper( string, start, mid) # solve the left half mapRight, numSubstrRight = countSubstrHelper( string, mid+1, end) # solve the right half # add number of substrings from left and right numSubstrSelf = numSubstrLeft + numSubstrRight # multiply the characters from left set with matching characters from right set # then add to total number of substrings for char in mapLeft: if char in mapRight: numSubstrSelf += mapLeft[char] * mapRight[char] # Add all the key,value pairs from right map to left map for char in mapRight: if char in mapLeft: mapLeft[char] += mapRight[char] else: mapLeft[char] = mapRight[char] # Return the map of character and the sum of substring from left, right and self return mapLeft, numSubstrSelf print(countSubstr("abcab")) # Contributed by Xavier Jean Baptiste 7 The time complexity of the above solution is O(nlogn) with space complexity O(n) which occurs if all elements are distinct This article is contributed by Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m jit_t Smitha Dinesh Semwal rameshtravel07 anikaseth98 xapatjb4 anandkumarshivam2266 Recursion Strings Strings Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Backtracking | Introduction Print all subsequences of a string Recursive Practice Problems with Solutions Print all possible combinations of r elements in a given array of size n Reverse a stack using recursion Write a program to reverse an array or string Reverse a string in Java C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack Different Methods to Reverse a String in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 169, "s": 52, "text": "We are given a string S, we need to find count of all contiguous substrings starting and ending with same character." }, { "code": null, "e": 181, "s": 169, ...
Building Heap from Array
06 Jul, 2022 Given an array of N elements. The task is to build a Binary Heap from the given array. The heap can be either Max Heap or Min Heap.Example: Input: arr[] = {4, 10, 3, 5, 1} Output: Corresponding Max-Heap: 10 / \ 5 3 / \ 4 1 Input: arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17} Output: Corresponding Max-Heap: 17 / \ 15 13 / \ / \ 9 6 5 10 / \ / \ 4 8 3 1 Suppose the given input elements are: 4, 10, 3, 5, 1.The corresponding complete binary tree for this array of elements [4, 10, 3, 5, 1] will be: 4 / \ 10 3 / \ 5 1 Note: Root is at index 0 in array. Left child of i-th node is at (2*i + 1)th index. Right child of i-th node is at (2*i + 2)th index. Parent of i-th node is at (i-1)/2 index. Simple Approach: Suppose, we need to build a Max-Heap from the above-given array elements. It can be clearly seen that the above complete binary tree formed does not follow the Heap property. So, the idea is to heapify the complete binary tree formed from the array in reverse level order following a top-down approach.That is first heapify, the last node in level order traversal of the tree, then heapify the second last node and so on. Time Complexity: Heapify a single node takes O(log N) time complexity where N is the total number of Nodes. Therefore, building the entire Heap will take N heapify operations and the total time complexity will be O(N*logN).In reality, building a heap takes O(n) time depending on the implementation which can be seen here.Optimized Approach: The above approach can be optimized by observing the fact that the leaf nodes need not to be heapified as they already follow the heap property. Also, the array representation of the complete binary tree contains the level order traversal of the tree.So the idea is to find the position of the last non-leaf node and perform the heapify operation of each non-leaf node in reverse level order. Last non-leaf node = parent of last-node. or, Last non-leaf node = parent of node at (n-1)th index. or, Last non-leaf node = Node at index ((n-1) - 1)/2. = (n/2) - 1. Illustration: Array = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17} Corresponding Complete Binary Tree is: 1 / \ 3 5 / \ / \ 4 6 13 10 / \ / \ 9 8 15 17 The task to build a Max-Heap from above array. Total Nodes = 11. Last Non-leaf node index = (11/2) - 1 = 4. Therefore, last non-leaf node = 6. To build the heap, heapify only the nodes: [1, 3, 5, 4, 6] in reverse order. Heapify 6: Swap 6 and 17. 1 / \ 3 5 / \ / \ 4 17 13 10 / \ / \ 9 8 15 6 Heapify 4: Swap 4 and 9. 1 / \ 3 5 / \ / \ 9 17 13 10 / \ / \ 4 8 15 6 Heapify 5: Swap 13 and 5. 1 / \ 3 13 / \ / \ 9 17 5 10 / \ / \ 4 8 15 6 Heapify 3: First Swap 3 and 17, again swap 3 and 15. 1 / \ 17 13 / \ / \ 9 15 5 10 / \ / \ 4 8 3 6 Heapify 1: First Swap 1 and 17, again swap 1 and 15, finally swap 1 and 6. 17 / \ 15 13 / \ / \ 9 6 5 10 / \ / \ 4 8 3 1 Implementation: C++ Java Python3 C# // C++ program for building Heap from Array #include <iostream> using namespace std; // To heapify a subtree rooted with node i which is// an index in arr[]. N is size of heapvoid heapify(int arr[], int n, int i){ int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { swap(arr[i], arr[largest]); // Recursively heapify the affected sub-tree heapify(arr, n, largest); }} // Function to build a Max-Heap from the given arrayvoid buildHeap(int arr[], int n){ // Index of last non-leaf node int startIdx = (n / 2) - 1; // Perform reverse level order traversal // from last non-leaf node and heapify // each node for (int i = startIdx; i >= 0; i--) { heapify(arr, n, i); }} // A utility function to print the array// representation of Heapvoid printHeap(int arr[], int n){ cout << "Array representation of Heap is:\n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << "\n";} // Driver Codeint main(){ // Binary Tree Representation // of input array // 1 // / \ // 3 5 // / \ / \ // 4 6 13 10 // / \ / \ // 9 8 15 17 int arr[] = { 1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17 }; int n = sizeof(arr) / sizeof(arr[0]); buildHeap(arr, n); printHeap(arr, n); // Final Heap: // 17 // / \ // 15 13 // / \ / \ // 9 6 5 10 // / \ / \ // 4 8 3 1 return 0;} // Java program for building Heap from Array public class BuildHeap { // To heapify a subtree rooted with node i which is // an index in arr[].Nn is size of heap static void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Function to build a Max-Heap from the Array static void buildHeap(int arr[], int n) { // Index of last non-leaf node int startIdx = (n / 2) - 1; // Perform reverse level order traversal // from last non-leaf node and heapify // each node for (int i = startIdx; i >= 0; i--) { heapify(arr, n, i); } } // A utility function to print the array // representation of Heap static void printHeap(int arr[], int n) { System.out.println( "Array representation of Heap is:"); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver Code public static void main(String args[]) { // Binary Tree Representation // of input array // 1 // / \ // 3 5 // / \ / \ // 4 6 13 10 // / \ / \ // 9 8 15 17 int arr[] = { 1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17 }; int n = arr.length; buildHeap(arr, n); printHeap(arr, n); }} # Python3 program for building Heap from Array # To heapify a subtree rooted with node i# which is an index in arr[]. N is size of heap def heapify(arr, n, i): largest = i # Initialize largest as root l = 2 * i + 1 # left = 2*i + 1 r = 2 * i + 2 # right = 2*i + 2 # If left child is larger than root if l < n and arr[l] > arr[largest]: largest = l # If right child is larger than largest so far if r < n and arr[r] > arr[largest]: largest = r # If largest is not root if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # Recursively heapify the affected sub-tree heapify(arr, n, largest) # Function to build a Max-Heap from the given array def buildHeap(arr, n): # Index of last non-leaf node startIdx = n // 2 - 1 # Perform reverse level order traversal # from last non-leaf node and heapify # each node for i in range(startIdx, -1, -1): heapify(arr, n, i) # A utility function to print the array# representation of Heap def printHeap(arr, n): print("Array representation of Heap is:") for i in range(n): print(arr[i], end=" ") print() # Driver Codeif __name__ == '__main__': # Binary Tree Representation # of input array # 1 # / \ # 3 5 # / \ / \ # 4 6 13 10 # / \ / \ # 9 8 15 17 arr = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17] n = len(arr) buildHeap(arr, n) printHeap(arr, n) # Final Heap: # 17 # / \ # 15 13 # / \ / \ # 9 6 5 10 # / \ / \ # 4 8 3 1 # This code is contributed by Princi Singh // C# program for building Heap from Arrayusing System; public class BuildHeap { // To heapify a subtree rooted with node i which is // an index in arr[].Nn is size of heap static void heapify(int[] arr, int n, int i) { int largest = i; // Initialize largest as root int l = 2 * i + 1; // left = 2*i + 1 int r = 2 * i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } // Function to build a Max-Heap from the Array static void buildHeap(int[] arr, int n) { // Index of last non-leaf node int startIdx = (n / 2) - 1; // Perform reverse level order traversal // from last non-leaf node and heapify // each node for (int i = startIdx; i >= 0; i--) { heapify(arr, n, i); } } // A utility function to print the array // representation of Heap static void printHeap(int[] arr, int n) { Console.WriteLine( "Array representation of Heap is:"); for (int i = 0; i < n; ++i) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver Code public static void Main() { // Binary Tree Representation // of input array // 1 // / \ // 3 5 // / \ / \ // 4 6 13 10 // / \ / \ // 9 8 15 17 int[] arr = { 1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17 }; int n = arr.Length; buildHeap(arr, n); printHeap(arr, n); }} // This code is contributed by Ryuga Array representation of Heap is: 17 15 13 9 6 5 10 4 8 3 1 ankthon SonalSharma3 princi singh mohityadav7 nidhi_biet unknown163 srm_ parascoding Arrays Heap Arrays Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Introduction to Data Structures Huffman Coding | Greedy Algo-3 Sliding Window Maximum (Maximum of all subarrays of size k) k largest(or smallest) elements in an array
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 196, "s": 54, "text": "Given an array of N elements. The task is to build a Binary Heap from the given array. The heap can be either Max Heap or Min Heap.Example: " }, { "code": null, ...
How to include an external JavaScript library to ReactJS ?
24 Aug, 2021 A JavaScript Library is a pre-written JavaScript file with some extremely useful code-snippets, objects, and functions so that we can reuse the functions, objects, and code-snippets to perform a common task. ReactJS itself is an example of a JavaScript library. But the file structure and coding syntax are a little bit different in ReactJS than in normal vanilla JavaScript. So in this article, we are going to learn how to add an external JavaScript library to a ReactJS Project. We are going to create a react application and include an external JavaScript library to ReactJS in three approaches. These are: Using react-script-tag Package.Using react-helmet Package.Using JavaScript DOM Methods. Using react-script-tag Package. Using react-helmet Package. Using JavaScript DOM Methods. Creating React Application: Step 1: Create a React application using the following command inside your terminal or command prompt:npx create-react-app name_of_the_app Step 1: Create a React application using the following command inside your terminal or command prompt: npx create-react-app name_of_the_app Step 2: After creating the react application move to the directory as per your app name using the following command:cd name_of_the_app Step 2: After creating the react application move to the directory as per your app name using the following command: cd name_of_the_app Project Structure: Our project structure will look like this. Now modify the default App.js file inside your source code directory according to any of the following approaches. Approach 1: Using react-script-tag Package This is the first method and the method with the least complexity as well. The react-script-tag is a package that comes up with a <script> tag that supports universal rendering. With the help of this library, we can directly append the <script> tag to our document. And inside the ‘src’ attribute of the script tag, we can include the URL of the external JavaScript library. Installation: Open a terminal inside your ReactJS project folder and write the following code to install react-script-tag Package. npm install --save react-script-tag Import ‘ScriptTag’ component: Import the built-in ‘ScriptTag’ component from the react-script-tag library at the top of the file where we want to add the script tag. import ScriptTag from 'react-script-tag'; Call the <ScriptTag> component inside our App.js Now call the <ScriptTag> component inside our App component. This is a self-closing JSX component. Now parse the URL of our desired library with the help of ‘src’ attribute. The hydrating attribute takes a boolean input. Make it true if the client is hydrating the server render. The default value is false. App.js import React from 'react';import './App.css';import ScriptTag from 'react-script-tag'; function App() { return ( <div className='App'> <h1>Geeksforgeeks : How to include an external JavaScript library to ReactJS?</h1> <ScriptTag isHydrating={true} type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" /> </div> );} export default App; Run the Application: Open the terminal and write the following command in your terminal. npm start Output: Inspect the output to check that our library is properly added or not. Approach 2: Using react-helmet Package The react-helmet is also a well-known npm package mostly used for adding an element at the head of a react document. We can add a script tag inside the head of the document using this package. Parsing the CDN of the library as a source of the script tag will eventually add this script to our document. Installation: Open the terminal inside your ReactJS project folder and write the following code to install react-helmet Package. npm install --save react-helmet Import ‘Helmet’ component: Import the ‘Helmet’ component from react-helmet package at the top of the source code file. import {Helmet} from "react-helmet"; Call the <Helmet> component inside our App.js file: Helmet is a non-self closing component. It is basically used to add HTML code inside the <head> of the document. It takes the HTML tags which are desired to remain inside <head> and outputs them. The Helmet package supports both server-side and client-side rendering. Call this component inside our JSX component named ‘App’ and create a basic HTML <script> tag inside it. Into the <script> tag add the URL of the jQuery library with the ‘src’ attribute. App.js import React from 'react';import './App.css';import {Helmet} from "react-helmet"; function App() { return ( <div className='App'> <h1>Geeksforgeeks : How to include an external JavaScript library to ReactJS?</h1> <Helmet> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript" /> </Helmet> </div> );} export default App; Run the application: Open the terminal and write the following command in your terminal. npm start Output: Inspect the output to check that our library is properly added or not. Approach 3: Using JavaScript DOM Methods Installing that many packages can make our application heavy and slow as well. So using JavaScript DOM methods is best. We have no need to install any external packages in this method. The steps of this method are: Create the function: Create a function that takes the URL of the desired library as a parameter. Using the document.createElement method creates an empty script tag. Set its ‘src‘ attribute as the parsed URL of our library. Set ‘async‘ as true, so that allows the program to be executed immediately where the synchronous code will block further execution of the remaining code until it finishes the current one. Append the created script tag using document.body.appendChild method. Export the function and call it whenever we want to add a custom library in our JSX code. Call the function: Call the function inside the App component enclosing it inside curly brackets. Pass the URL of our desired library as a string. App.js import React from 'react';import './App.css'; // Create the functionexport function AddLibrary(urlOfTheLibrary) { const script = document.createElement('script'); script.src = urlOfTheLibrary; script.async = true; document.body.appendChild(script);} function App() { return ( <div className="App"> <h1>Geeksforgeeks : How to include an external JavaScript library to ReactJS?</h1> {/* Call the function to add a library */} {AddLibrary( 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js')} </div> );} export default App; Run the Application: Open the terminal and write the following command in your terminal. npm start Output: Inspect the output to check that our library is properly added or not. Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to install bootstrap in React.js ? How to create a multi-page website using React.js ? How to do crud operations in ReactJS ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Aug, 2021" }, { "code": null, "e": 510, "s": 28, "text": "A JavaScript Library is a pre-written JavaScript file with some extremely useful code-snippets, objects, and functions so that we can reuse the functions, objects, and code-sn...
Python – Pandas dataframe.append()
08 Jul, 2022 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.append() function is used to append rows of other dataframe to the end of the given dataframe, returning a new dataframe object. Columns not in the original dataframes are added as new columns and the new cells are populated with NaN value. Syntax: DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None) Parameters :other : DataFrame or Series/dict-like object, or list of theseignore_index : If True, do not use the index labels.verify_integrity : If True, raise ValueError on creating index with duplicates.sort : Sort columns if the columns of self and other are not aligned. The default sorting is deprecated and will change to not-sorting in a future version of pandas. Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort. Returns: appended : DataFrame Example #1: Create two data frames and append the second to the first one. # Importing pandas as pdimport pandas as pd # Creating the first Dataframe using dictionarydf1 = df = pd.DataFrame({"a":[1, 2, 3, 4], "b":[5, 6, 7, 8]}) # Creating the Second Dataframe using dictionarydf2 = pd.DataFrame({"a":[1, 2, 3], "b":[5, 6, 7]}) # Print df1print(df1, "\n") # Print df2df2 Now append df2 at the end of df1. # to append df2 at the end of df1 dataframedf1.append(df2) Output :Notice the index value of second data frame is maintained in the appended data frame. If we do not want it to happen then we can set ignore_index=True. # A continuous index value will be maintained# across the rows in the new appended data frame.df1.append(df2, ignore_index = True) Output : Example #2: Append dataframe of different shape. For unequal no. of columns in the data frame, non-existent value in one of the dataframe will be filled with NaN values. # Importing pandas as pdimport pandas as pd # Creating the first Dataframe using dictionarydf1 = pd.DataFrame({"a":[1, 2, 3, 4], "b":[5, 6, 7, 8]}) # Creating the Second Dataframe using dictionarydf2 = pd.DataFrame({"a":[1, 2, 3], "b":[5, 6, 7], "c":[1, 5, 4]}) # for appending df2 at the end of df1df1.append(df2, ignore_index = True) Output : Notice, the new cells are populated with NaN values. Kaustav kumar Chanda Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON Create a Pandas DataFrame from Lists
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jul, 2022" }, { "code": null, "e": 266, "s": 52, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes im...
String class in Java | Set 1
24 Nov, 2020 String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. Creating a String There are two ways to create string in Java: String literalString s = “GeeksforGeeks”; String s = “GeeksforGeeks”; Using new keywordString s = new String (“GeeksforGeeks”); String s = new String (“GeeksforGeeks”); Constructors String(byte[] byte_arr) – Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding.Example:byte[] b_arr = {71, 101, 101, 107, 115}; String s_byte =new String(b_arr); //Geeks String(byte[] byte_arr, Charset char_set) – Construct a new String by decoding the byte array. It uses the char_set for decoding.Example:byte[] b_arr = {71, 101, 101, 107, 115}; Charset cs = Charset.defaultCharset(); String s_byte_char = new String(b_arr, cs); //Geeks String(byte[] byte_arr, String char_set_name) – Construct a new String by decoding the byte array. It uses the char_set_name for decoding.It looks similar to the above constructs and they appear before similar functions but it takes the String(which contains char_set_name) as parameter while the above constructor takes CharSet.Example:byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, "US-ASCII"); //Geeks String(byte[] byte_arr, int start_index, int length) – Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Example:byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 1, 3); // eek String(byte[] byte_arr, int start_index, int length, Charset char_set) – Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Uses char_set for decoding.Example:byte[] b_arr = {71, 101, 101, 107, 115}; Charset cs = Charset.defaultCharset(); String s = new String(b_arr, 1, 3, cs); // eek String(byte[] byte_arr, int start_index, int length, String char_set_name) – Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Uses char_set_name for decoding.Example:byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks String(char[] char_arr) – Allocates a new String from the given Character arrayExample:char char_arr[] = {'G', 'e', 'e', 'k', 's'}; String s = new String(char_arr); //Geeks String(char[] char_array, int start_index, int count) – Allocates a String from a given character array but choose count characters from the start_index.Example:char char_arr[] = {'G', 'e', 'e', 'k', 's'}; String s = new String(char_arr , 1, 3); //eek String(int[] uni_code_points, int offset, int count) – Allocates a String from a uni_code_array but choose count characters from the start_index.Example:int[] uni_code = {71, 101, 101, 107, 115}; String s = new String(uni_code, 1, 3); //eek String(StringBuffer s_buffer) – Allocates a new string from the string in s_bufferExample:StringBuffer s_buffer = new StringBuffer("Geeks"); String s = new String(s_buffer); //Geeks String(StringBuilder s_builder) – Allocates a new string from the string in s_builderExample:StringBuilder s_builder = new StringBuilder("Geeks"); String s = new String(s_builder); //Geeks String(byte[] byte_arr) – Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding.Example:byte[] b_arr = {71, 101, 101, 107, 115}; String s_byte =new String(b_arr); //Geeks byte[] b_arr = {71, 101, 101, 107, 115}; String s_byte =new String(b_arr); //Geeks String(byte[] byte_arr, Charset char_set) – Construct a new String by decoding the byte array. It uses the char_set for decoding.Example:byte[] b_arr = {71, 101, 101, 107, 115}; Charset cs = Charset.defaultCharset(); String s_byte_char = new String(b_arr, cs); //Geeks byte[] b_arr = {71, 101, 101, 107, 115}; Charset cs = Charset.defaultCharset(); String s_byte_char = new String(b_arr, cs); //Geeks String(byte[] byte_arr, String char_set_name) – Construct a new String by decoding the byte array. It uses the char_set_name for decoding.It looks similar to the above constructs and they appear before similar functions but it takes the String(which contains char_set_name) as parameter while the above constructor takes CharSet.Example:byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, "US-ASCII"); //Geeks byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, "US-ASCII"); //Geeks String(byte[] byte_arr, int start_index, int length) – Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Example:byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 1, 3); // eek byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 1, 3); // eek String(byte[] byte_arr, int start_index, int length, Charset char_set) – Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Uses char_set for decoding.Example:byte[] b_arr = {71, 101, 101, 107, 115}; Charset cs = Charset.defaultCharset(); String s = new String(b_arr, 1, 3, cs); // eek byte[] b_arr = {71, 101, 101, 107, 115}; Charset cs = Charset.defaultCharset(); String s = new String(b_arr, 1, 3, cs); // eek String(byte[] byte_arr, int start_index, int length, String char_set_name) – Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Uses char_set_name for decoding.Example:byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks byte[] b_arr = {71, 101, 101, 107, 115}; String s = new String(b_arr, 1, 4, "US-ASCII"); // eeks String(char[] char_arr) – Allocates a new String from the given Character arrayExample:char char_arr[] = {'G', 'e', 'e', 'k', 's'}; String s = new String(char_arr); //Geeks char char_arr[] = {'G', 'e', 'e', 'k', 's'}; String s = new String(char_arr); //Geeks String(char[] char_array, int start_index, int count) – Allocates a String from a given character array but choose count characters from the start_index.Example:char char_arr[] = {'G', 'e', 'e', 'k', 's'}; String s = new String(char_arr , 1, 3); //eek char char_arr[] = {'G', 'e', 'e', 'k', 's'}; String s = new String(char_arr , 1, 3); //eek String(int[] uni_code_points, int offset, int count) – Allocates a String from a uni_code_array but choose count characters from the start_index.Example:int[] uni_code = {71, 101, 101, 107, 115}; String s = new String(uni_code, 1, 3); //eek int[] uni_code = {71, 101, 101, 107, 115}; String s = new String(uni_code, 1, 3); //eek String(StringBuffer s_buffer) – Allocates a new string from the string in s_bufferExample:StringBuffer s_buffer = new StringBuffer("Geeks"); String s = new String(s_buffer); //Geeks StringBuffer s_buffer = new StringBuffer("Geeks"); String s = new String(s_buffer); //Geeks String(StringBuilder s_builder) – Allocates a new string from the string in s_builderExample:StringBuilder s_builder = new StringBuilder("Geeks"); String s = new String(s_builder); //Geeks StringBuilder s_builder = new StringBuilder("Geeks"); String s = new String(s_builder); //Geeks String Methods int length(): Returns the number of characters in the String."GeeksforGeeks".length(); // returns 13Char charAt(int i): Returns the character at ith index."GeeksforGeeks".charAt(3); // returns ‘k’String substring (int i): Return the substring from the ith index character to end."GeeksforGeeks".substring(3); // returns “ksforGeeks”String substring (int i, int j): Returns the substring from i to j-1 index. "GeeksforGeeks".substring(2, 5); // returns “eks”String concat( String str): Concatenates specified string to the end of this string. String s1 = ”Geeks”; String s2 = ”forGeeks”; String output = s1.concat(s2); // returns “GeeksforGeeks” int indexOf (String s): Returns the index within the string of the first occurrence of the specified string. String s = ”Learn Share Learn”; int output = s.indexOf(“Share”); // returns 6 int indexOf (String s, int i): Returns the index within the string of the first occurrence of the specified string, starting at the specified index. String s = ”Learn Share Learn”; int output = s.indexOf("ea",3);// returns 13 Int lastIndexOf( String s): Returns the index within the string of the last occurrence of the specified string. String s = ”Learn Share Learn”; int output = s.lastIndexOf("a"); // returns 14 boolean equals( Object otherObj): Compares this string to the specified object. Boolean out = “Geeks”.equals(“Geeks”); // returns true Boolean out = “Geeks”.equals(“geeks”); // returns false boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring case considerations. Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true int compareTo( String anotherString): Compares two string lexicographically. int out = s1.compareTo(s2); // where s1 ans s2 are // strings to be compared This returns difference s1-s2. If : out < 0 // s1 comes before s2 out = 0 // s1 and s2 are equal. out > 0 // s1 comes after s2. int compareToIgnoreCase( String anotherString): Compares two string lexicographically, ignoring case considerations. int out = s1.compareToIgnoreCase(s2); // where s1 ans s2 are // strings to be compared This returns difference s1-s2. If : out < 0 // s1 comes before s2 out = 0 // s1 and s2 are equal. out > 0 // s1 comes after s2. Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).String toLowerCase(): Converts all the characters in the String to lower case.String word1 = “HeLLo”; String word3 = word1.toLowerCase(); // returns “hello" String toUpperCase(): Converts all the characters in the String to upper case.String word1 = “HeLLo”; String word2 = word1.toUpperCase(); // returns “HELLO” String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.String word1 = “ Learn Share Learn “; String word2 = word1.trim(); // returns “Learn Share Learn” String replace (char oldChar, char newChar): Returns new string by replacing all occurrences of oldChar with newChar.String s1 = “feeksforfeeks“; String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks” Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeksProgram to illustrate all string methods:// Java code to illustrate different constructors and methods // String class. import java.io.*;import java.util.*;class Test{ public static void main (String[] args) { String s= "GeeksforGeeks"; // or String s= new String ("GeeksforGeeks"); // Returns the number of characters in the String. System.out.println("String length = " + s.length()); // Returns the character at ith index. System.out.println("Character at 3rd position = " + s.charAt(3)); // Return the substring from the ith index character // to end of string System.out.println("Substring " + s.substring(3)); // Returns the substring from i to j-1 index. System.out.println("Substring = " + s.substring(2,5)); // Concatenates string2 to the end of string1. String s1 = "Geeks"; String s2 = "forGeeks"; System.out.println("Concatenated string = " + s1.concat(s2)); // Returns the index within the string // of the first occurrence of the specified string. String s4 = "Learn Share Learn"; System.out.println("Index of Share " + s4.indexOf("Share")); // Returns the index within the string of the // first occurrence of the specified string, // starting at the specified index. System.out.println("Index of a = " + s4.indexOf('a',3)); // Checking equality of Strings Boolean out = "Geeks".equals("geeks"); System.out.println("Checking Equality " + out); out = "Geeks".equals("Geeks"); System.out.println("Checking Equality " + out); out = "Geeks".equalsIgnoreCase("gEeks "); System.out.println("Checking Equality " + out); //If ASCII difference is zero then the two strings are similar int out1 = s1.compareTo(s2); System.out.println("the difference between ASCII value is="+out1); // Converting cases String word1 = "GeeKyMe"; System.out.println("Changing to lower Case " + word1.toLowerCase()); // Converting cases String word2 = "GeekyME"; System.out.println("Changing to UPPER Case " + word2.toUpperCase()); // Trimming the word String word4 = " Learn Share Learn "; System.out.println("Trim the word " + word4.trim()); // Replacing characters String str1 = "feeksforfeeks"; System.out.println("Original String " + str1); String str2 = "feeksforfeeks".replace('f' ,'g') ; System.out.println("Replaced f with g -> " + str2); } }Output :String length = 13 Character at 3rd position = k Substring ksforGeeks Substring = eks Concatenated string = GeeksforGeeks Index of Share 6 Index of a = 8 Checking Equality false Checking Equality true Checking Equality false the difference between ASCII value is=-31 Changing to lower Case geekyme Changing to UPPER Case GEEKYME Trim the word Learn Share Learn Original String feeksforfeeks Replaced f with g -> geeksgorgeeks For Set – 2 you can refer: Java.lang.String class in Java | Set 2 This article is contributed by Rahul Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed aboveMy Personal Notes arrow_drop_upSave int length(): Returns the number of characters in the String."GeeksforGeeks".length(); // returns 13 "GeeksforGeeks".length(); // returns 13 Char charAt(int i): Returns the character at ith index."GeeksforGeeks".charAt(3); // returns ‘k’ "GeeksforGeeks".charAt(3); // returns ‘k’ String substring (int i): Return the substring from the ith index character to end."GeeksforGeeks".substring(3); // returns “ksforGeeks” "GeeksforGeeks".substring(3); // returns “ksforGeeks” String substring (int i, int j): Returns the substring from i to j-1 index. "GeeksforGeeks".substring(2, 5); // returns “eks” "GeeksforGeeks".substring(2, 5); // returns “eks” String concat( String str): Concatenates specified string to the end of this string. String s1 = ”Geeks”; String s2 = ”forGeeks”; String output = s1.concat(s2); // returns “GeeksforGeeks” String s1 = ”Geeks”; String s2 = ”forGeeks”; String output = s1.concat(s2); // returns “GeeksforGeeks” int indexOf (String s): Returns the index within the string of the first occurrence of the specified string. String s = ”Learn Share Learn”; int output = s.indexOf(“Share”); // returns 6 String s = ”Learn Share Learn”; int output = s.indexOf(“Share”); // returns 6 int indexOf (String s, int i): Returns the index within the string of the first occurrence of the specified string, starting at the specified index. String s = ”Learn Share Learn”; int output = s.indexOf("ea",3);// returns 13 String s = ”Learn Share Learn”; int output = s.indexOf("ea",3);// returns 13 Int lastIndexOf( String s): Returns the index within the string of the last occurrence of the specified string. String s = ”Learn Share Learn”; int output = s.lastIndexOf("a"); // returns 14 String s = ”Learn Share Learn”; int output = s.lastIndexOf("a"); // returns 14 boolean equals( Object otherObj): Compares this string to the specified object. Boolean out = “Geeks”.equals(“Geeks”); // returns true Boolean out = “Geeks”.equals(“geeks”); // returns false Boolean out = “Geeks”.equals(“Geeks”); // returns true Boolean out = “Geeks”.equals(“geeks”); // returns false boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring case considerations. Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true int compareTo( String anotherString): Compares two string lexicographically. int out = s1.compareTo(s2); // where s1 ans s2 are // strings to be compared This returns difference s1-s2. If : out < 0 // s1 comes before s2 out = 0 // s1 and s2 are equal. out > 0 // s1 comes after s2. int out = s1.compareTo(s2); // where s1 ans s2 are // strings to be compared This returns difference s1-s2. If : out < 0 // s1 comes before s2 out = 0 // s1 and s2 are equal. out > 0 // s1 comes after s2. int compareToIgnoreCase( String anotherString): Compares two string lexicographically, ignoring case considerations. int out = s1.compareToIgnoreCase(s2); // where s1 ans s2 are // strings to be compared This returns difference s1-s2. If : out < 0 // s1 comes before s2 out = 0 // s1 and s2 are equal. out > 0 // s1 comes after s2. Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase). int out = s1.compareToIgnoreCase(s2); // where s1 ans s2 are // strings to be compared This returns difference s1-s2. If : out < 0 // s1 comes before s2 out = 0 // s1 and s2 are equal. out > 0 // s1 comes after s2. Note- In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase). String toLowerCase(): Converts all the characters in the String to lower case.String word1 = “HeLLo”; String word3 = word1.toLowerCase(); // returns “hello" String word1 = “HeLLo”; String word3 = word1.toLowerCase(); // returns “hello" String toUpperCase(): Converts all the characters in the String to upper case.String word1 = “HeLLo”; String word2 = word1.toUpperCase(); // returns “HELLO” String word1 = “HeLLo”; String word2 = word1.toUpperCase(); // returns “HELLO” String trim(): Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.String word1 = “ Learn Share Learn “; String word2 = word1.trim(); // returns “Learn Share Learn” String word1 = “ Learn Share Learn “; String word2 = word1.trim(); // returns “Learn Share Learn” String replace (char oldChar, char newChar): Returns new string by replacing all occurrences of oldChar with newChar.String s1 = “feeksforfeeks“; String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks” Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeks String s1 = “feeksforfeeks“; String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // returns “geeksgorgeeks” Note:- s1 is still feeksforfeeks and s2 is geeksgorgeeks Program to illustrate all string methods: // Java code to illustrate different constructors and methods // String class. import java.io.*;import java.util.*;class Test{ public static void main (String[] args) { String s= "GeeksforGeeks"; // or String s= new String ("GeeksforGeeks"); // Returns the number of characters in the String. System.out.println("String length = " + s.length()); // Returns the character at ith index. System.out.println("Character at 3rd position = " + s.charAt(3)); // Return the substring from the ith index character // to end of string System.out.println("Substring " + s.substring(3)); // Returns the substring from i to j-1 index. System.out.println("Substring = " + s.substring(2,5)); // Concatenates string2 to the end of string1. String s1 = "Geeks"; String s2 = "forGeeks"; System.out.println("Concatenated string = " + s1.concat(s2)); // Returns the index within the string // of the first occurrence of the specified string. String s4 = "Learn Share Learn"; System.out.println("Index of Share " + s4.indexOf("Share")); // Returns the index within the string of the // first occurrence of the specified string, // starting at the specified index. System.out.println("Index of a = " + s4.indexOf('a',3)); // Checking equality of Strings Boolean out = "Geeks".equals("geeks"); System.out.println("Checking Equality " + out); out = "Geeks".equals("Geeks"); System.out.println("Checking Equality " + out); out = "Geeks".equalsIgnoreCase("gEeks "); System.out.println("Checking Equality " + out); //If ASCII difference is zero then the two strings are similar int out1 = s1.compareTo(s2); System.out.println("the difference between ASCII value is="+out1); // Converting cases String word1 = "GeeKyMe"; System.out.println("Changing to lower Case " + word1.toLowerCase()); // Converting cases String word2 = "GeekyME"; System.out.println("Changing to UPPER Case " + word2.toUpperCase()); // Trimming the word String word4 = " Learn Share Learn "; System.out.println("Trim the word " + word4.trim()); // Replacing characters String str1 = "feeksforfeeks"; System.out.println("Original String " + str1); String str2 = "feeksforfeeks".replace('f' ,'g') ; System.out.println("Replaced f with g -> " + str2); } } Output : String length = 13 Character at 3rd position = k Substring ksforGeeks Substring = eks Concatenated string = GeeksforGeeks Index of Share 6 Index of a = 8 Checking Equality false Checking Equality true Checking Equality false the difference between ASCII value is=-31 Changing to lower Case geekyme Changing to UPPER Case GEEKYME Trim the word Learn Share Learn Original String feeksforfeeks Replaced f with g -> geeksgorgeeks For Set – 2 you can refer: Java.lang.String class in Java | Set 2 This article is contributed by Rahul Agrawal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above AditiSinghai veervikram samarthbais255 basic_s Java-lang package Java-Strings Java School Programming Strings Java-Strings Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Python Dictionary Arrays in C/C++ Reverse a string in Java Introduction To PYTHON Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Nov, 2020" }, { "code": null, "e": 188, "s": 52, "text": "String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created." }, { "code": null, "e": 2...
PostgreSQL – SELECT DISTINCT clause
07 Oct, 2021 This article will be focusing on the use of SELECT statement with the DISTINCT clause to remove duplicates rows from a result set of query data. Removing duplicate rows from a query result set in PostgreSQL can be done using the SELECT statement with the DISTINCT clause. It keeps one row for each group of duplicates. The DISTINCT clause can be used for a single column or for a list of columns. Syntax:SELECT DISTINCT column_1 FROM table_name; If you desire to operate on a list of columns the syntax will somewhat be like below: Syntax:SELECT DISTINCT column_1, column_2, column_3 FROM table_name; Now, let’s look into a few examples for better understanding. For the sake of example, we will create a sample database as explained below: Create a database(say, Favourite_colours) using the commands shown below: CREATE DATABASE Favourite_colours; Now add a table(say, my_table) with columns(say, id, colour_1 and colour_2) to the database using the command below: CREATE TABLE my_table( id serial NOT NULL PRIMARY KEY, colour_1 VARCHAR, colour_2 VARCHAR ); Now insert some data in the table that we just added to our database using the command below: INSERT INTO my_table(colour_1, colour_2) VALUES ('red', 'red'), ('red', 'red'), ('red', NULL), (NULL, 'red'), ('red', 'green'), ('red', 'blue'), ('green', 'red'), ('green', 'blue'), ('green', 'green'), ('blue', 'red'), ('blue', 'green'), ('blue', 'blue'); Now check if everything is as intended by making a query as below: SELECT id, colour_1, colour_2 FROM my_table; If everything is as intended, the output will be like as shown below: Since, our database is good to go, we move onto the implementation of the SELECT DISTINCT clause. Example 1: PostgreSQL DISTINCT on one column SELECT DISTINCT colour_1 FROM my_table ORDER BY colour_1; Output: Example 2: PostgreSQL DISTINCT on multiple columns SELECT DISTINCT colour_1, colour_2 FROM my_table ORDER BY colour_1, colour_2; Output: akshaysingh98088 postgreSQL-clauses PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Oct, 2021" }, { "code": null, "e": 174, "s": 28, "text": "This article will be focusing on the use of SELECT statement with the DISTINCT clause to remove duplicates rows from a result set of query data. " }, { "code": null, ...